• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Top 14 Java Interview Questions on Static keyword

February 17, 2016 by javainterviewpoint 7 Comments

1. What is static keyword in Java?

Static is a Non-Access Modifier. Static can be applied to variable, method, nested class and initialization blocks (static block).

2. What is a static variable?

  • A Static variable gets memory allocated only once during the time of class loading.
  • All the instance of the class share the same copy of the variable, a static variable can be accessed directly by calling “<<ClassName>>.<<VariableName>>” without need to create an instance for the class.
  • value of a static variable will be common for all instances

public class StaticVariableExample 
{
    static int a =10;
    public static void main(String args[]){
        StaticVariableExample s1 = new StaticVariableExample();
        StaticVariableExample s2 = new StaticVariableExample();
        System.out.println("s1.a value :"+s1.a);
        System.out.println("s2.a value :"+s2.a);
        //Change s1 a value alone
        s1.a=20;
        System.out.println("s1.a value :"+s1.a);
        System.out.println("s2.a value :"+s2.a);
    }
}

Output will be
s1.a value :10
s2.a value :10
s1.a value :20
s2.a value :20

  • Local variables cannot be assigned as static it will throw compile time error “illegal start of expression”, as the memory cannot be assigned during class load.

3. What is a static method?

  • A static method belongs to the class rather than an object. It can be called directly by using the class name “<<ClassName>>.<<MethodName>>”
  • A static method can access static variables directly and it cannot access non-static variables and can only call a static method directly and it cannot call a non-static method from it.
  • Only the main() method which is static will be called by the JVM automatically, Not all the static method will be called automatically.

4. Can a static block exist without a main() method?

No. You cannot have a static block alone in the class without a main method.

This behavior was a valid one in Java 6,  If you have added a System.exit(0) at the end of the static-block, it will run with no errors without a valid main () method. This is because the static block is executed before a valid main method

However, this behavior was changed from Java 7 onwards, now you must include an explicit main () method, even though if it is never reached. For more details JLS chapter 12.4

5. Can we Overload static methods in Java

Yes, you can overload a static method in Java. Read More…

6. Can we Override static methods in Java

No, you cannot override a static method in Java as there will not be any Run-time Polymorphism happening. Read More…

7. Why main() method is declared as static?

If our main() method is not declared as static then the JVM has to create an object first and call which causes the problem of having extra memory allocation.

8. What is a static block?

  • A static block is a block of code inside a Java class that will be executed when a class is first loaded into the JVM. Mostly the static block will be used for initializing the variables.
  • The static block will be called only one while loading and it cannot have any return type, or any keywords (this or super).
class test
{
	static int val;
	static
        {
            val = 100;
        }
}

9.  Can we have multiple static blocks in our code?

Yes, we can have more than one static block in our code. It will be executed in the same order it is written.

10. What is a static class?

  • In Java only nested classes are allowed to be declared as static, a top level class cannot be declared as static.
  • Even though static classes are nested inside a class, they doesn’t need the reference of the outer class they act like outer class only. Read More…

11. Can constructors be static in Java?

In general, a static method means that “The Method belongs to the class and not to any particular object” but a constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static.

12. Why abstract method cannot be static in Java?

Suppose when you have a concrete method in an abstract class then that method can be static. Suppose we have a class like below

public class AbstractTest
{
    static void disp()
    {
        System.out.println("disp of static method");
    }
}

Then the disp() can be accessed by “AbstractTest.disp()”
However, for the same reason cannot be applied when you declare a static method to be abstract. Since static method can be called directly, making it abstract would make it possible to call an undefined method which is of no use, hence it is not allowed.

13. Can Interface in Java have static methods in it ?

Yes, From Java 8 onwards the interface can have static methods in it.

Before Java 8, Interface cannot have static methods in it because all methods are implicitly abstract. This is why an interface cannot have a static method.

14. Can abstract class have static variable in it ?

Yes, an abstract class can have static variables in it.

15. non-static method cannot be referenced from a static context ?

public class Test
{
    /** Non Static main method with String[] args**/
    public static void main(String[] args)
    {
        welcome();
    }
    
    void welcome()
    {
        System.out.println("Welcom to JavaInterviewPoint");
    }
}

The welcome() method which we tried calling is an instance-level method, we do not have an instance to call it . static methods belong to the class, non-static methods belong to instances of the class and hence it throws the error ” non-static method cannot be referenced from a static context “.

Filed Under: Core Java, Java, Java Interview Tagged With: Java, Java Interview Questions, Static, Static Keyword

Comments

  1. Priya says

    December 11, 2017 at 10:56 am

    All the above question are really very helpful for any java interview. I am searching for such sites , very well explained , thanks for sharing.

    Reply
  2. Kamlesh Chouhan says

    December 14, 2017 at 1:24 pm

    good question for fresher as well experience.

    Reply
  3. Mohit thakor says

    August 10, 2018 at 7:07 pm

    Thank you so much sir for such type of information….very helpful need more..

    Reply
  4. Damian says

    June 19, 2019 at 9:02 am

    Questions number 8.
    Nonstatic variable can not accessible inside static block.
    Correct me if I wrong here.

    Reply
    • javainterviewpoint says

      June 19, 2019 at 1:14 pm

      Yes, you are correct. I have corrected it now, thank you for the valuable feedback

      Reply
  5. Sushma says

    June 23, 2019 at 8:11 pm

    Hi,
    Question no 4
    As per java 8 ,static method cannot exist without main().
    Please correct if I am wrong.

    Reply
    • javainterviewpoint says

      June 24, 2019 at 10:11 am

      Yep, it was true from JDK 7 onwards, but while writing this article (JDK 6) this was a valid scenario. Thank you for the catch.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·