Methods & overloading
Computer Science · Java
Question 1 of 10
0What number does this Java code print? public class Main { static int pick(int x) { return x + 5; } static int pick(double x) { return -1; } public static void main(String[] args) { System.out.println(pick(8)); } }
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Methods & overloading explained
A method is a named block of code inside a class that can be called to do a job. Overloading means defining several methods with the same name but different parameter lists. Java decides which version to call by looking at the number and types of the arguments when the code is compiled. This lets one name serve several related jobs, such as adding two numbers or adding three.
Overloads must differ in their parameters, meaning the number, the types or the order of the types. Changing only the return type is not allowed, and neither is changing only the parameter names. If no version matches exactly, Java can widen an argument, so an int can be passed to a parameter of type double.
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
Worked example
Which version runs for each call, and what does it return?
- add(2, 3): two int arguments match the first method, giving 2 + 3 = 5.
- add(2.5, 1.0): two double arguments match the second method, giving 2.5 + 1.0 = 3.5.
- add(1, 2, 3): three arguments match only the third method, giving 1 + 2 + 3 = 6.
Java works out the choice when compiling, so a call that matches no version is a compile error rather than a runtime failure.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What number does this Java code print?
public class Main { static int pick(int x) { return x + 8; }
static int pick(double x) { return -1; }
public static void main(String[] args) { System.out.println(pick(4)); } }
Medium
What number does this Java code print?
public class Main { static int pick(int x) { return x + 2; }
static int pick(double x) { return (int) x * 10; }
public static void main(String[] args) { System.out.println(pick(1.5)); } }
Hard
What number does this Java code print?
public class Main { static int pick(int x) { return x + 4; }
static int pick(String s) { return s.length(); }
public static void main(String[] args) { System.out.println(pick('V')); } }