Variables in Java

In the Java programming language, the terms “field” and “variable” are both used; this is a common source of confusion among new developers since both often seem to refer to the same thing. The Java programming language defines the following kinds of variables:

Instance Variables (Non-Static Fields): Technically speaking, objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the rollno of one Student is independent of the rollno of another.

Class Variables (Static Fields): A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the name of the principal for a particular class of students could be marked as static since conceptually the name of the principal will be the same for all students in a college. The code static String namePrincipal = “Dr. Krishna Kaushal”; would create such a static field. A static field need not be final, but the keyword final could be added to indicate that the value of the field will never change.

Local Variables: Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count=0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared – which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible to the rest of the class.

Final Variables: A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. (In this usage, final is similar to const in C/C++/C#). For example:

final int NEW = 1;
final int OPEN = 2;
final int SAVE = 3;
final int QUIT = 4;

Subsequent parts of your program can now use NEW, OPEN, etc., as if they were constants, without fear that a value has been changed. It is a common coding convention to choose all uppercase identifiers for final variables. Variables declared as final do not occupy memory on a per-instance basis.

Thus, a final variable is essentially a constant. The keyword final can also be applied to methods, but its meaning is substantially different than when it is applied to variables. This second usage of final is described when inheritance is described.

Parameters: You’ve already seen examples of parameters, in the main method of the MainMethod class. Recall that the signature for the main method is public static void main(String args[]). Here, the args variable is the parameter of this method. The important thing to remember is that parameters are always classified as “variables” not “fields”. This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you’ll learn later in this tutorial.

Naming variables

Every programming language has its own set of rules and conventions for the kinds of names that you’re allowed to use, and the Java programming language is not different. The rules and conventions for naming your variables can be summarized as follows:

  1. Variable names are case-sensitive. A variable’s name can be any legal identifier – an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign “$”, or the underscore character “_”. The convention, however, is to always begin your variable names with a letter, not “$” or “_”. Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore characters; while it’s technically legal to begin your variable’s name with “_”, this practice is discouraged. White space is not permitted.
  2. Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases, it will also make your code self-documenting; fields named name, rollno, and totalmarks, for example, are much more intuitive than abbreviated versions, such as n, r, and tm,
  3. Keywords or reserved words can not be used as variable names.
  4. Other naming conventions are:
    1. Variable names of field name are written only in lowercase letters. For example, rollno, nameofstudent, totalmarks etc.
    2. Methods name are written in lowercase letters but if, it consists of more than one word, capitalize the first letter of each subsequent word. For example addData(), enterRollNo(), calculateTotalMarks() etc.
    3. Class names start with a capital letter and the first letter of each subsequent word is capitalized. For example Student, PrimeNumber, Bank Account, etc.
    4. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

You should ensure that you use meaningful names for your variables. The reasons for this are:

  • Meaningful names for variables are self-documenting (see what they do at a glance)
  • They are easier to understand
  • There is no correlation with the amount of space used in the .class file
  • Makes programs easier to read

Question: Why are the variables in the following list invalid? Give Reasons, value$sum, exit flag, 3lotsofmoney, char

Answer: ‘value$sum’ is a valid variable name and can be used in the program, ‘exit flag’ is an invalid name since it contains white space. ‘3lotsofmoney’ is an invalid name because it starts with a digit. ‘char’ is an invalid name since it is a keyword.

Declaration and Initialization of Variables

We must declare the type of variables used in the program. It must be done before their use in the program. The syntax of a variable declaration is:

<data-type>  <variable-namel>[,<variable-name2>,….];

This statement tells the compiler about the name of variables, which type of data can be stored in the variables, how much memory space to allocate, and the range of values that can be assigned to the variables.


int count, number, rollno;

The statement above declares three variables named count, number, and rollno. These variables can store integer type values from -2147483648 to +2147483647 and the compiler will allocate 4 bytes of memory to each variable. Similarly, we can declare variables of different types by using data types such as float, long and double, etc,

A variable must be initialized to a suitable value before its use otherwise compiler will not compile the program and generate an error message. The initialization can be done at declaration time or at the place of use after declaration. The explicit initialization of local variables is a must while fields are initialized to default values automatically if not initialized.

Initializing Variables at Declaration Time

In JAVA variables may be initialized with a value when they are declared. Consider the following declaration, which declares an integer variable count which is initialized to 10.

int count 10;  //Declaration & initialization together

Initializing Variables After Declaration

It is also possible to assign the value at any time to a variable after it is declared. For example, consider the following program segment

int count;  // Declaration of variable without initialization
count = 10:  // Initialization

Initializing Variables with Octal And Hexadecimal

Often, when writing systems programs, the programmer needs to use a different number base rather than the default decimal.

Integer constants can be initialized with octal or hexadecimal values by using the associated prefix, e.g., to define an integer as an octal constant use 0 (zero)

int sum = 0567;

To define an integer as a hex constant use 0x (zero followed by x or X)

int sum = 0x7ab4;
int flag = 0x7AB4;  /* Note upper or lowercase hex ok */

Dynamic Initializations

Dynamic initialization means the initialization of variables at execution time. In Java, variables can be initialized at the declaration time as well as after the declaration. Initialization at declaration time is sometimes known as static initialization. For example:

int a = 5;
float b = 23.45;

are static initializations.

Dynamic initialization can be achieved in many ways in Java.

Dynamic initialization through expression: The simplest way to achieve dynamic initialization is through the use of expression on the right-hand side of the assignment statement. Since this expression is evaluated at execution time so variable on the left-hand side will get its value after the expression is evaluated. For Example

int z=x+y%3;

Here x and y are int variables and declared and initialized before this expression. The variable z will get its value after the expression on the right-hand side is evaluated at execution time.

Dynamic Initialization through constructor: Since constructors are special methods. which are executed when objects of the class are declared and are used to initialize the member variables of the class so they initialize the member variables at execution time.


class InitialDemo
    int a;  // variable declared not initialized
    int b;  // variable declared not initialized
    InitialDemo()  // constructor
        a = 0;  // Initialize a to 0
        b = 0;  // Initialize b to 0
    InitialDemo(int x, int y)
        a = x;  // initialize a to the value of x
        b = y;  // initialize b to the value of y

Since these constructors will be executed when the object of the Initial Demo class is created in the main method the initialization will take place dynamically.

Dynamic initialization through user input: Variables can be initialized by taking input from the user. Since the user will enter the input when the input statement is executed so the variable will get its value dynamically at execution time. For example:

import java.io.*;
class InitialDemo2
    public static void main(String str[])
            DataInputStream dt = new DataInputStream(System.in);
            System.out.print("Enter your age = ");
            String st = dt.readLine();  // variable st is initialized
            int age = Integer.parseInt(st);
            age = age + 10;
            System.out.println("My Age after 10 years = " + age);
        catch(IOException ie){

Life Time of Variable

The lifetime of a variable refers to the time span from its creation to death. Variable is created by using a declaration statement. That is a variable that comes to life when it is declared. The death of the variable occurs when it falls out of scope.

Java does not support the concept of global variables that were extensively used in C and C++. In addition to local variables, to affect the life of variable Java support different categories of variables. These are instance variables, class variables, and parameters as discussed above.

Leave a Reply