2

I have written following code:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s = new String("abc");
    System.out.println(s.concat("def"));
}

it is returning me the output : "abcdef"

how is this possible if string is immutable.

Savi
  • 29
  • 2
  • Some what Similar Question answered well [here](http://stackoverflow.com/questions/1552301/immutability-of-strings-in-java) – mohanen b Oct 04 '16 at 06:30

3 Answers3

6

s.concat("def") returns a new String instance. The String instance referenced by s remains unchanged.

You can add another println statement to see that for yourself :

public static void main(String[] args) {
    String s = new String("abc");
    System.out.println(s.concat("def"));
    System.out.println(s);
}

You can also see that in the Javadoc of concat :

If the length of the argument string is 0, then this String object is returned. Otherwise, a String object is returned that represents 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.

The original String is returned only if you pass an empty String to this method.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

It returns a new new String not a changed String

try

public static void main(String[] args) {
    String s = new String("abc");
    System.out.println(s.concat("def"));
    System.out.println(s);
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

From Oracle Java Docs,

public String concat(String str)
Concatenates the specified string to the end of this string.

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

Examples:

 "cares".concat("s") returns "caress"
 "to".concat("get").concat("her") returns "together"

Parameters: str - the String that is concatenated to the end of this String.

Returns: a string that represents the concatenation of this object's characters followed by the string argument's characters.

Abhineet
  • 5,320
  • 1
  • 25
  • 43