Java concatenation

Concatenation means to add something like text or number at the end of some text or number.

Like, we have "hell" String and if we add 'o' at the end of that string then, it is called concatenation. Remember, String are concatenated but numbers are added.

In java, we use + sign for concatenate one String to another.

See, a simple example:


public class Main{
  public static void main (String[] args) {
    //String variables
    String firstName = "Mark";
    String lastName = "Smith";
    System.out.println(firstName + lastName);
  }
}
/**
 * Output:
 * Mark Smith
 */

Here, we used the + sign to concatenate two Strings.

But what if the variables are number?

I mentioned already that, Strings are concatenated but numbers are added.

Like:


public class Main{
  public static void main (String[] args) {
    //String variables
    String x = 10;
    String y = 10;
    System.out.println(x + y);
  }
}
/**
 * Output:
 * 20
 */

But, what will be the output for the below one?


public class Main{
  public static void main (String[] args) {
    //String variables
    String x = "10";
    String y = "10";
    System.out.println(x + y);
  }
}
/**
 * Output:
 * 1010
 */

Yes, you are right. Because, Now the variable x and y are seemd to be String not number.
That's why, instead of addition they were concatenated.

Concatenate String and number together:


public class Main{
  public static void main (String[] args) {
    //String variables
    System.out.println("The number is "+ 10);
  }
}
/**
 * Output:
 * The number is 10
 */

Yes, for this we also use + sign.

Note: concatenation starts from left to right. And, string are concatenated but numbers are added unless they seem to be String.

read more