The static keyword is one of the essential keyword in Java which represent the concept of static in programming. When you make something static, it is averse to change i.e. it is not dynamic and that is true for static variable, methods and class in Java. When you make a member variable static in Java, JVM assumes that the value of that variable will not change between instance and remain same for all objects of that class, hence it is also referred as class variable. Same is true for static methods, which is bonded during compile time because JVM assumes that their definition will not change because they are static and not virtual.
This property of static keyword provides a lot of convenience while coding but also put some restriction because static and Polymorphism are mutually exclusive. When you make a method static in Java, you cannot override it which means you compromise flexibility at the cost of convenience, hence object methods are generally non-static.
In this article, I am going to answer a lot of frequently asked questions about static keyword in Java e.g. what are static class, methods and variables in Java? When you should use static and what is the real use of making something static in Java.
I'll also answer questions related to capability of static keyword in Java e.g. can you overload static method in java, or whether you can override static method in Java? if no, then why not? What is the impact of accessing a static variable inside a non-static method and impact of static in concurrent java applications.
By going through all these frequently asked questions about static method, variables, class and initializer block, you will learn a lot of useful concepts, which will not only help you in your day-to-day coding but also on cracking the Java programming interview and doing well on core Java certifications like Java SE Developer or OCPJP, which solely focus on core Java fundamentals.
1. Can you make a class static in Java?
The answer is both yes and no. You cannot make a top level class static in Java i.e. a class which is not inside another class in Java, but you can make a nested class static in java i.e. a class which is inside another class. They are also known as Inner class in Java.
2. Can you make a method static in Java?
Yes, you can make a method static in Java, there is no problem with that. A static method though have some restriction on it e.g. you cannot access a non-static member variable inside a static method and you cannot override a static method in Java.
This property of static keyword provides a lot of convenience while coding but also put some restriction because static and Polymorphism are mutually exclusive. When you make a method static in Java, you cannot override it which means you compromise flexibility at the cost of convenience, hence object methods are generally non-static.
In this article, I am going to answer a lot of frequently asked questions about static keyword in Java e.g. what are static class, methods and variables in Java? When you should use static and what is the real use of making something static in Java.
I'll also answer questions related to capability of static keyword in Java e.g. can you overload static method in java, or whether you can override static method in Java? if no, then why not? What is the impact of accessing a static variable inside a non-static method and impact of static in concurrent java applications.
By going through all these frequently asked questions about static method, variables, class and initializer block, you will learn a lot of useful concepts, which will not only help you in your day-to-day coding but also on cracking the Java programming interview and doing well on core Java certifications like Java SE Developer or OCPJP, which solely focus on core Java fundamentals.
23 Static Variables, Methods and Class Interview Questions in Java
So, here we go, following are the frequently asked Java interview questions on static concepts, it covers how static variables are created and behave, how static class and method work and when to use them and intricacies involving them.1. Can you make a class static in Java?
The answer is both yes and no. You cannot make a top level class static in Java i.e. a class which is not inside another class in Java, but you can make a nested class static in java i.e. a class which is inside another class. They are also known as Inner class in Java.
2. Can you make a method static in Java?
Yes, you can make a method static in Java, there is no problem with that. A static method though have some restriction on it e.g. you cannot access a non-static member variable inside a static method and you cannot override a static method in Java.
Generally, a static method only work on the argument you pass them and they return value, instead of modifying object's state. Utility methods like Math.random() are made static in Java, so that you can call them easily without creating an instance of the class.
3. What is the difference between static and non-static method in Java?
There are many significant difference between static and non-static method in Java, here are some of them:
1) You cannot access a non-static variable inside static method in Java, but you can access a static variable inside a non-static method in Java.
2) You cannot override a static method in Java, but you can override a non-static method in Java provide it is not private.
3) You can call a static method in Java without creating an instance of the class, but you need an instance of the class which holds non-static method to invoke it.
4) A static method belongs to the class while a non-static method belong to object or instance of the class.
4. Can you make a variable static in Java?
Again the answer is both Yes and No. You can make a member variable static in Java, but you cannot make a local variable static in Java. A member variable is something which is declared inside a class but outside any method or block. They represent the stated of the object. When you make a variable static in Java then it belongs to class and has same values for all instances. They are also initialized at the time class is loaded into memory and can be accessed without creating instance of the class.
5. What is the difference between a static and non-static member variable in Java?
Similar to static vs non-static method in Java, there are a lot of difference between a static and non-static member variable, here are a couple of key differences between them:
1) You can access a static variable using class name but non-static variable are accessed via an object.
2) You can use a static variable without creating any object of the class, but you cannot do the same with non-static variables. You must create an object to use them.
3) A static variable is initialized at the time of the class loading but a non-static variable is initialized every time an object of the class is created, also known as instantiation.
4) A static variable has same values for all instances of object but a non-static variable has different values for each instance of the class. They form the object's state and since every instance is different than others, they should also be different.
5) You can use a static variable inside a static method in Java but using a non-static variable inside static method will result in compile time error as shown below:
6. Can you make a local variable static in Java?
No, you cannot make a local variable static in Java because it's scope is only within the block it is created and hence it could not belong to the class. Using a static variable will result in a compile time error as shown in following example:
7. Can you make a final variable static in Java?
Of course, you can make a final variable static in Java. Its normal practice to declare constant as static final variable in Java.
8. What is the use of static class in Java?
They are mostly used as utility class like Collections, Lists etc. Since they cannot contain state, they only contain method where are all the data required for processing is passed via method arguments. The advantage of static class is that you don't need to create instance to call a method, you can just call a static method using class name.
3. What is the difference between static and non-static method in Java?
There are many significant difference between static and non-static method in Java, here are some of them:
1) You cannot access a non-static variable inside static method in Java, but you can access a static variable inside a non-static method in Java.
2) You cannot override a static method in Java, but you can override a non-static method in Java provide it is not private.
3) You can call a static method in Java without creating an instance of the class, but you need an instance of the class which holds non-static method to invoke it.
4) A static method belongs to the class while a non-static method belong to object or instance of the class.
4. Can you make a variable static in Java?
Again the answer is both Yes and No. You can make a member variable static in Java, but you cannot make a local variable static in Java. A member variable is something which is declared inside a class but outside any method or block. They represent the stated of the object. When you make a variable static in Java then it belongs to class and has same values for all instances. They are also initialized at the time class is loaded into memory and can be accessed without creating instance of the class.
5. What is the difference between a static and non-static member variable in Java?
Similar to static vs non-static method in Java, there are a lot of difference between a static and non-static member variable, here are a couple of key differences between them:
1) You can access a static variable using class name but non-static variable are accessed via an object.
2) You can use a static variable without creating any object of the class, but you cannot do the same with non-static variables. You must create an object to use them.
3) A static variable is initialized at the time of the class loading but a non-static variable is initialized every time an object of the class is created, also known as instantiation.
4) A static variable has same values for all instances of object but a non-static variable has different values for each instance of the class. They form the object's state and since every instance is different than others, they should also be different.
5) You can use a static variable inside a static method in Java but using a non-static variable inside static method will result in compile time error as shown below:
6. Can you make a local variable static in Java?
No, you cannot make a local variable static in Java because it's scope is only within the block it is created and hence it could not belong to the class. Using a static variable will result in a compile time error as shown in following example:
7. Can you make a final variable static in Java?
Of course, you can make a final variable static in Java. Its normal practice to declare constant as static final variable in Java.
8. What is the use of static class in Java?
They are mostly used as utility class like Collections, Lists etc. Since they cannot contain state, they only contain method where are all the data required for processing is passed via method arguments. The advantage of static class is that you don't need to create instance to call a method, you can just call a static method using class name.
You can also use the static import feature of java to important static methods and use them as they are defined in same class. JUnit assertEquals() and Mockito mock() methods are best known examples of static methods in Java. Most of the unit testing libraries fives static methods for you to use for testing.
9. Can you make an abstract nested class static in Java?
14. Can you make a static method synchronized in Java?
Yes, you can make a static method synchronized in Java, there is no problem with that but the key thing to remember is that it will use a different lock to synchronized your critical section which means if same resource is modified by two different critical section where one using an object lock and other using a class lock i.e. a static synchronized method, you compromise the safety. This could lead to subtle multi-threading issue and should be avoided at all cost.
15. What is difference between a static synchronized and non-static synchronized method in Java?
The main difference between a static and non-static synchronized method in Java is that they both lock on different monitor. A static synchronized method uses a class level lock, obtained from the Class instance for that class, same as lock available to .class literal while non-static synchronized method uses object level lock. Remember, every instance has different object level lock. Because of this, a resource should not be shared between a static and non-static synchronized method in Java.
17. Can you access a non-static variable/method or inner class from a static method in Java?
No, you cannot access a non-static member e.g. a non-static variable, a non-static method or a non-static nested class, commonly known as Inner class from any static context in Java. This includes both static method as well as a static initializer block and a nested static class. Here is a code example to prove that point.
18. Can you change the value of a static variable in Java?
Yes, you can change the value of a static variable in Java provided it is not final. Though, it is recommended to declare a public static variable as final to prevent anyone changing its value because it is exposed to whole world and should be treated as read only or constant.
19. Can a static method call a non static method in Java?
No, a static method cannot call a non-static method in Java. it is illegal and doing so will result in compile time error.
20. What is the use of static variable in Java?
The real use of a static variable in Java is to provide same value to all instances. So if you have a scenario where a particular information/variable is same for all instances then that variable should be made static in Java.
21. What is the use of static block in Java?
The real use of a static block, also known as static initializer block is to initialize static variables and execute some code when a class is loaded. Since, static initializer block is executed only once in the life-time of a class i.e. when it is first loaded, it is good place for one time initialization code. By using static initializer block, you can run a Java program without using main method as shown here.
22. What is the use of static method in Java?
There are generally two kinds of methods exists in object oriented world, first which modifies objects state hence need access to member variables which forms object's state and second methods are those which doesn't change object's state, they work on the argument provided or do their own stuff e.g. utility method like Math.random() which generate random numbers.
8. When to make a class static in Java?
9. Can you overload a static method in Java?
10. Can you override a static method in Java?
11. Can you access a non-static variable inside a static method in Java?
That's all about some of the frequently asked questions about static in Java. As you have learned, static is a keyword which can be applied to class, methods and member variables in Java. Once you make a method static, you can call it without creating instance of holding class, same is true for static member variables, which you can access just by class name without creating instance of the class. A good understanding of when to use static keyword in Java with class, methods, and variable goes a long way. If you want to learn more about it, go and read Clean Code.
9. Can you make an abstract nested class static in Java?
This one is a tricky question so I leave that to you try first, let me know your answers in comments section, I will update the answer here once you guys have tried it out.
10. Can a static variable be initialized in a constructor?
Static variables are initialized at the time of class loading but yes, you can reinitialized them on constructor.
10. Can a static variable be initialized in a constructor?
Static variables are initialized at the time of class loading but yes, you can reinitialized them on constructor.
11. How to test static method in Java?
I often hear statements like static code is evil and they are hard to test, but those are very rare scenario when static method uses which cannot be mock. In most cases, you can test your static method just like non-static methods e.g. passing input and validating output. There is no different on that. You can use JUnit to test your static method, if you really need to mock your static method then you can also use PowerMock which allows mocking of static method unlike Mockito or EasyMock libraries.
12. Why outer class cannot be static in Java?
Any outder or top level class cannot be static in Java because it doesn't make sense. Static is property of member i.e. a member variable, method or a class because then it belongs to class. Since a top level class is an independent entity and doesn't belong to anyone, there is no sense making a outer class static in Java and rightfully Java compiler doesn't allow it.
13. What is a public final static member variable in Java?
It's a constant in Java, something whose value cannot be change. The combination of public, static and final keyword behave similar to const keyword of C++. The key thing to remember about these fields is that they are inlined during compilation i.e. value of these variables is copied to all the places they are used.
I often hear statements like static code is evil and they are hard to test, but those are very rare scenario when static method uses which cannot be mock. In most cases, you can test your static method just like non-static methods e.g. passing input and validating output. There is no different on that. You can use JUnit to test your static method, if you really need to mock your static method then you can also use PowerMock which allows mocking of static method unlike Mockito or EasyMock libraries.
12. Why outer class cannot be static in Java?
Any outder or top level class cannot be static in Java because it doesn't make sense. Static is property of member i.e. a member variable, method or a class because then it belongs to class. Since a top level class is an independent entity and doesn't belong to anyone, there is no sense making a outer class static in Java and rightfully Java compiler doesn't allow it.
13. What is a public final static member variable in Java?
It's a constant in Java, something whose value cannot be change. The combination of public, static and final keyword behave similar to const keyword of C++. The key thing to remember about these fields is that they are inlined during compilation i.e. value of these variables is copied to all the places they are used.
So, if variable is defined in one JAR and it is used in other JAR file and you change the value of final variable and recreated first JAR. The updated values will not reflect in second JAR until you compile it. That's the reason why you should compile your program everytime you upgrade your dependencies.
Yes, you can make a static method synchronized in Java, there is no problem with that but the key thing to remember is that it will use a different lock to synchronized your critical section which means if same resource is modified by two different critical section where one using an object lock and other using a class lock i.e. a static synchronized method, you compromise the safety. This could lead to subtle multi-threading issue and should be avoided at all cost.
15. What is difference between a static synchronized and non-static synchronized method in Java?
The main difference between a static and non-static synchronized method in Java is that they both lock on different monitor. A static synchronized method uses a class level lock, obtained from the Class instance for that class, same as lock available to .class literal while non-static synchronized method uses object level lock. Remember, every instance has different object level lock. Because of this, a resource should not be shared between a static and non-static synchronized method in Java.
16. Can you access a static variable, method, or nested static class from a non-static method in Java?
Yes, you can access a static members e.g. a static variable, a static method, or a nested static class from a non-static method in Java, there is no problem with that. Since static variable belongs to class, it can be accessed from both static and non-static context e.g. static initializer block, static method, or a nested static class. Here is a code sample to prove that point
Yes, you can access a static members e.g. a static variable, a static method, or a nested static class from a non-static method in Java, there is no problem with that. Since static variable belongs to class, it can be accessed from both static and non-static context e.g. static initializer block, static method, or a nested static class. Here is a code sample to prove that point
17. Can you access a non-static variable/method or inner class from a static method in Java?
No, you cannot access a non-static member e.g. a non-static variable, a non-static method or a non-static nested class, commonly known as Inner class from any static context in Java. This includes both static method as well as a static initializer block and a nested static class. Here is a code example to prove that point.
18. Can you change the value of a static variable in Java?
Yes, you can change the value of a static variable in Java provided it is not final. Though, it is recommended to declare a public static variable as final to prevent anyone changing its value because it is exposed to whole world and should be treated as read only or constant.
19. Can a static method call a non static method in Java?
No, a static method cannot call a non-static method in Java. it is illegal and doing so will result in compile time error.
20. What is the use of static variable in Java?
The real use of a static variable in Java is to provide same value to all instances. So if you have a scenario where a particular information/variable is same for all instances then that variable should be made static in Java.
21. What is the use of static block in Java?
The real use of a static block, also known as static initializer block is to initialize static variables and execute some code when a class is loaded. Since, static initializer block is executed only once in the life-time of a class i.e. when it is first loaded, it is good place for one time initialization code. By using static initializer block, you can run a Java program without using main method as shown here.
22. What is the use of static method in Java?
There are generally two kinds of methods exists in object oriented world, first which modifies objects state hence need access to member variables which forms object's state and second methods are those which doesn't change object's state, they work on the argument provided or do their own stuff e.g. utility method like Math.random() which generate random numbers.
So, if you have a method which doesn't need access to object's state or only dependent upon the argument you pass to them then its a good candidate for a static method. For a more in depth discussion on the use of static method in Java, please see when to make a method static in Java.
23. What is a class method and class variable in Java?
A static method or a static variable is also referred as class variable in Java.
23. What is a class method and class variable in Java?
A static method or a static variable is also referred as class variable in Java.
More Practice Questions based upon static concepts
Here are few more questions on static concepts which you can use to test your knowledge and understating of how static works in Java and how to use them. You can give your answer in comments and I can check that for you as well. You should be able to answer them if you have worked in Java for 1 to 2 years, but if you find it difficult feel free to ask
1. Can you make a constructor static in Java?
2. What is difference between a static class and Singleton in Java?
3. What is difference between a nested static class and non-static class in Java?
4. Can you make an interface static in Java?
5. When to make a variable static in Java?
4. Can you make an interface static in Java?
5. When to make a variable static in Java?
6. What is a static initializer block in Java?
7. When to make a method static in Java?
7. When to make a method static in Java?
8. When to make a class static in Java?
9. Can you overload a static method in Java?
10. Can you override a static method in Java?
11. Can you access a non-static variable inside a static method in Java?
12. Can you access a static variable inside a non-static method in Java?
13. Can you make a static method private in Java?
14. Can you declare a static method final in Java?
That's all about some of the frequently asked questions about static in Java. As you have learned, static is a keyword which can be applied to class, methods and member variables in Java. Once you make a method static, you can call it without creating instance of holding class, same is true for static member variables, which you can access just by class name without creating instance of the class. A good understanding of when to use static keyword in Java with class, methods, and variable goes a long way. If you want to learn more about it, go and read Clean Code.
Other Java Interview Questions topics you may like to explore
- Top 10 Java Generics Interview Questions and Answers (see here)
- 21 Final modifier interview questions (Answers)
- Top 10 Garbage collection interview questions in Java (see here)
- 21 Spring MVC Interview Questions with answers (spring questions)
- Top 50 multithreading and concurrency interview questions in Java (see here)
- Top 19 method overloading and overriding interview questions in Java (see here)
- Top 25 collections interview questions in Java (see here)
- Top 21 Inheritance interview questions in Java (see here)
- Top 30 OOP concept interview questions in Java (see here)
- Top 20 Design pattern and software design interview questions in Java (see here)
- 20 System Design Interview questions (System design questions)
- Top 10 Java String Interview Questions and answers (see here)
Very detailed and deep questions, thank you for sharing with me, you seems very knowledgeable.
ReplyDelete