개발/java

java - call by value, call by reference

mungmang 2021. 7. 11. 02:06
λ°˜μ‘ν˜•
μžλ°”λŠ” call by value (값에 μ˜ν•œ 호좜) λ°©μ‹μ΄λ‹€.

public class CallTest {

    public static void main(String[] args) {
        String test1 = "test1";
        String test2 = "test2";
        CallTest.callByValue(test1, test2); // 값에 μ˜ν•œ μ°Έμ‘°
        
        // CallTest.callByValue μ—μ„œ λ§€κ°œλ³€μˆ˜ 전달 ν›„ λ°”κΏ§λ‹€ ν•˜μ—¬, test1, test2에 영ν–₯ μ•ˆλ―ΈμΉ¨.
        System.out.println("test1:" + test1+", test2:"+test2); 
    }

    public static void callByValue(String test1, String test2) {
        String temp = test1;
        test1 = test2;
        test2  = temp;
        System.out.println("test1:" + test1+", test2:"+test2);
    }
}

/*
// result)
test1:test2, test2:test1
test1:test1, test2:test2
**/

ν•¨μˆ˜ 호좜 μ‹œ λ§€κ°œλ³€μˆ˜μ˜ 값을 κ·ΈλŒ€λ‘œ 전달!
μ „λ‹¬ν•œ κ°’ κ·ΈλŒ€λ‘œ μ‚¬μš©!
λ§€κ°œλ³€μˆ˜μ˜ 값듀은 각각의 λ‹€λ₯Έ λ©”λͺ¨λ¦¬ μœ„μΉ˜μ— μ €μž₯됨. 
ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ λ³€κ²½ν•œ 사항은 호좜자의 μ‹€μ œ λ§€κ°œλ³€μˆ˜μ— λ°˜μ˜λ˜μ§€λŠ” μ•ŠμŒ.

 

call by reference (μ£Όμ†Œμ— μ˜ν•œ 호좜)

λ§€κ°œλ³€μˆ˜λŠ” λ™μΌν•œ μœ„μΉ˜λ₯Ό μ°Έμ‘°ν•˜λ―€λ‘œ ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ λ³€κ²½ν•œ 사항은 μ‹€μ œ 호좜자의 λ§€κ°œλ³€μˆ˜μ— 반영됨.
ν•¨μˆ˜ 호좜 μ‹œ λ§€κ°œλ³€μˆ˜μ— μ£Όμ†Œλ₯Ό μ „λ‹¬ν•˜μ—¬ μ‚¬μš©!
참쑰에 μ˜ν•œ 호좜 (C++ 포인터)

/** 
C++ μ–Έμ–΄μ—μ„œ λ³€μˆ˜ μ£Όμ†Œλ₯Ό λ§€κ°œλ³€μˆ˜λ‘œ 전달 ν•˜μ˜€μ„ λ•Œ
result) 
test1:test2, test2:test1
test1:test2, test2:test1 // μ£Όμ†Œ 참쑰에 μ˜ν•΄ 값이 λ³€κ²½ 됨.
*/

 


μ°Έκ³ 

https://www.geeksforgeeks.org/difference-between-call-by-value-and-call-by-reference/

λ°˜μ‘ν˜•