Concatenating Strings


Concatenating Strings

One 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 Strings

This 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 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net