1Z0-811 1Z0-811 Java Methods and Scope 1 — Questions and Answers
Question 1: Which keyword is used to define a method that belongs to the class rather than an instance?
- static (Correct answer)
- final
- abstract
- void
Correct answer: static
The `static` keyword declares a method that belongs to the class itself and can be called without creating an instance.
Question 2: What is the return type of a method that does not return any value?
- null
- void (Correct answer)
- empty
- None
Correct answer: void
A method declared with `void` as its return type does not return any value to the caller.
Question 3: Which of the following correctly defines method overloading in Java?
- A subclass provides a specific implementation of a method defined in the parent class
- Multiple methods in the same class share the same name but have different parameter lists (Correct answer)
- A method calls itself recursively
- A method is declared in an interface and implemented in a class
Correct answer: Multiple methods in the same class share the same name but have different parameter lists
Method overloading occurs when multiple methods in the same class have the same name but differ in the number or types of parameters.
Question 4: What is the scope of a variable declared inside a method body?
- Class scope
- Package scope
- Local scope (Correct answer)
- Global scope
Correct answer: Local scope
A variable declared inside a method has local scope and is accessible only within that method.
Question 5: Which statement about the `return` statement is true?
- It can only be used in void methods
- It immediately exits the method and optionally returns a value (Correct answer)
- It must always appear at the very end of a method
- It can only return primitive types
Correct answer: It immediately exits the method and optionally returns a value
The `return` statement immediately terminates method execution and can pass a value back to the caller if the method is non-void.
Question 6: What happens if a method declares a return type but has a code path that does not return a value?
- It returns null automatically
- It returns 0 for numeric types
- The code will not compile (Correct answer)
- It throws a RuntimeException
Correct answer: The code will not compile
Java requires that all code paths in a non-void method return a value; missing return paths cause a compilation error.
Which keyword is used to define a method that belongs to the class rather than an instance?