[Java] Returning value not using return keyword

조현호_ChoHyeonHo·2024년 12월 31일

Code: ReturnTest.java

public class ReturnTest {
    public static void main(String[] args) {
        ReturnTest r = new ReturnTest();

        int result = r.add(3,5);
        System.out.println(result);

        int[] result2 = {0};
        r.add(3, 5, result2);
        System.out.println(result2[0]);
    }    
    int add(int a, int b){
        return a + b;
    }

    void add(int a, int b, int[] result){
        result[0] = a + b; // 배열은 참조형 자료라서 이것을 메인 메서드에서 출력할 수 있는 거지?
    }
}

Result

8
8

How?

The array is a reference type in Java, which means that when you pass an array to a method, you are passing a reference to the array, not a copy of the array. Therefore, any changes made to the array inside the method will be reflected in the original array.

profile
Behold the rabbit hole

0개의 댓글