There can be programming situations where you would like to have a field or a method that is not associated with a particular object of the class but with the whole class itself. The static keyword is useful in such scenarios. In this article, we will be taking a look at the static keyword in Java
- Introduction to Static
- Static Fields
- Static Methods
- Static Blocks
- Rules for Static Methods/Blocks
- Why is main method static
Introduction to Static
As mentioned earlier, the static keyword associates a member with a class and not with any object of the class. So, it can be accessed even before an object of the class is created. It can be accessed by using the class name followed by the dot operator, followed by the static member name. Since static members are associated with the class itself, they are also known as class members. Both instance fields as well as instance methods can be static. In addition, a block of code can also be declared as static.
Static Fields
A static field is simply a field that has the static keyword specified in its declaration. When a field is made static, only one copy of the field exists across all objects of a class. So in other words, while each object has its own copy of the instance fields, all the objects share the same copy of the static field.
Static fields are generally useful for storing values that are not tied down to a particular object like constants. They are also useful for storing values that must be shared across objects.
Sample Code
public class Book { int numberOfPages; //Line 1 static int bookCount; //Line 2 public static void main(String[] args) { //Line 3 Book.bookCount = 0; //Line 4 Book book1 = new Book(); //Line 5 book1.numberOfPages = 200; //Line 6 Book.bookCount = 1; //Line 7 Book book2 = new Book(); //Line 8 book2.numberOfPages = 300; //Line 9 Book.bookCount = 2; //Line 10 System.out.println("Number of pages in book2:"+book2.numberOfPages); //Line 11 System.out.println("Number of books:"+Book.bookCount); //Line 12 } }
- The code specifies a class called Book
- Line 1 declares an instance field called numberOfPages
- Line 2 declares a static field called bookCount
- Line 3 specifies a main method
- Line 4 initializes the static field bookCount to 0. Note that the static field is accessed using the class name (Book) followed by the dot operator (.)
- Line 5 creates a new Book object called book1
- Line 6 initializes the numberOfPages field of book1 to 200
- Line 7 sets the static field bookCount to 1
- Similarly, Lines 8-9 create book2 and initialize its numberOfPages to 300
- Line 10 sets the static field bookCount to 2
- Line 11 prints numberOfPages for book2
- Line 12 prints bookCount
Output
Number of pages in book2:300
Number of books:2
While static fields can be accessed via the class name, Java also allows them to be accessed via the object name. However, all the objects will refer to the same copy of the field and will have the same value.
The following code demonstrates this:
System.out.println("Number of books:"+book1.bookCount); System.out.println("Number of books:"+book2.bookCount);
This code produces the following output:
Number of books:2
Number of books:2
Though static fields can be accessed via an object of the class as shown above, it is generally not recommended to do so. Static fields should be accessed via the class name. This helps to easily distinguish between static fields and instance fields.
Static Methods
Just like fields, methods can also be made static by specifying the static keyword in the method declaration. Static methods can also be accessed via the class name. Static methods are mostly used to perform operations on static fields. They are also used to contain utility code that does not operate on the instance fields of an object and so is not tied down to an object.
Sample Code
public class StringUtil { public static boolean isEmpty(String str) { //Line 1 if(str == null || str.length() == 0) return true; else return false; } public static String toUpperCase(String str) { //Line 2 return str.toUpperCase(); } public static void main(String args[]) { //Line 3 String str = "Hello"; System.out.println("isEmpty: "+StringUtil.isEmpty(str)); //Line 4 System.out.println("toUpperCase:"+StringUtil.toUpperCase(str)); //Line 5 } }
- This code specifies a StringUtil class
- Line 1 defines a static method called isEmpty which returns true if the input String is empty
- Line 2 specifies a static method called toUpperCase that converts the input String to uppercase and returns it
- Line 3 specifies a main method which invokes the isEmpty and toUpperCase methods at Lines 4,5
- Just like static fields, static methods can also be invoked via an object of the class though it is not recommended to do so.
Output
isEmpty: false
toUpperCase:HELLO
Static Block
A block of code can also be declared as static. The static keyword needs to be used before the block. Such code gets executed only once when the class is loaded and before any other code (even main method). There can be multiple static blocks in a single class. In such a case, they are executed in the order in which they occur in the code. Static blocks are typically used to perform some complex initialization of static fields which cannot be done at the time of declaration.
Sample Code
public class DirectionsDemo { static Map<String,String> directions = new HashMap<String,String>(); //Line 1 static { //Line 2 System.out.println("In static block."); directions.put("N", "NORTH"); //Line 3 directions.put("S", "SOUTH"); //Line 4 directions.put("E", "EAST"); //Line 5 directions.put("W", "WEST"); //Line 6 } public static void main(String[] args) { //Line 7 System.out.println("In main method"); System.out.println("Direction corresponding to N is:"+directions.get("N")); //Line 8 } }
- This code specifies a DirectionsDemo class
- Line 1 defines a static Map called directions. Since it is not a simple data type like int, it cannot be initialized here at the time of declaration
- Line 2 specifies a static block. It adds some values to the directions Map at Lines 3-6
- Line 7 specifies a main method which retrieves the direction corresponding to “N” and prints it at Line 8
Output
In static block.
In main method
Direction corresponding to N is:NORTH
Rules For Static Methods and Static Blocks
Static Methods and static blocks need to follow the following rules:
- They can only access static fields. They cannot access instance fields
- They can only invoke other static methods. They cannot invoke instance methods.
- They cannot refer to this or super
Why is Java’s main method static?
In Java, the main method is the starting point of any Java application. Its signature is as follows:
public static void main(String args[]){ //code here }
So, the main method is declared as static. Since the main method is the starting point of any application, it is invoked by the JVM to get the application running. So, it is necessary to declare it as static so as to allow the JVM to invoke it before objects of the class are created.
Conclusion
So, just to summarize, the static keyword can be applied to a field, method or simply a block of code. Static fields are class level fields, only one copy of the field exists across all objects of a class. Both static fields/methods can be accessed using the class name. In addition to static fields/methods, a block of code can also be made static. Such code gets executed when the class is loaded and before any other code.