ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Methods
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 4.4

Methods

Method declaration, parameters, return types, overloading, varargs and pass-by-value

13 min readStage 1 · Foundations15 interview questions
Prerequisites
4.1 Classes · 3.3 Primitive vs Reference
Covers
Method declaration · Parameters · Return types · Method overloading · Varargs · Pass-by-value
Related
6.2 Method Overriding · 6.3 Polymorphism · B1V3 Lambdas and method references · Book 5 (clean functions)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

A method is a named block of code that belongs to a class and can be invoked with arguments. It may return a value. Instance methods run on a particular object and can use this; static methods belong to the class. The method's signature — its name and parameter types — identifies it within the class.

The parts of a method declaration
Figure 1 — The parts of a method declaration

Methods are the only way behaviour happens in Java: constructors, lambdas and even initialisers compile into methods in the class file. How methods are declared, overloaded and called therefore shapes both correctness and readability of all Java code.

2Why It Exists

Methods give a name to a piece of behaviour, hide how it is done, and allow it to be reused and tested. On objects they are the controlled entry points to state (4.2). A good method name documents intent better than any comment, and small methods also help the JIT, which inlines short methods into their callers.

3Core Concepts

Method declaration

A declaration contains, in order: modifiers (access, static, final, abstract, synchronized, default in interfaces), optional type parameters, the return type, the name, the parameter list, an optional throws clause, and the body (absent for abstract methods). The signature used for overloading is only the name and parameter types — not the return type, modifiers or exceptions.

KindDeclaredCalled asCan use this?
Instance methodvoid pay(Payment p)order.pay(p)Yes
Static methodstatic Order empty()Order.empty()No
Abstract methodabstract double area();through a subclass objectn/a — no body
Default method (interface)default void log() { … }through an implementing objectYes

Parameters

Parameters are local variables initialised with the argument values at the call. They can be declared final (never reassigned) and are effectively final if not reassigned. Good parameter lists are short, ordered consistently, and use specific types rather than primitives with hidden meaning: transfer(AccountId from, AccountId to, Money amount) is safer than transfer(long, long, BigDecimal), because the compiler rejects a customer ID, or any other value that is not an AccountId, where an account is expected. It still cannot catch from and to swapped, since both are AccountId values, so clear names and a consistent order still matter.

Return types

A method returns a value of its declared type, or nothing with void. Every path must end in return (or a thrown exception) for non-void methods. An overriding method may return a subtype of the overridden method's return type (covariant return, 6.2). When a result may legitimately be absent, returning Optional<T> makes that visible to the caller instead of returning null.

The four common return styles
Figure 2 — The four common return styles

Method overloading

Overloading means declaring several methods with the same name and different parameter types, such as println(int), println(String) and println(Object). The compiler chooses one at compile time using the static types of the arguments, in three phases: first without boxing or varargs, then with boxing, then with varargs. Within a phase it picks the most specific method; if none is most specific, the call is ambiguous and does not compile.

The three phases of overload resolution
Figure 3 — The three phases of overload resolution

Varargs

The last parameter, declared Type... name, accepts zero or more arguments. Inside the method it is an ordinary array; at the call site the compiler creates the array. Varargs rank last in overload resolution, so a fixed-arity overload always wins when it applies. Generic varargs (T...) can cause heap pollution warnings; @SafeVarargs marks methods that use the array safely.

Varargs are an array created by the compiler
Figure 4 — Varargs are an array created by the compiler

Pass-by-value

Java passes every argument by value: the parameter receives a copy of the argument. For a primitive, it is a copy of the number. For a reference, it is a copy of the reference — so the method can mutate the object that both copies refer to, but cannot make the caller's variable refer to a different object. There is no way in Java to write a method that swaps two of the caller's variables.

swap exchanges only its own copies of the references
Figure 5 — swap exchanges only its own copies of the references

4How It Works Internally

Each call pushes a frame on the calling thread's stack holding the parameters, local variables and operand stack; each return pops it. Deep or unbounded recursion therefore ends in StackOverflowError. The default stack size is typically around 1 MB per platform thread and can be changed with -Xss.

Frames on the call stack
Figure 6 — Frames on the call stack

The bytecode instruction used for a call depends on the method: invokestatic for static methods, invokespecial for constructors and super calls, invokevirtual for ordinary instance methods (dispatched on the object's run-time class) and, since Java 11, also for private ones, invokeinterface for interface methods, and invokedynamic for lambdas and string concatenation. The JIT inlines small and frequently called methods into their callers, removing the call overhead; this is why many small, well-named methods usually cost nothing at run time.

javac chooses the signature from static types; the JVM chooses the body from the receiver's class
Figure 7 — javac chooses the signature from static types; the JVM chooses the body from the receiver's class

Figure 7 separates the two decisions behind every call. javac chooses the signature from the static types of the arguments and writes it into the class file; at run time the JVM chooses which body implements that signature from the receiver's actual class. Overloading therefore never depends on run-time types, which is why Example 3 behaves as it does, while overriding always does (6.3).

5APIs / Features / Syntax

JAVADeclaration forms
public final class PriceCalculator {

    // instance method, final parameter, Optional return
    public Optional<Money> discountFor(final Customer customer) {
        return customer.isPremium() ? Optional.of(PREMIUM_DISCOUNT)
                                    : Optional.empty();
    }

    // overloads
    public Money total(Order order) { return total(order.lines()); }
    public Money total(List<Line> lines) { … }

    // varargs
    public static Money sum(Money first, Money... rest) {
        Money result = first;
        for (Money m : rest) result = result.plus(m);
        return result;
    }

    // generic method
    public static <T extends Comparable<T>> T max(T a, T b) {
        return a.compareTo(b) >= 0 ? a : b;
    }
}

6Practical Examples

Example 1 — What a method can and cannot change

JAVAPass-by-value in action
static void modify(int n, StringBuilder sb, List<String> list) {
    n = 99;                    // local copy — caller unaffected
    sb.append(" world");       // mutates the shared object — caller sees it
    list = new ArrayList<>();  // reassigns local copy — caller unaffected
    list.add("lost");
}

int n = 1;
StringBuilder sb = new StringBuilder("hello");
List<String> list = new ArrayList<>(List.of("kept"));
modify(n, sb, list);
System.out.println(n + " | " + sb + " | " + list);   // 1 | hello world | [kept]

Example 2 — Mini program: the declaration forms of section 5, running

Problem. The PriceCalculator in section 5 shows the declaration forms but leaves a method body out. This program completes it, with small records for the data, and calls each form: an instance method returning Optional, two overloads where one delegates to the other, a varargs method and a generic method.

JAVAPriceDemo.java
public class PriceDemo {
    record Money(BigDecimal amount) {
        static Money of(String v) { return new Money(new BigDecimal(v)); }
        Money plus(Money o) { return new Money(amount.add(o.amount)); }
        Money minus(Money o) { return new Money(amount.subtract(o.amount)); }
        @Override public String toString() { return amount.toPlainString(); }
    }
    record Line(String sku, Money price, int qty) {
        Money subtotal() {
            return new Money(price.amount().multiply(BigDecimal.valueOf(qty)));
        }
    }
    record Customer(String name, boolean premium) {}
    record Order(Customer customer, List<Line> lines) {}
 
    static final class PriceCalculator {
        private static final Money PREMIUM_DISCOUNT = Money.of("50.00");
 
        Optional<Money> discountFor(final Customer customer) {   // query
            return customer.premium() ? Optional.of(PREMIUM_DISCOUNT)
                                      : Optional.empty();
        }
        Money total(Order order) {                                // overload 1
            Money gross = total(order.lines());
            return discountFor(order.customer()).map(gross::minus)
                                                 .orElse(gross);
        }
        Money total(List<Line> lines) {                           // overload 2
            Money sum = Money.of("0.00");
            for (Line line : lines) sum = sum.plus(line.subtotal());
            return sum;
        }
        static Money sum(Money first, Money... rest) {            // varargs
            Money result = first;
            for (Money m : rest) result = result.plus(m);
            return result;
        }
        static <T extends Comparable<T>> T max(T a, T b) {        // generic
            return a.compareTo(b) >= 0 ? a : b;
        }
    }
 
    public static void main(String[] args) {
        var calc = new PriceCalculator();
        var lines = List.of(new Line("PEN", Money.of("25.00"), 4),
                            new Line("BOOK", Money.of("349.00"), 1));
        var asha = new Order(new Customer("asha", true), lines);
        var ravi = new Order(new Customer("ravi", false), lines);
        System.out.println("lines         " + calc.total(lines));
        System.out.println("asha premium  " + calc.total(asha));
        System.out.println("ravi          " + calc.total(ravi));
        System.out.println("ravi discount " + calc.discountFor(ravi.customer())
                .map(Money::toString).orElse("none"));
        System.out.println("sum of three  " + PriceCalculator.sum(
                Money.of("1.50"), Money.of("2.25"), Money.of("3.00")));
        System.out.println("sum of one    "
                + PriceCalculator.sum(Money.of("9.99")));
        System.out.println("max           " + PriceCalculator.max("apple", "pear")
                + ", " + PriceCalculator.max(7, 3));
    }
}
OUTPUT
lines         449.00
asha premium  399.00
ravi          449.00
ravi discount none
sum of three  6.75
sum of one    9.99
max           pear, 7

Why it behaves this way. total(Order) and total(List<Line>) share a name but not a parameter type, so javac picks one at compile time from the argument's static type; the Order overload reuses the List one and then applies the discount. discountFor returns Optional<Money>, so the caller has to decide what happens when there is none: map(gross::minus).orElse(gross) subtracts the discount only when it is present. sum takes one required Money and any number of others; with a single argument, rest is an empty array, so no special case is needed. max is generic: T is inferred as String for the first call and as Integer for the second, where the int arguments are boxed, and the bound Comparable<T> is what allows the call to compareTo.

Example 3 — Overload resolution surprises

JAVACompile-time selection
static void m(long x)    { System.out.println("long"); }
static void m(Integer x) { System.out.println("Integer"); }
static void m(int... x)  { System.out.println("varargs"); }

m(5);            // "long"    — phase 1: widening beats boxing
m(Integer.valueOf(5)); // "Integer"

static void log(Object o) { System.out.println("Object"); }
static void log(String s) { System.out.println("String"); }
Object x = "hi";
log(x);          // "Object"  — chosen by the declared type of x
log(null);       // "String"  — most specific applicable method

Example 4 — Returning results instead of mutating parameters

JAVAPrefer explicit results
// Hard to follow: result hidden in a mutated argument
void applyDiscount(Order order, List<String> warningsOut) { … }

// Clearer: return a result value
record DiscountResult(Money newTotal, List<String> warnings) {}
DiscountResult applyDiscount(Order order) { … }

Example 5 — Type-safe parameters

JAVASmall value types make parameter mistakes harder
record AccountId(long value) {}

// Easy to call with swapped arguments — compiles either way
void transfer(long fromId, long toId, BigDecimal amount) { … }

// Swapping is now visible only if the types differ; naming makes intent clear
void transfer(AccountId from, AccountId to, Money amount) { … }

Example 6 — When toString recurses: a cycle in the object graph

Problem. Section 8 notes that StackOverflowError in production usually comes from accidental recursion rather than deliberate algorithms. A customer that lists its orders, each of which names its customer, is the classic case: two innocent-looking toString methods end up calling each other.

JAVACycleToString.java
public class CycleToString {
    static final class Customer {
        final String id;
        final List<Order> orders = new ArrayList<>();
        final boolean idsOnly;                  // false = the buggy version
        Customer(String id, boolean idsOnly) {
            this.id = id;
            this.idsOnly = idsOnly;
        }
 
        @Override public String toString() {
            if (idsOnly) {                      // fix: refer to orders by id
                return "Customer{" + id + ", orders="
                        + orders.stream().map(o -> o.id).toList() + "}";
            }
            return "Customer{" + id + ", orders=" + orders + "}";  // cycle
        }
    }
 
    static final class Order {
        final String id;
        final Customer customer;
        Order(String id, Customer customer) {
            this.id = id;
            this.customer = customer;
            customer.orders.add(this);          // back-reference: a cycle
        }
        @Override public String toString() {
            return "Order{" + id + ", customer=" + customer + "}";
        }
    }
 
    public static void main(String[] args) {
        Customer buggy = new Customer("C-7", false);
        new Order("O-1", buggy);
        try {
            System.out.println(buggy);
        } catch (StackOverflowError e) {
            System.out.println("buggy: StackOverflowError");
        }
 
        Customer fixed = new Customer("C-8", true);
        Order first = new Order("O-2", fixed);
        new Order("O-3", fixed);
        System.out.println("fixed: " + fixed);
        System.out.println("fixed: " + first);
    }
}
OUTPUT
buggy: StackOverflowError
fixed: Customer{C-8, orders=[O-2, O-3]}
fixed: Order{O-2, customer=Customer{C-8, orders=[O-2, O-3]}}

Why it behaves this way. Printing buggy calls Customer.toString, which builds the string of its orders list, which calls Order.toString, which appends customer and so calls Customer.toString again. Each call adds a stack frame (Figure 6) and none returns, so the thread's stack fills up and the JVM throws StackOverflowError. The same happens with equals and hashCode that follow both directions of a relationship, and with JSON serialisers on two-way entity links. The fix is to stop following the relationship on one side: the fixed customer names its orders by ID, so an order's toString can still include its whole customer. The demo catches the error only to show it; real code should never rely on that.

Example 7 — What a varargs parameter really receives

Problem. Inside a varargs method the parameter is an ordinary array, and at each call the compiler decides whether to build a new array or to pass on one it was given. Most of the time that is invisible; with arrays, primitive arrays and null it is not.

JAVAVarargsPitfalls.java
public class VarargsPitfalls {
    static String count(Object... args) {
        return args == null ? "args is null" : args.length + " element(s)";
    }
 
    public static void main(String[] args) {
        System.out.println("count()                    -> " + count());
        System.out.println("count(a, b)                -> " + count("a", "b"));
        System.out.println("count(new Object[]{a, b})  -> "
                + count(new Object[] {"a", "b"}));        // the array IS args
        System.out.println("count(new int[]{1, 2, 3})  -> "
                + count(new int[] {1, 2, 3}));            // one Object: int[]
        System.out.println("count((Object) null)       -> "
                + count((Object) null));
        System.out.println("count((Object[]) null)     -> "
                + count((Object[]) null));
        System.out.println("Arrays.asList(int[]).size  -> "
                + Arrays.asList(new int[] {1, 2, 3}).size());
        System.out.println("List.of(1, 2, 3).size      -> "
                + List.of(1, 2, 3).size());
    }
}
OUTPUT
count()                    -> 0 element(s)
count(a, b)                -> 2 element(s)
count(new Object[]{a, b})  -> 2 element(s)
count(new int[]{1, 2, 3})  -> 1 element(s)
count((Object) null)       -> 1 element(s)
count((Object[]) null)     -> args is null
Arrays.asList(int[]).size  -> 1
List.of(1, 2, 3).size      -> 3

Why it behaves this way. With separate arguments, or none, javac builds a new Object[]. When the only argument already is an Object[], javac passes it as the array itself, so count sees its two elements. An int[] is not an Object[] but a single object, so javac wraps it in a one-element array; Arrays.asList(new int[] {1, 2, 3}) has the same surprise and returns a list holding one int[]. A null cast to Object is one null element, while a null cast to Object[] is passed as the array, so args itself is null; an uncast count(null) compiles with a warning and behaves like the second case. A varargs method that callers may pass arrays to should not assume that the array is non-null.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
Expecting a method to reassign the caller's variableChange silently lostReturn the new value
Surprising mutation of argument objectsCallers see unexpected changesDocument mutation, or work on copies / immutable types
Overloads that differ only by boxed vs primitive or by Object vs a subtypeUnexpected method chosenUse distinct names (findById, findByEmail)
Boolean flag parameters: render(true, false)Unreadable calls, two methods in oneSeparate methods or an enum parameter
Long parameter listsSwapped arguments, poor readabilityParameter objects, value types, builders
Returning null for "no result"NullPointerException in callersOptional, empty collections, or exceptions
Unbounded recursionStackOverflowErrorIteration, or bounded depth
Passing an array or a primitive array to a varargs methodAn Object[] becomes the arguments themselves and an int[] a single argument, so counts and contents are wrongPass separate arguments or a List; use IntStream or boxed arrays for primitives (Example 7)
toString, equals or hashCode that follow both sides of a relationshipMutual recursion ends in StackOverflowError, often only when a log line or a HashSet touches the objectRefer to the other side by ID on at least one side (Example 6)
Methods that both change state and return informationCallers cannot ask without causing a side effect, and a retried call repeats the changeSeparate commands from queries; if one call must do both, name it after the change, e.g. nextId()

8Performance & Production Considerations

  • Method calls are usually free after JIT inlining. Very large methods (thousands of bytecodes) are not inlined or even compiled, which is one practical reason — beyond readability — to keep methods small.
  • Megamorphic call sites (many implementations seen at one call) cannot be inlined and are slower; this rarely matters outside very hot paths.
  • Varargs allocate an array on every call; in hot paths, frameworks provide fixed-arity overloads (for example logging APIs with one, two and three arguments) for this reason.
  • StackOverflowError in production often comes from accidental recursion — mutual toString or equals calls, JSON serialisation of cyclic object graphs — rather than deliberate algorithms.
  • An exception costs most when it is created. Filling in its stack trace walks the whole call stack, so a method that reports an ordinary outcome, such as "not found", by throwing is slow in a hot path. Return Optional or a result type there, and keep exceptions for real failures.

9Architecture & Design Considerations

At component boundaries, method signatures are API contracts. Guidelines that pay off in large systems:

  • Command–query separation: a method either changes state (command, usually void) or returns information (query, no side effects), not both.
  • Intention-revealing names: approveLoan(application) rather than process(data, 3).
  • Explicit absence and failure: Optional for absent results, exceptions for failures, never magic values.
  • Stable signatures: adding parameters to public methods breaks callers; overloads or parameter objects allow evolution.
  • Domain types for parameters: Money, AccountId, DateRange instead of raw primitives catch mistakes at compile time.

10Interview Questions & Answers

Q1L1 · BasicConcept

What makes up a method signature in Java?

The method name and the ordered list of parameter types. Return type, modifiers, parameter names and throws clauses are not part of the signature for overloading purposes.

Q2L1 · BasicConcept

What is the difference between a static and an instance method?

A static method belongs to the class, is called on the class, and has no this. An instance method is called on an object, can use this and the object's fields, and is dispatched dynamically if overridden.

Q3L2 · IntermediateInternals

What is method overloading, and when is the overload chosen?

Declaring several methods with the same name and different parameter types. The compiler chooses among them at compile time, based on the static types of the arguments, using widening first, then boxing, then varargs, and picking the most specific match.

Q4L2 · IntermediateInternals

How do varargs work?

The last parameter, declared Type..., receives an array. The compiler builds the array from the arguments at the call site, or passes an empty array if there are none. Varargs methods are considered last in overload resolution. Example 7 shows what the method receives for arrays and null.

Q5L3 · Senior EngineerTricky

Is Java pass-by-value or pass-by-reference? Prove it.

Pass-by-value. A method that assigns a new object to its parameter does not change the caller's variable — for example, a swap method cannot swap the caller's references. What looks like pass-by-reference is the method mutating a shared object through its copy of the reference.

Q6L3 · Senior EngineerTricky

Which method is called by m(5) given m(long) and m(Integer)?

m(long). Overload resolution's first phase allows widening but not boxing, and int to long is a widening conversion, so m(long) is found before boxing is ever considered.

Q7L3 · Senior EngineerScenario

A service throws StackOverflowError when logging certain objects. What is the likely cause?

A cycle in the object graph combined with recursive toString, equals, hashCode or JSON serialisation — for example Order referencing Customer referencing its Orders. Break the cycle in those methods (print IDs, not objects), configure the serialiser to handle back-references, or use DTOs for output. Example 6 reproduces it.

Q8L3 · Senior EngineerTrade-off

Why do logging APIs offer overloads like debug(String, Object) and debug(String, Object, Object) as well as varargs?

Every varargs call allocates an array, even when the log level is disabled. Fixed-arity overloads avoid that allocation on hot paths; varargs remain for the rare calls with many arguments.

Q9L4 · Technical ArchitectDesign

What guidelines would you set for public method design in shared libraries?

Small, intention-revealing methods; command–query separation; domain types instead of primitive parameters; Optional or exceptions rather than null; no boolean flag parameters; parameter objects for more than a few arguments; and backward-compatible evolution through new overloads or new methods rather than changed signatures.

Q10L5 · Solution ArchitectDesign

How do method-level design choices affect a system's evolvability across teams?

Method signatures of shared modules and service clients are contracts. Primitive-heavy, flag-driven or null-returning signatures push knowledge into every caller and make changes breaking. Explicit domain types, clear semantics and additive evolution let teams change implementations independently — the same principles as API versioning at service level.

Q11L2 · IntermediateCode

What does this program print?

JAVAOverloadQuiz.java
public class OverloadQuiz {
    static String f(long x)    { return "long"; }
    static String f(Integer x) { return "Integer"; }
    static String f(Object x)  { return "Object"; }
    static String f(int... x)  { return "int..."; }
 
    public static void main(String[] args) {
        short s = 1;
        char c = 'a';
        System.out.println(f(1) + " " + f(s) + " " + f(c) + " "
                + f(Integer.valueOf(1)) + " " + f(1L) + " " + f() + " "
                + f("x"));
    }
}

It prints long long long Integer long int... Object. In phase 1, without boxing or varargs, int, short and char all widen to long, so f(long) is chosen before boxing is considered, and f(1L) matches it exactly. An Integer argument fits both f(Integer) and f(Object) in phase 1, and the more specific f(Integer) wins. f() has no arguments, so only the varargs overload applies, in phase 3, and a String fits only f(Object). javac makes every one of these choices from static types.

Q12L3 · Senior EngineerTricky

What does Arrays.asList(new int[] {1, 2, 3}).size() return, and why?

It returns 1. asList(T... a) is generic, and T cannot be the primitive int, so the int[] is not treated as the varargs array: T is inferred as int[] and the array becomes the single element of a List<int[]>. With an Integer[], or with List.of(1, 2, 3), the size is 3. Example 7 shows the same rule for a plain Object... parameter.

Q13L3 · Senior EngineerInternals

Which bytecode instructions does javac use for method calls, and how does the JIT make virtual calls cheap?

invokestatic for static methods, invokespecial for constructors and super calls, invokevirtual for instance methods, private ones included since Java 11, invokeinterface for interface methods and invokedynamic for lambdas and string concatenation. A virtual call needs the receiver's run-time class, but the JIT profiles each call site: if it has seen one class or two, it inlines those methods behind a cheap type check and falls back to a real virtual call only at megamorphic sites. Class hierarchy analysis also lets it treat a method that nothing overrides as non-virtual, and recompile if a subclass is loaded later (Figure 7).

Q14L4 · Technical ArchitectTrade-off

For a lookup that may find nothing, should a method return null, return Optional or throw an exception?

Return Optional<T> when absence is a normal outcome the caller must handle, as in findByEmail: the signature says so, and the caller has to unwrap it. Throw when absence breaks a precondition, as in getById for an ID that must exist, so the failure is loud and carries context. Return an empty collection, never null, for results with several values. Plain null saves an allocation but moves the knowledge into documentation and produces NullPointerException far from the cause; keep it for private code or measured hot loops. Optional is meant for return values, not for fields or parameters.

Q15L5 · Solution ArchitectTrade-off

A widely used library method needs a new optional parameter. Do you add an overload, a parameter object or a new method?

Changing the existing signature is ruled out for a published API: it breaks every caller at compile time, and already-compiled clients with NoSuchMethodError at run time. A delegating overload is cheapest for one optional value, but overloads multiply quickly and can make calls ambiguous, especially with null arguments. A parameter object or builder, such as a SearchRequest, absorbs future options without new signatures, at the cost of a new type. A new method name is right when the behaviour really differs. For a library many teams use, I would move to a parameter object once there are more than two or three options, and deprecate the old forms with a stated removal date.

Test your knowledge on this topic →Flashcards from this topic's 15 questions, filtered by level and type.

Key Takeaways

  • A signature is name plus parameter types; overloads are chosen at compile time.
  • Overload phases: widening, then boxing, then varargs; most specific wins.
  • Java is always pass-by-value; references are copied, objects are shared.
  • Each call is a stack frame; small methods are inlined by the JIT.
  • Design method signatures as contracts: clear names, domain types, explicit absence.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.