How InOut parameter will work in java?

Objective:
Objective of this article is to explain How references will work in java or How InOut parameter will work in Java?

Explanation:
We studied in C language the importance of  pointers similarly we need to know how references are working in java. Without knowing how object references are working in java, we cant understand application flow properly.

Lets take one example in java related to references as well as InOut parameter in java.

class Student{ 
     private Integer id; 
     private String name; 
     //setter and getter 
 } 
 class Main{ 
     public static void main(String arg…){ 
         Student s1=new Student(); 
         System.out.println(s1.getId()); 
         System.out.println(s1.getName()); 
         m1(s1); 
         System.out.println(s1.getId()); 
         System.out.println(s1.getName()); 
     } 
     public static void m1(Student s3){ 
         s3.setId(10); 
         s3.setName("ranga"); 
         s3=null;
     } 
 }

In the above program we used new keyword only one time so entire program will have only one student object created.

Once we create object s1 is pointing to that object and its id,name values initialize with null values like the below screenshot.

When we execute the below code, it will return with null value.

System.out.println(s1.getId());//null 
System.out.println(s1.getName());//null

When we call m1(s1); then Student s3=s1; then s3 reference also pointing to same object which is already referred by s1 reference. Look at the below image,

When we execute s3.setId(10); and s3.setName(“Ranga”); then s3 reference id value(null) override with 10 and name value(null) override with “Ranga”. Look at the below diagram,

When we do s3=null then it will lost the connection with that reference and m1 method execution is over because it doesn’t return anything because of it’s return type is void. Look at the below diagram,

The below diagram illustrates, that the previously setting s3 values are pointing to s1 because s3 lost connection with them.

Now it we print id and name of s1 reference, it will print id as 10 and name is “Ranga” because s1 is pointing to Student object which has the values of 10 and “Ranga”.

I hope this helped you to understand about references in Java. Let us know your thoughts. Happy Learning 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s