Tutoriallearn.com

Easy Learning


Home

Search Tutoriallearn.com :



Object reference variable

Object reference variable points to an object. See the following code fragment:

student s1 = new student();
student s2 = s1;
In this code, s1 is an object. s2 is an object reference variable which is pointing to object s1 . There is no copy of object s1 is assigned to s2 . No separate memory is allocated to s2 object. Instead s2 is referring to same object memory (i.e. memory of s1 object).
Consider the following class:
class student {
	String name;
	int rollno;
	void setdata(int r, String n){
		name = n;
		rollno = r;
	}
	void dispdata(){
		System.out.println("Student name is "+name);
		System.out.println("Rollno is "+r);
	}
}

class demo {
	public static void main(String args[]){
		student s1 = new student();
		student s2 = s1;
		
		s1.setdata(1234,"Amit Kumar");
		s2.dispdata();
	}
}

Output

Student name is Amit Kumar
Rollno is 1234
Here, you can see that data is stored using s1 object. Object s2 is displaying same data. It means that both (s1 and s2) are appointing to same data. Following figure is also showing this concept:
Object Ref Pic

S1 and S2 both are different. For example, If S1 object is assigned null value. (i.e. s1 = null). Then s1 will not point to class data members:rollno and name (Referring the above image). Here s2 reference variable (In other words, s2 object) is still referring to class data members: rollno and name .






© Copyright 2016-2025 by tutoriallearn.com. All Rights Reserved.