is reference delivery or value passing in Java?

Source: Internet
Author: User
Tags getcolor

Objective

One of the most common misconceptions you can make in learning the Java programming language is whether Java is a value pass or a reference pass. Come around this topic today to uncover the fog.

Concept

First come to know what is value passing what is a reference pass.

    • Value Passing: Copies the method's actual parameter value to another variable, and then the copied object is passed, which is why it is referred to as "value passing"

    • Reference passing: a reference to the actual parameter is passed to the method, which is why it is referred to as the "pass-through" reason.

Example Analysis 1
问题:如果java是使用引用传递的话,为什么在函数中 变量的交换会没有卵用呢?答案:java通过引用来操作对象,并且所有Object类型的变量都是引用一个地址。但是,java传递方法参数并不是引用传递,而是值传递。

For example, let's take a look:

publicvoidbadSwap(intint var2){  int temp = var1;  var1 = var2;  var2 = temp;}

When the Badswap () method ends, the variables that were originally passed in as actual parameters are still their original values, that is, the method is not used for eggs. If the parameter of this method is changed from int to object class, the result is still the same. Because Java is passed by value to pass an object reference. That may not be clear, let's take another example.

public void tricky (point arg1, point arg2) {arg1. x= -;Arg1. Y= -;Point temp = arg1;Arg1 = arg2;Arg2 = Temp;}public static void Main (String [] args) {Point pnt1 = new Point (0,0);Point pnt2 = new Point (0,0);System. out. println("X:"+ pnt1. x+"Y:"+pnt1. Y); System. out. println("X:"+ Pnt2. x+"Y:"+pnt2. Y);System. out. println(" ");Tricky (Pnt1,pnt2);System. out. println("X:"+ pnt1. x+"Y:"+ pnt1. Y); System. out. println("X:"+ Pnt2. x+"Y:"+pnt2. Y); }

Two objects Pnt1 and Pnt2 are constructed, and the initial x, y values are 0. After passing in the tricky () party
method, modify the value of the X, Y, and args1 of the row parameter in the methods, and then swap the direction of the line parameter.

Execute the Main method and enter the following

X0 Y: 0X0 Y: 0X100 Y: 100X0 Y: 0

According to the output results, you can find that the actual parameter Pnt1 value has been modified, Pnt2 property has not changed, that is, Pnt1 box Pnt2 exchange failed! This is the most easily confused.
Pnt1 and Pnt2 are definitely object references, and when Pnt1 and Pnt2 are passed into the tricky () method,
Because Java is a value pass, it is similar to replication, equivalent to copying and a pnt1-like line parametric arg1, which also has a reference to the same pointer as the PNT1 variable. Figure one shows the two references to the same address after passing the value.


Figure 1. method, an object will have at least two references after the object reference parameter is passed in the

In the example above, the value of modifying an object in a method takes effect because the references to the two variables point to the same object. But because Arg1 is a copy of a variable, so the exchange of words just exchanged arg1 point, this is why the exchange will fail.

Figure 2 shows the reference Exchange in the method parameter only, not the original parameter exchange.

If you need to successfully exchange references for pnt1 and Pnt2, you can only modify their references directly externally.


Figure 2:java is passed by value, copy a variable like pnt1, and they have the same reference. After the method call, only the references to Arg1 and Arg2 are exchanged.

There may be a lot of people in the country who know the laws of the passing, but they are still accustomed to the basic type is the value of the pass, the reference type variable is a reference pass, because the parameters of the method does have an external variable reference. This is a personal understanding. I'm more inclined to pass the value: After passing the value, the parameter in the method has the same value as the actual parameter (the underlying type is a value and the object type is a reference), so it has a reference. If a reference is passed, it is passed directly to the object that is stored in the heap (that is, the object is copied straight). Of course, it's just my personal knowledge.

Example Analysis 2
public   Class  Test {private  static  int  A; private     int  b; public  static  void  main  (string[] args) {System.        out . println (a);        Modify (a); System.        out . println (a);    return ; } private  static      void  modify  (int  a) {a++; }}

Knowing that Java is a value pass, the results are clear.

The value of output a must be the same.

Java is always passed by value instead of by reference, and then an example

Example Analysis 3
publicclass Balloon {    private String color;    publicBalloon(){}    publicBalloon(String c){        this.color=c;    }    publicgetColor() {        return color;    }    publicvoidsetColor(String color) {        this.color = color;    }}

The balloon class has a color property.

 Public classTest { Public Static void Main(string[] args) {Balloon red =NewBalloon ("Red");//memory ReferenceBalloon Blue =NewBalloon ("Blue");//memory ReferenceSwap (red, blue); System. out. println ("Red color="+red.getcolor ()); System. out. println ("Blue color="+blue.getcolor ());        Foo (blue); System. out. println ("Blue color="+blue.getcolor ()); }Private Static void Foo(Balloon Balloon) {//baloon=100Balloon.setcolor ("Red");//baloon=100Balloon =NewBalloon ("Green");//baloon=200Balloon.setcolor ("Blue");//baloon =}//generic Swap Method     Public Static void Swap(Object O1, Object O2)        {Object temp = O1;        O1=o2;    O2=temp; }}

Since I've analyzed an example before, I'm not going to analyze each step in detail here.

You can see the original source of the example, there are every step of the analysis process, but also the video detailed explanation (should be to turn over the wall)

Example Analysis 3
Example 3 Analysis Link: Java is pass by Value and not pass by Reference

About the reference to the knowledge, you can see my article heap and stack

Conclusion

Recently too busy man also a bit lazy so long not updated blog, must quickly recover. Please leave a message if you have questions. Like just a second, power is eternal, give me a praise! Look forward to your attention!

is reference delivery or value passing in Java?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.