Interviewer: Brother, talk about Java by value or by reference?

Brother, I haven't updated the interviewer series for a long time. It really made me wait in a hurry, so I came here to remind me. I have been looking for a job for a while, so I can learn a little bit from my second brother's article and I have more confidence!

To be honest, it has been 1 week since the reader trust you sent me this message. It's not that I'm neglecting, it's true that there are too many content that can be updated. No, two readers invariably asked me to update the article on whether Java is passed by value or by reference. I actually wrote this question before, but it seems that the answer is not perfect enough, so I plan to interview Rewrite an article from the perspective.

Seven years ago, I returned to the quaint Luoyang from the mild and humid Suzhou, and "interviewed" several interviewers with a mentality of "I have the world". One of them was called Lao Ma, which impressed me deeply. Because he threw an interview question at the time and stunned me: Tell me about Java by value or by reference.

I was young and energetic at the time, and thought that all the interview questions could be answered well. I didn't expect to be "made things difficult" by the old horse-it turns out that Luoyang, the desert of the Internet, also has technical experts. Looking back now, my face was flushed with shame unconsciously: the real dish at that time! Anyway, it's time to write an article to analyze the difference between passing by value and passing by reference.

There are two common ways to pass parameters to methods, one is "pass by value" and the other is "pass by reference". The C language itself only supports value passing, its derivative C++ supports both value passing and reference passing, while Java only supports value passing.

01, value transfer VS reference transfer

First of all, we must figure out what is passing by value and what is passing by reference. Otherwise, it would be meaningless to discuss whether Java is passing by value or by reference.

When a parameter is passed between two methods by value, the caller and the callee actually use two different variables-the variable in the callee (original value) is one of the variables in the caller Make copies, and modifying any of them will not affect the other variable.

When a parameter is passed between two methods by reference, the caller and the callee use the same variable, and when the variable is modified, both sides are visible.

Java programmers tend to confuse value passing and reference passing mainly because Java has two data types, one is a basic type, such as int, and the other is a reference type, such as String.

Basic types of variables store actual values, while reference type variables store references to objects—pointing to the address of the object in memory. Values ​​and references are stored in the stack, and objects are stored in the heap.

Interviewer: Brother, talk about Java by value or by reference?

 

The reason for this difference is because:

  • The advantage of the stack is that the access speed is faster than the heap, second only to the registers directly located in the CPU. But the disadvantage is that the data size and life cycle in the stack must be determined.
  • The advantage of the heap is that the memory size can be dynamically allocated, and the life cycle does not need to be told to the compiler in advance. Java's garbage collector will automatically take away the data that is no longer used. However, due to dynamic allocation of memory at runtime, the access speed is slow.

02, basic types of parameter transfer

As we all know, Java has 8 basic data types, namely int, long, byte, short, float, double, char and boolean. Their values ​​are directly stored in the stack, and whenever passed as a parameter, a new copy of the original value (actual parameter) will be used for the formal parameter. The formal parameters will be cleared from the stack at the end of the called method.

Consider the following code:

public class PrimitiveTypeDemo {
    public static void main(String[] args) {
        int age = 18;
        modify(age);        System.out.println(age);
    }    private static void modify(int age1) {
        age1 = 30;
    }}

1) The age in the main method is a basic type, so its value 18 is directly stored in the stack.

2) When the modify() method is called, a copy of the actual parameter age (formal parameter age1) is created, and its value is also 18, but it is elsewhere in the stack.

3) Any modification to the formal parameter age will only affect itself and not the actual parameters.

Interviewer: Brother, talk about Java by value or by reference?

 

03, reference type parameter passing

Look at a piece of code that creates a reference type variable:

Writer writer = new Writer(18, "沉默王二");

Is writer an object? Or is it a reference to an object? In order to clarify this problem, we can split the above code into two lines of code:

Writer writer;
writer = new Writer(18, "沉默王二");

If the writer is an object, there is no need to create an object through the new keyword, right? That is to say, the writer is not an object, it is just a variable before the "=" operator is executed. So who is the target? new Writer(18, "Silent King Two"), it is an object, stored in the heap; then, the "=" operator assigns the object reference to the writer variable, so the writer should be called an object reference at this time, and it is stored in In the stack, the address of the object in the heap is saved.

Whenever a reference type is passed as a parameter, a copy (formal parameter) of the object reference (actual parameter) is created. The address of the formal parameter is the same as the actual parameter.

Consider the following code:

public class ReferenceTypeDemo {
    public static void main(String[] args) {
        Writer a = new Writer(18);
        Writer b = new Writer(18);
        modify(a, b);        System.out.println(a.getAge());
        System.out.println(b.getAge());
    }    private static void modify(Writer a1, Writer b1) {
        a1.setAge(30);
        b1 = new Writer(18);
        b1.setAge(30);
    }}

1) Before the modify() method is called, the objects pointed to by the actual parameters a and b are different, even though the age is 18.

Interviewer: Brother, talk about Java by value or by reference?

 

2) When the modify() method is called, the actual parameters a and b both create a new copy on the stack, namely a1 and b1, but the objects they point to are the same (a and a1 point to objects a, b and b1 Point to object b).

Interviewer: Brother, talk about Java by value or by reference?

 

3) In the modify() method, the age of the formal parameter a1 is modified to 30, which means that the age of the object a has changed from 18 to 30, and the actual parameter a also points to the object a, so the age of a has also become 30; The formal parameter b1 points to a new object, and then the age of b1 is modified to 30.

Interviewer: Brother, talk about Java by value or by reference?

 

Modifying the age of a1 means modifying the age of a at the same time, because they point to one object; modifying the age of b1 has no effect on b, because they point to two objects.

The output of the program is as follows:

30
18

Sure enough, it is consistent with our analysis.

04, finally

Well, my dear readers, the above is the entire content of this article. After reading it, when the interviewer asks whether Java is pass by value or pass by reference, you don't have to worry about making things difficult. I am the second king of silence, an interesting programmer. Originality is not easy, do not have to vote in vain, please give me a thumbs up for this article , this will be my strongest motivation to write more quality articles.

Author: Silence king

Link: https://juejin.im/post/5ea10ca4518825736d27ae23

Source: Nuggets

Guess you like

Origin blog.csdn.net/GYHYCX/article/details/108646137