1.3 Variables & ScopeHomepage  « Java5 Certification « 1.3 Variables & Scope

In this lesson we examine the declaration, initialization and usage of primitives, arrays, enums, and objects as static, instance and local variables and their respective scopes.

Lets take a look at the points outlined at the Oracle Website for this part of the certification.

  • Section 1: Declarations, Initialization and Scoping

    • Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

Variables in Javago to top of page Top

Java comes with two types of variables to choose from, primitives and reference, both of which can be declared as static variables, instance variables, method parameters and local variables. Java is a strongly typed language and as such cares about the type of the variables we declare. So what does this statement actually mean? Well whenever you declare a variable in Java, you have to give it a type, or the compiler complains when you come to compile your code. You also have to name the variable and there are rules on naming.

type diagram

Naming Rules and Keywords

These rules apply to all variables, as well as classes and methods (collectively known as identifiers)

  • Must start with a letter, the underscore symbol (_) or the dollar sign ($). A name can't start with a number or any other symbol.
  • You can use numbers after the first letter, you just can't start with a number.
  • You cannot use keywords or names recognized by the compiler. See the table below for the words you can't use.

Click a link in the table below to show lesson usage for any keyword you're interested in:

Java5 Keywords

Although not a rule as such it's also important to know that identifiers are case-sensitive.

Variable Scope

In Java we can declare variables anywhere within a block of code. A block starts with its opening curly brace and ends with its closing curly brace. A block and where it resides defines the type of the variable and the scope of the enclosed data. Therefore each time you start a new block of code you start a new scope. Scope determines the visibility and lifetime of the variables within it. Java comes with three kinds of scope and we name variables according to the scope they reside in as detailed in the table below.

Variable Scope Lifetime
staticStatic variables apply to the class as a whole and are declared within the class but outside a method.Exists for as long as the class it belongs to is loaded in the JVM.
See the Static Members lesson for more information.
instanceInstance variables apply to an instance of the class and are declared within the class but outside a method.Exists for as long as the instance of the class it belongs to.
See the Instance Variables & Scope lesson for more information.
localLocal variables apply to the method they appear in.Exists until the method it is declared in finishes executing.
See the Method Scope lesson for more information.

Access Modifiers

The table below shows the four types of access available in Java for members (variables, inner classes and methods).

Access modifier Description
publicA member may be declared with the public access modifier, and if it is the member is accessible to all other classes everywhere, assuming the class it resides in is accessible.
protectedA member may be declared with the protected access modifier, and if so, is only accessible within its own package and also by a subclass of its class in other packages..

See the Packages lesson for more information on packaging.
See the Inheritance Basics lesson for more information on subclassing.
no modifier
package-private / (the default)
If a member has no explicit access modifier it is only accessible within its own package.
privateA member may be declared with the private access modifier, and if it is the member is only accessible within its own class.

Non-access Modifiers

The table below shows the types of non-access modifiers available for use with variables.

static variable and instance variable modifiers local variable modifiers

Primitive Variablesgo to top of page Top

The table below lists the eight primitive types available in Java5:

Primitive Types
Type Description Bit Width Range
boolean and char
booleantrue/false valuesJVM specifictrue or false
charCharacter160  to  65535 - ('\u0000' to '\uffff' Unicode)
signed numeric integers
byte8-bit integer8-128  to  127
shortShort integer16-32,768  to  32,767
intInteger32-2,147,483,648  to  2,147,483,647
longLong integer64-9,233,372,036,854,775,808  to  9,233,372,036,854,775,807
signed floating point
floatSingle-precision float32varies
doubleDouble-precision float64varies

Reference Variablesgo to top of page Top

Reference variables are concerned with objects and how we access them. The reference variable doesn't hold the object itself but some bits that act as a pointer to an address in memory where the object exists. How the JVM holds this bits isn't important for us as programmers, just the fact that this memory address pointer is used by the JVM to access a unique object. There are three steps involved in object creation:

object creation

So lets go through the three step process above:

  1. Declaration - Here. we declare a reference variable named moggy of type Cat and the JVM allocates space for it.
  2. Creation - Tells the JVM to allocate space on The Heap for a new Cat object.
  3. Assignment - Assign the new Cat object to the reference variable moggy.

Arraysgo to top of page Top

An array in Java is an object that contains a collection of values which can be a collection of primitive data types or a collection of reference variable types.

  • An array of primitives data types is a collection of values that constitute the primitive values themselves.
  • An array of reference variable types is actually a collection of pointer values which point to the memory address where each object is stored on The Heap.

Whichever variable type the array holds, primitive or reference, the array itself is still an object. In Java you can define a one dimensional array which is an object that refers to a collection of values repeated one or more times, or multi dimensional arrays which are a collection of array objects (arrays of arrays). Multi dimensional arrays may contain the same number of elements in each row or column and are known as regular arrays or an uneven number of elements in each row or column which are known as irregular arrays.

Array Creation

Array creation is a three step process as outlined below and can be achieved using separate statements or combined into a single statement.

  1. Array declaration
  2. Array allocation
  3. Array element initialization

Array Notes

As you can see from the table above there is a lot of ways to create arrays in Java. There are several points about arrays shown in the table above that we will highlight again here before we go into some code examples:

  • Array indexes are zero-based.
  • When declaring an array the square brackets can appear after the type, after the array name or in the case of multi dimensional arrays a combination of both.
  • After allocation of an array, each element of the array is initialized with the default for the array type:
    • object - null
    • boolean - false
    • char - /u0000
    • integer types (byte, short, int and long) - 0
    • floating-point types (float, double) - 0.0
  • For multiple statement array creation the new keyword is mandatory.
  • For single statement array creation the size of the array is calculated by the number of values that are assigned to the array and should not be specfied.

Enumsgo to top of page Top

In their simplest form enumerations are just a list of constants that define a new data type. Before Java5 the only way to do this would have been using static final variable to define Java constants. The difference between using enumerations and static final variables to define Java constants, is that with static final variable we can't guarantee that another piece of code won't set an invalid value, instead of using one of our static final variables. With enumerations, objects of the enumerated type can only hold values defined in the list of constants such as months of the year and days of the week for example. Lets look at some code to see this in action:

  Enumeration of soups
enum Soup {

We create an enumeration using the enum keyword. The identifers TOMATO, CHICKEN and PRAWN are known as enumeration constants and are implicitly declared as public, static members of Soup. When we declare enumeration constants it's not obligatory to use all uppercase letters, but it lets others see this is a constant and so we use this convention here.

Related Java5 Tutorials

Beginning Java5 - Primitive Variables
Beginning Java5 - Method Scope
Objects & Classes - Arrays
Objects & Classes - Reference Variables
Objects & Classes - Enumerations
Objects & Classes - Static Members
Objects & Classes - Instance Variables & Scope
OO Concepts - Interfaces

go to home page Java5 Tutor Homepage go to home page Top