Two Types of Assignment Statements

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

When

value = 32912;

is executed nothing new is created. A bit pattern representing 32912 is stored in value.

Two Types of Assignment Statements

There is a difference between the statements:

value = 32912;

and

str   = new String( "The Gingham Dog" );

In the first statement, value is a primitive type, so the assigment statement puts the data directly into it. In the second statement, str is an object reference variable (the only other possibility) so a reference to the object is put into that variable.

Important: A Java variable never contains an object.

There are only primitive variables and object reference variables, and each contains a specific kind of information:

 Information it ContainsWhen on the left of =
primitive variableContains actual data.Previous data is replaced with new data.
reference variableContains information on how to find an object (a reference).Old reference is replaced with a new reference

How do you tell the two kinds of variables apart? Easy: look at how the variable is declared. Unless it was declared to be of a primitive type, it is an object reference variable. A variable will not change its declared type.

QUESTION 9:

How are the following variables declared? Click on the button of your choice.

Declaration PrimitiveObject Reference
int foo;
String st;
boolean flag;
Scanner scan;