Java String Concatenation

In this chapter you will learn:

  1. How to add strings together
  2. Example - Java String Concatenation
  3. Example - uses string concatenation to create a very long string
  4. Example - How to concatenate String with other data types
  5. Example - mix other types of operations with 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);//  w  w w . j  a v a  2s. c  o m
  }
}

Example 2

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

 
public class Main {
  public static void main(String args[]) {
/*from  w  ww  .  java2 s  .co  m*/
    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 ww.  ja va  2  s  . co  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);/*from  ww w  .j  a v a2s  .  co  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".

Next chapter...

What you will learn in the next chapter:

  1. What are Java Arithmetic Operators
  2. Use Java Arithmetic Operators to do calculation
  3. Example - How to use basic arithmetic operators to do calculation
Home »
  Java Tutorial »
    Java Langauge »
      Java Data Types
Java Primitive Data Types
Java boolean type
Java char type
Java char value escape
Java byte type
Java short type
Java int type
Java long type
Java float type
Java double type
Java String type
Java String Escape
Java String Concatenation