String concat() Method

      No Comments on String concat() Method




In Java, String concat() method is used to concat the specified string to the end of current string.

Let’s take an example to understand this.

Example 1: Java String concat() Method

package com.masterjavatutorial;
public class Test {
    public static void main(String[] args) {
	String str="HelloWorld";
	String concat = str.concat(null); 
	System.out.println(concat);
    }
}

Output of the above program is as below:

HelloWorldJava

What if “null” is concat to the current String. It would give NullPointerException.

package com.masterjavatutorial;
public class Test {
    public static void main(String[] args) {
	String str="HelloWorld";
	String concat = str.concat("Java"); 
	System.out.println(concat);
    }
}

Output of the above method is as below:

Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.concat(String.java:2027)
	at com.masterjavatutorial.Test.main(Test.java:5)