Tutoriallearn.com
Easy Learning
Search Tutoriallearn.com :
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(); } }
Student name is Amit Kumar Rollno is 1234Here, 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: