TIL | JAVA 기본형 매개변수 / 참조형 매개변수 / 반환타입

김윤희·2022년 8월 1일
0

기본형 매개변수 / 참조형 매개변수

기본형 매개변수


메서드의 매개변수 타입이 기본형일때

  • 기본형 매개변수 - 변수의 값을 읽기만 할 수 있다(read only)
  • 참조형 매개변수 - 변수의 값을 읽고 변경할 수 있다(read & write)

📌기본형 매개변수

class Data{ int x;}
class Ex{
	public static void main(String args){
    	Data d =new Data();//객체 생성
        d.x  = 10;
        System.out.println("main() : x =" + d.x);
        
        change(d.x);
        System.out.println("After change(d.x)");
        System.out.println("main() : x =" + d.x);
    }
    
    static void change(int x){		//기본형 매개변수(값만 복사)
    	x = 1000;
        System.out.println("change() : x =" + x;
    }
}

결과
main() : x = 10
change() : x = 1000
After change(d.x)
main() : x = 10



참조형 매개변수


메서드의 매개변수 타입이 참조형일때

📌참조형 매개변수

class Data2{ int x;}
class Ex2{
	public static void main(String args){
    	Data2 d =new Data2();//객체 생성
        d.x  = 10;
        System.out.println("main() : x =" + d.x);
        
        change(d);	//(객체의 주소를 전달)
        System.out.println("After change(d)");
        System.out.println("main() : x =" + d.x);
    }
    
    static void change(Data2 d){		//참조형 매개변수(객체의 주소를 받음)
    	d.x = 1000;
        System.out.println("change() : x =" + x;
    }
}

결과
main() : x = 10
change() : x = 1000
After change(d)
main() : x = 1000


📌참조형 반환타입

class Data3{ int x;}
class Ex2{
	public static void main(String args){
    	Data3 d =new Data3();//객체 생성
        d.x  = 10;
        
        Data3 d2 = copy(d);	
        System.out.println("d.x ="+d.x);
        System.out.println("d2.x ="+d2.x);
    }
    
    static Data3 copy(Data3 d){		
    	Data3 tmp = new Data3();	//새로운 객체 tmp를 생성한다
    	tmp.x = d.x;	//d.x의 값을 tmp.x에 복사한다
        return tmp;		//복사한 객체의 주소를 반환한다
    }
}

결과
d.x = 10
d2.x = 10

0개의 댓글