Call by Value | Call by reference

Dmitry Klokov·2021년 1월 11일
0

JAVA

목록 보기
2/13
post-thumbnail
post-custom-banner

Primitive Type

// Counter.java
public class Counter {
	public int count = 0;
}
// Updater.java
public class Updater {
    public void update(int count) {
        count += 1;
    }
}
// Main.java
public class Main {

    public static void main(String[] args) {
        Counter c = new Counter();
        System.out.println("before update : " + c.count); // 0

        Updater u = new Updater();
        u.update(c.count);
        System.out.println("after update : " + c.count); // 0
    }
}

Reference Type

// Updater.java
public class Updater {
    public void update(Counter counter) {
        counter.count += 1;
    }
}
// Main.java
public class Main {

    public static void main(String[] args) {
        Counter c = new Counter();
        System.out.println("before update : " + c.count); // 0

        Updater u = new Updater();
        u.update(c);
        System.out.println("after update : " + c.count); // 1
    }
}
profile
Power Weekend
post-custom-banner

0개의 댓글