|
Java™ by example!
|
|
|
How do I concatenate two Strings?
There are two ways to concatenate one string to another. The most common is to use the (rather ambiguous) + operator:
 String s1 = "Hello, "; String s2 = "world!"; String s3 = s1 + s2; System.out.println(s3); // prints out: Hello, world!
|
The String class also provides a method concat that does just the same:
 String s1 = "Hello, "; String s2 = "world!"; String s3 = s1.concat(s2); System.out.println(s3); // prints out: Hello, world!
|
In the previous example, the method concat is invoked on s1. s1 remains unchanged and a completely new String will be created. A String is immutable! Once you assigned it a value, it cannot change anymore during its lifetime. You will always have to create a new String object.
Further Information
Author of answer: unknown
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|