<aside> <img src="/icons/table_red.svg" alt="/icons/table_red.svg" width="40px" /> Table of Contents
</aside>
<aside> 💡
<aside> 💡
Java Variables
Example:
int age = 27; // integer variable having value 27
String name = "Hello" // string variable
How to Declare Java Variables?
We can declare variables in Java as pictorially depicted below:
From the image, it can be easily perceived that while declaring a variable, we need to take care of two things that are:
In this way, a name can only be given to a memory location. It can be assigned values in two ways:
How to Initialize Java Variables?
It can be perceived with the help of 3 components explained above:
Example:
// Declaring float variable
float simpleInterest;
// Declaring and initializing integer variable
int time = 10, speed = 20;
// Declaring and initializing character variable
char var = 'h';
Types of Java Variables
There are different types of variables  which are listed as ****follows:
Local Variables
Instance Variables
Static Variables
Type of variable listed here in detail.
Local Variables
A variable defined within a block or method or constructor is called a local variable.
The Local variable is created at the time of declaration and destroyed after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variables are declared, i.e., we can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined scope.
Example 1:
// Java Program to show the use of local variables
import java.io.*;
class SampleProgram {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Output:
Local Variable: 10
Example 2:
// Java Program to show the use of
// Local Variables
import java.io.*;
public class SampleProgram {
public static void main(String[] args)
{
// x is a local variable
int x = 10;
// message is also a local variable
String message = "Hello, world!";
System.out.println("x = " + x);
System.out.println("message = " + message);
if (x > 5) {
// result is a local variable
String result = "x is greater than 5";
System.out.println(result);
}
// Uncommenting the line below will result in a
// compile-time error System.out.println(result);
for (int i = 0; i < 3; i++) {
String loopMessage
= "Iteration "
+ i; // loopMessage is a local variable
System.out.println(loopMessage);
}
// Uncommenting the line below will result in a
// compile-time error
// System.out.println(loopMessage);
}
}
Output:
x = 10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2