Open In App

Java Variables

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated.

Key Components of Variables in Java:

A variable in Java has three components, which are listed below:

  • Data Type: Defines the kind of data stored (e.g., int, String, float).
  • Variable Name: A unique identifier following Java naming rules.
  • Value: The actual data assigned to the variable.

Note: There are three types of variables in Java: Local, Instance, and a .

Example of variable declaration:

int age = 25; // Integer variable

String name = “Java”; // String variable

double salary = 50000.50; // Double variable

How to Declare Java Variables?

The image below demonstrates how we can declare a variable in Java:

Variables in Java

 


From the image, it can be easily perceived that while declaring a variable, we need to take care of two things that are:

  1. data type: In Java, a data type define the type of data that a variable can hold. 
  2. variable name: Must follow Java naming conventions (e.g., camelCase).

In this way, a name can only be given to a memory location. It can be assigned values in two ways: 

  • Variable Initialization
  • Assigning value by taking input

How to Initialize Java Variables?

It can be perceived with the help of 3 components explained above:

Java Variables Syntax

 


Example: 

// Declaring float variable

float simpleInterest;

// Declaring and initializing integer variable

int time = 10, speed = 20;

// Declaring and initializing character variable

char var = ‘h’;


Types of Java Variables

Now let us discuss different types of variables  which are listed as follows: 

  • Local Variables
  • Instance Variables
  • Static Variables
Types of Variables in Java


Let us discuss the traits of every type of variable listed here in detail.

1. Local Variables 

A variable defined within a block or method or constructor is called a local variable. 

  • The Local variable is created at the time of declaration and destroyed when the function completed its execution.
  • The scope of local variables exists only within the block in which they are declared.
  • We first need to initialize a local variable before using it within its scope.

Example: This example show how a local variable is declared and used inside the main method and it can not be used outside of it.

Java
// Java Program to show the use of local variables
import java.io.*;

class Geeks {
    public static void main(String[] args)
    {
        // Declared a Local Variable
        int var = 10;

        // This variable is local to this main method only
        System.out.println("Local Variable: " + var);
    }
}

Output
Local Variable: 10


Example: This example demonstrates that local variables are only accessible within the block in which they are declared

Java
// Java Program to show the use of 
// Local Variables
import java.io.*;

public class Geeks {
    
    public static void main(String[] args)
    {
        // x is a local variable
        int x = 10;

        // message is also a local
        // variable
        String message = "Hello, world!";

        System.out.println("x = " + x);
        System.out.println("message = " + message);

        if (x > 5) {
            // result is a
            // local variable
            String result = "x is greater than 5";
            System.out.println(result);
        }

        // Uncommenting the line below will result in a
        // compile-time error System.out.println(result);
        for (int i = 0; i < 3; i++) {
            String loopMessage
                = "Iteration "
                  + i; // loopMessage is a local variable
            System.out.println(loopMessage);
        }

        // Uncommenting the line below will result in a
        // compile-time error
        // System.out.println(loopMessage);
    }
}

Output
x = 10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2


2. Instance Variables

Instance variables are known as non-static variables and are declared in a class outside of any method, constructor, or block. 

  • Instance variables are created when an object of the class is created and destroyed when the object is destroyed.
  • Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier, then the default access specifier will be used.
  • Initialization of an instance variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
  • Scope of instance variables are throughout the class except the static contexts.
  • Instance variables can be accessed only by creating objects.
  • We initialize instance variables using constructors while creating an object. We can also use instance blocks to initialize the instance variables.

Example: This example demonstrates the use of instance variables, which are declared within a class and initialized via a constructor, with default values for uninitialized primitive types.

Java
// Java Program to show the use of
// Instance Variables
import java.io.*;

class Geeks {

    // Declared Instance Variable
    public String geek;
    public int i;
    public Integer I;
    public Geeks()
    {
        // Default Constructor
        // initializing Instance Variable
        this.geek = "Sweta Dash";
    }

    // Main Method
    public static void main(String[] args)
    {
        // Object Creation
        Geeks name = new Geeks();

        // Displaying O/P
        System.out.println("Geek name is: " + name.geek);
        System.out.println("Default value for int is "+ name.i);
      
        // toString() called internally
        System.out.println("Default value for Integer is: "+ name.I);
    }
}

Output
Geek name is: Sweta Dash
Default value for int is 0
Default value for Integer is: null


3. Static Variables

Static variables are also known as class variables. 

  • These variables are declared similarly to instance variables. The difference is that static variables are declared using the static keyword within a class outside of any method, constructor, or block.
  • Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how many objects we create.
  • Static variables are created at the start of program execution and destroyed automatically when execution ends.
  • Initialization of a static variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
  • If we access a static variable like an instance variable (through an object), the compiler will show a warning message, which won’t halt the program. The compiler will replace the object name with the class name automatically.
  • If we access a static variable without the class name, the compiler will automatically append the class name. But for accessing the static variable of a different class, we must mention the class name as 2 different classes might have a static variable with the same name.
  • Static variables cannot be declared locally inside an instance method.
  • Static blocks can be used to initialize static variables.

Example: This example demonstrates the use of static variables, which belong to the class and can be accessed without creating an object of the class.

Java
// Java Program to show the use of
// Static variables
import java.io.*;

class Geeks {
    
    // Declared static variable
    public static String geek = "Sweta Dash";
  
    public static void main(String[] args)
    {

        // geek variable can be accessed without object
        // creation Displaying O/P Geeks.geek --> using the
        // static variable
        System.out.println("Geek Name is: " + Geeks.geek);

        // static int c = 0;
        // above line, when uncommented,
        // will throw an error as static variables cannot be
        // declared locally.
    }
}

Output
Geek Name is: Sweta Dash


Instance Variables vs Static Variables

Now let us discuss the differences between the Instance variables and the Static variables:

  • Each object will have its own copy of an instance variable, whereas we can only have one copy of a static variable per class, irrespective of how many objects we create. Thus, static variables are good for memory management.
  • Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of the instance variable. In the case of a static variable, changes will be reflected in other objects as static variables are common to all objects of a class.
  • We can access instance variables through object references, and static variables can be accessed directly using the class name.
  • Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed. Static variables are created when the program starts and destroyed when the program stops.

Syntax: Static and instance variables

class Geeks

{

// Static variable

static int a;

// Instance variable

int b;

}

Common Mistakes to Avoid

The common mistakes that can occur when working with variables in Java are listed below:

  • Using uninitialized local variables: Accessing a local variable without initializing it leads to a compile-time error.
  • Confusing == and .equals() for Strings: == is used to compare object references, while .equals() is used to compare the content of the strings.
  • Modifying static variables incorrectly: Changing static variables in a multi-threaded environment can lead to thread safety issues

Best Practices

  • Use meaningful names: Choose meaningful variable names (e.g., userAge instead of a) which makes the code more readable.
  • Follow camelCase naming: Use camelCase for variable names (e.g., studentName) better readability.
  • Initialize variables before use: It is always recommended to initialize a variable first before using it, so that we can prevent compile-time errors.
  • Use final for constants: It is also recommended to declare constant with final keyword. It is used to indicate the this value can not be changed.
  • Avoid public instance variables: Use getters and setters instead of public instance variables to maintain encapsulation and control over variable access.


Next Article
Article Tags :
Practice Tags :

Similar Reads