Java Methods


Java Methods Interview with follow-up questions

1. What is a method in Java and why is it used?

A method is a named block of code that performs a specific task — it takes optional parameters, executes statements, and optionally returns a value. It's the basic unit of behavior on a class.

int add(int a, int b) {   // name, parameters, return type
    return a + b;
}

Why methods are used: reusability (write once, call many times), abstraction (callers use the name without knowing the internals), readability/maintainability (small, single-purpose units), and decomposition of a large problem into manageable pieces. They also enable polymorphism via overriding.

Points interviewers like: a method's signature is its name + parameter list (this is what overloading varies); methods can be instance (operate on object state via this) or static (class-level); and Java passes arguments by value — for objects, the reference is copied, so the method can mutate the object but can't reassign the caller's variable. Good practice (and a current expectation) is keeping methods short and single-responsibility; modern Java also offers concise alternatives like lambdas/method references for passing behavior, but named methods remain the foundation.

↑ Back to top

Follow-up 1

Can you explain the structure of a method?

A method in Java has the following structure:

  () {
    // method body
    // statements
    // return statement (if applicable)
}
  • The access_modifier determines the visibility of the method (e.g., public, private, protected).
  • The return_type specifies the type of value that the method returns. If the method does not return a value, the return type is void.
  • The method_name is the identifier for the method.
  • The parameter_list specifies the input parameters that the method accepts.
  • The method body contains the statements that define the functionality of the method.
  • The return statement is used to return a value from the method (if applicable).

Follow-up 2

What is the difference between a method and a function?

In Java, the terms 'method' and 'function' are often used interchangeably, but there is a subtle difference between them. A method is a piece of code that is associated with an object or a class, whereas a function is a standalone piece of code that can be called independently.

In other words, a method is always associated with an object or a class, and it can access the instance variables and methods of that object or class. On the other hand, a function is not associated with any object or class, and it can only access the variables and methods that are passed to it as arguments.

Follow-up 3

What are the different types of methods in Java?

There are several types of methods in Java:

  1. Instance methods: These methods are associated with an instance of a class and can access the instance variables and methods.
  2. Static methods: These methods belong to the class itself and can be called without creating an instance of the class.
  3. Constructor methods: These methods are used to create and initialize objects of a class.
  4. Getter and setter methods: These methods are used to get and set the values of the instance variables.
  5. Overloaded methods: These methods have the same name but different parameter lists.
  6. Recursive methods: These methods call themselves to solve a problem by breaking it down into smaller subproblems.
  7. Abstract methods: These methods are declared in an abstract class or interface and do not have a body. They are implemented by the subclasses or implementing classes.

Follow-up 4

Can you provide an example of a method?

Sure! Here's an example of a method in Java:

public class Calculator {
    public int add(int num1, int num2) {
        int sum = num1 + num2;
        return sum;
    }
}

In this example, the Calculator class has a method called add that takes two integers as input parameters and returns their sum. The method is declared as public, so it can be accessed from other classes. Inside the method, the sum of the two numbers is calculated and stored in a variable called sum. Finally, the sum variable is returned as the result of the method.

2. What are the rules for defining a method in Java?

A method declaration has this shape, and naming the parts is what interviewers want:

[modifiers] [] returnType methodName([parameters]) [throws Exceptions] { body }
  • Modifiers — access (public/protected/private/package-private) and others (static, final, abstract, synchronized, default).
  • Return type — required; use void if it returns nothing. A non-void method must return a value on every path.
  • Name — by convention a camelCase verb; need not be unique if overloaded.
  • Parameters — zero or more typed parameters; supports varargs (String... args).
  • throws clause — declares checked exceptions the method may throw.
  • Body{ ... }, except for abstract/native/interface-abstract methods which have none.
public static  T firstOrDefault(List list, T def) throws IllegalArgumentException { ... }

The clarification interviewers reward: the method signature is the name + parameter types onlynot the return type or throws clause — which is why you can't overload on return type alone, and why an override must keep a compatible signature (it may narrow the return type via covariant returns and may not add broader checked exceptions). Abstract/interface methods omit the body; static/final affect overriding.

↑ Back to top

Follow-up 1

What happens if we don't follow these rules?

If we don't follow the rules for defining a method in Java, the code will not compile and we will get a compilation error. The compiler will check for any violations of the method definition rules and report them as errors.

Follow-up 2

Can you provide an example of a correctly defined method?

Sure! Here's an example of a correctly defined method in Java:

public int addNumbers(int a, int b) {
    int sum = a + b;
    return sum;
}

In this example, the method is named addNumbers and it takes two parameters of type int. It calculates the sum of the two numbers and returns the result as an int value.

Follow-up 3

What is the role of the return type in a method?

The return type in a method specifies the type of value that the method will return. It indicates the type of data that the method will produce as its result. The return type is declared before the method name in the method signature. If the method does not return a value, the return type should be void.

Follow-up 4

Can a method have the same name as its class?

Yes, a method can have the same name as its class. This type of method is called a constructor. A constructor is a special method that is used to initialize objects of a class. It has the same name as the class and does not have a return type. Constructors are called automatically when an object is created using the new keyword.

3. What is method overloading in Java?

Method overloading means defining multiple methods with the same name but different parameter lists in the same class (different number, types, or order of parameters). The compiler picks which one to call based on the arguments — so it's resolved at compile time (a form of static/compile-time polymorphism).

int    add(int a, int b)            { return a + b; }
double add(double a, double b)      { return a + b; }
int    add(int a, int b, int c)     { return a + b + c; }

The rule and gotchas interviewers test:

  • Overloads must differ in the parameter list; you cannot overload on return type alone (the signature ignores return type).
  • Overload resolution happens at compile time using the static (declared) types of the arguments, with a preference order: exact match → wideningautoboxingvarargs. This can surprise you (e.g. add(1, 2) picks the int version over the double one; passing a null can be ambiguous).
  • Don't confuse it with overriding (same signature, subclass, runtime dispatch).

It's used for convenience/readability — offering variants of an operation (like the many println(...) overloads) — but avoid overloads so similar that callers (or you) can't tell which is invoked.

↑ Back to top

Follow-up 1

Can you provide an example of method overloading?

Sure! Here's an example of method overloading in Java:

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }
}

Calculator calculator = new Calculator();
int result1 = calculator.add(5, 10); // Calls the first add method
double result2 = calculator.add(3.5, 2.5); // Calls the second add method

Follow-up 2

What are the rules for method overloading?

The rules for method overloading in Java are as follows:

  1. The methods must have the same name.
  2. The methods must have different parameter lists (number of parameters or types of parameters).
  3. The methods may have different return types, but it is not considered for method overloading.
  4. The methods may have different access modifiers.
  5. The methods may throw different exceptions.

Follow-up 3

What is the advantage of method overloading?

The advantages of method overloading in Java are:

  1. Readability: Method overloading allows developers to use the same method name for similar operations, making the code more readable and easier to understand.
  2. Reusability: Method overloading promotes code reusability by allowing multiple methods with the same name to perform different tasks based on the parameters.
  3. Flexibility: Method overloading provides flexibility in choosing the appropriate method based on the arguments passed.

Follow-up 4

Is it possible to overload main() method in Java?

Yes, it is possible to overload the main() method in Java. The main() method can be overloaded by defining multiple methods with the same name but different parameter lists. However, only the main() method with the standard signature (public static void main(String[] args)) will be executed when the program is run from the command line.

4. What is method overriding in Java?

Method overriding is when a subclass provides its own implementation of a method inherited from its superclass, keeping the same signature. It's the basis of runtime (dynamic) polymorphism: the JVM dispatches to the actual object's version at runtime, not the reference type's.

class Animal { String sound() { return "..."; } }
class Dog extends Animal {
    @Override String sound() { return "Woof"; }   // overrides
}
Animal a = new Dog();
a.sound();   // "Woof" — resolved at runtime by the real type

The rules and gotchas interviewers probe:

  • Same name and parameters; return type must be the same or a covariant (narrower) subtype.
  • Access can't be more restrictive; the override may not throw broader checked exceptions.
  • static, final, and private methods can't be overridden (static methods are hidden, not overridden; resolved by reference type).
  • Always use @Override — it makes the compiler verify you actually overrode something (catches typos/signature mismatches).
  • Use super.method() to call the parent's version.

Use it to specialize or extend inherited behavior. A modern note: prefer overriding within a deliberate hierarchy, and consider sealed types so the set of overriders is closed and works cleanly with pattern-matching switch.

↑ Back to top

Follow-up 1

Can you provide an example of method overriding?

Sure! Here's an example:

class Animal {
    public void makeSound() {
        System.out.println("Animal is making a sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog is barking");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        animal.makeSound(); // Output: Animal is making a sound

        Dog dog = new Dog();
        dog.makeSound(); // Output: Dog is barking
    }
}

In this example, the Dog class extends the Animal class and overrides the makeSound() method. When the makeSound() method is called on an instance of Dog, it prints "Dog is barking" instead of the default message from the Animal class.

Follow-up 2

What are the rules for method overriding?

The rules for method overriding in Java are as follows:

  1. The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
  2. The access level of the overriding method cannot be more restrictive than the access level of the method being overridden. For example, if the method in the superclass is declared as public, the overriding method in the subclass must also be declared as public.
  3. The overriding method cannot throw a checked exception that is not declared by the overridden method. However, it can throw a narrower or unchecked exception.
  4. The @Override annotation should be used to indicate that a method is intended to override a superclass method. This is optional but recommended for better code readability and to catch any accidental mistakes in method signature.

Follow-up 3

What is the advantage of method overriding?

The advantage of method overriding is that it allows a subclass to provide its own implementation of a method defined in its superclass. This enables the subclass to modify or extend the behavior of the superclass method according to its specific requirements. Method overriding is a key feature of polymorphism in object-oriented programming, as it allows different objects to respond to the same method call in different ways.

Follow-up 4

Can we override static method in Java?

No, we cannot override static methods in Java. When a method is declared as static, it belongs to the class rather than an instance of the class. Subclasses cannot override static methods because they are associated with the class itself, not with individual objects. However, it is possible to declare a static method with the same name in the subclass, but it will not be considered as an overriding method. Instead, it will be treated as a separate method that hides the static method of the superclass.

5. What is the difference between method overloading and method overriding?

They sound similar but are fundamentally different:

Overloading Overriding
Where same class (or inherited) subclass redefines superclass method
Signature same name, different parameters same name and parameters
Binding compile-time (static) runtime (dynamic dispatch)
Polymorphism static / compile-time dynamic / runtime
Return type can differ (ignored in resolution) same or covariant
Keyword use @Override
// Overloading — same class, different params
int sum(int a, int b)            { ... }
int sum(int a, int b, int c)     { ... }

// Overriding — subclass, same signature
class Shape { double area() {...} }
class Circle extends Shape { @Override double area() {...} }

The crisp way to state it: overloading is "same name, different parameters, chosen by the compiler"; overriding is "same signature, chosen by the runtime type". Gotchas worth mentioning: you can't overload on return type alone; overload resolution uses the declared (static) argument types, while overriding uses the actual object type; and static/final/private methods can be overloaded but not overridden. Overloading is about convenience APIs; overriding is the engine of polymorphism.

↑ Back to top

Follow-up 1

Can you provide an example to illustrate the difference?

Sure! Here's an example to illustrate the difference between method overloading and method overriding:

public class Shape {
    public void draw() {
        System.out.println("Drawing a shape");
    }
}

public class Circle extends Shape {
    public void draw() {
        System.out.println("Drawing a circle");
    }

    public void draw(int radius) {
        System.out.println("Drawing a circle with radius " + radius);
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape = new Shape();
        shape.draw(); // Output: "Drawing a shape"

        Circle circle = new Circle();
        circle.draw(); // Output: "Drawing a circle"
        circle.draw(5); // Output: "Drawing a circle with radius 5"
    }
}

In this example, the Shape class has a draw method that prints "Drawing a shape". The Circle class extends the Shape class and overrides the draw method to print "Drawing a circle". It also overloads the draw method by adding a new method with an additional int parameter to print "Drawing a circle with radius [radius]".

When the draw method is called on an instance of the Shape class, it calls the draw method in the Shape class. When the draw method is called on an instance of the Circle class, it calls the overridden draw method in the Circle class. When the draw method with an int parameter is called on an instance of the Circle class, it calls the overloaded draw method in the Circle class.

Follow-up 2

In what scenarios would you use method overloading versus method overriding?

Method overloading is useful when you want to provide multiple ways to perform a similar operation with different parameters. For example, you might have a calculateArea method that can calculate the area of a square, rectangle, or circle by accepting different parameters. Method overloading allows you to define multiple calculateArea methods with different parameter types or numbers.

Method overriding, on the other hand, is useful when you want to provide a specific implementation of a method in a subclass that is different from the implementation in the superclass. This is often used when you want to customize the behavior of a method for a specific subclass.

In summary, method overloading is used when you want to provide multiple ways to perform a similar operation, while method overriding is used when you want to provide a specific implementation of a method in a subclass.

Follow-up 3

What is the impact on performance for each?

In terms of performance, method overloading and method overriding have different impacts.

Method overloading has no significant impact on performance because the decision of which method to call is made at compile-time based on the arguments passed to it. The compiler determines the appropriate method to call based on the method signature.

Method overriding, on the other hand, can have a slight impact on performance because the decision of which method to call is made at runtime. When a method is overridden, the JVM needs to determine the actual type of the object at runtime and then call the appropriate method based on the actual type.

However, the impact on performance is usually negligible unless there are a large number of method calls or the method being overridden is computationally intensive.

In general, it is more important to focus on code readability, maintainability, and design principles when deciding whether to use method overloading or method overriding, rather than solely considering performance.

Follow-up 4

Can both be used in the same class?

Yes, both method overloading and method overriding can be used in the same class.

Method overloading allows you to define multiple methods with the same name but different parameters in a class. These methods can have different return types, different number of parameters, or different types of parameters.

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameters as the method in the superclass.

By using both method overloading and method overriding, you can provide multiple ways to perform a similar operation with different parameters and also customize the behavior of a method for a specific subclass.

It is important to note that method overloading and method overriding are independent concepts and serve different purposes, so they can be used together in the same class without any issues.

6. What are lambda expressions, functional interfaces, and the Stream API?

Introduced in Java 8, these enable a functional, declarative style:

  • Functional interface — an interface with a single abstract method (@FunctionalInterface), e.g. Runnable, Comparator, and the java.util.function types (Function, Predicate, Supplier, Consumer).
  • Lambda — a concise instance of a functional interface: (a, b) -> a + b. Method references (User::getName) are shorthand.
  • Stream API — a pipeline for processing collections declaratively: a source → intermediate ops (filter, map, sorted, lazy) → a terminal op (collect, reduce, forEach, count).
List names = users.stream()
    .filter(u -> u.age() >= 18)
    .map(User::name)
    .sorted()
    .toList();                      // Java 16+

Points interviewers want: streams are lazy (nothing runs until the terminal op), don't mutate the source, and shouldn't have side effects; use Collectors (groupingBy, toMap, joining) for aggregation; and parallelStream() can parallelize but only helps for large, CPU-bound, stateless work. Related modern APIs: Optional for null-safety. This whole area is among the most-tested in 2026 Java interviews.

↑ Back to top

Live mock interview

Mock interview: Java Methods

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.