I see that java has two ways to make String objects, one with the constructor and the other with just the literal value. I understand the difference between the two, but why have two different ways to make String object.
2 Answers
Why does Java have two ways to make String objects?
Because they serve different purposes.
- A literal allows you to easily and concisely create a
String
with a fixed1 content. - A
String
constructor allows you to create aString
with variable content; e.g. characters read from a file.
Now, in theory, they could do away with string literal support. But can you imagine how unpleasant it would be if you had to write stuff like this:
System.out.println(new String(new char[]{'H', 'e', 'l', 'l', 'o'}));
all of the time?
(Even assembly languages have support "string" literals ... for some definition of string. Expressing constant text data as an array of byte or character literals would be a major impediment to readability, even in the context of assembly code ... which is hard to read at the best of times.)
1 - Fixed at compile time.

- 698,415
- 94
- 811
- 1,216
How else would you do it? Suppose we have to write
String s = new String("hello world");
How is the String object that is the argument to the String constructor to be obtained?
The buck has to stop somewhere.
You could, I suppose, say that "..." was not a String object but was an entirely different thing, and that entirely different thing could be used nowhere except in String constructors, but what has that really bought you except inconvenience?
And then, of course, if "..." was not a String, then given the existence of myFunc(String s)
it would not be possible to invoke myFunc("fubar")
unless we also have a rule automatically promoting the "..." to a String.
If we had that rule, then we could also write String s = "hello world"
.

- 1,124
- 4
- 4