Static Keyword in Java
In this blog, you will learn how to use the static keyword in Java to create class variables and methods that are shared by all instances of a class.
Static keyword in Java is used to manage memory. This keyword is applied to variables, methods, blocks, and nested classes. When you apply the static keyword to a member, it indicates that the member belongs to the class itself rather than to individual instances of the class. There is only one copy of the member that is shared by all instances of the class. You can use the static keyword to create utility methods or to create variables that need to be shared among all instances of a class.
The static keyword in Java is used for the following:
Explore Best Online Java Courses
Static Variable
A static variable is a class variable that is shared by all instances of the class. Static keyword is used to declare a static variable. It is initialized when the class is loaded.
Example of using a Static Variable
public class Employee { // Static variable to keep track of the total number of employees public static int numEmployees = 0; private String name; private int id; // Constructor to create a new employee object public Employee(String name) { // Store the name and assign a unique ID this.name = name; this.id = numEmployees; // Increment the numEmployees counter numEmployees++; } // Getter method to return the name of the employee public String getName() { return name; } // Getter method to return the ID of the employee public int getId() { return id; } // Static method to return the total number of employees public static int getNumEmployees() { return numEmployees; }}
Explanation:
- The Employee class includes a static variable called numEmployees that is used to keep track of the total number of Employee objects that have been created.
- The numEmployees variable is incremented every time a new Employee object is created in the classβs constructor.
- The Employee class also has a getNumEmployees method that returns the current value of the numEmployees variable.
For the above example, you can create instances of the Employee class and call the methods as needed:
Employee e1 = new Employee("Alice");Employee e2 = new Employee("Bob");Employee e3 = new Employee("Charlie");
System.out.println("Number of employees: " + Employee.getNumEmployees()); // Outputs "Number of employees: 3"
Best-suited Java courses for you
Learn Java with these high-rated online courses
Static Method
A static method is a method that is associated with the class itself, rather than with any particular instance of the class. It is declared with the static keyword and can be called without creating an instance of the class.
Example of using a Static Method
public class MyClass { // Static method public static void sayHello() { System.out.println("Hello!"); } public static void main(String[] args) { // Call the sayHello method without creating an instance of the MyClass class MyClass.sayHello(); // Outputs "Hello!" }}
Explanation
- sayHello is a static method in the MyClass class
- This method can be called without creating an instance of the MyClass class
- The method prints string βHello!β on the console
- Syntax for using a a static method: ClassName.methodName(arguments)
- For example, the sayHello method is called using MyClass.sayHello().
Static Block
A static block is a block of code that is executed when a class is first loaded. It is useful for initializing static variables.
Example of using a Static Block
Problem: Imagine you are organizing a field trip to the zoo. You want to keep track of the number of permission slips you have received from the studentsβ parents or guardians.
Solution: Use a static block to initialize a static variable that keeps track of the number of permission slips received. As students bring in their permission slips, increment the static variable. Finally, print the number of permission slips received to the console.
public class FieldTrip { // Static variable to keep track of the number of permission slips received public static int permissionSlipsReceived; // Static block to initialize the permissionSlipsReceived variable static { permissionSlipsReceived = 0; } public static void main(String[] args) { // As students bring in their permission slips, increment the permissionSlipsReceived variable permissionSlipsReceived++; permissionSlipsReceived++; // Print the number of permission slips received System.out.println("Permission slips received: " + permissionSlipsReceived); // Outputs "Permission slips received: 2" }}
Explanation
- Initialize a static variable permissionSlipsReceived to 0 in a static block.
- Static block is executed when the FieldTrip class is first loaded and the value of the permissionSlipsReceived variable is set to 0.
- The main method increments the permissionSlipsReceived variable each time a student brings in a permission slip.
- The main method prints the number of permission slips received to the console.
Static Nested Class
A static nested class is a nested class that is declared with the static keyword. It is associated with the outer class and has access to all of the static members of the outer class.
Example of using Static Nested Class
Imagine you are building a system to store information about people and their addresses. For this you have to design a class called Person that has a name and an address. The address should have a street and a city. The Person class should include a method to return the name of the person, and a method to return an instance of the address. The address class should have a method to return the full address as a string
public class Person { // Field to store the name of the person private String name; // Static inner class to represent the address of the person public static class Address { // Fields to store the street and city of the address private String street; private String city; // Method to return the full address as a string public String getFullAddress() { return street + ", " + city; } } // Method to return the name of the person public String getName() { return name; } // Method to return an instance of the Address class public Address getAddress() { return new Address(); }}
In the above example, the Address class is a static inner class that represents the address of a person. The Address class has two fields to store the street and city of the address, and a method to return the full address as a string. The Person class has a field to store the name of the person, and methods to return the name and an instance of the Address class.
You can use the Person and Address classes as follows:
// Create a new person with a name and addressPerson person = new Person();person.name = "John Smith";Person.Address address = person.getAddress();address.street = "123 Main St.";address.city = "New York";
// Print the person's name and full addressSystem.out.println("Name: " + person.getName()); // Outputs "Name: John Smith"System.out.println("Address: " + address.getFullAddress()); // Outputs "Address: 123 Main St., New York"
Scenario based example to understand Static Keyword in Java
Scenario: You are creating a Java application that manages a database of customer records. You want to create a Customer class that represents a customer record, and you want to be able to search for customers by their customer ID.
Problem: You need a way to search for customers by their customer ID without creating an instance of the Customer class.
Solution: Use the static keyword to declare a static method in the Customer class that searches for customers by their customer ID. A static method can be called without creating an instance of the Customer class, making it easy to search for customers from anywhere in the application.
public class Customer { // Array to store customer records private static Customer[] customerList = new Customer[10]; // Counter to keep track of the number of customers in the list private static int numCustomers = 0; // Customer ID and name private int id; private String name; public Customer(int id, String name) { // Store the ID and name for this customer this.id = id; this.name = name; // Add this customer to the list and increment the counter customerList[numCustomers] = this; numCustomers++; } public static Customer findById(int id) { // Search the list for a customer with the given ID for (int i = 0; i < numCustomers; i++) { if (customerList[i].id == id) { return customerList[i]; } } // If no customer is found, return null return null; } public int getId() { return id; } public String getName() { return name; }}
Explanation
- The customerList array stores the customer record.
- numCustomers variable keeps track of the number of customers in the list.
- The Customer constructor stores the ID and name for a new customer, adds the customer to the customerList array, and increments the numCustomers counter.
- The findById method searches the customerList array for a customer with the given ID and returns the customer if found, or null if not found.
You can use this Customer class like this:
// Create some customer recordsCustomer customer1 = new Customer(1, "John Smith");Customer customer2 = new Customer(2, "Jane Doe");Customer customer3 = new Customer(3, "Bob Johnson");
// Search for a customer by IDCustomer foundCustomer = Customer.findById(2);
// Print the customer's nameSystem.out.println("Found customer: " + foundCustomer.getName()); // Outputs "Found customer: Jane Doe"
Conclusion
You can use static methods in Java for tasks that do not depend on the state of any particular instance of a class. You can use these methods from the class without creating an instance of the class.
FAQs
How does Static keyword help in managing memory?
The static keyword helps in managing memory in Java by allowing you to create variables and methods that are shared by all instances of a class. This can help to reduce memory usage by eliminating the need to create a separate copy of the member for each instance of the class.
How does static variables and static methods reduce the amount of memory that is used by your program?
By using static variables and methods, you can reduce the amount of memory that is used by your program, because you do not need to create a separate copy of the member for each instance of the class. This can be especially useful when you have a large number of instances of a class, because it can help to reduce the overall memory usage of your program.
Why static keyword is used to create utility methods?
Static keywords are used to create static methods. These useful for creating utility functions because they can be called directly from the class, without the need to create an instance of the class. This can make it easier to reuse code and perform tasks that do not depend on the state of any particular instance of a class.
Why use static keyword to create constants?
The static keyword is used to create constants in Java because it allows you to declare a variable that cannot be modified after it is initialized.
Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio