Concatenating StringsOne of the common manipulations you will perform on Strings is to concatenate two or more String objects together. One way to do this is by using the concatenation operator, + . String name = "Jackson"; System.out.println("My boy is "+name); The argument to the left of the + operator must be a String or the compiler will think you are using the arithmetic addition operator instead. The argument to the right of the operator can be any type. When you concatenate a non- String reference type to a String , the system uses the toString() method to return a String representation of the non- String type and then concatenates the result. For primitives, the primitive value is converted to a String . Another way to concatenate Strings is by using the concat() method of the String class. public String concat(String str) When the concat() method is used, the argument String is concatenated onto the String on which the method is called. A NullPointerException is thrown if the input argument is null . Example: Concatenating StringsThis example demonstrates the different ways of concatenating String objects. The literal " molar mass is " is concatenated to a String variable named gas using the concat() method. The + operator is then used to concatenate the String representation of the value of a double value onto the String . public class ConcatDemo { public static void main(String args[]) { String gas = "air"; double molarMass = 0.02885; // The concat() method concatenates two Strings String label = gas.concat(" molar mass is "); // The + operator concatenates the String // representation of the value of the molarMass // variable onto the label String. System.out.println(label + molarMass); } } Output ” air molar mass is 0.02885 |