In this chapter, we will discuss the variables in Java and the types of variables in java. We will see how to declare and use it. In Java, we use different variable types like static variables in java, instance variable in java, java global variable, and a local variable in java.
Here is the table content of the article.
1. Declaration of variable
2. Initialization of variable
3. Declaration with Initialization of variable
4. Types of variables
5. Local variables
6. Instance variables
7. Static/class variables
8. Why local variables must be initialized in java?
9. Rules/Naming conventions for variables
10. Difference between local variable and global variable
11. Difference between static variable and instance variable
12. Local Variable Type Inference (Java var)
Youtube video available in the Hindi language
A variable behaves like a container that holds the value that can change during the program’s execution. It is just the name of a memory location. A variable always binds with a datatype.
int a = 5;
Here “a” is a variable associated with value 5.
“int” is the data type of variable “a”. It means “a” can hold numeric values.
NOTE: A variable must be declared before use.
Declaration of variable
data_type variable_Name
data_ type: Type of data that you want to store in this variable.
variable_Name: Name of variable.
int a
Here the data type of variable is “int” and “a” is the variable name.
Initialization of variable
After the declaration of a variable, you can initialize the variable. When we assign the value to a variable it means we initialize the variable. To initialize a variable, follow this syntax:
variable_Name = value
a = 5;
As we already discuss “a” is a variable name and its data type is int. So, it can store integer values.
Declaration with Initialization of variable
You can declare the variable with assign the value to it.
data_type variable_Name = value;
int a = 5;
So we have two ways to declare and assign the value to variables.
Types of variables
1. Local variable in java
- A Local variable in the method
- A local variable in a static block
- A local variable in instance block
- A local variable in Constructor
2. Global variable in java
- Instance variables
- Static/class variables
1. local variable in java
When we declare a variable inside the body of a method or block or constructor then it’s known as a local variable. You can’t access these variables outsides of the method. These variables are created in memory when the function/block/constructor is called. After completion of the execution of function/block/constructor, these variables get destroyed by JVM. We can access these variables only within that block because the scope of these variables exists only within the block. The initialization of the local variables is mandatory. If you don’t initialize the variable compiler will throw a runtime exception. Let’s see how to define the local variable.
A Local variable in the method
We can create a local variable within the method and use it. But the scope of variables lies within the method. Because these variables get created when the method gets invoked and destroyed after the execution of the method. You can’t leave a local variable without a declaration. It’s mandatory to initialize the local variable.
public class Student { public void studentRollNo() { // local variable rollNo, Its declared in studentRollNo () int rollNo = 5; System.out.println("Student Roll no is : " + rollNo); } public static void main(String args[]) { Student student = new Student(); student.studentRollNo(); } }
Output: Student Roll no is : 5
In the above program, the variable rollNo is defined in the function studentRollNo(). If we use the variable rollNo outside of the StudentRollNo() function, the compiler will show an error.
public class Student { public void studentRollNo() { // local variable rollNo, Its declared in studentRollNo () int rollNo = 5; System.out.println("Student Roll no is : " + rollNo); } public static void main(String args[]) { // using local variable rollNo outside it's scope System.out.println("Student Roll no is : " + rollNo); } }
Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem: rollNo cannot be resolved to a variable at Student.main(Student.java:13)
A local variable in a static block
When we declare a variable within the static block. It’s known as a local variable within a static block. But a local static variable doesn’t accessible outside the block because it has limited scope. The scope lies within the braces. If you are a beginner then you can read the topic of the static block later. Let’s see the example:
public class MainClass { static { String name = "JavaGoal"; } public static void main(String[] args) { System.out.println("Name :"+name); } }
Output: Compilation error
In the above example, the variable name is declared within a static block so we can’t access it outside the block.
A local variable in instance block
Like static block, We can declare a variable in the instance block and that is known as a local variable in the instance block. We can perform actions on variables only within the instance block because we can’t access the variable outside the block.
public class MainClass { { String name = "JavaGoal"; name = name + "Website"; } public static void main(String[] args) { System.out.println("Name :"+name); } }
Output: Compilation error
A local variable in Constructor
A variable declared within the constructor is also known as a local variable and it will be accessible only within the constructor. Let’s take an example:
public class MainClass { public static void main(String[] args) { System.out.println("Main method"); new MainClass(); } MainClass() { // Local variable int a = 5; System.out.println("value of a: "+a); } }
Output: Main method
value of a: 5
2. Global variable in java
The global variable always declares outside the method/block/constructor. It is always get declared within the body of the class. Unlike local variables, the scope of these variables is not limited. We can access the global variable within the class or outside the class. Global variables are categorized in two ways: Instance variable in java and Static/Class variable in java
Instance variable in java
A variable declared outside the method/block/constructor but inside the class is called an instance variable in java. We don’t use the static keyword with the instance variable because if we use static with it, It makes it a class variable and it will be common for all instances/Objects.
- Whenever we create an object of the class, the JVM creates one copy of the instance variable and associates it with the object. The copy gets destroyed when the object gets destroyed.
- We can specify the access modifier/access specifier for instance variables. By default, JVM provides the default access specifier.
- Initialization of Instance Variable is not Mandatory. Its default value depends on the data type of variable.
- To access the instance variable we always need to create the object.
An important point about instance variables
Every object has its own separate copy of the instance variable. If we created two objects of a class, then each object contains its own instance variables. Let’s understand with an example:
public class Student { // instance variable int rollNo; public void printStudentRollno() { System.out.println("Student Roll No: "+rollNo); } public static void main(String args[]) { // Creating first object of Student class. //This object creates separate copy of "rollNo". Student firstStudent = new Student(); // Assign the roll no to first Student firstStudent.rollNo = 5; // print the first student roll no firstStudent.printStudentRollno(); // Creating second object of Student class. //This object also creates separate copy of "rollNo". Student secondStudent = new Student(); // Assign the roll no to second Student secondStudent.rollNo = 8; // print the second student roll no secondStudent.printStudentRollno(); } }
Output:
Student Roll No: 5
Student Roll No: 8
Explanation of the above example
As you can see in the above program the variable “rollNo” is an instance variable. In case we have multiple objects as in the above program, each object will have its own copies of instance variables. We have changed the instance variable by different objects it doesn’t reflect another object’s value. It is clear from the above output that each object will have its own copy of the instance variable.
Memory representation: Objects are always created in heap memory
Static variable in java/class variable in java
When we use a static keyword with an instance variable it makes it a class variable. The Static variable is known as a class variable because they are associated with the class and common for all the objects of a class.
We will read this topic in a separate post. If you want it in detail please read it.
- By use of the static keyword, we can create static variables within a class and it should be outside of any method/constructor/block.
- Whenever JVM loads a class in the memory, it creates one copy of a static variable in memory. Static variables are common for all objects of a class because a static variable is associated with the class.
- Static variables are created at the start of program execution and destroyed automatically when execution ends.
- Initialization of Static Variable is not Mandatory. JVM provides the default value to the static variable based on the data type of the variable.
- The static variables are directly accessible by class name. If we access the static variable by an object, the compiler shows the warning message. The compiler replaces the object name with the class name at the time of execution.
NOTE: We don’t need to create an object of that class to access static variables.
Syntax to access static variables:
Class_Name.variable_name
public class Student { // instance variable int rollNo; // static variable static int count; public void printCountAndRollNo() { System.out.println("Student Roll No: "+rollNo); System.out.println("Student count: "+count); } public static void main(String args[]) { // Creating first object of Student class. //This object creates separate copy of "rollNo". Student firstStudent = new Student(); // Assign the roll no to first Student firstStudent.rollNo = 5; // Assigning count to first firstStudent.count = 1; // print the first student roll no firstStudent.printCountAndRollNo(); // Creating second object of Student class. //This object also creates separate copy of "rollNo". Student secondStudent = new Student(); // Assign the roll no to second Student secondStudent.rollNo = 8; // Assigning count secondStudent.count = 2; // print the second student roll no secondStudent.printCountAndRollNo(); } }
Output:
Now number of Student is: 1
Now number of Student is: 2
Memory representation: Objects are always created in heap memory
As you see in the example “count” is a static variable. So that can access it through the class name. All the objects will share the same “count” variable.
public class Student { // instance variable int rollNo; // static variable static int count; public void printCountAndRollNo() { System.out.println("Student Roll No: "+rollNo); System.out.println("Student count: "+count); } public static void main(String args[]) { // Creating first object of Student class. //This object creates separate copy of "rollNo". Student firstStudent = new Student(); // Assign the roll no to first Student firstStudent.rollNo = 5; // Assigning count to first Student.count = 1; // print the first student roll no firstStudent.printCountAndRollNo(); // Creating second object of Student class. //This object also creates separate copy of "rollNo". Student secondStudent = new Student(); // Assign the roll no to second Student secondStudent.rollNo = 8; // Assigning count Student.count = 2; // print the second student roll no secondStudent.printCountAndRollNo(); } }
Both objects access the static variable from a static pool. We will discuss it in a static keyword.
Why does local variable need to be initialized in java?
As we know local variables have limited scope and lifetime. They can’t be accessible outside the method/block/constructor, so the compiler can predict the execution route of the local variables. Due to the limited scope and lifetime of a variable, the compiler identifies the declared variable and instructs a programmer to initialize it.
If the compiler allows a local variable without initialization, that leads to the possibility of a potential bug in the program.
Now you must think, that the compiler should provide the default value as it provides in the case of global variables. But initializing every variable with a default value takes a hit on the performance.
Rules/Naming conventions for variables
- The variable name should start with a lowercase letter such as name, marks, etc.
- Variable should begin with [a-z or A-Z] Or $(dollar), and _ (underscore).
- It can start with special characters like $(dollar), and _ (underscore).
- If the name contains multiple words, then you can use two ways to write it:
- First, Start it with a lowercase letter followed by an uppercase letter such as firstName, and lastName. It is known as the camelCase convention.
- Second, You can append an underscore(_) between the multiple words. Example: first_Name, last_Name, etc
- You should avoid the use of one-character variables such as a, b,c
Youtube video available in the Hindi language
Difference between local variable and global variable
We have read the local and global variables. Let’s find out what is the difference between the local variables and the global variables. Finds the local variable and instance variable in java.
Scope
The local variable has limited scope than the global variable. Because it always declares within function/constructor/block. So, it can’t be accessible outside the function/constructor/block.
But the global variable has large scope than the local variable because it is always declared outside the function/constructor/block. The global variables are always accessible to the whole class.
Lifetime
The lifetime of local variables starts when a function/constructor/block gets invoked and ends with the completion of the execution of a particular function/constructor/block.
The lifetime of the global variable depends on the type of variable.
For static variable: The lifetime of static variables starts when the class gets loaded and ends when the class will be destroyed from memory.
For non-static/Instance variable: The instance variable gets loaded when we create an object of the class and destroyed when the object gets destroyed.
Use of data
If we want to use the local variable in different methods, then we have to pass it as an argument/parameter.
But a global variable is accessible everywhere in the class. We don’t need to pass it as arguments.
Default value
It is mandatory to initialize the local variable. If we don’t initialize a local variable the compiler throws a compilation error because JVM doesn’t provide default values to local variables.
JVM provides default values if we don’t initialize the variable. The default value depends on the data type of variable. Like 0 for int, and false for boolean.
Duplicate names of the variables
A local variable can have the same names but in a different method/block/constructor. Because they have limited scope and don’t affect each other.
But the name of the global variable must but unique. We can’t use duplicate names of the global variables. The changes in the global variable create an effect in the whole class wherever it is used.
Youtube video available in the Hindi language
Difference between static variable and instance variable
Let’s discuss the difference between the static and non-static variables in java because non-static variables are instance variables. This is known as the difference between class variable and instance variable.
Instance variables
1. When we declare a global variable without a static keyword that is known as an instance variable. We don’t use the static keyword with instance variables. Because the instance variable binds with the instance/object of the class.
2. When we create an instance/object of a class then JVM creates a copy of instance variables associated with the corresponding object. The instance variable gets destroyed when the instance/object is destroyed.
3. The instance variables are accessible through the object.
4. In non-static methods, Instance variables are accessible directly by name within the class. But in the static method, we have to use the object name.
5. Instance variables are not common for all objects because JVM creates a separate copy of each instance variable when we create an object.
Class variables(static variables)
1. When we declare a global variable with the static keyword that is known as class variable/ static variable. Class variables are also known as static variables because we use static keywords. These variables directly bind to class instead of instance/object.
2. But static variables load in memory during the class loading. When JVM loads the class in memory then a static variable gets created in Static pool memory. The static variables get destroyed when the program stops.
3. The static variables are accessible directly by class name.
4. In static or non-static methods, we can directly access the static variables by the name of the variable within the same class.
5. But static variables are standard(Common) for all objects of class because they bind with class, not instance/object.
Local Variable Type Inference (Java var)
Java 10 introduced a new feature called local variable type inference. In this section, we will discuss the Local variable type inference. This feature allows one to define a variable using var without specifying its type of it. A local variable can define by the use of the var keyword in java. In Java var is the most common way to declare local variables.
Everyone knows we must declare a data type with the variable name. From Java 10 onwards, we don’t need to declare data type with a local variable. We can simply use the var keyword. The compiler automatically detects the data type of the variable at compile time. Now the developer can skip the data type declaration only for local variables and the compiler will infer the data type.
Here is the table content of this article that we will cover.
- Why has the var keyword in the java feature been introduced?
- How to declare local variables by use of var?
- Is var not a keyword?
- Where can var be used?
- Where var cannot be used?
Why has the var keyword in the java feature been introduced?
Before java 10, to declare a local variable we use the specific syntax:
Class_name variable_name = new Class_name(arguments);
Let’s see some examples and have a discussion on the same.
Example 1: ArrayList<String> listOfString = new ArrayList<String>(); Example 2: String hello = “Hello world!”; Example 3: String string = "This is a simple string for java example"; Example 4: Collector<String, ?, Map<String, Long>> byOccurrence = groupingBy(Function.identity(), counting()); Map<String, Long> wordFrequency = Arrays.stream(string.split(" ")).collect(byOccurrence);
Explanation of var keyword example
The above examples are completely fine. But there are a few points that I want to discuss here:
1. In the first example, The type of variable clearly depends on the expression on the right-hand side, So the mentioning same thing before the name of the variable makes it redundant.
2. In the second example, we can clearly see the right-hand side is a string. Because it’s enclosed in double inverted commas. So variable declaration can be shorter.
3. The above two examples were simple so let’s discuss the 3rd example. Here we are using the Collector for groupBy and the output of one collector will be the input for the second one. So, we can simply use the var to reduce the complexity.
How to declare local variables by use of var?
You can simply right the var instead of mentioning the variable with datatype on the left side.
Syntax:
var variable_Name = new ClassName(arguments);
import java.util.Arrays; import java.util.HashMap; public class UseOfVar { public static void main(String[] args) { var intValue = 5; var stringValue = "JavaGoal.com"; var floatValue = 5.5f; var longValue = 5.5555; var listOfIds = Arrays.asList(1, 2, 3, 4, 5); var hashMap = new HashMap<Integer, String>(); System.out.println(intValue); System.out.println(stringValue); System.out.println(floatValue); System.out.println(longValue); System.out.println(listOfIds.toString()); System.out.println(hashMap); } }
Output: 5
JavaGoal.com
5.5
5.5555
[1, 2, 3, 4, 5]
{}
Is var not a keyword
In java, var is not a keyword but it’s a reserved type name. Also, keywords in Java cannot be used as identifiers. As we know a keyword has more restrictions than the reserved word. A keyword can’t be used for any type of identifier like variables, methods, classes, interfaces etc. But a reserved type name has fewer restrictions.
- We can use the var as a local variable
- Use of var as a method name
- Use of var as the package name
- Can’t use it as a class name
// Creating a package name with var package var; public class UseOfVar { public static void main(String[] args) { // Creating a local variable by use of var var var = new UseOfVar(); // Calling the method var.var(); } // Here we are using var as method name private void var() { System.out.println("Using var as method name"); } }
Output: Using var as method name
Where can var be used?
In java 10, developers skip the type declaration only for local variables (those defined inside method definitions, initialization blocks, for-loops, and other blocks like if-else). Let’s see different places where we can use it.
- Local variable initializers
- Use in loop
- In a static/instance initialization block
- Resource variables of the try-with-resources statement
Local variable initializers
In this example, we will create a different type of object by use of var. This example will explain the use of var
a Local variable. For each variable, we will use the data type and var, then see the result. Both ways should work fine.
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class UseOfVar { public static void main(String[] args) { int intValue = 5; String stringValue = "JavaGoal.com"; float floatValue = 5.5f; double doubleValue = 5.5555; List<Integer> listOfIds = Arrays.asList(1, 2, 3, 4, 5); HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); var intValue1 = 5; var stringValue1 = "JavaGoal.com"; var floatValue1 = 5.5f; var doubleValue1 = 5.5555; var listOfIds1 = Arrays.asList(1, 2, 3, 4, 5); var hashMap1 = new HashMap<Integer, String>(); System.out.println(intValue); System.out.println(stringValue); System.out.println(floatValue); System.out.println(doubleValue); System.out.println(listOfIds.toString()); System.out.println(hashMap); System.out.println(intValue1); System.out.println(stringValue1); System.out.println(floatValue1); System.out.println(doubleValue1); System.out.println(listOfIds1.toString()); System.out.println(hashMap1); } }
Output: 5
JavaGoal.com
5.5
5.5555
[1, 2, 3, 4, 5]
{}
5
JavaGoal.com
5.5
5.5555
[1, 2, 3, 4, 5]
{}
Use in loops
You can use the var in the loops to declare a local variable. Here, we will use var to declare the index value as well as a normal variable.
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class UseOfVar { public static void main(String[] args) { var list = Arrays.asList(1,2,5,6,8,4,7); for(var i = 0; i < list.size(); i++) { var a = 5; System.out.println("Value of i: "+ i + " and a: "+a); } for (var val : list) { System.out.println("Value from enhanced for loop: " + val); } var x = 0; while(x < list.size()) { var string = "Hello world!"; System.out.println("Value from while loop: " + list.get(x)); x++; } } }
Output: Value of i: 0 and a: 5
Value of i: 1 and a: 5
Value of i: 2 and a: 5
Value of i: 3 and a: 5
Value of i: 4 and a: 5
Value of i: 5 and a: 5
Value of i: 6 and a: 5
Value from enhanced for loop: 1
Value from enhanced for loop: 2
Value from enhanced for loop: 5
Value from enhanced for loop: 6
Value from enhanced for loop: 8
Value from enhanced for loop: 4
Value from enhanced for loop: 7
Value from while loop: 1
Value from while loop: 2
Value from while loop: 5
Value from while loop: 6
Value from while loop: 8
Value from while loop: 4
Value from while loop: 7
In a static/instance initialization block
We are already familiar with static blocks and instance blocks. So here we can declare a local variable by use of var.
public class UseOfVar { static { var x = "Hi there"; System.out.println(x); } public static void main(String[] args) { // main method } }
Output: Hi there
Resource variables of the try-with-resources statement
On the other hand, the var
type is a very nice fit for try-with-resource. For example:
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; public class UseOfVar { public static void main(String[] args) { try (PrintWriter writer = new PrintWriter(new File("welcome.txt"))) { writer.println("Welcome message"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } }
Where var cannot be used
- For Global variable
- In Method parameters
- In Method return types
- Local variable declarations without any initialization
- Cannot use null for initialization
1. For Global variable: You can’t create a variable with var at class level (Global variable or class variable). It can be used only for local variables. If you try to create a global variable with var you will get a compile-time error.
class TryToUseVar { var a = 5; public static void main(String args[]) { System.out.println("Hello world!"); } }
Output: java: ‘var’ is not allowed here
2. In method parameter: You can’t use var in method parameters. It shows a compilation error if we use it in parameters.
class TryToUseVar { public static void main(String args[]) { System.out.println("Hello world!"); TryToUseVar.sample(1,5); } private static void sample(var a, var b) { System.out.println(a+b); } }
Output: java: ‘var’ is not allowed here
3. In Method return types: We can’t return the var from any type of method. Java doesn’t permit it. It shows a compilation error.
class TryToUseVar { public static void main(String args[]) { System.out.println("Hello world!"); TryToUseVar.sample(1,5); } private static var sample(int a, int b) { return (a+b); } }
Output: Compilation error
4. Local variable declarations without any initialization: As we know, we can leave the initialization of local variable. It means we can just declare then and later we can assign the value. But when we use var we have to initlize the local variable.
class TryToUseVar { public static void main(String args[]) { int i; // valid statement var a; // Invalid statement System.out.println("Hello world!"); } }
Output: Compilation error
5. Cannot use null for initialization: We can’t initialize a variable by null. It is not allowed. It shows a compilation error.
class TryToUseVar { public static void main(String args[]) { int i = 0; // valid statement var a = null; // Invalid statement System.out.println("Hello world!"); } }
Output: Compilation error