String Concatenation in Java

Java 8Object Oriented ProgrammingProgramming

You can concatenate two strings in Java either by using the concat() method or by using the ‘+’ , the “concatenation” operator.

The concat() method

The concat() method appends one String to the end of another. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.

Example

public class ConncatSample {
   public static void main(String []args) {
      String s1 = "Hello";
      String s2 = "world";
      String res = s1.concat(s2);
      System.out.print("Concatenation result:: ");
      System.out.println(res);
   }
}

Output

Concatenation result:: Helloworld

The ‘+’ operator

Just like the concat method the ‘+’ operator also performs the concatenation operation on the given operators.

Example

public class ConncatSample {
   public static void main(String []args) {
      String s1 = "Hello";
      String s2 = "world";
      String res = s1+s2;
      System.out.print("Concatenation result:: ");
      System.out.println(res);
   }
}

Output

Concatenation result:: Helloworld
raja
Published on 09-Feb-2018 10:31:40
Advertisements