When you write:
OddEven number = new OddEven();
You actually do two things : 1) you declare a variable number
of type OddEven
and 2) you assign a reference to a new instance of class OddEven
. But because a variable can hold any subtype of a type, writing number = new OddEven();
wouldn't be enough for the compiler to know the real type of the number
variable. So, you have to declare it too. Java is a strongly typed language, which means that every variable and every expression has a type that is known at compile time. You may want to read the whole Chapter 4. Types, Values, and Variables of the Java Language Specification (JLS) to learn more on this.
Now, when your write:
String str = "abc";
Things are a bit different. Characters enclosed in double quotes, "abc"
here, are called a string literal which is already a reference to an instance of String
and always refers to the same instance of class String
. Quoting the section 3.10.5 String Literals of the JLS:
Each string literal is a reference
(§4.3) to an instance
(§4.3.1, §12.5) of class
String
(§4.3.3). String
objects have a constant value. String
literals-or, more generally, strings
that are the values of constant
expressions (§15.28)-are
"interned" so as to share unique
instances, using the method
String.intern
.
So, String str = "abc";
is certainly not converted into String str = new String("abc");
which is absolutely not equivalent as I've read in some comments and answers. Running the following class:
public class Test {
public static void main(String[] args) {
String one = "abc";
String two = "abc";
String abc = new String("abc");
System.out.println(one == two);
System.out.println(one == abc);
}
}
Produces the output below:
true
false
And demonstrates that one
and two
are references to the same instance but that abc
is a reference to another instance (i.e. an extra unnecessary object has been created).
Actually, using new String(String)
is a inefficient way to construct new strings and should only be used to force a substring to copy to a new underlying character array, as in
String tiny = new String(monster.substring(10,20))