In this Tutorial, we will Explore Java Variables, Types of Variables, Java Instanceof, Scope & Lifetime of a Variable with the help of Examples:
We will also see a few frequently asked questions that would help you in understanding the topic better.
After going through this tutorial, you will be gaining insights into the Java variables, local and global variables, the instance variable, and other sub-topics related to Java variables.
=> Check ALL Java Tutorials Here.
Table of Contents:
Java Variables
As we know a Java variable is a storage unit in a Java program. A Java variable is a combination of ‘type’, ‘identifier’, ‘identifier value’. Declaring a variable requires ‘type’ and ‘identifier’.
However, when you specify the value of a variable after declaring the variable, this process is called the initialization of a variable.
Syntax:
type identifier [ = value][, identifier [= value] ...]
Examples
// declaring three variables a, b and c. int a, b, c; // initializing variables a and c. int a = 10, b, c = 5;
Dynamic Initialization
Here, we will see the dynamic initialization of a variable. We will be calculating the discriminant of the quadratic equation of mathematics.
The mathematical formula for calculating discriminant is b²-4ac for the equation ax² +bx +c
All we have to do is to calculate the discriminant using dynamic initialization.
public class DynamicInitialization { public static void main(String[] args) { int a = 1, b = 2, c = 3; /* * d is dynamically initialized which will be the * discriminant of the quadratic equation */ double d = b*b -4*a*c; System.out.println("Discriminant is: " + d); } }
Output
Scope And Lifetime Of Variables
In this section, we will discuss the scope and lifetime of a Java variable. Here, we will take a variable ‘a’ that will be known to the entire program and then demonstrate the value of that variable which will be specific to a block inside the program.
Again we will create another variable ‘b’ inside a block that depends on the value of ‘a’. As soon as the scope ends, the scope of variable ‘b’ also ends whereas ‘a’ is still known to the program.
class VariableScope { public static void main(String args[]) { // a is known to entire program int a; a = 15; // starting new scope known only to this block if (a == 15) { int b = 20; // a and b both known here. System.out.println("a and b: " + a + " " + b); a = b / 2; } /* b is unknown here which means * if we print b, it will throw an error * whereas a is still known */ System.out.println("a is " + a); } }
Output
Java Variable Types
In this section, we will learn about the various types of Java variables mentioned below.
- Local variable
- Instance variable
- Static or Class variable
Local Variables
These variables are declared inside the body of a method. These can be used within the same method where it is being initialized.
Some of the properties of a Local Variable include:
- Local variables are declared inside a method, constructor, or block.
- No access modifiers for local variables.
- These can be used only within the same block, method, or constructor where it is initialized.
- No default value after you have declared your local variable. You need to initialize your declared local variable.
- It can’t be defined by a static keyword.
Given below is the program in which we have used local variables initialized within a method of a class. As “height” is a local variable initialized with the calculate() method, the scope of this variable will be confined within the method.
public class local { public void calculate() { // initialized a local variable "height" int height = 0; // incrementing the value of height height = height + 170; System.out.println("height is: " + height + " cm"); } public static void main(String args[]) { // a is a reference used to call calculate() method local a = new local(); a.calculate(); } }
Output
Instance Variables
Instance variables are those variables that are declared inside a class. Unlike Local variables, these variables cannot be declared within a block, method, or constructor.
Enlisted below are the properties of the Instance variable:
- They are declared within a class but outside a block, method or constructor.
- It cannot be defined by a static keyword.
- Unlike Local variables, these variables have a default value.
- The integer type has a default value ‘0’ and the boolean type has the default value ‘false’.
- Unlike Local variables, we have access modifiers for Instance variables.
Given below is the program where we have demonstrated the instance variable. We have declared variables outside the main method and then assigned the values to them by using objects keeping one variable the “number” unassigned.
Finally, we have printed the values of these Instance variables and the unassigned variable “number” has printed ‘0’ by default.
public class instance { // Declaring instance variables public int rollNum; public String name; public int totalMarks; public int number; public static void main(String[] args) { // created object instance in = new instance(); in.rollNum = 95; in.name = "Saket"; in.totalMarks = 480; // printing the created objects System.out.println(in.rollNum); System.out.println(in.name); System.out.println(in.totalMarks); /* * we did not assign the value to number so it * will print '0' by default */ System.out.println(in.number); } }
Output
Static Or Class Variable
Unlike the Local and Instance variable (where we can not use static), we have another variable type which is declared as static and is known as “Static or Class variable”.
Given below are some of the properties of the Static or Class variable:
- These variables cannot be local.
- Static variables are shared among all the instances of a class.
- The default values of Static/Class variables are the same as the Instance variables.
- Static variables can be used within a program by calling the className.variableName
- The memory allocated to store Static variables is Static memory.
In the below program, we are calculating the circumference of a circle by using a private variable radius and a constant pi. Both these variables are declared as static.
public class StaticVariable { // radius is declared as private static private static int radius; // pi is a constant of type double declared as static private static final double pi = 3.14; public static void main(String[] args) { // assigning value of radius radius = 3; // calculating and printing circumference System.out.println("Circumference of a circle is: " + 2*pi*radius); } }
Output
Java instanceof
The Java instanceof is an operator that is used to tell whether the created object is an instance of the type or not. Type can be a Class or an interface.
The return type is Boolean i.e. either “true” or “false”.
For Example, In the below program, we have created a reference variable a1 of type A and tried to find whether a1 is an instance of A or not. As a1 is an instance of A, it returned “true”.
class A { public static void main(String args[]) { A a1 = new A(); System.out.println(a1 instanceof A); } }
Output
Frequently Asked Questions
Q #1) What are Java Global Variables?
Answer: Global variables are those variables that are accessed by the entire program and it is declared at the beginning of the program.
Global variables do not belong to Java as Java is a pure Object Oriented programming language and everything belongs to the Java Class. Just to protect data and members (variables) of the Class, Java does not support Global variables.
However, we have Static variables that are globally declared and is accessible by all method, subclass of a program.
Q #2) How to clear the value of a variable in Java?
Answer: It can be done using an inbuilt method of Java that is java.DoubleAdder.reset().
The syntax of this method is
Public void reset();
This method belongs to the package “java.util.concurrent.atomic.DoubleAdder” so you need to import this package before you proceed.
In the below program, we have added a few elements into DoubleAdder and then tried resetting it and finally printed the value after the reset operation.
import java.util.concurrent.atomic.DoubleAdder; public class clearValue { public static void main(String[] args) { DoubleAdder a = new DoubleAdder(); // adding elements into DoubleAdder a.add(99); a.add(83); a.add(75); a.add(105); //Printing the value of 'a' System.out.println("Value after adding elements: " +a); // resetting the value of a a.reset(); // Printing the value of 'a' after reset System.out.println("Value after resetting: " + a); } }
Output
#3) How to check the following Variable Type in Java?
String a = “test”;
Answer: If the variable is of type String then you can use referenceVariable.getClass().getName().
class A { public static void main(String args[]) { String a = "test"; System.out.println(a.getClass().getName()); } }
Output
#4) How to update a variable in Java?
Answer: Given below is a simple program where we have updated a variable in Java.
public class updateVariable { public static void main(String[] args) { int a = 10; System.out.println(a); a = 20; System.out.println(a);}}
Output
Conclusion
In this tutorial, we have discussed Java Variables and provided an insight into the Dynamic Initialization, scope, and lifetime of a variable along with explaining the different Java variable types and Java instanceof operator.
Each major concept was explained with proper programming examples to help you understand the topic better.
Suggested reading =>> VBA Variables and Option Explicit
Towards the end, we also saw a couple of frequently asked questions that will let you know about the different questions which could be asked during Java interviews.
=> Watch Out The Simple Java Training Series Here.