Strings in Java
String Class is immutable, i.e. once created and initialized, cannot be changed on the same reference. String, Integer, Byte, Short, Float, Double and all other wrapper class`s objects are immutable.
There are two ways to crate String object
- Using string literal
- Using new Keyword
Using string literal
If you are using string literal to create the object then first JVM will check this object in string pool or not. If String object is already exist in the pool then a reference will return same instance and but if string is not persent in the String pool then new object is created in the pool.
Example: Using string literal
String s1="Ali" String s2="Java" //new object create in the constant pool String s3="Java" //no new object create in the constant pool
Using new keyword
When you are creating string object using new keyword then JVM create new object in the string pools without check this object is present or not in pool.
Example: Using new keyword
String sObj = new String("Hello Dear");
Concatenating or Appending Strings in Java
You can join strings in Java by using + operator
String s1 = "Hello"; String s2 = "Dear"; System.out.println(s1 + " " + s2);
You can join strings in Java by using concat() method
String s1 = "Hello"; String s2 = "Dear"; String s3 = s1.concat(s2);
If you want to compare two String object are exactly same or not, always use equals() method instead of equality operator. The equals() method returns true if both object contains same contents. If not, it returns false.
Example: Equals() Method
String s1 = "ali"; String s2 = "ali1"; String s3 = "ali"; String s4 = "ALI"; System.out.println(s1.equals(s2) ); System.out.println(s1.equals(s3) ); System.out.println(s1.equals(s4) );
The two strings s1 and s3 are equal, but s1 is not equal to s2 and to s4.
false true false
Example: == Operator
== operator compares two object references to check whether they refer to same instance or not.
String s1 = "Ali"; String s2 = "Ali"; String s3 = new string ("Ali"); method(sl == s2) //true method(s1 == s3) //false