Home  >  Q&A  >  body text

java - Help: Analyze the following code in detail, I am confused.

public class T1 {

public static void rename(String aa){
    
    aa="AA";
    
}

public static void main(String args[ ]){
    
    String aa="BB";
    
    rename(aa);

    System.out.println(aa);
}

}
My understanding:
aa in the rename method is in the stack memory, and aa in the main method is in the heap memory. Executing the rename method will not modify aa in the main method. Worth it, right?

阿神阿神2685 days ago663

reply all(3)I'll reply

  • 迷茫

    迷茫2017-05-17 10:01:16

    Call by value is the most commonly used evaluation strategy: the formal parameters of a function are copies of the actual parameters passed when called. Modifying the value of the formal parameter does not affect the actual parameter.

    When called by reference, the formal parameters of the function receive implicit references to the actual parameters, rather than copies. This means that if the values ​​of function parameters are modified, the actual parameters will also be modified. At the same time both point to the same value.

    Java Core Technology (I) mentioned that Java is all passed by value. First of all, for basic types, functions cannot modify its value. For reference types, functions cannot modify it to point to another object. So it's all passed by value.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-17 10:01:16

    No, the aa inside the function points to the new address, and the external aa still points to the address of "BB", so the result is BB

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-17 10:01:16

    The function does not pass the AA in the MAIN function when passing value, but makes a copy of the value of AA and then passes it in

    reply
    0
  • Cancelreply