Java Call By Reference
Chapter:
Miscellaneous
Last Updated:
23-03-2017 20:02:04 UTC
Program:
/* ............... START ............... */
class Student {
private String studentName;
public Student(String name) {
this.studentName = name;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String name) {
this.studentName = name;
}
}
public class JavaCallByReference {
public static void main(String[] args) {
Student s1 = new Student("John");
System.out.println("1: " + s1.getStudentName());
changeReference(s1); // It won't change the reference!
System.out.println("2: " + s1.getStudentName());
modifyReference(s1); // It will change the object that the reference
// variable "John" refers to!
System.out.println("3: " + s1.getStudentName());
}
public static void changeReference(Student s1) {
Student s2 = new Student("Smith");
s1 = s2;
}
public static void modifyReference(Student s1) {
s1.setStudentName("Carol");
}
}
/* ............... END ............... */
Output
Notes:
-
Call by Reference is - passing object references by value. Because two copies of the same reference refer to the same actual object, changes made in one reference variable are visible through the other variable.
- The term Pass by Reference (java does not support) means that when an argument is passed to a method, the invoked method gets a reference to the original value, not a copy of its value. If the method modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory.
Tags
Call By Reference, Java, Miscellaneous