Java String Concatenation

Description

You can use + operator to concatenate strings together.

Example 1

For example, the following fragment concatenates three strings:

 
public class Main {
  public static void main(String[] argv) {
    String age = "9";
    String s = "He is " + age + " years old.";
    System.out.println(s);//from  w ww  . j av a 2  s  . com
  }
}

Example 2

The following code uses string concatenation to create a very long string.

 
public class Main {
  public static void main(String args[]) {
//w w  w .j  a  v  a 2  s .com
    String longStr = "A java 2s.      com" + 
                     "B j a v a 2 s . c o m                     " + 
                     "C java                 2s.com" + 
                     "D java2s.com .";

    System.out.println(longStr);
  }
}

Example 3

You can concatenate strings with other types of data.

 
public class Main {
  public static void main(String[] argv) {
    int age = 1;/*w  w w.  j a v a2  s.c o m*/
    String s = "He is " + age + " years old.";
    System.out.println(s);
  }
}

The output:

Example 4

Be careful when you mix other types of operations with string concatenation. Consider the following:

 
public class Main {
  public static void main(String[] argv) {
    String s = "four: " + 2 + 2;
    System.out.println(s);/*w w w  . j a  v a  2s.c  o  m*/
  }
}

This fragment displays

rather than the

To complete the integer addition first, you must use parentheses, like this:


String s = "four: " + (2 + 2);

Now s contains the string "four: 4".





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures