java is pass by value


Java passes everything by value – including references.

What this means is that if you pass an object, you can modify properties of that object, and they will persist after you return, but you can’t replace the object in its entirety with a completely new object, because you can’t actually modify the reference – only what the reference points to.

class testjava
{
	private static void foo(Object bar) {
    bar = null;
}
	public static void main(String[] args)
	{
	String baz = "Hah!";
	foo(baz);
    System.out.println(baz);
	}
}

output = Hah!

public class Main1 {
    public static void main(String[] args) {
        String temp = "Vinay";
        print(temp);
        System.err.println(temp);
    }
    private static void print(String temp) {
        temp = null;
    }
}

output = vinay

Duke, the Java Mascot, in the waving pose. Duk...

Image via Wikipedia

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s