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

  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

    ReplyDelete
  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

    ReplyDelete

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  https://timesofindia.indiatimes.com/rssfeedstopstories.cms  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 - CountDownLatch (Part 12)

A CountDownLatch is a synchronizer which allows one thread to wait for one or more threads before starts processing. A good application of  CountDownLatch is in Java server-side applications where a thread cannot start execution before all the required services are started. Working A  CountDownLatch is initialized with a given count which is the number of threads it should wait for. This count is decremented by calling countDown() method by the threads once they are finished execution. As soon as the count reaches to zero, the waiting task starts running. Code Example Let us say we require three services, LoginService, DatabaseService and CloudService to be started and ready before the application can start handling requests. Output Cloud Service is up! Login Service is up! Database Service is up! All services are up. Now the waiting thread can start execution. Here, we can see that the main thread is waiting for all the three services to start before starting its own

I/O in Java - Masterclass (Part 0)

IO in Java Java input and output processes the input and produces the output based on the input. Java uses streams to perform input and output operations. In this masterclass on I/O, we will learn about the nitty gritty details of the File IO/NIO with lots of code examples. You can follow the below trail to dive deep into Java I/O Part 1 - Basics Part 2 - IO vs. NIO Part 3 - try-with-resources Part 4 - Directory Operations Part 5 - File Operations Part 6 - Temporary File Operations All of these posts include code examples to understand the concept. 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 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 😊