Table Of Content
Introduction To Strings
- Strings is a collection of characters or a array of characters.
- It is a non-primitive datatype.
- In java Strings are treated as object because the memory is allocated in heap segment.
- Ex. "Nandan", "2" etc.....
Types Of String
1. Immutable String
- Once String object is created its data or state can't be changed but a new String object is created
- Ways Of Creating Immutable String
String s = new String("Nandan");
String s = "Nandan";
char []a ={a,b,c,d};
byte[] a={97,98,99,100};
2. Mutable String
- Those Strings whose content can be changed without creating a new object
- To create a mutable string, we can use StringBuffer and StringBuilder class. Both classes create a mutable object of string but which one we should use is totally depends on the scenario
public class MutableString
{
public static void main (String[] args)
{
StringBuffer str1 = new StringBuffer("JavaGoal");
StringBuilder str2 = new StringBuilder("Learning");
System.out.println("Value of str1 before change :" + str1);
System.out.println("Value of str2 before change :" + str2);
str1.append(".com");
str2.append(" website");
System.out.println("Value of str1 after change :" + str1);
System.out.println("Value of str2 after change :" + str2);
}
}
//output
Value of str1 before change :JavaGoal
Value of str2 before change :Learning
Value of str1 after change :JavaGoal.com
Value of str2 after change :Learning website
Note
Immutable String
- Once String object is created its data or state can't be changed but a new String object is created