String Concatenation in Java
String Concatenation in Java: String Concatenation in Java can be possible by two ways,
- Using + operator.
- Using Concat() Function.
Example Program:
[java]
package com.ngdeveloper.com;
public class StringConcatenation {
public static void main(String[] args) {
String hVariable = "hello ";
String wVariable = "world";
String hwVariable = hVariable.concat(wVariable);
String a = "java";
String b = "domain";
String javadomain = a + b;
System.out.println("String concatenation using concat() : "+hwVariable);
System.out.println("String concatenation using + operator : "+javadomain);
}
}
[/java]
Output:
String concatenation using concat() : hello world
String concatenation using + operator : javadomain
Difference between + and concat():
Using + operator:
1. Any type of variable can be concatenated, it is not mandatory to be a string variable.
[java]
String firstVar = "Java";
int secVar = 11;
String plusConcat = firstVar + secVar;
System.out.println(plusConcat); // prints Java11
[/java]
2. String can be null and it will not throw null pointer exception.
[java]
String myVar = null;
String plus = myVar + "java";
System.out.println(plus); // prints nulljava
[/java]
Using Concat():
1. Argument must be string for concatenation using concat()
[java]
a.concat(11) //it is not possible
[/java]
2. String must not be null, if it is null then it will throw null pointer exception.
[java]
String myVar = null;
String value = "java";
System.out.println(myVar.concat(value)); // throws null pointer exception
[/java]