1

Can someone explain the following scenario?

String s = "Testing";
s.concat("Java 1");
System.out.println(s);
s = s.concat(" Java 2");
System.out.println(s);

The output of the above is:

Testing
Testing Java 2
2
  • 4
    You should read the javadoc of the method. That is where the contract and behavious of the method is explained. Commented May 2, 2013 at 8:44
  • 3
    The first statement is similar to writing only: 42 + 42; while the second one is similar to doing something like: int s = 42 + 42; Commented May 2, 2013 at 9:04

5 Answers 5

7

This is because, in Java String object is immutable (value stored in the object cannot be changed). When you perform operations such as concat or replace, internally a new object is created to hold the result.

Sign up to request clarification or add additional context in comments.

Comments

3

When you said

String s = "Testing";
s.concat("Java 1"); // this returns a new String which is "TestingJava 1"
System.out.println(s);

The concat method produced a new String which was not stored by your program. The reason for returning new String shows immutable behaviour of String class in java.

For mutable string operations you can use StringBuilder or StringBuffer

Comments

1

String.concat returns concatinated string which you ignored, try this

String s = "Testing";
s = s.concat("Java 1");

Comments

1

Read docs:

the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

your s.concat("Java 1"); returning a new string

Comments

1

1) In the first you are not assign s a new value.
2) Second time you are assigning s a new value like s = s.concat(" Java 2");

Comments