r/javahelp • u/PanScout20 • May 07 '20
How come Strings are not initialized like a normal object?
My understanding is the way you initialize any object would be like this:
ClassName objectName = new ClassName();Yet String is also an object but you don't need the
newkeyword or the call to the constructor to initialize it you just write
String b = "Hello World";Why is this? And is it possible to recreate such syntax with other classes?
8
u/eigengrau- May 07 '20
Don't really know the answer but want to mention one cool thing that's not obvious about String literals: you can actually call methods on them. For example:
"hello world".toUpperCase()Not sure if it's possible to recreate the syntax. Here's a SO post with more info: https://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal
1
u/evils_twin May 07 '20
Here is an article about the special way Strings are stored in memory
I found it quite interesting that String b = "Hello World"; is actually stored different in memory than String b = new String("Hello World");
1
u/ryosen Extreme Brewer May 07 '20
When Java was designed, it was competing with C. Strings in C were a notorious pain to work with as you had to treat them as a string of bytes. To make Java more attractive and to help encourage adoption, strings were designed to work as a first class object. The ease of use of primitives with the advanced functionality and ability to extend of objects.
0
May 07 '20
[deleted]
5
u/PanScout20 May 07 '20
So its essentially just a special exception for String to make it easier to type?
2
u/morhp Professional Developer May 07 '20
Yes, it's a special compiler feature for Strings. Instead of writing
"Hello"you could always writenew String(new char[]{'H', 'e', 'l', 'l', 'o'}).intern()and get roughly the same result, but that's of course way too annoying for general usage.
1
May 07 '20
[removed] — view removed comment
2
u/NobodyAsYouExpect Intermediate Brewer May 07 '20
Happy cake day. Except you avoid literal pool in your second code block. So for it to be same, you would call String#intern() for your object.
1
u/someone-elsewhere May 07 '20
Important to be aware that using a String literal stores that string only once in the active application. So:
String ob1="hello"; String ob2="hello"; // this refers to the same memory String instance as ob1 String ob3 = new String("hello"); // this creates a new String object ob1==ob2; // (true as they point to the same object) ob1==ob3; // (false, different objects) ob1.equals(ob2); // (true, comparing the String object hash codes will be the same) ob1.equals(ob3); // (true, comparing the String object hash codes will be the same)So technically it's not the same as your code creates 2 different objects.
21
u/x42bn6 May 07 '20
Java calls these "literals". These literals in Java are restricted to primitive types (e.g.
intandchar),Stringandnull.I presume that the reason why we have special syntax for these literals is down to simplicity - we use them so often in code, it would be a pain to call a constructor every single time. At the time of Java's conception, it was a common pattern for strings to have either single- or double-quotes in other languages, so this was an easy pattern to copy.
However, you can construct a
Stringwith an explicit constructor. Many constructors, in fact, such as one allowing you to specify a character set. There's alsoString.valueOf(...)to convert from things like numbers. Constructing a newStringwith a constructor is fairly rare.There is, however, another thing special about
Stringliterals - they are automatically interned. This means that two suchStringobjects have the same reference in memory, and thus==comparisons on them will returntrue. You should, of course, still use theequalsmethod in 99.9% of cases to compareStringinstances. You can also manually internString(with the conveniently-namedinternmethod) - again something you should probably not need to use in 99.9% of cases.With primitive types - they also have corresponding classes (e.g.
Integer), but these come with an additional concept - boxed types. Boxed types have benefits (such as being able to be referenced in generics) but also come with caveats (e.g. you can have a nullIntegerobjects, which can throw confusingNullPointerExceptions).It's not possible to have your own literals in Java.