Java Reference
In-Depth Information
If you do not want str to refer to any other String object after it has been initialized, you can declare it final ,
like so:
final String str = new String("str cannot refer to other object");
str = new String("Let us try"); // A compile-time error. str is final
it is the String object in memory that is immutable, not the reference variable of the String type. if you
want a reference variable to refer to the same String object in memory all the time, you must declare the reference
variable final .
Tip
Comparing Two Strings
You may want to compare the sequence of characters represented by two String objects. The String class overrides
the equals() method of the Object class and provides its own implementation, which compares two strings for
equality based on their contents. For example, you can compare two strings for equality, as shown:
String str1 = new String("Hello");
String str2 = new String("Hi");
String str3 = new String("Hello");
boolean b1, b2;
b1 = str1.equals(str2); // false will be assigned to b1
b2 = str1.equals(str3); // true will be assigned to b2
You can also compare string literals with string literals or string objects, as shown:
b1 = str1.equals("Hello"); // true will be assigned to b1
b2 = "Hello".equals(str1); // true will be assigned to b2
b1 = "Hello".equals("Hi"); // false will be assigned to b1
Recall that the == operator always compares the references of two objects in memory. For example, str1 == str2
and str1 == str3 will return false , because str1 , str2 and str3 are references of three different String objects in
memory. Note that the new operator always returns a new object reference.
If you want to compare two strings based on the Unicode values of their characters, you can use the compareTo()
method. Its signature is
public int compareTo(String anotherString)
It returns an integer, which can be 0 (zero), a positive integer, or a negative integer. It compares the Unicode
values of the corresponding characters of two strings. If any two characters differ in their Unicode values, the method
returns the difference between the Unicode values of those two characters. For example, "a".compareTo("b") will
return -1 . The Unicode value is 97 for a and 98 for b . It returns the difference 97 - 98 , which is -1 . The following are
examples of string comparisons:
"abc".compareTo("abc") will return 0
"abc".compareTo("xyz") will return -23 (value of 'a' - 'x')
"xyz".compareTo("abc") will return 23 (value of 'x' - 'a')
 
 
Search WWH ::




Custom Search