Pages

Wednesday, August 31, 2011

Java Variable passing and Assignment operation


Java Variable passing and Assignment operation
A variable can be considered as a holder containing a bit pattern. In primitive type variables those patterns contains the value of the variable. But what about variable which are referring to objects. Well that dose not contains the actual object; they just contain a bit pattern to get the actual object. Then what is the format?? I don’t know, but it somehow gets the object using the bit pattern.

What happens when you assign a value to a variable? Well, if it’s a primitive type the bit pattern representing the value get stored in the variable, if it’s a object type some bit pattern get stored so that it would refer to the actual object. Some times casting might be required and can generate weird results. Try this for example (byte b= (byte) 128 ;). If you can’t guess the result, you might have to do little bit of reading. I’m not going to talk about this here.

When you assign a variable to another variable, if it’s a primitive variable value of the variable get copied to the new variable.

Int a=5;
Int b=a;

If you change the value of b ( b=6) value of a remains 5. This is because variable b get a copy of the bit pattern stored in a, when the assignment is done. So, there is no drama in assignment operation when it comes to primitive type variables.

But when it comes to object type variables, there is a little bit of drama. Look at the following,

class Test{
            int t;
}
Test a=new Test();
Test b=a;
b.t=1;
System.out.println(“b.t=”+b.t);
System.out.println(“a.t=”+a.t);
Output would be
b.t=1;
a.t=1;

This happens because both a and b contains the same bit pattern which refer to a single object. But if you assign a newly created object to b after assigning this would be different.

Test a=new Test();
Test b=a; //bit pattern of a get copied to b, therefore both refer to the same object
b=new Test(); // b get a new bit pattern therefore b is referring to a different object
b.t++;
System.out.println(“b.t=”+b.t);
System.out.println(“a.t=”+a.t);
Output would be
b.t=1;
a.t=0;

Comments in the code would clarify it!!!!!!
There is one exception when you consider String objects. Those are treated differently. Strings cannot be modified. A new String would be created by the VM when you “change” a String. Look at the following

String a=”test”;
String b=a; // both b and a refer to the same string
b=b+” change”; // new string is created and b refers to the new String, original string is //left //unchanged

When you pass variables to methods similar thing would happen. A copy of the bit pattern would get passed in to the method, thus causing similar effects to those mentioned above.