Deep parsing of parameter transfer _java of methods in Java programming

Source: Internet
Author: User

Before reading this article, according to their own experience and understanding, you can first think and choose the Java function parameter transfer mode:
A. Is it passed by value?
B. Passed by reference?
C. Partial by value part by reference?
The right answer is not announced here, so let's find out for ourselves the answer by a simple example:
1. Define a Type value first

public static class Value { 
  private String value = ' value '; 
  Public String GetValue () {return value;} 
  public void SetValue (String value) {this.value = value;} 
} 

2. Write two functions newvalue and Modifyvalue:newvalue will point the arguments to a new object, Modifyvalue will call the SetValue method of the parameter to modify the value of the object.

public static void NewValue (value value) { 
  value = new value (); 
  Value.setvalue ("new value"); 
  System.out.println ("in newvalue, hashcode =" + value.hashcode () + ", value =" + Value.getvalue ()); 
} 
   
public static void Modifyvalue (value value) { 
  value.setvalue ("New value"); 
  System.out.println ("in modifyvalue, hashcode =" + value.hashcode () + ", value =" + Value.getvalue ()); 
} 

3. Simple test Code

public static void Main (string[] args) { 
  value value1 = new value (); 
  System.out.println ("before modify, Hashcode =" + value1.hashcode () + ", value =" + Value1.getvalue ()); 
  Point the value1 to the new value object 
  newvalue (value1); 
  System.out.println ("after modify, Hashcode =" + value1.hashcode () + ", value =" + value1.getvalue () + "\ n"); 
  Value value2 = new value (); 
  System.out.println ("before modify, Hashcode =" + value2.hashcode () + ", value =" + Value2.getvalue ()); 
  Modifies the internal value of an object 
  Modifyvalue (value2) using the Set method of object; 
  System.out.println ("after modify, Hashcode =" + value2.hashcode () + ", value =" + Value2.getvalue ()); 
} 

4. Execution Results log:

 before modify, Hashcode = 12677476, value = value in NewValue, hashcode = 33263331, VA Lue = new value after modify, Hashcode = 12677476, value = value before modify, Hashcode = 6413875, value = value in Modifyvalue, hashcode = 6413875, value = new value after modify, Hashcode = 6413875, value = new value 


5. Result Analysis:
above code This is a very common programming pattern: in the perimeter definition | save | Get a value or object, pass this object as a parameter to a method, modify the object's properties, behavior in the method. However, the two methods NewValue and Modifyvalue change the same way, after the method call, the object in the periphery seems to have a big difference! How do you understand this difference? Let's get warm. The concept of passing by value, passing by reference:
* Passing by value means that when a parameter is passed to a function, the function receives a copy of the original value. Therefore, if the function modifies the argument, only the copy is changed, and the original value remains unchanged.
* Passing by reference means that when a parameter is passed to a function, the function receives the memory address of the original value, not a copy of the value. Therefore, if the function modifies the argument, the original value of the parameter (in the calling code outside the function block) changes as well.
The correct answer: The A--java function is passing arguments by value!
to analyze the log:
* The first log output, the value1 parameter is changed to point to the new object within the NewValue method, and the hashcode and value values of the new object are output, but after jumping out of the NewValue method field, There is no change in the value1 in the main method, which conforms to the definition and characteristics of passing by value, and if passed by reference, the value1 should be changed after the NewValue (value value) method is invoked.
* The second segment of the log output, value2 within the Modifyvalue method SetValue operation, hashcode unchanged and value was modified, after leaving the Modifyvalue method field, in the main method value2 has actually changed. People who have used C + + can easily interpret this phenomenon as: passing function arguments by reference! Because this and C + + in the passing of the reference is very similar! But here is the easiest place to fall into the wrong places! The underlying principle behind the different phenomena of the
two-piece log is that: The Java language is passed parameters by value, passing objects by reference; The objects that are manipulated in Java are actually references to action objects, object itself is stored in the heap, and the object's "references" are kept in registers or stacks.
Pseudocode describes the differences between the NewValue method and the Modifyvalue method:

newvalue{ 
  value_ref2 = value_ref1;  Pass in the reference Value_ref1 by value, get value_ref1 copy 
  value_obj2 = new value ();  Value_obj2 is created, initialized in "heap" 
  value_ref2-> value_obj2;  Value_ref2 points 
to value_obj2 value_ref2->value_obj2.setvalue ("xxx");//VALUE_OBJ2 value is modified 
PrintValueObj2 ();      The value of OBJ2 is printed here 
} 
modifyvalue{ 
  value_ref2 = value_ref1;  Incoming reference Value_ref1 by value, value_ref1 copy 
value_ref2->value_obj1.setvalue ("xxx");//value_obj1 Value modified 
PrintValueObj1 ();      The value of Obj1 is printed here 
} 

That's clear enough! VALUE1_REF1, when the function is passed as a parameter, is first copied a copy of Value1_ref2 for the function domain, at which point the two ref points to the same value_obj; the code in the NewObject function [value = new value ();] In fact, the VALUE1_REF1 is pointed to a new object Value_obj2, after which the set operation is the operation of the new object, and the Modifyvalue function is directly manipulating the value_obj1 through the set method, which is different from the NewValue function.

Passing parameters by value
you need to provide parameters when calling a method, which you must provide in the order specified by the parameter list.
For example, the following method prints a message continuously n times:

public static void Nprintln (String message, int n) {for
 (int i = 0; i < n; i++)
  System.out.println (message); 
   }

Example
The following example shows the effect of passing by value.
The program creates a method that is used to exchange two variables.

public class Testpassbyvalue {public

  static void Main (string[] args) {
   int num1 = 1;
   int num2 = 2;

   System.out.println ("Before Swap method, Num1 are" +
             NUM1 + "and num2 is" + num2);

   Call swap method
   Swap (NUM1, num2);
   System.out.println ("After Swap method, Num1 are" +
             NUM1 + "and num2 is" + num2);
  }
  /** a method for exchanging two variables/public
  static void (int n1, int n2) {
   System.out.println ("\tinside the");
   System.out.println ("\t\tbefore swapping N1 are" + N1
              + "N2 is" + N2);
   Exchange N1 with N2 value
   int temp = n1;
   N1 = n2;
   N2 = temp;

   System.out.println ("\t\tafter swapping N1 are" + N1
              + "N2 is" + N2);
  }


The results of the above instance compilation run are as follows:

Before swap method, NUM1 is 1 and num2 are 2
    Inside the Swap method
        before swapping N1 is 1 N2 are 2 after
        Swapp ing N1 is 2 n2 are 1 after
swap method, Num1 are 1 and num2 is 2

Pass two arguments to call the swap method. Interestingly, the value of the argument does not change after the method is invoked.

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.