Skip to main content Link Menu Expand (external link) Document Search Copy Copied

JAVA Call By Value vs Call By Reference?

Table of contents


๋จผ์ €, Call By Value์™€ Call By Reference์˜ ์ •์˜๋ฅผ ์‚ดํŽด๋ณด์ž.

  • Call By Value : ์ธ์ž๋กœ ๋ฐ›์€ ๊ฐ’์„ ๋ณต์‚ฌํ•˜์—ฌ ์ฒ˜๋ฆฌํ•œ๋‹ค. ๋ณต์‚ฌํ•œ ๊ฐ’์„ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ ์›๋ณธ ๋ฐ์ดํ„ฐ์— ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋Š”๋‹ค.
  • Call By Reference : ์ธ์ž๋กœ ๋ฐ›์€ ๊ฐ’์˜ ์ฃผ์†Œ๋ฅผ ์ฐธ์กฐํ•˜์—ฌ ์ฒ˜๋ฆฌํ•œ๋‹ค. ์›๋ณธ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ ๊ฐ’์— ์˜ํ–ฅ์„ ์ค€๋‹ค.


์ •์˜๋กœ ์‚ดํŽด๋ณด๋ฉด, ์ž๋ฐ”์—์„œ ์›์‹œ ํƒ€์ž…์„ ๋‹ค๋ฃฐ ๋•, Call By Value์ด๊ณ  ๊ฐ์ฒด๋ฅผ ๋‹ค๋ฃฐ ๋• Call By Reference ์ธ ๊ฒƒ ๊ฐ™๋‹ค.

๐Ÿ’ก ํ•˜์ง€๋งŒ! ์ž๋ฐ”๋Š” ์˜ค์ง Call By Value๋กœ๋งŒ ๋™์ž‘ํ•œ๋‹ค๊ณ  ํ•œ๋‹ค.


public class Test {
    public static void main(String[] args) throws NoSuchAlgorithmException {

        Test test = new Test();

        Sample sample = new Sample(1);
        test.test(sample);
        System.out.println(sample.value);
    }

    void test(Sample sample) {
        sample = new Sample(2);
    }
    
    
    static class Sample{
        int value;
        public Sample(int value) {
            this.value = value;
        }
    }
}

์œ„์™€ ๊ฐ™์€ ์ฝ”๋“œ๋กœ ์‚ดํŽด๋ณด์ž.

test() ๋ฉ”์„œ๋“œ๋Š” Sample ๊ฐ์ฒด๋ฅผ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์•„ value๊ฐ’์ด 2์ธ Sample๋กœ ํ• ๋‹นํ•˜๊ณ  ์ข…๋ฃŒ๋œ๋‹ค.

๐Ÿ’ซ ์ด์ „์— ์‚ดํŽด๋ณธ, Call By Reference ์ •์˜์— ์˜ํ•˜๋ฉด ๊ฐ์ฒด๊ฐ€ ์ฐธ์กฐํ•˜๊ณ  ์žˆ๋Š” ์ฃผ์†Œ๊ฐ’์„ ์ „๋‹ฌํ•˜๊ธฐ ๋•Œ๋ฌธ์—

๋ฉ”์„œ๋“œ ์ˆ˜ํ–‰ ํ›„ value์˜ ๊ฐ’์€ ๋ณ€๊ฒฝ๋˜์•ผ ํ•  ๊ฒƒ์ด๋‹ค.

ํ•˜์ง€๋งŒ, ๊ฒฐ๊ณผ๋Š” value๋Š” ๊ทธ๋Œ€๋กœ 1์ธ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.


๊ทธ๋ฆผ์œผ๋กœ ๊ณผ์ •์„ ์‚ดํŽด๋ณด๋ฉด,

image-20230412191843021

test ๋ฉ”์„œ๋“œ์— sample์ด ์ฐธ์กฐํ•˜๊ณ  ์žˆ๋˜ ์ฃผ์†Œ๊ฐ’์„ ๋„˜๊ฒจ์ค€๋‹ค.

๊ทธ๋Ÿฌ๋ฉด test ์Šคํƒ์—๋Š” Heap ์˜์—ญ์— ์กด์žฌํ•˜๊ณ  ์žˆ๋˜ Sample ๊ฐ์ฒด๋ฅผ ๋ฐ”๋ผ๋ณด๊ณ  ์žˆ๋Š” sample์„ ๊ฐ–๊ฒŒ ๋œ๋‹ค.

image-20230412192028508

๊ทธ๋ฆฌ๊ณ  test ๋ฉ”์„œ๋“œ์˜ sample = new Sample(2); ์— ์˜ํ•ด ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ๋ฐ”๋ผ๋ณด๋Š” sample์œผ๋กœ ๋ฐ”๋€๋‹ค.

image-20230412192223959

๊ทธ๋ฆฌ๊ณ  test ๋ฉ”์„œ๋“œ๊ฐ€ ์ข…๋ฃŒ๋˜๋ฉด, test ์Šคํƒ์— ์žˆ๋˜ sample์€ ์‚ฌ๋ผ์ง€๊ณ  Heap ์˜์—ญ์— value๊ฐ’์ด 2์ธ ๊ฐ์ฒด๋Š” ๋‚จ์•„์žˆ๊ฒŒ ๋˜๊ณ , GC์— ์˜ํ•ด ์ •๋ฆฌ ๋  ๊ฒƒ์ด๋‹ค.

์ฆ‰, ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ฐธ์กฐ ๋ณ€์ˆ˜๋ฅผ ๋„˜๊ธฐ๋ฉด, ๋ฉ”์„œ๋“œ๋Š” ์ฃผ์†Œ๊ฐ’์„ ๋ณต์‚ฌํ•ด์„œ ๊ทธ ์ฃผ์†Œ๊ฐ’์„ ๋ฐ”๋ผ๋ณด๋Š” ์ƒˆ๋กœ์šด ์ง€์—ญ ๋ณ€์ˆ˜๋ฅผ ํ•˜๋‚˜ ๋” ๋งŒ๋“œ๋Š” ์…ˆ์ธ ๊ฒƒ์ด๋‹ค.

๊ทธ๋ž˜์„œ ์›๋ž˜ ์กด์žฌํ•˜๋˜ sample์—๋Š” ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋Š”๋‹ค.

์ฆ‰, ์ž๋ฐ”๋Š” Call By Value ๋ฐฉ์‹์ด๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ๊ฒ ๋‹ค!


์ฐธ๊ณ ํ•œ ๋ธ”๋กœ๊ทธ

  1. https://deveric.tistory.com/92