Skip to main content

Types of variables in Java

What is a variable?

A variable is a piece of memory which stores a data value. Thus, a variable has a data type. Primarily there are eight primitive data types in java. We will learn about these in a later post.

Variables are typically used to store information which our Java program needs to do its job. This can be any kind of information ranging from texts, codes (e.g. country codes, currency codes etc.) to numbers, temporary results of multi-step calculations etc.

You can declare a variable as below - 
datatype name [initialization];
Initialization of a variable is not mandatory in all cases.

Types of variables

There are three types of variables in Java. We will discuss them one by one.

1. Local variables - 

  • They can be declared in a method, constructor, or block. 
  • When a method is entered, an area is pushed onto the call stack which contains slots for each local variable and parameter. 
  • When the method is called, the parameter slots are initialized to the parameter values.
  • When the method exits, this area is popped off the stack and the memory becomes available for the next called method. 
  • Parameters are essentially local variables which are initialized from the actual parameters. 
  • Local variables are not visible outside the method.
For example, see below code snippet.
float getDiscount(int price) {
  float discount;
  return discount;
Here, discount is the local variable.

2. Instance variables -

  • These are declared in a class, but outside a method. 
  • When an object is allocated in the heap, there is a slot in it for each instance variable value. 
  • Therefore an instance variable is created when an object is created and destroyed when the object is destroyed. 
  • Visible in all methods and constructors of the defining class should generally be declared private but may be given greater visibility (public/protected/default).
For example, see below code snippet.
class Student {
 String name;
 int age;
Here, name and age are instance variables.

3. Static/Class variables

  • These are declared with the static keyword in a class, but outside a method. 
  • There is only one copy per class, regardless of how many objects are created from it.
  • They are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.
For example, see below code snippet.
class Student {

 int a;
 static int id = 35;

 void change() {


public class StaticVariableDemo {

 public static void main(String[] args) {

  Student o1 = new Student();
  Student o2 = new Student();

  o1.change(); = 1;
Here, id is a static or class variable which can be accessed using the class name.

A sample Java program

Below is a sample java code that illustrates the usage of all three variable types
 * @author Anirudh Sharma
public class TypesOfVariables {

 // instance variable
 private int instanceVarible;

 // static variable
 public static int staticVariable = 30;

 public static void main(String args[]) {

  // local variable - accessed only in the main method
  int localVariable = 100;

  // creating an instance of the class to access the instance variable
  TypesOfVariables obj = new TypesOfVariables();

  // usage of all three types of variables
  System.out.println("Value of instance variable instanceVarible: " + obj.instanceVarible);
  System.out.println("Value of static variable staticVariable: " + TypesOfVariables.staticVariable);
  System.out.println("Value of local variable localVariable: " + localVariable);
And the output of this program will be -
Value of instance variable instanceVarible: 0
Value of static variable staticVariable: 30
Value of local variable localVariable: 100


In this post, we have gone through the different types of variables in Java. You can find the code of these examples on my GitHub repository. Feel free to fork or open issues, if any.

I would love to hear your thoughts on this and would like to have suggestions from you to make it better. Feel free to befriend me on Facebook, Twitter or Linked In or say Hi by email.
Happy Coding 😊.


  1. This is what commonly happens to the newbies in the business industry who do not know how to effectively market their product or service or service.Best Sites like FMovies

  2. but you can still afford some pretty good cleaning coverage with a service that provides you a housekeeper on a scheduled plan.Fraud Triangle


Post a Comment

Popular posts from this blog

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects - making connections caching retrying failed requests threading response parsing error handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from  using the Retrofit library. To work with Retrofit, we need three classes -  Model class to map the JSON data Interfaces which defines the possible HTTP operations Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The respon

Threads in Java - Masterclass (Part 0)

Threads in Java Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading. One should exploit this feature, especially with all these multiple core machines nowadays. Below are a few reasons why we should use multithreading - 1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a proc

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user. The output of this UI will be like this - Profile page screen I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started. Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml file Navigate to app\src\main\res\values\styles.xml Change the style value from DarkActionBar to NoActionBar as below <resources> <!-- Base application theme. --> <style name= "AppTheme" parent= "Theme.AppCompat.Light.NoActionBar" > <!-- Customize your theme here. --> <item name= "colorPr