Java String Concatenation

In this chapter you will learn:

  1. How to add strings together
  2. How to concatenate String with other data types
  3. How to concatenate one string to the other with concat method

Add strings together

You can use + operator to concatenate strings together. 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);//ja v a 2 s.com
  }
}

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

public class Main {
  public static void main(String args[]) {
/*from jav  a  2 s  .c o  m*/
    String longStr = "A demo 2s.      com" + 
                     "B d e m o 2 s . c o m                     " + 
                     "C demo                 2s.com" + 
                     "D demo2s.com .";

    System.out.println(longStr);
  }
}

Concatenate String with Other Data Types

You can concatenate strings with other types of data.

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

The output:

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 j a  va 2s . c  om*/
  }
}

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".

concat one string to the other with concat method

String concat(String str) concatenates the specified string to the end of this string.

public class Main {
  public static void main(String[] argv) {
    String str = "demo2s.com";
    /*from j  a  v a 2s. c  o m*/
    str = str.concat("Demo2s.com");
    System.out.println(str);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to create String object with String constructors
  2. How to create a string from byte array
  3. How to create a string from part of a byte array
  4. How to create String from char array
  5. How to create String from part of a char array
  6. How to create a String from another string