Brother, it has been a long time since I updated the articles of the interviewer series. I am really anxious, so I come here specially to urge you. I am looking for a job in recent period of time, can learn from the second elder brother’s article a little more confidence!
To be honest, it’s been a week since readers trust You sent me this message. I don’t mean to snub you, but there’s a lot of updatable content. Two readers have asked me to update my article on whether Java is value passing or reference passing — a question I’ve already written about, but which I’m going to rewrite in the context of an interview.
Seven years ago, when I returned from the mild, humid city of Suzhou to the quaint city of Luoyang, I interviewed several interviewers with a “I have the world” attitude. One of them, Old Ma, impressed me. Because he threw me off with an interview question: Tell me whether Java is passed by value or by reference.
At that time, I was young and energetic. I thought I could answer all the interview questions fluently, but I did not expect to be “difficult for me” by the old horse. Luoyang, the desert of the Internet, also had technical experts. Now recall, face involuntarily on the blush of shame: at that time true food! Anyway, it’s time to write an article that dissects the difference between value passing and reference passing.
There are two common ways of passing parameters to methods, “value passing” and “reference passing.” The C language itself only supports value passing, and its derivative C++ supports both value passing and reference passing, while Java only supports value passing.
01. Value passing VS reference passing
First of all, we need to be clear about what value passing is and what reference passing is, otherwise the discussion of Java as value passing or reference passing is meaningless.
When a parameter is passed as a value between two methods, the caller and the called are actually using two different variables — the variable in the called (the original value) is a copy of the variable in the caller, and changes to either variable will not affect the other.
When a parameter is passed by reference between two methods, the caller and the called are using the same variable, and both are visible when the variable is modified.
The main reason Java programmers confuse value passing with reference passing is that Java has two types of data: a primitive type, such as int, and a reference type, such as String.
Primitives store actual values, while referential variables store references to objects — their memory address. Values and references are stored in the stack, while objects are stored in the heap.
The reason for this difference is that:
- The advantage of the stack is that access is faster than the heap, second only to registers located directly in the CPU. The downside is that the size and lifetime of the data in the stack must be fixed.
- The advantage of the heap is that memory can be allocated dynamically, the lifetime of the heap does not have to be told to the compiler in advance, and Java’s garbage collector automatically collects data that is no longer used. But because memory is allocated dynamically at run time, access speed is slow.
02. Basic type of parameter passing
As you know, Java has eight basic data types: int, Long, byte, short, float, double, char, and Boolean. Their values are stored directly on the stack, and each time they are passed as arguments, a new copy of the original value (argument) is made for the parameter. The parameter is cleared from the stack at the end of the called method.
Take a look at this 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; }}Copy the code
1) Age in main is a basic type, so its value 18 is stored directly on the stack.
2) When the modify() method is called, a copy of the age argument (age1) is created, also with the value 18, but elsewhere in the stack.
3) Any modification to the parameter age will only affect itself and not the argument.
03. Parameter passing of reference type
Let’s look at the code that creates a reference type variable:
Writer writer = new Writer(18."Silent King II.");
Copy the code
Is writer an object? Or a reference to an object? To clarify this, we can split the above code into two lines:
Writer writer;
writer = new Writer(18."Silent King II.");
Copy the code
If writer were an object, there would be no need to create the object with the new keyword, right? That is, writer is not an object, just a variable until the “=” operator executes. So who is the object? New Writer(18, “Silent King II “), which is an object, stored in the heap; The “=” operator then assigns a reference to the object to the Writer variable, which should then be called an object reference, which is stored on the stack and holds the address of the object in the heap.
Each time a reference type is passed as an argument, a copy (parameter) of the object reference (argument) is created, which holds the same address as the argument.
Take a look at this 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); }}Copy the code
1) Before calling modify(), arguments A and b refer to different objects, even though they are both 18.
2) When the modify() method is called, new copies of arguments A and b are created on the stack, a1 and b1 respectively, but to the same objects (A and A1 point to object A, b and b1 point to object B).
3) In the modify() method, we modify the age of parameter A1 to 30, which means that the age of object A has changed from 18 to 30, and the age of object A has changed from 30. Parameter b1 refers to a new object, and the age of b1 is subsequently changed to 30.
Changing the age of A1 means changing the age of A, because they point to the same object; Changing 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
Copy the code
Sure enough, it fits our analysis.
04, finally
Well, my dear readers, that’s all for this article. After reading it, you don’t have to worry about being picked on when an interviewer asks if Java is passed by value or by reference. I am silent King 2, an interesting programmer. Original is not easy, do not want a free ticket, please praise for this article, this will be my writing more high-quality articles of the strongest power.
If you think this article is helpful to you, please search “Silent King ii” on wechat and read it for the first time. Reply [666] there is also a 500G HIGH-DEFINITION teaching video (classified) that I prepared for you. Interview on GitHub