Java parameter is pass by value
In Java, when a parameter is pass to a method, the parameter is passed by value. Here is an example that demonstrates parameters are passed by value in Java methods.
The Animal class
public class Animal { private String animal; public Animal(String a) { animal=a; } public String getAnimal() { return animal; } public void setAnimal(String animal) { this.animal = animal; } public String toString() { return "The animal is: " + this.getAnimal(); } }
The PassByValueTest
public class PassByValueTest { /* Java is pass-by-value. * For primitives, you pass a copy of the actual value. * For reference of objects, you pass a copy of the reference. */ public static void main(String args[]) { Animal a = new Animal("Bird"); //As expected, it will print the animal is Bird. System.out.println(a.toString()); changeAnimal(a); // Now, it will print the animal is Dog because the object reference // by a was changed in the method changeAminal.So, any other reference // to this object will see the changes."); System.out.println(a.toString()); System.out.println("-----------------------------------"); Animal b = new Animal("Bird"); //As expected, it will print the animal is Bird. System.out.println(b.toString()); changeReference(b); // Now, it will print the animal is Bird again, because the method // changeReference changes the reference, so it's creating a new // reference that points to a new object, the object referenced by // the original reference is unchanged."); System.out.println(b.toString()); System.out.println("-----------------------------------"); // x doens't change, because it copies the value to the // changeInt method, the value in the method are separate // from the original value."); int x=3; System.out.println("x is: " + x); changeInt(x); System.out.println("x is: " + x); } public static void changeAnimal(Animal animal) { //Copies the reference of animal to b, //so now animal and b both pointing to the same object. Animal b = animal; b.setAnimal("Dog"); } public static void changeReference(Animal animal) { Animal c = animal; c= new Animal("Cat"); } public static void changeInt(int y) { int z=y; z=5; } }
The output:
-
The animal is: Bird
The animal is: Dog
———————————–
The animal is: Bird
The animal is: Bird
———————————–
x is: 3
x is: 3
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts