Introduction

A variable specifies a memory location that contains data. The data can be numbers, characters and so on. There are three types of variables in Java:
  1. Local variables
  2. Instance variables
  3. Class variables

Local variables

  • A method uses local variables for storing its temporary state.
  • Generally, these are declared inside the methods, constructors or blocks of code.
  • These should always be declared and initialized before their use.
  • We cannot access local variables anywhere other than the specific methods, constructors or blocks of code in which they are declared.
  • When the method is executed completely, these local variables are destroyed.
Example:
  1. package myclass1;
  2. class Myclass1 {
  3. public void classStrength() {
  4. int strength = 100;
  5. strength = strength - 10;
  6. System.out.println("Class strength is : " + strength);
  7. }
  8. public static void main(String args[]) {
  9. Myclass1 count = new Myclass1();
  10. count.classStrength();
  11. }
  12. }
Output:
local variable.jpg

Instance variables

  • These are also known as non-static variables.
  • These are declared inside a class, but outside a method, constructor or a block of code.
  • Instance variables have a default value.
  • These are created and destroyed when the object is created and destroyed respectively.
  • Inside the class these can be accessed directly by calling their names.
  • Instance variables can be accessed by all methods, constructors or blocks of code in the same class.
Example:
  1. package myclass1;
  2. class Myclass1 {
  3. public String location;
  4. private int id;
  5. public Myclass1(String Location) {
  6. location = Location;
  7. }
  8. public void id(int classid) {
  9. id = classid;
  10. }
  11. public void Location() {
  12. System.out.println("Location : " + location);
  13. System.out.println("id :" + id);
  14. }
  15. public static void main(String args[]) {
  16. Myclass1 scl = new Myclass1("ndl");
  17. scl.id(10090);
  18. scl.Location();
  19. }
  20. }
Output:
instance variable.jpg

Class variables

  • These are also known as static variables.
  • These are declared inside a class with a static keyword, but outside a method, constructor or a block of code.
  • These variables are created and destroyed when the program starts and ends respectively.
  • Class variables also have a default value.
  • These variables can be accessed just by referring to them with the class name.
Example:
  1. package myclass1;
  2. class Myclass1 {
  3. private static int rollno;
  4. public static final String CLASS = "class topper";
  5. public static void main(String args[]) {
  6. rollno = 10;
  7. System.out.println(CLASS + " roll no is :" + rollno);
  8. }
  9. }
Output:
class variable.jpg

Summary

This article will introduce you to the various types of variables in Java and their properties.