Reading Note for OCP Java SE7 I by Manning Publication, Chapter 4

Note: All tips that is written by book will has a sign near it.
All code example in this post comes from book.

Chapter 3: String, StringBuilder, Arrays, and ArrayList

If two strings are created by new keyword, they are referring two different objects.

If two strings are created by = operator or double quotes, they are reference varaibles, so they are refering the same object. In this case, if the string never exists before, a new string object will be created in string constant pool. otherwise they will point to existing string object.

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
String str1 = new String("Test");
String str2 = new String("Test");
System.out.println(str1 == str2);
/*
Output false, since str1 and str2 are referring different objects.
"new" keyword does not create string object in String Constant Pool/String Pool.
*/
String str3 = "Test1";
String str4 = "Test1";
System.out.println(str3 == str4);
/*
Output true.
The process is: Java can not find a "Test1" in pool of String objects,
so it create a "Test1" string and refer str3 to it.
*/

The literal value for String is null.

String is immutable. Once it is created, it can not be modified again.