Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String variable setting - reference or value?

The following Java code segment is from an AP Computer Science practice exam.

String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);

The output of this code is "abc ab" on BlueJ. However, one of the possible answer choices is "abc abc". The answer can be either depending on whether Java sets String reference like primitive types (by value) or like Objects (by reference).

To further illustrate this, let's look at an example with primitive types:

int s1 = 1;
int s2 = s1; // copies value, not reference
s1 = 42;

System.out.println(s1 + " " + s2); // prints "1 42"

But, say we had BankAccount objects that hold balances.

BankAccount b1 = new BankAccount(500); // 500 is initial balance parameter
BankAccount b2 = b1; // reference to the same object
b1.setBalance(0);
System.out.println(b1.getBalance() + " " + s2.getBalance()); // prints "0 0"

I'm not sure which is the case with Strings. They are technically Objects, but my compiler seems to treat them like primitive types when setting variables to each other.

If Java passes String variables like primitive type, the answer is "abc ab". However, if Java treats String variables like references to any other Object, the answer would be "abc abc"

Which do you think is the correct answer?

like image 659
ianonavy Avatar asked Apr 29 '11 17:04

ianonavy


People also ask

Is Java string passed by value or reference?

Java is always Pass by Value and not pass by reference, we can prove it with a simple example. Let's say we have a class Balloon like below. And we have a simple program with a generic method to swap two objects, the class looks like below.

Is string call by value or reference?

All arguments in Java are passed by value. When you pass a String to a function, the value that's passed is a reference to a String object, but you can't modify that reference, and the underlying String object is immutable.

Is string a reference?

String is a reference type, but it is immutable. It means once we assigned a value, it cannot be changed. If we change a string value, then the compiler creates a new string object in the memory and point a variable to the new memory location.


1 Answers

java Strings are immutable, so your reassignment actually causes your variable to point to a new instance of String rather than changing the value of the String.

String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);

on line 2, s1 == s2 AND s1.equals(s2). After your concatenation on line 3, s1 now references a different instance with the immutable value of "abc", so neither s1==s2 nor s1.equals(s2).

like image 156
digitaljoel Avatar answered Sep 23 '22 22:09

digitaljoel