[post-views]
In this lesson, you will learn
All variables must be declared before they can be used. Initializing a variable means assigning it an initial value.
In Java, you can initialize a variable at the time of declaration or later in the code.
Variable initialization at the time of the declaration
// Initializing 'age' with the value 25
// at the time of declaration
int age = 25;
Variable initialization later in the code
int height; // Declaration
height = 180; // Initialization later in the code
Following are some examples of variable declarations of various types. Some include an initialization.
| Variables | Descriptions |
| int age; | declare a variable age of int type |
| int x, y, z; | declares three ints, x, y, and z. |
| int age = 32, price, weight = 50; | declares three more ints, initializing age and weight. |
| byte z = 22; | initializes z. |
| double pi = 3.14159; | declares an approximation of pi. |
| char ch = ‘a’; | the variable ch has the value ‘a’. |
| float weight=20.50f; | String name=” Jack”; |
| long val=35L; | 35L is a long value |
| String name=”Jack”; | the variable name holds the value Jack |
{}) are only accessible within that block.
public class ScopeExample {
public static void main(String[] args) {
int x = 10; // x is local to the main method
if (x > 5) {
int y = 20; // y is local to the if block
System.out.println(x + y);
}
// System.out.println(y); // Error: y is not accessible here
}
}
For example, variables (declared within a class but outside any method), their lifetime is tied to the lifetime of the object they belong to.
public class LifetimeExample {
int instanceVar; // Instance variable, part of the object's state
public void someMethod() {
int localVar = 5; // Local variable, exists only during
// the method's execution
System.out.println(instanceVar + localVar);
}
}
Understanding the scope and lifetime of variables is crucial for writing robust and maintainable Java code.
It helps in managing memory efficiently and prevents unintended access to variables in different parts of the code.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.