Java String Variable

Java String Variable


String Variable In Java
One important thing is that string is not a data Type in java String is a class.
The first letter of String will be in upper case as string is a class
The String type is used to declare string variables. You can also declare arrays of strings. A quoted string constant can be assigned to a String variable. A variable of type String can be assigned to another variable of type String. You can use an object of type String as an argument to println( ). For example, consider the following fragment  -
String str = "this is a test";

System.out.println(str);
Here, str is an object of type String. It is assigned the string “this is a test”. This string is displayed by the   println( ) statement.
Now we will see examples to write string 
Example1 -
 
String a = "Ram";
String b = "Ram";

System.out.println(a==b);//true
System.out.println(a.equals(b));//true
 
 2. By new keyword-
 
String a = new Stirng("Ram");
String b = new Stirng("Ram");

System.out.println(a==b);//false
System.out.println(a.equals(b));//true
Note -
1. == operator compare memory address.
2. .equals() Method compare the content.
String are immutable[unmodified]-
● When we assign new value to string literal then new pool created inside the constant pool of heap memory.
● Objects of the String class are immutable. Every method in the class that appears to modify a String actually creates and returns a brand new String object containing the modification. The original String is left untouched.
Example -
 
String a = "Ram";
      a = "garg";
System.out.println(a);// output is garg
a[1] ='p'// CT error
 
 
Example -
 
String a = "Ram";
char b  = a[1];// CT error
a[1] ='p'// CT error
 
Note -
Now as we have seen already one doubt in your head would be  - Why String is immutable in java. The answer to this question is as follows -
When multiple string literals have same value then only one pool created inside the constant pool of heap memory when we change one string literal value then all literals value will be changed that is why String are immutable in java.
 
String a = "Ram";
String b = "Ram";
String c = "Ram";
String d = "Ram";
String e = "Ram";
a  =  "Manoj";

System.out.println(a);// Manoj
System.out.println(b);// Ram
System.out.println(c);// Ram
System.out.println(d);// Ram
System.out.println(e);// Ram