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;
  discount=price*(20/100);
  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() {

  System.out.println(id);
 }
}

public class StaticVariableDemo {

 public static void main(String[] args) {

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

  o1.change();

  Student.id = 1;
  o2.change();
 }
}
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

Conclusion

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 😊.

Comments

Popular posts from this blog

Threads in Java - Masterclass (Part 0)

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 processor busy can be a tough task e…

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 connectionscachingretrying failed requeststhreadingresponse parsingerror 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 https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes -  Model class to map the JSON dataInterfaces which defines the possible HTTP operationsRetrofit.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 response is returned as a Call object…

Threads in Java - Basics (Part 1)

Hello everyone, today we are going to discuss one of the most important concepts in Java - Multithreading.
In the first part of this multi-part blog series, we will be discussing the basics of threads, how can we create them? which is the best approach? and many other questions like these. So without further ado, let's get started.
What are threads? Let's say you are Batman (pretty cool, eh? 😊) and your arch-enemy, the master alchemist Ra's al Ghul has brewed a dangerous potion from the Lazarus Pit. To avenge his earlier defeats by the hands of The Dark Knight, he has spread the potions all over the Gotham city.  Now, the only way to save citizens of Gotham is to find the cure of the potion (hidden in the city somewhere) and find Ra's as well before he can devise a new plan to destroy the city.  Batman calls Nightwing (the original Robin) and asks his help in finding Ra's. Batman decides to find the cure of the deadly potion. In the end, both Batman and Robin wer…