Types of Variables in Java with Examples

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.

Variables in java

Keeping you updated with latest technology trends, Join DataFlair on Telegram

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.

Summary

In this article, we learnt 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.

Do rate DataFlair at Google if you liked our article.

3 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?

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.