Wednesday, July 2, 2008

Java is pass by value.....Always! - Part2

In the last post we saw what exactly pass by value and pass by reference means and strictly speaking its a fact that there is nothing like pass by reference in java. So we can say that java is pass by value...always! This post is a continuation so if you havn't please go through the first part - Java is pass by Value.....Always! - Part1

However note that, for the clarity of understanding the pass by value is when we pass a value and pass by reference is when we pass a reference to something.
Now lets look at the code which demonstrates pass by value and pass by reference.

Suppose there is a class TV, which contains a string which shows its state and its setters and getters.(Note:For the time please forget about the access modifiers..etc because this is just to make you understand one concept..I havnt run this program so it may have some errors/exceptions. But this code is perfect to make you understand what you need to at this point of time.)


class TV
{
string state; // this stores whether TV is currently ON or OFF

TV(string h)
{
this.state=h; //constructor assign a state for new TV object
}

setState(string s)
{
this.state=s;
}

string getState()
{
return(state);
}
}

The following code will demonstrate the pass by value with variable i and pass by reference with references remote1 and remote2.

class example1
{
int i=2;
public static void main()
{
TV remote1= new TV("OFF");
func2(i);
func3(remote1);
}

func2(int j)
{
System.out.println(j); // this will print 2
j=3;
System.out.println(j); // this will print 3
System.out.println(i); // this will print 2
}


func3(TV remote2)
{
System.out.println(remote2.getState()); //this will print OFF
remote2.setState("ON");
System.out.println(remote1.getState()); //this will print ON
System.out.println(remote2.getState()); //this will print ON
}

}


Here i and j are variables and they are independant of eachother. remote1 and remote2are references and they point to the same object, so both can turn on and off the same TV!

Have some doubts still? Go..on.. post a comment.. I will try my best to answer.

No comments: