Created
February 4, 2020 07:04
-
-
Save dandvl/a88a4a8e49c6bcd4e83c104bdb1413b7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
JAVA arguments are always pass by value (that means a copy of it)- either the arg is primitive value or an object’s reference like “object@1f89ab83” in the heap memory. | |
Therefore we can change the state of the object passed but not its reference, and if we create another reference with the keyboard “new”. | |
**/ | |
public class JavaPassByValue{ | |
public static void main(String[] args) { | |
Person person = new Person("Donatelo"); | |
Person person2 = new Person("Leo"); | |
changeNameInstance(person); | |
System.out.println(person.getName()); //prints Donatelo because the reference wasn't modified | |
changeNameSetter(person2); | |
System.out.println(person2.getName()); //prints Raph | |
} | |
//receives the copy of the reference Person@1f89ab83 | |
public static void changeNameInstance(Person person) { | |
person = new Person("Mike"); //creates another reference Person@4d90a | |
System.out.println(person.getName()); //prints Mike | |
} | |
//receives the copy of the reference | |
public static void changeNameSetter(Person person) { | |
//changes the state of the object referenced | |
person.setName("Raph"); | |
} | |
} | |
class Person{ | |
private String name; | |
public Person(String name){ | |
this.name = name; | |
} | |
public String getName(){ | |
return name; | |
} | |
public void setName(String name){ | |
this.name = name; | |
} | |
} | |
//javac JavaPassByValue.java | |
//java JavaPassByValue | |
//discussion https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment