Skip to main content

Java is always Pass-By-Value. Never Pass-by-Reference. Explanation.


We often read about how Java is pass by value but very often there is a confusion that behavior is different in case of primitives and object references leading to following statement (which is kind of 'aid to memory' rather than anything else):

Java does pass-by-value for primitives and pass-by-reference for object references.

Consider following code snippet.

public class House{
  String type;
  public House(String type){
    this.typetype;
  }
  
  public String getHouseType(){
   return this.type
  }
  
  public void setHouseType(String type){
   this.typetype;
  }
}


public class MainClass{

  public static void main(String[] args){
    House myHouse; ///Line 0
    myHouse = new House("Flat"); ///Line 1
    System.out.println("Output1: "+myHouse.getHouseType());
    
    foo(myHouse); ///Line 2
    System.out.println("Output2: "+myHouse.getHouseType());
        
  }
  
  public static void foo(House myNeighborHouse){
    myNeighborHouse = new House("villa"); ///Line 3
  }
  
  public static void zoo(House myNeighborHouse){    
    myNeighborHouse.setHouseType("apartment");  ///Line 4
  } 
  
}


Output:

Output1: Flat
Output2: Flat

Let's see what happens behind the scenes. 

At Line 0 , we create a new Reference of type House and name it 'myHouse'. Note that at this point this reference is not assigned to any object. It is just there, doing nothing!

At Line 1, we create a new object of type House and make myHouse point to it. See below figure.



This is assuming that our House object has been created at memory address 354638 in the Java heap. And myHouse is pointing to the object at this location. So far so good.

At Line 2, we pass 'myHouse' reference to the 'foo' method. Now since Java is pass-by-value as we said in the very beginning, what is passed to foo is a COPY of the myHouse reference. I have named the argument in foo as 'myNeighborHouse' just for clarity. Even if the argument was named 'myHouse' it would still be a copy of original 'myHouse' reference that we created at Line 0.

 So what happens is this:

Since myNeighborHouse is an exact copy of myHouse, it is pointing to the same location as 'myHouse', the object at location 354638.

Now, at Line 3 in foo method, we create another House object (supposedly at location 364733) and myNeighborHouse is made to point to this new object.


Now you don't need to be Sherlock to see that myHouse is not impacted at all! Whatever we do to myNeighborHouse in 'foo', myHouse does not get impacted. That's why Output2 is 'Flat' not 'villa' as you may have expected.

However if we add following code in main( ):

   zoo(myHouse); ///Line 5
   System.out.println("Output3: "+myHouse.getHouseType());

The output will be:
apartment

Why? Because now we changed the property of the object being pointed by myNeighborHouse and since both myHouse and myNeighborHouse are pointing to object at same location, the change is reflected in myHouse as well!

So what we saw was elementary fact that in Java everything, primitive or reference, is always passed by value only. Did this post clarify your doubts?

Comments

Popular posts from this blog

File upload problem: UTF-8 encoding not honored when form has multipart/form-data

The problem that I was facing was something like this. I was using Apache Commons File Upload library to upload and download some file.

I had a form in which user can upload a file and another field 'name' in which she can give any name to the file being loaded.


When I submitted the form, the file was uploaded fine but the value in name field was garbled. I followed all the possible suggestions I found:

<%@page pageEncoding="UTF-8"%> set. <%@page contentType="text/html;charset=UTF-8"%gt; set after the first directive. <meta equiv="Content-Type" content="text/html;charset=UTF-8"> in the head. enctype="multipart/form-data" attribute in the form. accept-charset="UTF-8" attribute in the form.
in the Servlet:
before doing any operations on request object: request.setCharacterEncoding("UTF-8"); For accessing the value

FileItem item = (FileItem) iter.next();

if (item.isFormField()) {

//For regular…

java.lang.IllegalArgumentException: Malformed \uxxxx encoding

I was getting this exception during build while running ant. Googling didn't help much and I was flummoxed because the same code was running fine till now.

My code reads a text file and does some operations on the basis of values read. It was only when I saw the text files I understood the error. I had copied the text in wordpad and saved it as .txt file. Wordpad had put lot of formatting information before and after the content. Also there was "\par" after every line, which was giving this error.

So moral of the story: if you get this exception check your properties file (or any other file that your code might be reading.)

Easiest way to print Timestamp in Java

Rather than using Calendar.getTime() we can use java.sql.Timestamp class to get the time stamp which gives date and time till millisecond precision.

System.out.println(new Timestamp(System.currentTimeMillis()));

Above will give you current timestamp in this format: 2010-07-27 16:37:45.39