LoginSignup
0
0

java メソッド 配列

Last updated at Posted at 2024-04-15

引数に配列を用いる、
値渡しと参照渡しがるというが厳密には参照の値渡しというみたい:sweat_smile:

違い

引数の渡し方の違い

値渡し(一部訂正)

public class Sample {
 public static void main(String[] args) {
  int num = 5;
  samlpe(num);
  System.out.println(num); 
  
  }

  public static void sample(int num) {
   int += 5;
   System.out.println(num);
  }
}


出力結果
10
5

変数の値を直接コピーするので変数は変化しない
呼び出し元のアドレスの情報のみが渡される(値そのものが渡される)

参照の値渡し

public class Sample {
 public static void main(String[] args) {
  int[] num = {5};
  sample(num);
  System.out.println(num[0]);
  }

 public static void sample(int[] num) {
  num[0] += 5;
  System.out.println(num[0]);
 }
}


出力結果
10
10
public class Sample {
 public static void main(String[] args) {
  String[] hello = {"hello"};
  sample(hello);
  System.out.println(hello[0]);
  }

 public static void sample(String[] hello) {
  hello[0] = "こんにちは";
  System.out.println(hello[0]);
 }
}


出力結果
こんにちは
こんにちは

呼び出し先で配列の実態を書き換えると、呼び出し元にも変更がある
呼び出し元のアドレスが渡される。

String型は参照の値渡しのみ!
勉強になります!!

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0