I\'m a C++ guy learning Java. I\'m reading Effective Java and something confused me. It says never to write code like this:
String s = new String(\"silly\");
String str1 = "foo";
String str2 = "foo";
Both str1 and str2 belongs to tha same String object, "foo", b'coz Java manages Strings in StringPool, so if a new variable refers to the same String, it doesn't create another one rather assign the same alerady present in StringPool.
String str1 = new String("foo");
String str2 = new String("foo");
Here both str1 and str2 belongs to different Objects, b'coz new String() forcefully create a new String Object.
Java strings are interesting. It looks like the responses have covered some of the interesting points. Here are my two cents.
strings are immutable (you can never change them)
String x = "x";
x = "Y";
string comparisons are contingent on what you are comparing
String a1 = new String("A");
String a2 = new String("A");
a1
does not equal a2
a1
and a2
are object referencesI think you're on the wrong path with trying to use the caseinsensitive class. Leave the strings alone. What you really care about is how you display or compare the values. Use another class to format the string or to make comparisons.
i.e.
TextUtility.compare(string 1, string 2)
TextUtility.compareIgnoreCase(string 1, string 2)
TextUtility.camelHump(string 1)
Since you are making up the class, you can make the compares do what you want - compare the text values.
String is one of the special classes in which you can create them without the new Sring part
it's the same as
int x = y;
or
char c;
when they say to write
String s = "Silly";
instead of
String s = new String("Silly");
they mean it when creating a String object because both of the above statements create a String object but the new String() version creates two String objects: one in heap and the other in string constant pool. Hence using more memory.
But when you write
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
you are not creating a String instead you are creating an object of class CaseInsensitiveString. Hence you need to use the new operator.
It is a basic law that Strings in java are immutable and case sensitive.
You can't. Things in double-quotes in Java are specially recognised by the compiler as Strings, and unfortunately you can't override this (or extend java.lang.String
- it's declared final
).