일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 내돈내산
- vercel
- JavaScript
- C++
- js
- 차등프라이버시
- server비교
- 미디어쿼리
- html
- DB
- react_usecallback
- props {}
- node.js 초기설정
- 제로샷-원샷-퓨샷
- react_usememo
- map()함수
- 커밋메시지 변경하기
- 자식커밋 쌍방향 재배치 오류
- css
- 자바
- 알고리즘
- react_usereducer
- java
- branch 합치기
- 웹개발
- 코린이
- react_useeffect
- 웹개발공부
- React
- 소스트리
Archives
- Today
- Total
Soony's House
[JAVA] Java의 인자 전달 , 포인터 ? - call by value, call by reference 본문
💡Language/JAVA
[JAVA] Java의 인자 전달 , 포인터 ? - call by value, call by reference
soonybutter 2024. 9. 29. 11:41728x90
※ JAVA의 인자 전달
- 자바에서 지원하는 타입에는 primitive type과 reference type이 있다.
- primitive type : byte, char, short, int, long, float, double, boolean 등과 같은 자바 기본 타입
- reference type : java.lang.object를 상속받는 모든 객체
1. primitive type이 인자로 전달되는 경우
public class test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 10;
System.out.println("a = "+a);
add(a);
System.out.println("a = "+a);
}
static void add(int x) { // a의 값을 1증가 시켜주는 함수
x++;
}
}
a = 10 a = 10
값이 바뀌지 않는 것을 보아 Call By Value임을 알 수 있다.
2. 객체 레퍼런스가 인자로 전달되는 경우
class Point{
int x;
Point(int x){
this.x = x;
}
}
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Point p = new Point(10);
System.out.println("a = "+p.x);
add(p);
System.out.println("a = "+p.x);
}
static void add(Point a) { // a.x 값을 1 증가 시켜주는 함수
a.x++;
}
}
a = 10 a = 11
값이 바뀌는 것을 보아 Call By Reference임을 알 수 있다.
3. 배열이 인자로 전달되는 경우
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {10, 20};
System.out.println("x = "+a[0]+", y = "+a[1]);
swap(a);
System.out.println("x = "+a[0]+", y = "+a[1]);
}
static void swap(int x[]) { // x[0]와 x[y] 값을 교환하는 함수
int temp = x[0];
x[0] = x[1];
x[1] = temp;
}
}
x = 10, y = 20 x = 20, y = 10
값이 바뀌는 것을 보아 Call By Reference임을 알 수 있다.
[정리] primitive type은 Call By Value, reference type은 Call By Value
728x90
'💡Language > JAVA' 카테고리의 다른 글
[JAVA] sort함수, 배열 정렬(오름차순, 내림차순) (0) | 2024.10.14 |
---|---|
[JAVA] String 비교하기 (7) | 2024.09.30 |
[JAVA] 자바 Int형 Char형 변환 (1) | 2024.09.23 |
[JAVA] 입출력(I/O)- 스트림(Stream), 버퍼(Buffer), File입출력스트림 정리 (1) | 2024.09.07 |
[JAVA] 자바 예외처리(Exception)- try catch문, throw, throws (13) | 2024.09.04 |