by Dinesh Thakur

Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. We can also concatenate strings with other types of data after converting them into strings. Java converts other data types into its string representation by calling valueOf() defined by String. For the simple types, valueOf() returns a string equivalent of the value with which it is called. For objects, valueOf()calls the toString() method on the object.

String Concatenation in Java Example

Here is an example in which unite several strings :

String first = "Hello";

String second = "Java";

System.out.println (first + second); / / HelloJava

String output = first + second + "";

int number = 2 ;

System.out.println (output + number);

/ / HelloJava 2

In the example, initialize two variables of type String and asked them values. On the third line joining the two strings and file the results - the method println (), in order to print it on the bracket, next line joining the two strings and add a space at the end. returned result recorded in a variable called output. The last line unite the contents of the output string with the number 2 (the content of variable number) and file the result again to print. The returned result will be automatically converted to type String, because the two variables are of a different type .

Concatenation (adhesion of two strings ) strings is slow operation and should be used carefully . The use of Class StringBuilder StringBuffer or in need of iterative ( repetitive ) operations on strings .

class StringConcat        

{
            public static void main(String args[])
            {
                        String t = "Hello ";
                        String m = "Java";
                        System.out.println(t+ m);
            }
}

String Concatenation in Java Example