SCJP Study Guide:
Declarations, Initialization and Scoping

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents
XyzWs SCJP Study Guide: Variable


What is a Variable?

A variable is a place to store a piece of information  such as numeric values, characters, strings, or computer memory addresses. The variable represents its stored information and such information can be changed.

Variables play an important role in computer programming because they enable programmers to write flexible programs. Rather than entering data directly into a program, a programmer can use variables to represent the data. Then, when the program is executed, the variables are replaced with real data. This makes it possible for the same program to process different sets of data.

Every variable has a name, called the variable name, and a data type. The variable name refers to the information that the variable contains. In other words, a program refers to a variable's value by the variable's name.

A variable's data type indicates what sort of value the variable can hold (such as whether it is an integer, a floating-point number, or a character) and what operations can be performed on it.

The opposite of a variable is a constant. Constants are values that never change. Because of their inflexibility, constants are used less often than variables in programming.

Variable Declarations:

Before you can make a reference to a variable, you must declare it. A variable declaration introduces one or more variables with some storage locations. Declarations define new entities in a program and associate an identifier with it. Varaiable declarations in Java are of the general  form:

[Modifiers] Type Identifier


The variable's name must be a legal identifier -- an unlimited length sequence of Unicode characters that begins with a letter, a currency character, or a connecting character. Here are the rules you do need to know:

  • Identifiers MUST start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ), and are followed by any combination of letters, currency characters, connecting characters, and digits.
  • Identifiers MUST NOT have the same spelling as Java keywords or boolean literals (true or false) or null.
  • Identifiers CANNOT start with a digit.
  • Letter are usually the lowercase and uppercase letters a to z and A to . Digits are 0 to 9.
  • Identifiers in Java ARE case-sensitive; Tow identifiers are considered identical if they consist of the same sequence of Unicode characters, i.e. xyz is different from Xyz.

Identifiers should conform to following guidelines: [Code Conventions for the Java Programming Language (Chapter 9)]

In all-lowercase ASCII letters that are related to a domain, beginning with the top level domain.
Classes and Interfaces
Class identifiers should be nouns which start with a uppercase letter and use uppercase letter at word boundaries.
Should be verbs that start with a lowercase letter but use uppercase letter at word boundaries.
Meaningful names that (like methods) begin with a lowercase letter.
Constants are all uppercase and use the underscore ( _ ) between word boundaries.
Note that underscore (_) are accepted only as word boundaries in all uppercase identifiers for constants. Underlines should not be used within variables or methods, e.g. payment_Index or get_Payment violate this guideline.

Types of Variables in Java

Every variable must have a data type. A variable's data type determines the values the variable can contain and the operatios that can be performed on it. For example, the Integer type variable can contain only integral values (both positive and negative). You can perform arithmetic operations, such as addition, on integer variables.
In the Java world, Variables have either a primitive type or a reference type (some object):

  • In case of primitive types, the value is copied during assignments and all other forms of access. Variables declared as primitive types are not object references. They are placeholders for storing primitive values. Once a primitive has been declared, its primitive type can never change, although in most case its value can change.
  • In case of reference types, variable is used to refer to (or access) an object. Reference variables have either a null value (not referencing any objects) or they point to some objects. Assignment of variables of reference types cause the object to be shared.
    Arrays, enums, classes, and interfaces are reference types. A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do; you need to use the variable's name instead.

Java Field Modifiers and Local Variable Modifier

Java field modifier has definition a keyword that specifies how restricted the access is to a field. The class variables and instance variables are fields defined inside a class body and outside any method's body.

Modifier Meaning
Cannot change its value. static final fields are compile-time constants.

Accessible only within the class that defines it.


Accessible only within the class that defines it, any calsses that defined in the same package with owing class, and any subclasses.


Accessible anywhere its class is.


A static field is a class field. There is only one instance of the field, regardless of the number of class instances created. It can be accessed through the class name.


The field is not part of the persistent state of the object and should not be serialized with the object. Used with object serialization; see


 The field can be accessed by unsynchronized threads, so certain optimizations must not be performed on it. This modifier can sometimes be used as an alternative to synchronized. This modifier is very rarely used.

no modifier
Accessible only within the class that defines it and any classes that defined in the same package with owing class.

Rules (A compile-time error occurs if any rules have been broken):

  • the same field modifier can not appear more than once in a class/instance variable declaration;
  • a class/instance variable declaration can not have more than one of the access modifiers public, protected, and private;
  • a class/instance variable declaration can not have both final and volatile modifiers.

If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with publuc, protected, private, static, final, transient, and volatile left to right order.

So far, we only talk about modifiers for class variables and instance variables. What kinds of modifiers can be used in local variable? There is only one modifier can be used by local variables that is final modifier. The following table shows the local variable modifier:

Modifier Meaning
Cannot change its value.
no modifier
Accessible only within the block that defines it.

Primitive Data Type

A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a character, or a boolean value (see the figure). For example, an integer value is 32 bits of data in a format known as two's complement, the value of a char is 16 bits of data formatted as a Unicode character, and so on.
A variable of primitive type contains a value of a particular size and format.

The following table lists, by data type, all the primitive data types supported by the Java platform, their sizes and formats, and a brief description of each.

Data Type Description
Bit Size Range Min/Max values Default
byte Byte-length integer
signed 8-bit integer (8-bit two's complement) -(27) to 27-1 -128 to 127 0
short Short Integer
signed 16-bit integer (16-bit two's complement) -(215) to 215-1 -32,768 to 32,767 0
int Integer signed 32-bit integer (32-bit two's complement) -(231) to 231-1 -2,147,483,648 to 2,147,483,467 0
long Long integer signed 64-bit integer (64-bit two's complement)
-(263) to 263-1 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0l
Real Numbers
float Single-precision floating point signed 32-bit floating-point (32-bit IEEE 754)
NEGATIVE_INFINITY to POSITIVE_INFINITY Can also have the value NaN (Not a number) 0.0f
double Double-precision floating point signed 64-bit floating-point (32-bit IEEE 754) NEGATIVE_INFINITY to POSITIVE_INFINITY Can also have the value NaN (Not a number) 0.0d
char A single character 16-bit Unicode 2.0 character 0 to 216-1 0 to 65,535 \0000
boolean A boolean value (true or false) n/a true or false n/a false

  • arithmetic with floating-point numbers will never throw an exception; instead one of the constant values: NEGATIVE_INFINITY, POSITIVE_INFINITY, or NaN are returned.
  • by default integer values are of type int and floating-point values are of type double

You can put a literal primitive value directly in your code. The following table gives some examples of literal values for various primitive types:

Examples of Literal Values
Literal Value Data Type
178 int
8864L long
37.266 double
37.266D double
87.363F float
26.77e3 double
'c' char
true boolean
false boolean

Integer Literals (Decimal Literals, Octal Literals, Hexadecimal Literals)

The literal values of these integer types are written using positive or negative decimal, hexadecimal, or octal integers. Hexadecimal values are preceded by 0x or 0X and use the letters a through f (uppercase or lowercase) to represent the digits 10 through 15. Octal numbers are preceded by 0. All three integer literal (decimal, hexadecimal, octal) are defined as int by default, but you can specify a long integer by putting an 'L' or 'l' after the number. The following table gives some examples of  conversion between decimal, hexadecimal, and octal values:

Decimal Value

Hexadecimal Value

Octal Value

Code Example




class LiteralValueExample {
    public static void main(String[] args) {
        int     x = 14;
        int     x1 = 0X0el;
        int     x2 = 016;
        long  y = 123l, y1  = 0x7bL, y2 = 0173;
        System.out.println("x = " + x + "   x1 = " + x1 + "   x2 = " + x2);
        System.out.println("y = " + y + "   y1 = " + y1  + "  y2 = " + y2);







Foalting-Point Literals

A series of digits with a decimal point is of type double. The float and double types represent 32- and 64-bit IEEE 754 floating-point numbers. Float numbers have the f or F suffix. Double numbers have d or D. If no suffix is provided, the default double type is assumed. Floating-point numbers can be written using any of the following forms:


    Digits.Digitsopt ExponentPartopt FloatTypeSuffixopt

    .Digits ExponentPartopt FloatTypeSuffixopt

    Digits ExponentPart FloatTypeSuffixopt

    Digits ExponentPartopt FloatTypeSuffix

    ExponentPart: ExponentIndicator SignedInteger

    ExponentIndicator: one of e and E

    SignedInteger: Signopt Digits

    Sign: one of
    + -

    FloatTypeSuffix: one of
    f, F, d, and D

The elements of the types float and double are those values that can be represented using the IEEE 754 32-bit single-precision and 64-bit double-precision binary floating-point formats, respectively.

For exampl:  The largest positive finite float literal is 3.40282347e+38f. The smallest positive finite nonzero literal of type float is 1.40239846e-45f. The largest positive finite double literal is 1.79769313486231570e+308. The smallest positive finite nonzero literal of type double is 4.94065645841246544e-324.

Character Literals

A literal character value is any single Unicode character between single quote marks. You can also type in the Unicode value of the character (hexadecimal values), using the Unicode notation of prefixing the value with \u. For example the following are the same defined the letter 'A' in the defferent form:

    char  ch = 'A';
    char  ch1 = '\u0041';

Character literals can also be some special characters that require the use of the escape character:
Esc Char Unicode Char Definition
\n \u000A newline
\t \u0009 tab
\b \u0008 backspace
\r \u000D return
\f \u000C form feed
\ddd   octal value -- Octal character constants can have three digits or less (\000 through \377)
Other special cases:
signle quote  (display as ')
double quote (display as ")
backslash (dispaly as \)

Boolean Literals

The two boolean literals are simply true and false. They are case sensitive.

String Literals

String literals are represented as a sequence of characters enclosed in double quotes. Character escape codes (such as '\r', '\n', and so on) can be used in String literals.

Declaring Primitive Data Type Variable

Primitive variables can be declared as class variables (statics), instance variables, method parameters, or local variables.

  class someClass {

      // Instance Variable
      field_modifier variable_type instanceVariableName;

      // Class Variable
      field_modifier static variable_type classVariableName;

      returnType someMethod() {

         // Local Variable
         localvariable_modifier variable_type localVariableName;

Class Variables

Sometimes you want to create a variables whose value is shared by all instances of a class. Such a variable is known as a class variable aslo known as static variable. There is always only one copy of a class variable, regardless of the number of object instances that are created from that class. If one object instance of that class changes the value of a class variable then all the other instances see the same changed value. You access a class variable directly though the class, and not thourgh an object instance.

Both instance variables and class variables are declared inside a class body but outside of any method bodies. A class variable MUST have the keyword static as the modifier within a class declaration.The exception is for an interface declaration, class variables can be declared with or without the keyword static within an interface declaration. Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields (see more detail here).  You access a class variable by specifying the name of the class, followed by a dot, followed by the name of the variable.  For example;

class ClassVariables {
    static int x = 5;
    static int x1;
    public static void main(String[] args) {
        System.out.println("x = " + x + "    x1 = " + x1);

Class variables are in scope from the point the class is loaded into the JVM until the the class is unloaded. Class are loaded into the JVM the first time the class is referenced: often when the first object of that class in instantiated with the new operator. They are the most long-lived kind of variable and come the closest to being a global variable.

Class variables can be initialized by an assignment statement; for example "x = 5;". You also can assign a value when you declare the class variable. Unassigned declaration of a class variable will get the default value, except the class variable has "static final" modifiers which must be assigned a value at the declaration time and can not change its value.


  • Static variables are NOT serialized;
  • Static variables get the same DEFAULT values instance variables get;
  • Variables and methods marked static belong to the class who declares them, not associate with any particular instance of that class;
  • Static method can access static variables and can't access instance variables.

Instance Variables

Instance variables are any variables, without "static" field modifier, that are defined within the class body and outside any class's methods body.  Instance variables are in scope as long as their enclosing object is in scope. An instance variable is a part of the object that contains it and cannot live independently of it. Instance variables can be used by all methods of a class. All object instances have their own copies of instance variables. Each object instance has its own copy of an instance variable, each object instance can assign a unique value to an instance variable without modifying the values of other copies of the instance variable. You access instance variables directly from their containing object instances.

Local Variables

Local variables have the most limited scope. They are only valid from the line they are declared on until the closing curly brace of the method or code block within which they are declared. The local variable's scope is only that method, this means that the local variable can be used only within the method in which it was created.

  • Every local variable declaration statement is immediately contained by a block ({ ... }). Local variable declaration statements may be intermixed freely with other kinds of statements in the block.
  • A local variable declaration can also appear in the header of a for statement. In this case it is executed in the same manner as if it were part of a local variable declaration statement.
  • Local variables declaration have one and only one final modifer can be used.

The scope of a variable determines where it can be used. Syntactically, scope of any variable is the code between the curly braces of where it is declared.

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |