Types of Variables in Java with Examples

Free Java courses with 37 real-time projects - Learn Java

Before studying what Variables in Java are, let’s go through some primary concepts in real life which mirrors the concept of variables.

Imagine it’s summer and you are very thirsty. You want to have water. But as soon as you are about to quench your thirst, you begin to observe that water is always in something. Right? It can be a bottle, it can be a glass, or it can be in a cup. These are containers or variables. They contain a value, in this case, water. However, the value of the container may change. This results in the name “Variable’ which means that the value inside it can change.

Considering the example at hand, the tumbler can have anything be it juice, water or a milkshake. This is the basic concept of a variable.

Java Variables

When Java executes a program, the values are stored in containers called variables. It is the name of a memory location.
It is also a basic unit of storage.
Variables must be declared before they are used and the changes in variables make actual changes in the memory location.

In Java ,variables are declared as <datatype><variable_name>=<Variable_value>

For Example- int i=76, String s=”DataFlair”;

Types of Variables in Java

Java variables are of 3 types:

1. Java Local Variable
2. Instance Variable in Java
3. Java Static Variable

1. Local Variable in Java

A local variable is a variable which has value within a particular method or a function. Outside the scope of the function the program has no idea about the variable. Consider a real life example, where you have an embarrassing nickname which is known to your parents. But no other person outside your house knows it, right?

That is exactly how a local variable works. It is known locally. Hence the name. Local variables cannot be declared static.

For Example:

class DataFlair {
  int a = 9,
  b = 10;
  void LearnJava {
    int local_j = 45; // A local variable
    String s = ”DataFlair Training”; //A local variable
  }
}

A local variable cannot be accessed directly outside a function.

2. Java Instance Variable

Instance variables are those which are declared inside the body of a class but not within any methods. These differ with each instance of the class created although they have the same identity.

Example:

import java.io. * ;
class Person {
  int height,
  weight; // Instance Variables
  Person(int h, int w) {
    this.height = h;
    this.weight = w;
  }
  void run() {
    System.out.println(“Huff Puff”);
  }
  void print() {
    System.out.println(“Now my weight is” + this.weight);
  }
  public static void main(String[] args) throws IOException {
    Person A = new Person(170, 65);
    A.run();
    A.print();
  }
}

Output:

Huff Puff
Now my weight is 65.

The variables height and weight are the instance variables, i,e, they are unique for every instance created.

These cannot be initialized with a static keyword. However one instance of the Person class cannot share the details of the other instance of the same class.

3. Static Variables in Java

What if we want a variable that is shared across all the instances of a class? That’s where static variables come in. These are class- level variables which are the same for all the instances generated . As soon a class loads, the static variables get their initialization.

Static Variables are declared in the following way:
static <variable_name> =<variable_value>

For Example:

import java.io. * ;
class DataFlair {
  static int studentCount;
  DataFlair() {
    studentCount = 15;
  }
  void addStudent() {
    studentCount++;
  }

  public static void main(String[] args) throws IOException {
    DataFlair java = new DataFlair();
    DataFlair python = new DataFlair();
    java.addStudent();
    python.addStudent();
    System.out.println("Total Students " + studentCount);
  }
}

Output:

Total Students 17

Hence we observe that the static variable is shared across both the instances created java and python for the class DataFlair. This also helps us in counting the total number of students who have joined DataFlair!

Declaring Java Variables

In Java, the variables have to be declared previously because unlike python,Java is a statically typed language. The variables have to be declared before its use in the program. If a variable is used and then declared, it outputs an error. The reason for this is that the compiler starts executing the lines from top to bottom. As soon as the compiler gets an initialization command it reserves memory with the name mentioned in the program . If a particular variable is used in a line and it is not declared with a proper data type in any of the previous lines, then the compiler throws an error.

Example program to illustrate declaring variable concepts:

import java.io.IOException;

class DeclareVar {
  public static void main(String[] args) throws IOException {
    int a = 10,
    b = 4;
    System.out.println(c); // This accesses c before its declaration. 
    int c = 74;
  }
}

Output:

DeclareVar.java:7: error: cannot find symbol
System.out.println(c);
^
symbol: variable c
location: class DeclareVar
1 error

Variable Naming Conventions in Java

There are particular conventions to be followed when naming variables to enhance the readability of the program.
Some of them are:

a. Its convention to start the names of a variable with an alphabet rather than an underscore or a dollar sign

b. Variable names can have any alphabets or numbers after the first letter. However, spaces are not allowed.

c. The reserved words such as int,static,void and so on cannot be used as variable names.

d. Constant values can be stored in variables which are named in “ALL_CAPS”.

e. Variables which need two distinct words can be written together using camelCase.

Example– int amountOfWater=1000; //This preserves the meaning of variable.

Quiz on Variables in Java

Summary

In this article, we learned about the various kinds of variables in Java and their uses. In programming the cautious and efficient use of variables leads to faster outputs and memory optimization. Variables are key in programming and without variables storing data would be impossible.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

7 Responses

  1. Dorice Kagisa says:

    I really like how you guys explain and try to put some concepts clear
    Have just started to learn java …..wanna be more …..and I hope this is the perfect place where I can get help with all the questions I have

  2. Harika says:

    what is the scope/lifetime of static variable?is it also available outside class?

  3. harivignesh says:

    in static variable example..how the student count variable value shows as 17 instead of 15 or 16 in final print statement,i dont know the mode of execution.so could you please explain?

    • Siddharth Shikhare says:

      static variables are those, which are common to all objects of that class(i.e. objects of the class). Memory is assigned to static variables when the class is loaded in memory and all objects of that class share it. In the example you mentioned, memory is assigned to the static variable ‘studenCount’ when class ‘DataFlair’ is loaded in memory and initialized to 15. Only one instance of ‘studentCount’ is created and initialized to 15 and is shared by all objects of DataFlair class i.e. ‘java’ and ‘python’. When java.addStudent() is called, value of ‘studentCount’ is increased by 1, which becomes (15 + 1 = )16. When python.addStudent() is called, value of ‘studentCount’ is again increased by 1, which becomes (16 + 1 = )17. This is how static variables work. Remember that, only one copy of a static variable is created and is shared by all objects of that class.

  4. devendra says:

    color is not changing in a quiz

  5. devendra says:

    color is not changing in a quiz

Leave a Reply

Your email address will not be published. Required fields are marked *