Types of variables in Java with examples: Local, Instance & Static

Types of variables in Java with examples: Local, Instance & Static

11 Sep 2024
Beginner
9.33K Views
10 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate

Variables in Java: An Overview

Variables in Java serve as data storage containers, allowing programmers to manipulate and work with information efficiently within their programs. Using the right variables can not only make the code easier to read but also help optimize your program. 
In this Java tutorial, we'll get into the details of Java variables. Java Online Training is a convenient option for gaining expertise in Java and harnessing its power for various applications. 
Start coding with confidence—join our Java Full Stack Developer Certification Training and gain hands-on experience.

Read More - Top 50 Java Interview Questions For Freshers

What is a Variable in Java?

Variables work as a container to store the values of data. It saves the data while the language is executing a program. Every variable has a data type that understands and designates the quantity and type of the value that can be stored by the container. It is a memory location that memorizes the location of the data. Knowing about variables in Java is one of the most important reasons to learn about Java.

Variable Declaration

Various types of declaration happen by using Java variables such as

  • Strings- which stores text, Such as "Hello world".
  • Int- it stores any integer, specifically any whole number without decimal.
  • Float- stores "floating point" numbers that include decimal values.
  • Char- it stores characters such as 'x', and 'y'. It is denoted by single quotes.
  • Boolean- store values if true or false state.
To declare the variable programmers need to focus on two things:
  1. Datatype: It denotes the types of Data that are going to be stored.
  2. data_name: A particular name of that variable

Rules for Declaring Variables in Java

  • You can begin the variable's name with an alphabet, a dollar or underscore symbol, or a currency symbol, but not any other special symbol.
  • A variable's name cannot contain more than 64 characters.
  • You cannot use blank spaces while declaring a variable.
  • Java-reserved keywords cannot be used as variable names.
  • The variable name must appear to the left of the assignment operators.

Let's look at the variable declaration in our Java Playground.

Example

class Example
{
 public static void main ( String[] args )
 {
  long payAmount = 184; //the declaration of the variable

  System.out.println("The variable contains: " + payAmount );
 }
}

Output

Long payAmount = 184;

Variable Initialization

For initializing the variable, there are 3 major components are
  • datatype: it defines what type of data is going to be stored in a variable
  • variable_name: Particular name of the variable
  • value: initially stored value in the variable

Read More - Java Web Developer Salary

Types of Variables in Java

There are three types of variables in Java:
Types of Variables in Java

1. Local Variables in Java

  • It is created when a block is entered into the storage, and then it calls and destroys the block just after exiting from the function.
  • It is important to initialize a local variable before using it.

Example

import java.io.*;

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

  // This variable is local to this main method only

  System.out.println("Local Variable: " + var);
 }
}

This demonstration in our Java Compiler illustrates the concept of local variables with a scope that is only the main method by declaring and initializing a local variable "var" with the value 89.

Output

Local Variable: 89

2. Instance Variables in Java

  • An instance variable is created when an object class is generated and it gets destroyed when the same object class is destroyed
  • Programmers can use access specifiers, for instance variables
  • It is not mandatory to initialize instance variables

Example

import java.io.*;
class DNT
{
 public String student; // Declared Instance Variable
 public DNT()
 { // Default Constructor
  this.student= "Urmi Bose"; // initializing Instance Variable
 }
//Main Method
 public static void main(String[] args)
 {
  // Object Creation
  DNT name = new DNT();
  System.out.println("Student name is: " + name.student);
 }
}

In this Java example, the class "DNT" contains a declaration for an instance variable named "student" that is initialized in the default constructor to demonstrate the use of instance variables. An object of the class is then constructed to allow access to and printing of the student's name.

Output

Student name is : Urmi Bose

3. Static Variables in Java

  • Static variables are declared as instance variables.
  • It is created to start the execution of the program and then destroy it automatically after the execution ends.
  • It uses static keywords for the declaration of the static variable within a class

Example

import java.io.*;
class DNT
{
public static String student= "Urmi Bose"; //Declared static variable

 public static void main (String[] args) {

 //student variable can be accessed without object creation
  System.out.println("Student Name is : "+DNT.student);
 }
}

This Java example prints the value "Urmi Bose" from a static variable named "student" that is declared inside the class "DNT," enabling access by class name simply without creating an object.

Output

Student Name is: Urmi Bose

Difference between Instance and Static Variable in Java

  • In Java, instance variables are stored in separate copies within each object, but static variables are shared across all objects within a class to facilitate memory management. 
  • While changes to static variables impact all objects since the class shares them, changes to instance variables are limited to the object to which they belong. 
  • Static variables can only be accessed directly with the class name; instance variables can only be accessed through object references. 
  • Static variables are produced at the program's start and destroyed at its conclusion, whereas instance variables are created and destroyed along with objects.
Summary
This article covers the definition of the variable, variable declaration, variables in Java, variables in Java example, and variable initialization. Additionally, it provides a comprehensive understanding of different types of variables and, makes it a valuable resource for Java Full Stack Certification Course preparation.

FAQs

In Java, variables serve as storage containers for data types like numbers, text, and objects.

Local, instance and static variables are the three different categories of variables in Java.

The data type and variable name must be specified when declaring a variable in Java.

Assigning an initial value to a declared variable in Java usually takes place on the same line of code or later.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this