Declaring Methods  «Prev  Next»


Lesson 2Declaring variables
ObjectiveDescribe how variables are declared and assigned objects.

Declaring variables in Java

Variable declarations associate a type with a variable name (identifier). They also (optionally) initialize the variable to a value of its type. Variables of a primitive type store values of their type. Variables of an object type store references to objects of their type.

Variables of primitive and object types
Variables of primitive types and object types

field Variable

A field variable, also referred to as a field or a member variable, is a variable that is declared as a member of a class. It stores state information about the class (static variables) or about instances of the class (non-static) variables. A local variable is a variable that is declared and used within a method.


Field or member variable versus a local variable in a method
Field or member variable versus a local variable in a method

  1. Field variable: A variable that is a member of a class.
  2. Field: Short for field variable.
  3. Member variable: Another name for a field variable.


The following variable declarations are legal in Java.
package com.java.basics;
public class VariableInitialization {
 public static void main(String[] args) {
  int a, b, c;
  a = b = c = 100;
  int f, g, h = 100;
  int x = 100, y, z;
 }
}

Modern Java

Field Variables

The following syntax is used to declare a field variable:
modifiers type variableName initializer;
Variables may be declared using the modifiers
  1. final,
  2. private,
  3. protected,
  4. public,
  5. static,
  6. transient, and
  7. volatile
These modifiers are covered later in this module. The variable's type may be a primitive type, class name, interface name, or array type. The optional initializer consists of an equals sign followed by an expression that evaluates to a value of the variable's type. Arrays may be initialized using a special array initialization expression that you'll learn about in the next lesson.

Local variables

Local variables are declared in the same way as field variables except that local variables may only use the final modifier. The final modifier (refer to Module 3) identifies that a local variable may be accessed by an inner class once the variable has been assigned a value. Final local variables may not be modified once they have been initialized.

Atomic variables

Click on the link below to read about the Atomic variables and classes that support lock-free thread-safe programming on single variables.
Atomic Variables