배움과 기록의 장
[Java] 배열의 요소와 값, 배열과 주소값 본문
배열과 배열의 요소를 이리저리 할당/재할당 할 때, 주소값이 저장되는지 값이 저장되는지 헷갈릴 때가 많아서
혼자 이것저것 쳐봤다
배열의 요소와 값
1. 코드
int[] a = new int[]{1,2,3,4,5};
System.out.println(a);
System.out.println(a.length);
for(int i = 0; i < a.length; i++){
System.out.printf("%d ",a[i]);
}
System.out.println();
int[] b = new int[5];
b[2] = a[2]; // int형인 a[2] 라는 값이 저장됨
System.out.println(b);
System.out.println(b.length);
for(int i = 0; i < b.length; i++){
System.out.printf("%d ",b[i]);
}
System.out.println();
b[2] = 10;
System.out.println(b);
System.out.println(b.length);
for(int i = 0; i < b.length; i++){
System.out.printf("%d ",b[i]);
}
System.out.println();
System.out.println("a의 배열이 변할까용?");
for(int i = 0; i < a.length; i++){
System.out.printf("%d ",a[i]);
}
2. 출력
3. 결론
b[2] = a[2] 를 하면 값만 저장되는 것이기 때문에, b[2] 값을 바꿔도 a[2]는 바뀌지 않는다.
b와 a가 서로 전혀다른 배열을 참조하고 있기 때문에 b의 변화가 a에 아무런 영향도 미치지 않는다.
배열과 주소값
1. 코드
b= a; // a라는 객체의 주소값이 저장됨
System.out.println(b);
System.out.println(b.length);
for(int i = 0; i < b.length; i++){
System.out.printf("%d ",b[i]);
}
System.out.println();
b[2] = 10;
System.out.println(b);
System.out.println(b.length);
for(int i = 0; i < b.length; i++){
System.out.printf("%d ",b[i]);
}
System.out.println();
System.out.println("a의 배열이 변할까용?");
for(int i = 0; i < a.length; i++){
System.out.printf("%d ",a[i]);
}
2. 출력
3. 결론
b = a 를 하면 a가 참조하고 있는 배열의 주소값이 b에 저장되는 것이기 때문에, b[2]를 바꾸면 a[2]도 바뀐다.
b와 a가 같은 배열의 주소값을 가지고 있기 때문에 b의 변화가 a에 영향을 미칠 수 있게된다.
반응형
'backend > java' 카테고리의 다른 글
[Java] Stringifyjson (0) | 2025.04.09 |
---|---|
[Java] 예외 처리 (0) | 2025.04.09 |
[Java] 제네릭 (0) | 2025.04.08 |
[Java] Enum (0) | 2025.03.23 |