Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 99
Distinguishing between Primitives and Reference Types
ОглавлениеThere are a few important differences you should know between primitives and reference types. First, notice that all the primitive types have lowercase type names. All classes that come with Java begin with uppercase. Although not required, it is a standard practice, and you should follow this convention for classes you create as well.
Next, reference types can be used to call methods, assuming the reference is not null
. Primitives do not have methods declared on them. In this example, we can call a method on reference
since it is of a reference type. You can tell length
is a method because it has ()
after it. See if you can understand why the following snippet does not compile:
4: String reference = "hello"; 5: int len = reference.length(); 6: int bad = len.length(); // DOES NOT COMPILE
Line 6 is gibberish. No methods exist on len
because it is an int
primitive. Primitives do not have methods. Remember, a String
is not a primitive, so you can call methods like length()
on a String
reference, as we did on line 5.
Finally, reference types can be assigned null
, which means they do not currently refer to an object. Primitive types will give you a compiler error if you attempt to assign them null
. In this example, value
cannot point to null
because it is of type int
:
int value = null; // DOES NOT COMPILE String name = null;
But what if you don't know the value of an int
and want to assign it to null
? In that case, you should use a numeric wrapper class, such as Integer
, instead of int
.