Variables in Java – Explore its Types with Syntax and Examples!

Today, in this tutorial we will get to know about the role of Variables in Java and also we will have a look at the types of Java Variables along with some examples that will further help you to write your programs easily. So let’s start with what Java Variables are all about.

Variables in Java

A variable is a named memory location that holds the data value of a particular data type. A variable in Java is a kind of container that contains the value during program execution.

Variable is a basic unit of storage in a program that represents reserved storage locations, whose values can be manipulated during the execution of a program. We assign a variable with a datatype.

As the name itself suggests, the word variable can be broken down into 2 words- “vary” + “able”, which means the value of variables can change.

  • Variables are also called symbolic variables because they are named.
  • A variable is a memory area, and this memory location gets affected when any manipulation or operation is done on the variables.
  • In Java, we should declare all the variables before using them.
  • Each variable has a specific data type, which determines its memory and the type of data that it can store.
  • Variables are typically used to store information ranging from text, codes (e.g. state code, city code, etc.) to numbers, temporary results of complex calculations, etc.

Example:

For instance, the following statement declares a variable country_code of type int-

int country_code ;

Hold On! Before learning further, it is necessary for you to first learn about Data types in Java.

Declaration of a Variable

To declare the variable, we must specify the data type followed by the unique name of the variable.

Syntax:

The declaration of a variable generally takes the following syntax:

dataType variableName ;

Where dataType is a type-specifier which is any Java data type and variableName is the unique name of a variable. A variable name is an identifier, thus all the naming conventions/rules of an identifier must be applied for naming a variable.

Example:

double payRate ;

Here, payRate is a variable of double data type.

Some other variable declarations are –

float area ;
char grade ;
String sentence ;

When more than one variable of the same data type needs to be defined, we use a type specifier followed by a comma-separated list of variables.

Example:

double salary, wage, portNumber ;
int month, day, year ;
long length, radius ;

Note: While naming the variables, make sure to follow the naming conventions and rules of identifiers which are as follows:

1. The variable names cannot contain white spaces, for example, long dist ance = 1000; is invalid because the variable name has a space in it.

2. A variable name can begin with a special character dollar ($) and underscore ( _ ).

3. The first letter of a variable cannot be a digit.

4. A variable name should begin with a lowercase letter, for example, int number. For lengthy variable names having more than one word, we can use camelCase, for example, int salaryPerDay; float rateOfInterest; ,etc. are valid.

5. We cannot use keywords like int, for, while, class, etc as a variable name.

6. Variable names are case-sensitive in Java.

Initialization of a Variable

We have already discussed how to declare a variable. But this does not provide the initial value to the variable that is, the variable remains uninitialized. Now we will discuss how to initialize a variable that is providing a value to a variable.

Syntax:

We can assign a value to a variable by the following syntax:

variableName = value ;

Example:

payRate = 2500;

Combining the declaration and initialization, we can write-

dataType variableName = value ;

Example:

double area = 378.87 ;

The following diagram illustrates the variable declaration and its memory allocation:

java-variable-declaration-&-its-memory-allocation

Code Snippet:

public class VariableTutorial
{
  public static void main(String args[])
  {
    // Declaring and initializing the variables
    long hoursWorked = 50;
    double payRate = 40.0, taxRate = 0.10, taxPayable;
    System.out.println("Hours Worked: " +hoursWorked);
    // Performing operations on variables
    System.out.println("Payment Amount: " + (hoursWorked * payRate));
    taxPayable = hoursWorked * payRate * taxRate;
    System.out.println("Tax Payable: " +taxPayable);
  }
}

Output:

Hours Worked: 50
Payment Amount: 2000.0
Tax Payable: 200.0

Initial Values of Variables

There is no default value for local variables, so we have to assign a value to a local variable before its first use. However, each class variable, instance variable or array component is initialized with a default value when it is created:

Type Initial/Default value
byte 0(Zero) of byte type
short 0(Zero) of byte type
int 0
long 0L
float 0.0F
double 0.0D
char null character i.e., ‘\u0000’
boolean false
All reference types null

Code to understand the concept of default values of class or instance variables:

public class DefaultValues
{
  //declaring Primitive types
  byte byteNum;
  short shortNum;
  int intNum;
  long longNum;
  float floatNum;
  double doubleNum;
  char charValue;
  boolean flag;
  DefaultValues object1;
  //declaring Reference types
  String mySentence;
  public void getDefaultValues()
  {
    System.out.println("The Default value of byte is: " +byteNum);
    System.out.println("The Default value of short is: " +shortNum);
    System.out.println("The Default value of Int is: " +intNum);
    System.out.println("The Default value of long is: " +longNum);
    System.out.println("The Default value of float is: " +floatNum);
    System.out.println("The Default value of double is: " +doubleNum);
    System.out.println("The Default value of char is: " +charValue);
    System.out.println("The Default value of boolean is: " +flag);
    System.out.println("The Default value of String is: " +mySentence);
    System.out.println("The Default value of Object is: " +object1);

  }
  public static void main(String args[])
  {
    DefaultValues object = new DefaultValues();
    object.getDefaultValues();
  }
}

Output:

The Default value of byte is: 0
The Default value of short is: 0
The Default value of Int is: 0
The Default value of long is: 0
The Default value of float is: 0.0
The Default value of double is: 0.0
The Default value of char is:
The Default value of boolean is: false
The Default value of String is: null
The Default value of Object is: null

Types of Java Variables

Java allows the variables to be declared at any place or within any block. That is, in Java, we can declare the variables at many places, we can declare them either at the start of the program or inside any classes, method/functions or inside the main method.

Scope determines which variables are visible to other parts of your program and also what is the lifetime of those variables. Depending upon the scope, visibility, and access to the variables, they can be classified under 3 categories.

The 3 types of variables in Java are –

  1. Local Variables
  2. Instance Variables
  3. Static Variables

types-of-variables-in-java

1. Local Variables in Java

A local variable in Java is a variable that we declare inside a body of a method, block or a constructor. We can use the local variable only within that method and the other methods of the class are unaware of the existence of this variable.

A block starts with an opening curly brace and ends with a closing curly brace. The scope of a local variable is restricted to a particular block. Its lifetime is within the parenthesis in which it is declared.

That is, it is created when a function is called or a block is entered and gets destroyed once it exits that method, block or constructor.

  • We cannot define the local variables as static”. We can use the “final” keyword before a local variable.
  • The scope and access of these variables exist only inside the block in which we declare them.
  • We cannot use access modifiers for the local variables.
  • Internally, a stack implementation is used to implement the local variables.
  • Initialization of Local Variable is necessary – there is no default value for local variables, so we should declare a local variable and assign it with an initial value before its first use.
  • If we do not initialize the value of a local variable, then we will get a Compile Time Error.

Declaration of a Local Variable

Every local variable is declared within a block { … }. We can also declare local variables in the header of a “for” statement.

Example:

for(int i = 10 ;i >= 1; i--)
        {
                  // Body of for loop
        }

In the above example, int i = 10 is a declaration of a local variable i. Its scope is only limited to the “for” loop.

Syntax of a Local Variable:

class ClassName
{
       methodName(){
             <DataType> localVariableName;
             localVariableName = value;
             }
}

Here, methodname is the name of the method, DataType refers to the data type of local variables like int, float, long, double, etc and localVariableName is the name of the local variable and value is the initial value of the local variable.

Example:

double area()
    {
   	int length=10; //local variable
   	int breadth = 5; //local variable
   	double areaOfRectangle = length * breadth; //local variable
   	return areaOfRectangle;
    } // scope of all local variables ends here.

Code Snippet 1:

public class EmployeeSalary
{
  public void getSalary()
  {
      long salary = 30000; //declaring a local variable
  }
  public static void main(String args[])
  {
      System.out.println("Salary of the Employee is: " +salary);
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
salary cannot be resolved to a variable
at EmployeeSalary.main(EmployeeSalary.java:10)

Reason for error: Accessing local variable “salary” outside its scope(function getSalary()) gives an error.

Code Snippet 2:

public class EmployeeSalary
{
  public void getSalary()
  {
    //declaring a local variable
    long salary;
    //declaring and initializing local variables
    int workingDaysInAMonth = 25, salaryPerDay = 1000; salary = workingDaysInAMonth * salaryPerDay ;
    System.out.println("Salary of the Employee is: " +salary);
  }
  public static void main(String args[])
  {
      EmployeeSalary employee = new EmployeeSalary();
      //accessing local variable by calling method in which it is present
      employee.getSalary();
  }
}

Output:

Salary of the Employee is: 25000

2. Instance Variables in Java

A variable that is declared inside the class but outside any method, constructor or block body is called an instance variable. An instance variable is a non-static variable that is, we can not declare it as static.

It is called an instance variable because its value is instance-specific (related to objects) and is not shared with other instances/objects as each object of the class has its own set of values for these non-static variables.

  • As we declare an instance variable in a class, these variables are created when an object of the class is created with the use of a “new” keyword and destroyed when the object is destroyed.
  • We can access instance variables only by creating objects. Also, we can use these variables using the “this” pointer inside the same class.
  • We can also declare instance variables with access specifiers (private, public or default). If we do not explicitly set any access specifier for the instance variables then Java assumes them as default access specifiers.
  • It is not necessary to initialize an instance variable. If we do not initialize it with a value, it gets a default value. We have already discussed the list of the default values of instance variables in the introductory part of the variables, in this article.
  • Heap Allocation is used to store the instance variables and a slot of memory is created for each instance variable value. Each object has its own copy of the instance variables that is, these variables cannot be shared among objects.
  • The instance variables are visible to all methods, constructors, and blocks in the class. Normally, it is recommended that we should declare the instance with a “private” access specifier.

Declaration of an instance variable

We can declare instance variables inside a class. We can also declare them outside a method, block or constructor.

Syntax of an Instance Variable:

class ClassName
{
       <DataType> instanceVariableName;
       instanceVariableName = value;
       // class body
}

Example:

Class AreaofShapes
{
  //These are instance variables, present inside the class
   		double rectangleArea;
   		double squareArea;
   		double circleArea;
}

Code Snippet:

public class AreaOfShapes
{
  //Declaring instance variables
  double breadth;
  double length;
  double areaOfRectangle;
  double areaOfSquare;

  public static void main(String args[])
  {
      //Creating First Object area1
      AreaOfShapes area1 = new AreaOfShapes();
      //Accessing instance variables through the first object
      area1.length = 50;
      area1.breadth = 25;
      area1.areaOfRectangle= area1.length * area1.breadth;

      //Displaying details for first object
      System.out.println("Details from the first object-");
      System.out.println("Length of Rectangle: " +area1.length);
      System.out.println("Breadth of Rectangle: " +area1.breadth);
      System.out.println("Area of Rectangle: " +area1.areaOfRectangle);

      //Creating second Object area2
      AreaOfShapes area2 = new AreaOfShapes();
      //Accessing instance variables through the second object
      area2.length = 75.5;
      area2.breadth = 68;
      area2.areaOfRectangle= area2.length * area2.breadth;

      //Displaying details for the second object
      System.out.println("\nDetails from the second object-");
      System.out.println("Length of Rectangle: " +area2.length);
      System.out.println("Breadth of Rectangle: " +area2.breadth);
      System.out.println("Area of Rectangle: " +area2.areaOfRectangle);
  }
}

Output:

Details from the first object-
Length of Rectangle: 50.0
Breadth of Rectangle: 25.0
Area of Rectangle: 1250.0Details from the second object-
Length of Rectangle: 75.5
Breadth of Rectangle: 68.0
Area of Rectangle: 5134.0

From the above program, it is clear that each instance (object) of the class has its own copy of the instance variable.

We changed the value of instance variables using the object “area2” in the program but there was no effect or change in the values of the other object “area1”. This shows that objects have their own (separate) copy of the instance variable.

3. Static Variables in Java

A variable that is declared inside a class but not inside the method, constructor or a block, with the static keyword is called static or class variable.

Static variables are also called class variables because they are associated with the class and are common for all the instances of the class. That is, one copy of the static variable is shared among all objects of the class.

For example, if we create multiple objects of a class and access the static variable using objects, it will be common for all, that is, the changes made to the variable using one of the objects would reflect when we access it through the other objects of the class.

  • Static variables are created at the start of program execution and get destroyed automatically after the execution of the program.
  • Unlike instance variables, there is only one copy of a static variable per class, irrespective of the number of objects we create from the class.
  • The initialization of static variables is not mandatory. If we do not initialize it with a value, it gets a default value similar to the instance variables.
  • Static variables can be declared as public/private, final, and static. These variables are the constant variables that never change from their initial values.
  • Static memory allocation is very helpful to store the static/class variables.
  • We can access the static variables by calling it with the class name, that is ClassName.variableName. We can also directly access the static variables inside static methods and static blocks.
  • The visibility of the static variable is similar to instance variables. However, we mostly declare the static variables as public, since they must be available for all objects of the class.
  • The values of static variables can also be assigned during the declaration or within the constructor. Also, we can assign the values in special static initializer blocks.

Note:

  • If we try to access the static variable through an object, the compiler will show the warning message but will not halt the program. The compiler will automatically replace the object name with the class name.
  • If we access the static variable without the class name, the compiler will automatically add the class name.

Syntax of a Static Variable:

class ClassName{
static <DataType> <variable_name>;
}

Example:

class MyClass{
static int number; //number is a static variable
}

Code Snippet:

public class Student
{
  //Declaring static variables inside the class
  public static int marks;
  public static String studentName = "John";

  public static void main(String args[])
  {
    //accessing static variable without creating object
    Student.marks = 80;
    System.out.println("The marks of student "+Student.studentName +"are:     "+Student.marks);

    //creating 3 objects of the class
    Student student1 = new Student();
    Student student2 = new Student();
    Student student3 = new Student();

    //Accessing the statc variable through objects
    System.out.println(student1.studentName);
    System.out.println(student2.studentName);
    System.out.println(student3.studentName);

    //We can directly access the static variable like this
    System.out.println(marks);

    //changing the value of the static variable by 1 object
    student1.studentName= "Sam";

    // change made by one object is reflected to all other objects
    System.out.println(student1.studentName);
    System.out.println(student2.studentName);
    System.out.println(student3.studentName);
  }
}

Output:

The marks of student John are: 80
John
John
John
80
Sam
Sam
Sam

As we can see, all three objects (student1, student2, student3) displays the same output irrespective of the object (student1) through which it has been accessed. This is the reason why we can access the static variables directly without using objects like this:

System.out.println(static_Variable_Name);

Do note that only static variables can be accessed like this. We cannot access the instance and local variables like this!!

Summary

Here we came to the end of our blog on Java Variables. Now you know that variables in Java play an extremely important role in programming. They are very useful for writing programs.

In this article, we have discussed the Java variables and their types in detail along with their respective examples, syntax and logical codes so that you can easily understand them. Now, you can use these Java variables in your programs flexibly.

If you have any queries, do let us know with the help of the comment section below.