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:

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

Values that are not compatible with the type of the variable cannot be assigned. For example:

Invalid declarations / initializations - won’t compile
Scanner input = 7.0;                   // Can't assign a double value to a Scanner variable
String str = new Scanner(System.in);   // Can't assign Scanner to String
int x = "Hello";                       // Can't assign String to int
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. For example:

produces a reference of type Scanner
new Scanner(System.in);

Because the statement above returns a reference (memory address) of type Scanner, we can assign it to a variable of type Scanner:

valid because the type of the reference and the type of the variable are compatible
Scanner input = new Scanner(System.in);

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.