Strings
Strings in Java are treated as an object rather than as an array of characters.
Difference between String and String literal
The string is a whole object in Java with a bunch of properties and methods whereas a String literal is just a sequence of characters.
A string object is created in the Heap area and a String literal is stored in a designated area in the heap area called as "String Constant Pool" where duplicates are not allowed.
String a = "Aman";
String b = "Aman";
They both will refer to the same literal in the SCP.
String a = new String("Aman");
String b = new String("Aman");
Whereas in this code two string objects will be created although internally they both will refer to the same String literal in SCP.
Ways to Initialise a String
// First Way
String s = new String("xyz");
// Second Way
String s = "abc";
// Third Way
Char chars[] = {'x','y','z'};
String s = new String(chars);
// You can see that String literal is just same as array of characters.
Mutable and Immutable
Strings can be mutable and immutable. By the name, it is clear that mutable ones cannot be changed and immutable ones can be changed.
Strings made using the "String" class are immutable which means that changing their value using their reference variable will make a new String in SCP whereas in mutable strings by changing their value the existing String will be affected.
Mutable strings are made using StringBuilder and StringBuffer classes.
To access all the string methods you have to use the "toString" method on them.
StringBuilder sb1 = new StringBuilder("Aman");
sb1 = "Aman Kumar";// Aman Kumar
sb1.toString().toUpperCase(); // AMAN KUMAR