1.3. Reference Types and Assignment Values

Consider the following reference type variable declaration:

SomeType varName;

Here, we use SomeType as a placeholder for any reference type (class, array, or interface).

The values that can be assigned to varName are null and any reference to an object whose type is compatible with SomeType. In Java, a reference to an object of a particular type is always compatible with a variable of the same type. Here are some examples:

Scanner scan = new Scanner(System.in); // same types
String str = "Hello";                  // same types

Foreshadowing:

Object references are also compatible with a variable when the type of that is a superclass or interface of the reference type being assigned. We will discuss this in more detail later in the semester once interfaces and inheritance are introduced.

When you invoke a constructor using new SomeClassName() (or similar), the type of the reference produced by the expression is the same as the class name. This reference can be assigned to any compatible variable or returned in any method with a compatible return type. In other words, the types don’t have to match - they just have to be compatible. We will define this term formally in the upcoming chapters.