Java Interview Prep: Mastering Static and Final Keywords


When preparing for a Java interview, understanding static and final keywords is essential, as they are frequently discussed. Below is an overview of what static and final mean in Java, along with some examples and interview-style questions to help with your preparation.

Understanding static and final in Java


1. static Keyword:

  • Definition: The static keyword is used to declare class-level members. When a method or variable is marked as static, it belongs to the class rather than an instance of the class.
  • Usage:
    • Static Variables: These are shared by all instances of the class. There's only one copy of the static variable for all objects.
    • Static Methods: These belong to the class itself, so they can be called without creating an instance of the class. Static methods can only access static members of the class.
    • Static Block: This is used for static initialization of a class. It is executed once when the class is loaded into memory.

Example:

class Example {
    static int count = 0;  // Static variable

    static void increment() {  // Static method
        count++;
    }
}

Important Notes:

  • Accessing static methods and variables: You can access them directly using the class name or through an instance, but it's recommended to use the class name.

    Example.increment(); // Preferred way to call static method
    System.out.println(Example.count); // Access static variable

2. final Keyword:

  • Definition: The final keyword in Java is used to declare constants, prevent method overriding, and prevent class inheritance.
  • Usage:
    • Final Variable: A final variable cannot be reassigned once initialized.
    • Final Method: A final method cannot be overridden by subclasses.
    • Final Class: A final class cannot be subclassed (inherited).

Example:

final class Constants {  // Final class cannot be inherited
    final int MAX_SIZE = 100;  // Final variable, cannot be reassigned
}

Important Notes:

  • Final Parameter: A final parameter means the value cannot be changed inside the method.

    public void printMessage(final String message) {
        // message = "Hello"; // Error: cannot assign a value to a final variable
        System.out.println(message);
    }

Common Interview Questions on static and final


1. Can we override a static method?

  • Answer: No, static methods cannot be overridden in Java. They are resolved at compile time based on the reference type, not the object type. If a static method with the same signature exists in a subclass, it hides the superclass's static method (method hiding), not overriding.

    Example:

    class Parent {
        static void display() {
            System.out.println("Parent's display");
        }
    }
    
    class Child extends Parent {
        static void display() {  // Method hiding, not overriding
            System.out.println("Child's display");
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            Parent p = new Child();
            p.display(); // Output: Parent's display, not Child's display
        }
    }

2. What happens when we try to inherit a final class?

  • Answer: You cannot inherit a final class. A final class cannot be subclassed. If you try to extend a final class, the compiler will throw an error.

    Example:

    final class FinalClass {}
    
    class SubClass extends FinalClass {  // Compilation error
        // Cannot inherit from final class 'FinalClass'
    }

3. What is the difference between final and static final variables?

  • Answer:
    • A final variable is a constant that cannot be reassigned once it is initialized.
    • A static final variable is a constant that belongs to the class rather than an instance of the class. It is commonly used for constants that are shared across all instances of the class.
    Example:
    class Example {
        final int x = 10;  // Instance-level constant
        static final int MAX_SIZE = 100;  // Class-level constant
    }

4. Can we modify a final method?

  • Answer: No, you cannot override a final method in a subclass. A final method is intended to be a method that cannot be changed by subclasses.

    Example:

    class Parent {
        final void display() {
            System.out.println("Display method");
        }
    }
    
    class Child extends Parent {
        @Override
        void display() {  // Compilation error: Cannot override final method
            System.out.println("Modified display method");
        }
    }

5. Can a method be both static and final?

  • Answer: Yes, a method can be both static and final. A static method is associated with the class, and a final method cannot be overridden. This is useful when you want to create a utility method that should not be modified in subclasses and can be called without creating an instance of the class.

    Example:

    class Utility {
        static final void printMessage() {
            System.out.println("This is a utility method.");
        }
    }
    

Key Takeaways for Interview Preparation:

  • static: Used for class-level methods and variables. Static members are shared across all instances of the class.
  • final: Used to create constants, prevent method overriding, and prevent inheritance.
  • Combination (static final): Commonly used to define constant values that belong to the class (e.g., public static final double PI = 3.14159).

Familiarize yourself with these concepts, and practice explaining them in clear terms, as these are often discussed in both theoretical and coding interviews.


Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete