17

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?

4
  • Have you looked at the documentation for String? Does it say whether it's a class or a primitive? Apr 29, 2011 at 17:44
  • You might want to read the javadoc as it answers your questions. Apr 29, 2011 at 18:01
  • 5
    System.out.println(s1 + " " + s2); // prints "1 42" is not true ... it prints "42 1"
    – whytheq
    Oct 31, 2013 at 9:02
  • @whytheq I get "42 1" as my output. I read this and I was like WTF? s2 has already copied the value before s1 is reassigned 42.
    – Codist
    Jan 2, 2014 at 3:29

9 Answers 9

32

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).

2
  • 1
    It is and it does, but that doesn't actually answer the OP's more fundamental question. Apr 29, 2011 at 17:45
  • 5
    Sure it does. It implicitly explains that his comparison of the String case to the BankAccount are not the same. One is assigning a new instance, whereas the other is simply modifying an existing one. For clarity s1=s1+"c" basically equates to b=new StringBuilder(s1);b.append('c');s1=b.toString();
    – Robin
    Apr 29, 2011 at 18:18
14

The difference between your BankAccount and a String is that a String is immutable. There is no such thing as 'setValue()' or 'setContent()'. The equivalent example with your bank account would be :

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

So if you think of it this way (not actually what the compiler does, but functionally equivalent) the String concatenation scenario is:

String s1 = "ab";
String s2 = s1;
s1 = new String("abc");
System.out.println(s1 + " " + s2); //prints "abc ab"
10

It is not relevant whether String is treated like a primitive or like an object!

In the String example, the concatenation of two strings produces a new String instance, which is then assigned to s1. The variable s2 still references the unchanged(!) old String instance.

Assuming the BankAccount had a method to set the balance, which returns a new BankAccount, your example could look like this:

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

Indeed, String is a class and it's assigned / passed by reference. But what's confusing is the statement:

String s = "abc";

Which suggests that String is a primitve ( like 'int x = 10;' ); But that's only a shortcut, the statement 'String s = "abc";' is actually compiled as 'String s = new String( "abc" );' Just like 'Integer x = 10;' is compiled as 'Integer x = new Integer( 10 );'

This mechanism is called 'boxing'.

And more confusing is: there's a class 'Integer' and a primitive 'int', but String doesn't have a primitive equivalent (allthough char[] comes close)

Sije de Haan

8

In Java, String objects are assigned and passed around by reference; it this respect they behave exactly like any other object.

However, Strings are immutable: there isn't an operation that modifies the value of an existing string in place, without creating a new object. For example, this means that s1 = s1 + "c" creates a new object and replaces the reference stored in s1 with a reference to this new object.

5

String is a class, so a String variable is a reference. But it's a language intrinsic, in the sense that Java has special handling and syntax for it, which is why you can do things like your example.

See e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.

4

java.lang.String is an object, not a primitive.

What the code did in the first example is:

  1. Define s1 as "ab"
  2. Set s2 equal to the same underlying object as s1
  3. Set s1 equal to a new string that is the combination of s1's old value and "c"

But to answer your question about reference or value, it's by reference.

1

The assertion

if Java treats String variables like references to any other Object, the answer would be "abc abc"

is incorrect. Java does treat String variables like references to any other Object. Strings are Objects but the answer is "abc ab" none the less.

The issue is not what the assignment operator does. The assignment operator assigns a reference to a String object in every case in your example.

The issue is what the concatenation operator ('+') does. It creates a new String object. As other have said, this is necessary because a String object is immutable but it is an issue of operator behaviour and not merely because String is immutable. The concatenation operator could return a new Object even if a String object were mutable.

In contrast, in your second example, b1.setBalance(0) does not create a new object, it modifies the existing object.

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

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

Doesn't print "1 42" but "42 1".Take each discrete line into consideration.First s1 assigns 1, then s2 assigns s1, which is 1 up until now(suppose java didn't see the third line yet.) Then java sees the third line and immediately changes s1 into 42.After that java was told to print what it knows so far, and that is s1 is 42 and s2 is 1(the old s1).

As for the String the same thing happens.

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

Fort String it doesn't necessarily changes s1 but rather s1 now refers to a new String object in the heap memory, but the old "ab" object is still there, with a new reference of s2!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.