What is Variables?
Variable is a name of memory location or identifier that is used to store and manipulate data within a program.
Syntax
data_type var_name = value;
Example
// Integeric Types
byte byteValue = 127; // Here, byteValue is a variable of type byte
short shortValue = 32767; // Here, shortValue is a variable of type short
int intValue = 2147483647; // Here, intValue is a variable of type int
long longValue = 9223372036854775807L; // Here, longValue is a variable of type byte. Note the 'L' suffix for long literals
// Floating Types
float floatValue = 3.14f; // Here, floatValue is a variable of type float. Note the 'f' suffix for float literals
double doubleValue = 2.71828; // Here, doubleValue is a variable of type double.
// Character Type
char charValue = 'A'; // Here, charValue is a variable of type char
// Boolean Type
boolean booleanValue = true; // Here, booleanValue is a variable of type boolean
Types of Variables
Java variables can be classified into three main categories based on their scope.
1. Local Variables
Example
public class Local {
public static void main(String[] args) {
int x = 10; // Local variable
System.out.println(x);
}
}
2. Instance Variables
Example
public class Instance {
int y; // Instance variable
void fun(){
}
}
3. Static Variable
Example
public class Static {
static int z; // Static variable
}