Saturday, February 2, 2008

pass by reference java

Truth #1: Everything in Java is passed by value. Objects, however, are never passed at all.

That needs some explanation - after all, if we can't pass objects, how can we do any work? The answer is that we pass references to objects. That sounds like it's getting dangerously close to the myth, until you look at truth #2:

Truth #2: The values of variables are always primitives or references, never objects.

This is probably the single most important point in learning Java properly. It's amazing how far you can actually get without knowing it, in fact - but vast numbers of things suddenly make sense when you grasp it.

[source]





public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Radio radio_1=new Radio();

//The value of status before calling
//the method
System.out.println("Old Value of status="+radio_1.status);

//call the method that changes
//status
Switcher switcher1 =new Switcher();
switcher1.on(radio_1);

//note that the value of status is changed
System.out.println("Old Value of status="+radio_1.status);

}

}


class Radio {

int status=0;


}

class Switcher{

public void on(Radio i){
//this will change the value of
//status even after the method is called
//
i.status=1;

}

}

output:
Old Value of status=0
Old Value of status=1

0 comments:

Category Cloud

Label Cloud