OCA Java SE 8 Building Blocks - Variables

Declaring and Initializing Variables

A variable is a name for a piece of memory that stores data.

To initialize a variable, you just type the variable name followed by an equal sign, followed by the desired value:

String aName = "a"; 
int numberAnimals = 1; 

Declaring Multiple Variables

You can declare and initialize multiple variables in the same statement.

String s1, s2; 
String s3 = "yes", s4 = "no"; 

Four String variables were declared: s1, s2, s3, and s4.

You can declare many variables in the same declaration as long as they are all of the same type.

You can initialize any or all of those values inline.

In the following code three variables were declared: i1, i2, and i3.

However, only one of those values was initialized: i3.

The other two remain declared but not yet initialized.

int i1, i2, i3 = 0; 

Each code separated by a comma is a declaration of its own.

The initialization of i3 only applies to i3. It has nothing to do with i1 or i2 even though they are in the same statement.

The following code cannot compile since it tries to declare multiple variables of different types in the same statement.

int num, String value; // DOES NOT COMPILE 

We can use the shortcut to declare multiple variables in the same statement only when they are in the same type.

The following statement is legal. It declares two variables without initializing them.

boolean b1, b2; 

The following statement is legal. It declares two variables and initializes only one of them.

String s1 = "1", s2; 

The following statement is not legal. You cannot declare two different types in the same statement.

double d1, double d2; 

To declare multiple variables in the same statement, they must share the same type declaration and not repeat it. We can change the above code to the following.

double d1, d2; //would have been legal. 

The following statement is legal. Although int does appear twice, each one is in a separate statement. A semicolon (;) separates statements in Java.

int i1; int i2; 

The following statement is not legal. We have two completely different statements on the same line. The second one is not a valid declaration because it omits the type.

int i3; i4; 


Java has precise rules about identifier names.

The same rules for identifiers apply to anything you are free to name, including variables, methods, classes, and fields.

There are only three rules for legal identifiers:

  • The name must begin with a letter or the symbol $ or _.
  • Subsequent characters may also be numbers.
  • You cannot use the same name as a Java reserved word.

A reserved word is a keyword that Java has reserved so that you are not allowed to use it.

Java is case sensitive, so you can use versions of the keywords that only differ in case.

The following is a list of all the reserved words in Java. const and goto aren't actually used in Java.

abstract   assert      boolean    break         byte 
case       catch       char       class         const* 
continue   default     do         double        else 
enum       extends     false      final         finally 
float      for         goto*      if            implements 
import     instanceof  int        interface     long 
native     new         null       package       private 
protected  public      return     short         static 
strictfp   super       switch     synchronized  this 
throw      throws      transient  true          try 

void       volatile    while 

The following examples are legal:

okidentifier           // all letters
$OK2Identifier         // start with $ and mix letter and digits
_alsoOK123awer3r       // start with underscore
__asdf$                // start with two underscores and ends with $

These examples are not legal:

3DPointClass            // cannot begin with a number 
hollywood@vine          // @ is not a letter, digit, $ or _ 
*$coffee                // * is not a letter, digit, $ or _ 
public                  // public is a reserved word  

Java uses CamelCase to name variables and classes.

In CamelCase, each word begins with an uppercase letter.

This makes multiple-word variable names easier to read.

Method and variables names begin with a lowercase letter followed by CamelCase.

Class names begin with an uppercase letter followed by CamelCase.

Don't start any identifiers with $. The compiler uses this symbol for some files.

Default Initialization of Variables

Before we can use a variable, it needs a value.

Some types of variables can have its value automatically, and others require the programmer to set it.

We need to know differences between the defaults for local, instance, and class variables.

Local Variables

A local variable is a variable defined within a method.

Local variables must be initialized before we can use them.

They do not have a default value and we cannot use them in calculation or try to get its value.

The following code is fine.

public class Main {
  public static void main(String[] args) {
     int i;

While the following code has compile error.

public class Main {
  public static void main(String[] args) {
     int i;
     System.out.println(i); // cannot access value from i

The compiler will not let you read an uninitialized value. For example, the following code generates a compiler error:

4: public int myMethod() { 
5:  int y = 10;  
6:  int x;  
7:  int reply = x + y; // DOES NOT COMPILE 
8:  return reply; 
9: }  

y is initialized to 10 and x is not initialized before it is used in the expression on line 7, the compiler generates the following error:

Test.java:5: variable x might not have been initialized 
        int reply = x + y; 

Until x is assigned a value, it cannot appear within an expression.

We can change the code above as follows to fix the compile error.

public int valid() { 
  int y = 10; 
  int x; // x is declared here 
  x = 3; // and initialized here 
  int reply = x + y; 
  return reply; 

The following code cannot initialize myValue if the check is false.

public void myMethod(boolean check) { 
  int answer; 
  int myValue; 
  if (check) { 
    myValue = 1; 
    answer = 1; 
  } else { 
    answer = 2; 
  System.out.println(myValue); // DOES NOT COMPILE 

Instance and Class Variables

Variables that are not local variables are instance variables or class variables.

Instance variables are also called fields. Class variables are shared across multiple objects.

A class variable has the keyword static before it.

Instance and class variables do not require you to initialize them.

As soon as you declare Instance and class variables, they are given a default value.

If the compiler doesn't know what value to use, it can give the value: null for an object and 0/false for a primitive.

The following table lists Default initialization values by type

Variable typeDefault initialization value
byte, short, int, long0 (in the type's bit-length)
float, double0.0 (in the type's bit-length)
char'\u0000' (NUL)
All object referencesnull