Variables in Java with Examples

A variable is a name assigned to a memory to allocate space for storing a data value in a program. Each variable in Java is of a specific type.

Java is a statically-typed programming language, meaning that a variable must always be declared before it is used. Declaring of a variable involves stating the variable's type and name.

Example of variables:

String name;
byte diceNumber;
short age;
int rollNumber;
float fee;
double amount;

In the above example, name, diceNumber, age, rollNumber, fee, and amount are variables while String, byte, short, int, float, and double are their data types.

A variable can also be declared with access modifiers. For example:

public String name;
private int age;

Here, public and private are access modifiers.

Types of Variables in Java

Variables in Java are of three types:

  1. Instance variable
  2. Static/Class variable
  3. Local variable

Instance variable

An Instance variable is a variable that is declared inside a class and outside of any method and constructor. An instance variable is declared without the static keyword, therefore it is also called non-static variable. The instance variables are visible to all methods, constructors, and blocks in the class where they are declared.

An instance variable can only be called through objects.

The following code shows instance variables:

public class Student {
    /* Declaring instance variables or non-static variables
    *with private access visibility */

    private String name;
    private int rollNumber;

Static/Class variable

A static variable is declared with the static keyword. Static variables are also called Class variables. A static variable is declared inside a class but outside of any constructor and method.

Static variables are usually used for declaring constants. Constants are variables with a fixed value. Constants value cannot be changed after it has been assigned.

Static variables belong to class and not objects. Therefore we do not need any object to access static variables in Java. Generally, public variables can be accessed from everywhere, and private variables can only be accessed from within the class where it is declared.

A static variable is initialized only once and only a single copy of such variable is created and shared at class level, however many times it is called in a program.

In Java, static variables are declared using the uppercase letters. For example:

public class Student {

   public static String NAME_CODE = "abc";
   private static int STREET_NO = 11;

To access static variables in another class, all we need to do is use the name of the class followed by a dot (.) and the name of the static variable.

Here is an example of how we can access the static variable of one class in another class. However, it's important to note that if the static variable in a class has the private modifier, it won't be accessible from other classes.

public class School {

    public void printStudentDetail() {

    /* We do not have to create an object of Student class for
     * accessing static variables. We use a reference of class Student
     * followed by a dot and static variable. */
    String studentName = Student.NAME;

    //Printing student's name in console
    System.out.println("Student's name is " + studentName);


Local variable

A local variable is declared within the body of a method, constructors or blocks. We can use the local variable only within that method where it is declared. Other methods in the same class aren’t even aware that the variable of one method exists.

A default value is never assigned to an uninitialized local variable by the compiler. Therefore, a local variable must always be assigned a value before it is used otherwise accessing an uninitialized local variable will result in a compile-time error.

In the example below, name variable is local variable:

public class Actor {

public static void main(String[] args) {
    //Declaring local variable.
    String name = "abc";

    //Printing local variable in console.
    System.out.println("Actor's name is " + name);

We can also declare local variables within blocks of code marked by braces. 

The example below demonstrates declaring of local variables within blocks of code marked by braces:

public class Employee {

    public static void main(String[] args) {

        //Declaring local variables
        double salary = 1000;
        double totalSalary = 0;

        if(salary == 1000) {
           //Declaring local variable within blocks of code.
           double bonusAmount = 5000;
           totalSalary = salary + bonusAmount

        //Printing local variable
        System.out.println("Total salary is " + totalSalary);

The output of the above code is as follows:

Total salary is 6000.0

Variable Naming Conventions

The best variable naming convention is to choose a variable name that will tell the reader what the variable is for and what the variable is representing in the program. For example: if you wish to store a roll number on Student, a variable name such as rollNo would be easier to remember than a variable name such as var2.

There are rules and conventions related to the naming of variables in Java. The rules are:

  • Java variable names are case sensitive. The variable name hello is not the same as Hello or HELLO.
  • Java variable names must start with a letter or underscore _ or a dollar sign $ character. After the first character in a variable name, the name can also contain numbers from 0 to 9 (in addition to letters, the dollar sign $, and the underscore _ character). No special characters are allowed.
  • We cannot use reserved keywords as variables name in Java. For example: the words String or while are reserved words in Java. Therefore, you cannot String or while as a variable name.
  • All uppercase letters are used to identify constant variables.

Here are some examples of valid and invalid variable names:

Valid Variable Names
Invalid Variable Names