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
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
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
42 + 42;while the second one is similar to doing something like:int s = 42 + 42;