Variables in Java Programming: Everything You Need to Know

Master Java variables! From declaration to usage, grasp the fundamentals. Explore data types, scopes, and best practices for effective variable handling in Java programming. Start your Java journey now!

A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable

A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed.

variables in java

 

    int data=50;//Here data is variable  

Types of Variables

There are three types of variables in Java:

  • local variable
  • instance variable
  • static variable

types of variables in java

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.

Example to understand the types of variables in java

    public class A  
    {  
        static int m=100;//static variable  
        void method()  
        {    
            int n=90;//local variable    
        }  
        public static void main(String args[])  
        {  
            int data=50;//instance variable    
        }  
    }//end of class   

Java Variable Example: Add Two Numbers

    public class Simple{    
    public static void main(String[] args){    
    int a=10;    
    int b=10;    
    int c=a+b;    
    System.out.println(c);    
    }  
    }    

Output:

20

Java Variable Example: Widening

    public class Simple{  
    public static void main(String[] args){  
    int a=10;  
    float f=a;  
    System.out.println(a);  
    System.out.println(f);  
    }}  

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)

    public class Simple{  
    public static void main(String[] args){  
    float f=10.5f;  
    //int a=f;//Compile time error  
    int a=(int)f;  
    System.out.println(f);  
    System.out.println(a);  
    }}  

Output:

10.5
10

Java Variable Example: Overflow

    class Simple{  
    public static void main(String[] args){  
    //Overflow  
    int a=130;  
    byte b=(byte)a;  
    System.out.println(a);  
    System.out.println(b);  
    }}  

Output:

130
-126

Java Variable Example: Adding Lower Type

    class Simple{  
    public static void main(String[] args){  
    byte a=10;  
    byte b=10;  
    //byte c=a+b;//Compile Time Error: because a+b=20 will be int  
    byte c=(byte)(a+b);  
    System.out.println(c);  
    }}  

Output:

20

Java Variables

In Java, Variables are the data containers that save the data values during Java program execution. Every Variable in Java is assigned a data type that designates the type and quantity of value it can hold. A variable is a memory location name for the data.

Variables in Java

Java variable is a name given to a memory location. It is the basic unit of storage in a program.

  • The value stored in a variable can be changed during program execution.
  • Variables in Java are only a name given to a memory location. All the operations done on the variable affect that memory location.
  • In Java, all variables must be declared before use.

How to Declare Variables in Java?

We can declare variables in Java as pictorially depicted below as a visual aid.

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. datatype: Type of data that can be stored in this variable. 
  2. data_name: Name was given to the variable. 

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 Variables in Java?

It can be perceived with the help of 3 components that are as follows:

  • datatype: Type of data that can be stored in this variable.
  • variable_name: Name given to the variable.
  • value: It is the initial value stored in the variable.

Java Variables Syntax

 

Illustrations:

// 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 Variables in Java

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

  1. Local Variables
  2. Instance Variables
  3. 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. 

  • These variables are created when the block is entered, or the function is called and destroyed after exiting from the block or when the call returns from the function.
  • The scope of these variables exists only within the block in which the variables are declared, i.e., we can access these variables only within that block.
  • Initialization of the local variable is mandatory before using it in the defined scope.

Time Complexity of the Method:

Time Complexity: O(1)
Auxiliary Space: O(1)

Below is the implementation of the above approach:

// Java Program to implement
// Local Variables
import java.io.*;

class GFG {
	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 :

package a;
public class LocalVariable {
	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 :

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

2. Instance Variables

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

  • As instance variables are declared in a class, these 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.
  • 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.

The complexity of the method:

Time Complexity: O(1)
Auxiliary Space: O(1)

Below is the implementation of the above approach:

// Java Program to demonstrate
// Instance Variables
import java.io.*;

class GFG {

	// Declared Instance Variable
	public String geek;
	public int i;
	public Integer I;
	public GFG()
	{
		// Default Constructor
		// initializing Instance Variable
		this.codequs = "Shubham Jain";
	}

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

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

Output

codequs name is: Shubham Jain
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.

The complexity of the method:

Time Complexity: O(1)
Auxiliary Space: O(1)

Below is the implementation of the above approach:

// Java Program to demonstrate
// Static variables
import java.io.*;

class GFG {
	// Declared static variable
	public static String codequs= "Shubham Jain";

	public static void main(String[] args)
	{

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

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

Output

Codequs Name is : Shubham Jain

Differences Between the Instance Variables and the 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 GFG
{
    // Static variable
    static int a; 
    
    // Instance variable
    int b;        
} 

Conclusion

The Important points to remember in the articles are mentioned below:

  • Variables in Java is a data container that saves the data values during Java program execution.
  • There are three types of variables in Java Local variables, static variables, and instance variables.

Java Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

  • String - stores text, such as "Hello". String values are surrounded by double quotes
  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • boolean - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

type variableName = value;

Where type is one of Java's types (such as int or String), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Example

Create a variable called name of type String and assign it the value "John":

String name = "John";
System.out.println(name);

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;
System.out.println(myNum);

You can also declare a variable without assigning the value, and assign the value later:

Example

int myNum;
myNum = 15;
System.out.println(myNum);

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example

Change the value of myNum from 15 to 20:

int myNum = 15;
myNum = 20;  // myNum is now 20
System.out.println(myNum);

Final Variables

If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only):

Example

final int myNum = 15;
myNum = 20;  // will generate an error: cannot assign a value to a final variable

Other Types

A demonstration of how to declare variables of other types:

Example

int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";

What Are Variables in Java? Types, Examples, Declare, Initialize

Variables play a fundamental role in the world of programming, and Java, being one of the most widely used programming languages, relies heavily on them. Whether you are an experienced Java developer or just starting to explore the basics of programming, understanding variables in Java is essential to harnessing the power of this language.

Java variables act as containers that store data and allow us to manipulate and operate on that data within our programs. They provide a way to hold information temporarily or permanently, enabling us to create dynamic and interactive applications. By using variables, we can assign values to them, modify those values, and perform various computations based on the stored data.

Java, being a statically-typed language, requires us to declare variables explicitly before using them. This declaration process involves specifying the type of data a variable will hold, giving it a meaningful name, and optionally assigning an initial value. Once declared, we can access and modify the data stored in a variable throughout the program, making it a powerful tool for building complex applications.

Variables in Java come in different types, including primitive types such as integers, floating-point numbers, characters, and booleans, as well as more complex types like objects and arrays. Each type has its own characteristics and usage patterns, and understanding them is crucial for effective programming.

Here, we will learn everything about variables in Java, including their types, rules for declaration and initialization, and examples, and much more.

What is Variable in Java?

The word variable is a combination of two words, ‘vary’ and ‘able’, meaning its value can be changed. Java Variable is a named memory location that programs can easily manipulate. In other words, it is a data container to store values of data during the execution of a Java program

Each variable is assigned a specific data type, which determines the type of quantity of the value it holds along with the range of values that can be stored in the memory and the set of operations that are possible to apply to a variable. 

A variable is a basic storage unit in a program that has the following features:

  • Value saved in a variable can be changed during program execution.
  • Variables must be declared before use.
  • Java variables are names assigned to a memory location, and any operation performed on these variables affects that location. 

Example of Variable in Java

Here's an example of a variable declaration and initialization in Java:

public class Example {
    public static void main(String[] args) {

        // Declaring and initializing a variable
        int age = 25;

        // Printing the value of the variable
        System.out.println("Age: " + age);

        // Modifying the value of the variable
        age = 30;

        // Printing the updated value of the variable
        System.out.println("Updated Age: " + age);

    }
}

In this example, we declare a variable called age of type int and initialize it with the value 25. We then print the value of the variable using System.out.println(). After that, we modify the value of the age variable to 30 and print the updated value.

How to Declare Variables in Java?

To declare a variable in Java, it’s required to specify the data type and assign a unique name to the variable. 

The diagram below accurately shows Java variables declaration:

According to the diagram, it is clear that we need to consider two key factors while declaring a variable:

datatype: It means the type of data stored in the variable.

data_name: It signifies the name given to the variable. 

A name is given to a memory location, which can be assigned values in two ways:

Variable Initialization

Assigning value by taking input

Example of Java Variable Declaration

Here's an example of variable declaration in Java:

public class Example {
    public static void main(String[] args) {

        // Variable declaration
        int age;
        double salary;
        String name;
        boolean isEmployed;

 

In this example, we declare four variables: age of type int, salary of type double, name of type String, and isEmployed of type boolean

How to Initialize Variable in Java?

Variable initialization is perceived with the help of three components:

  • datatype: Type of data stored in the variable.
  • variable_name: Name given to the variable.
  • value: The initial value stored in the variable.

You can initialize variables in Java at the time of declaration or later in the code. 

Here are a few examples:

1. Initialize variables at the time of declaration:

int age = 25;
double salary = 50000.00;
String name = "John Doe";
boolean isEmployed = true;

2. Initialize variables later in the code:

int age; // Declaration
age = 25; // Initialization

double salary; // Declaration
salary = 50000.00; // Initialization

String name; // Declaration
name = "John Doe"; // Initialization

boolean isEmployed; // Declaration
isEmployed = true; // Initialization

3. Initialize variables using user input:

import java.util.Scanner;
public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        System.out.print("Enter your name: ");
        String name = scanner.next();
        System.out.println("Age: " + age);
        System.out.println("Name: " + name);
        scanner.close();
    }
}

Types of Variables in Java (With Examples)

There are three variable types in the Java programming language:

1. Local Variable

Variables that can’t be defined with the ‘static’ keyword are called local variables in Java. They are declared inside the method body and used only within that method, while other methods in a class don’t know that the variable exists. 

A local variable in Java is created when the constructor, block, or method is entered and destroyed when it exits from the constructor, block, or method.

They exist only within the constructor, method, or block they are declared, which means we can access the local variables only within the declared block.

They are implemented at the stack level internally.

You can’t use access modifiers for local variables in Java.

It is necessary to initialize local variables before using them in a defined scope.

Local variables have no default value, so they are declared and assigned an initial value before the first use. 

Example of Local Variable in Java

public class LocalVariableExample {
    public static void main(String[] args) {

        int x = 5; // Local variable declaration and initialization
        System.out.println("The value of x is: " + x);

        // Updating the value of x
        x = 10;
        System.out.println("The updated value of x is: " + x);

        // Using a local variable in a loop
        for (int i = 0; i < 5; i++) {
            System.out.println("The value of i is: " + i);
        }
        // Uncommenting the line below will result in a compile-time error
        // System.out.println("The value of i outside the loop is: " + i);
    }
}

In the example, we declare a local variable named x of type int inside the main method. We initialize it with the value 5 and then print its value to the console. Later, we update the value of x to 10 and print the updated value.

Additionally, we show the usage of a local variable i within a for loop. The i variable is declared within the loop's scope and is used to control the loop iteration. It is only accessible within the loop block and cannot be accessed outside of it.

If you uncomment the last line, an error will occur because i is a local variable limited to the scope of the for loop, and attempting to access it outside the loop is not allowed.

2. Instance variable

Instance variables are declared within a class but outside a method. They are defined without the ‘static’ keyword. As their value is instance-specific and they are not shared among instances, they are called instance variables. 

These types of variables in Java are declared in a class and outside the body of a method, block, or constructor. They are declared at a class level before or after use.

They are created when an object is created using the ‘new’ keyword and destroyed when the object is destroyed.

Initialization of instance variables is not necessary, and their default value is based on the data type. For example, String is null; int is 0, the float is 0.0f, and the Wrapper class, such as integer, is null. 

Intialialization is possible using constructors while creating an object or using instance blocks. 

They hold values referenced by more than one method, block, constructor, or key part of an object’s state present throughout the class.

Unlike local variables, instance variables can use access modifiers. If no access modifier is specified, the default modifier will be used.

It is possible to access instance variables only by creating objects. You can access instance variables directly by calling the variable name within a class. When they are within static methods, they must be accessed using the fully qualified name.

They are visible for all blocks, constructors, and methods in a class. It is better to make these variables private, but they can have visibility for subclasses by using access modifiers.

They have default values. For example, Boolean has false; default has a 0 value and object reference has a null value. The values are assigned during variable declaration or within the constructor. 

Example of Instance Variable in Java:

public class InstanceVariableExample {
    private int count; // Instance variable
    public void increment() {
        count++; // Accessing and modifying the instance variable
    }
    public void displayCount() {
        System.out.println("The count is: " + count); // Accessing the instance variable
    }
    public static void main(String[] args) {
        InstanceVariableExample obj1 = new InstanceVariableExample();
        InstanceVariableExample obj2 = new InstanceVariableExample();
        obj1.increment();
        obj1.displayCount(); // Output: The count is: 1
        obj2.increment();
        obj2.displayCount(); // Output: The count is: 1
    }
}

In the example, we define a class named InstanceVariableExample. Inside this class, we declare an instance variable named count of type int. The count variable is not static, which means it is associated with each instance of the class rather than being shared among all instances.

Within the class, we have two methods: increment() and displayCount(). The increment() method increments the value of the count instance variable by one. The displayCount() method simply prints the value of the count instance variable.

In the main() method, we create two objects (obj1 and obj2) of the InstanceVariableExample class. Each object has its own copy of the instance variable count. We call the increment() method on both objects, and then we call the displayCount() method to print the value of count for each object.

As a result, we see that each object maintains its own separate copy of the instance variable count. When we increment count on one object, it does not affect the value of count in the other object.

3. Static variable

Static variable, or a class variable in Java, is declared as static and is initialized only once at the beginning of the program execution. They must be initialized before initializing any instance variables. You can share a single copy of these variables and share it with the instances of the class. 

Class variables is another name for static variables in Java. They are declared the same way as instance variables. But the difference is static variables are declared within the static keyword in a class but outside of any method, block, or constructor. 

Their visibility is also similar to instance variables. Most class variables are declared public as they need to be available for users of a class.

They can be accessed with the class name ClassName.VariableName. If you access a class variable like an instance variable, the compiler will send a warning message and replace the object name with the class name automatically without stopping the program.

Static variables are created at the beginning of program execution and destroyed automatically once the execution ends.

They are stored in the static memory.

You can have only one copy of a static variable per class, no matter how many objects you create from it.

Initializing static variables is not mandatory. Values can be assigned either during declaration or within the constructor. The default values of these variables are dependent on the data type of the variable. For Boolean, it is false; for String, it is null; for numbers, it is 0; and for the object reference, it is null. 

They are hardly used other than being declared constants, which can be final, public/private, and static. Also, constant variables don’t change their initial value. 

Example of Static Variable in Java

public class StaticVariableExample {
    private static int count; // Static variable
    public StaticVariableExample() {
        count++; // Incrementing the static variable in the constructor
    }
    public void displayCount() {
        System.out.println("The count is: " + count); // Accessing the static variable
    }
    public static void main(String[] args) {
        StaticVariableExample obj1 = new StaticVariableExample();
        obj1.displayCount(); // Output: The count is: 1
        StaticVariableExample obj2 = new StaticVariableExample();
        obj2.displayCount(); // Output: The count is: 2
    }
}

Here, we define a class named StaticVariableExample. Inside this class, we declare a static variable named count of type int. The count variable is declared with the static keyword, which means it is associated with the class itself rather than individual instances (objects) of the class. All objects of the class share the same copy of the static variable.

We also have a constructor in the class, which is invoked when an object is created. In the constructor, we increment the value of the static variable count by one.

The displayCount() method simply prints the value of the static variable count.

In the main() method, we create two objects (obj1 and obj2) of the StaticVariableExample class. When we create each object, the constructor is called, and the static variable count is incremented.

Finally, we call the displayCount() method on both objects, which prints the value of count for each object. Since the static variable is shared among all objects, the count increments for each object creation.

As a result, we see that both objects have access to and modify the same static variable, and any changes made to the static variable are reflected across all instances of the class.


Related Videos

Variables in Java ✘【12 minutes】

Variables in Java

Introduction to Variables in Java

#java

Variables in Java Programming: Everything You Need to Know
1.20 GEEK