1. Declaration: Static variables are declared using the static keyword before the variable type. They are typically declared at the class level, outside of any methods or constructors.
2. Memory Allocation: Static variables are allocated memory when the class is loaded into memory, and they persist throughout the entire execution of the program.
3. Accessing Static Variables: Static variables can be accessed directly using the class name followed by the variable name, without creating an instance of the class.
4. Sharing Data: Since static variables are shared among all instances of the class, modifying their value from one object will affect the value seen by all other objects of the same class.
5. Common Usage: Static variables are commonly used to represent constants, configuration settings, or shared resources that need to be accessed by multiple objects of the same class.
Here's an example that demonstrates the usage of a static variable in Java:
javapublic class Car {
private String brand;
private String model;
private static int numberOfCars; // Static variable
public Car(String brand, String model) {
this.brand = brand;
this.model = model;
numberOfCars++; // Incrementing the static variable on each object creation
}
public static int getNumberOfCars() { // Static method to access the static variable
return numberOfCars;
}
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Camry");
Car car2 = new Car("Honda", "Civic");
Car car3 = new Car("Ford", "Mustang");
System.out.println("Number of cars created: " + Car.getNumberOfCars()); // Accessing static variable using the class name
System.out.println("Car 1: " + car1.getBrand() + " " + car1.getModel());
System.out.println("Car 2: " + car2.getBrand() + " " + car2.getModel());
System.out.println("Car 3: " + car3.getBrand() + " " + car3.getModel());
}
}
The output of the above program will be:
outputNumber of cars created: 3
Car 1: Toyota Camry
Car 2: Honda Civic
Car 3: Ford Mustang
Explanation: In the main() method, three Car objects are created using different brand and model combinations. Each time a Car object is created, the numberOfCars static variable is incremented. Since there are three Car objects created, the value of numberOfCars will be 3.
When we call Car.getNumberOfCars() to access the static variable, it returns the current value of numberOfCars, which is 3. This value is then printed to the console.
Finally, the brand and model details of each Car object are printed, showing the respective brand and model values for each car.
No comments:
Post a Comment