Understanding Java Variables
In Java, a variable is a container that holds data that can be manipulated or used in the program. Variables are defined with a specific data type, and their values can change during the execution of the program.
Declaration and Initialization:
A variable is declared by specifying its data type and name. It can also be initialized with an initial value at the time of declaration or later in the program.
// Declaration
int age;
// Initialization
age = 25;
// Declaration and Initialization
double price = 49.99;
Types of Variables:
Local Variables: Defined within a method and have local scope.
void exampleMethod() {
// Local variable
int localVar = 10;
}
Instance Variables: Belong to an instance of a class and are declared inside a class but outside any method.
public class MyClass {
// Instance variable
int instanceVar = 42;
}
Static Variables: Belong to the class rather than instances of the class and are declared using the
static keyword.
public class MyStaticClass {
// Static variable
static int staticVar = 100;
}
Example:
Here's an example demonstrating the use of variables in Java:
public class VariableExample {
public static void main(String[] args) {
// Declaration and Initialization
int x = 5;
int y = 10;
// Performing operations using variables
int sum = x + y;
// Output the result
System.out.println("Sum: " + sum);
}
}
Note:
Understanding how to declare, initialize, and use variables is fundamental to Java programming. Choose meaningful variable names and use proper data types to enhance code readability and maintainability.