Java – String Is Immutable And Pass By Value Example

There are three popular questions in Java code interviews:

  • Is Java “pass by value” or “pass by reference”?
  • If you pass an object to a function and change the value does it really change?
  • If you pass a String object to a function and change the value does it really change?

We can find the answers with this simple example. Please try to guess what will be the output.

package com;
public class Main {
public static void main(String[] args) {
MyString myString = new MyString("x");
String str = "x";
System.out.println("1: " + myString.getName() + " " + str);
foo(myString, str);
System.out.println("@important 3: " + myString.getName() + " " + str);
// reset
myString = new MyString("x");
str = new String("x");
System.out.println("4: " + myString.getName() + " " + str);
fee(myString, str);
System.out.println("@important 6: " + myString.getName() + " " + str);
String str2 = str;
str2 += "*SPOILED*";
System.out.println("7: " + str + " " + str2);
}
public static void foo(MyString myString, String str) {
myString.setName("y");
str = "y";
System.out.println("2: " + myString.getName() + " " + str);
}
public static void fee(MyString myString, String str) {
myString = new MyString("y");
str = new String("y");
System.out.println("5: " + myString.getName() + " " + str);
}
}
class MyString {
private String name;
public MyString(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
view raw Main.java hosted with ❤ by GitHub

The output is:

1: x x
2: y y
@important 3: y x
4: x x
5: y y
@important 6: x x
7: x x*SPOILED*

 

[1] https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

[2] https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: