java

String Concatenation in Java

In this tutorial, we are going to see how to concatenate two strings in Java.

In java, the concatenation of strings forms a new string which is the combination of several strings. There are two ways to concatenate a string in Java:

  • By using the operator +
  • By using the concat() method

 

Method 1 : By using the operator +
public class Main {
	public static void main(String args[]){
		String str = "Hello" + " World!";
		System.out.println(str);
	}
}

Output:

Hello World!

The concatenation operator can concatenate not only strings but also primitive values.

public class Main {
	public static void main(String args[]){
		String str = "Hello" + " World!" + 3 + 4;
		System.out.println(str);
	}
}

Output:

Hello World!34
 

Method 2 : By using the concat() method
public class Main {
	public static void main(String args[]){
		String str1 = "Hello";
		String str2 = " World!";
		String res = str1.concat(str2);
		System.out.println(res);
	}
}

Output:

Hello World!
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *