전문 인터넷 중독자 • 게임 애호가 • 기술 창작자
전문 인터넷 중독자 • 게임 애호가 • 기술 창작자

Java가 값 전달 언어인 이유에 대한 설명

Java는 값 전달 언어입니다. (스스로 테스트해 보세요) 그게 무슨 뜻인지 이해하시나요?
이 페이지는 여러분의 편의를 위해 열정적인 AI 인턴들이 영어에서 번역한 것입니다. 아직 학습 중이므로 몇 가지 오류가 있을 수 있습니다. 가장 정확한 정보는 영어 버전을 참조하세요.
블로그 Java가 값 전달 언어인 이유에 대한 설명

이 블로그 게시물은 2010년 7월에 게시되었으므로, 읽는 시점에 따라 일부 내용이 최신이 아닐 수 있습니다. 안타깝게도 정보의 정확성을 보장하기 위해 게시물을 항상 최신 상태로 유지하는 것은 어렵습니다.

    One day, some time ago, while I was searching through the web for an answer to something (not surprisingly) code related, I somehow stumbled upon a thread over at Stack Overflow. I cannot find the original post at the moment, but basically the author presented a piece of code and asked why it didn't work. Another developer replied and said it was due to that Java is a pass-by-value language and not pass-be-reference.

    Test yourself first

    Even though I don't have his original code, I have written my own version below. But before I explain what a pass-by-value actually means, look at this code below and try to answer two questions: What will it print? And more importantly do you understand why?
    public class Test { public static void main(String[] args) { Person p = new Person(); p.setName("Alice"); build(p); System.out.println(p.getName()); } public static void build(Person p) { p.setName("Bob"); p = new Person(); p.setName("Christy"); } } class Person { private String name = ""; public void setName( String name ) { this.name = name; } public String getName() { return name; } }
    The correct answer is "Bob". If you thought it was "Christy", trust me - you are not alone. It's a common mistake. Let me explain how it works.

    Pass-by-value vs Pass-by-reference: The business card example

    As you have been taught that in school Java manipulate objects by reference and all object variables are references.
    To try and explain this with strings to the real world, lets say there is a business man called Fred. In Java you could say that Fred is an instance object of the BusinessMan class:
    new BusinessMan("Fred");
    In your pocket you find his business card with Fred's phone number The business card is obviously not Fred himself, but just a pointer to him - just as a reference variable in Java towards an object. The variable is not the object but only simply an arrow or a link to the object:
    BusinessMan businessCard = new BusinessMan("Fred");
    So when you give (pass) the business card to someone else (call a method) you don't give them Fred himself, but a business card (reference) to Fred, containing the information where Fred is.
    But here is the distinction between pass-by-value and pass-by-reference. When you give the business card you don't actually give them your business card. You make a copy of the business card and give them the copy. Meaning now have two business cards pointing to Fred. This is pass-by-value. If you actually gave them the business (and not make a copy) it would be pass-by-reference.
    Now if you point your own business card (not the copy you created) to some other business man (maybe by scratching over Fred's phone number and and writing Ken's instead), there would be still a business card pointing towards Fred - the one you copied and gave away.

    A graphical explanation of the code

    I our code we created a new variable reference p and point it towards a new instance of Person and set the variable name to Alice.
    Person p = new Person(); p.setName("Alice"); Example 1
    Then we call the method build which create a new variable (also called p) and copies the original p’s value reference. This leaves us with two variables called p that are pointing towards the same Person, however the second p only exists inside the method build.
    Example 2
    Next we rename the name "Alice" to "Bob".
    p.setName("Bob"); Example 3

    Hold on, doesn't this prove that Java is a pass-by-reference language?

    Here is a common trap for new Java developers. Since we obviously manage to rename the person from alice to bob in our method, but the change is also viewable outside the method, doesn't this mean Java is actually a pass-by-reference language?
    No, not really. Everything in Java is passed as values. When you send an object to a method, you actually don't send the reference, nor the actual object. You simply send the value of the reference, not the reference it self.
    This means that even though you can rename alice to bob, you can't replace the original p outside the method by doing p = new Person() - as I will demonstrate below.

    Continuing with the graphical example

    But now we create a second Person, point the method variable p towards it and call them Christy.
    p = new Person(); p.setName("Christy"); Example 4
    This means there are now two variables (both called p) pointing towards two different Person-objects.
    So when we, outside the method, get the original p’s name (which did however get changed from Alice to Bob inside the method) we are referring towards the first Person.
    System.out.println(p.getName());
    Resulting in that "Bob" will be printed.

    How to pass-by-reference in Java

    Java is strictly a pass-by-value language, meaning Java does not pass method arguments by reference but as values. This is even stated in the language specifications.
    However there are situations where you would like to pass-by-reference inside the method, for example you actually want to change the variable outside - inside the method.
    The best solution is to create a generic wrapper class around the object and call the method with that as the argument instead. This would allow you to re-point the actual object via the wrapper class.
    public class Ref { private T obj; public Ref(T value) { this.obj = value; } public void set(T value) { obj = value; } public T get() { return obj; } }

    Special Agent Squeaky님이 작성했습니다. 최초 게시일 2010년 7월 7일. 최종 업데이트일 2010년 7월 7일.

    📺 스퀴키의 최신 영상을 시청하세요!

    라이브 스트림에 간단한 실시간 자막을 추가하는 방법