Consider the following Java method:
public static int multiplyByTwo(int x) {
return x * 2;
}
public static void main(String[] args) {
System.out.println(multiplyByTwo(5));
}What will be printed when main runs?
public static int multiplyByTwo(int x) { return x * 2; } public static void main(String[] args) { System.out.println(multiplyByTwo(5)); }
Think about what the method returns when given 5.
The method multiplies the input by 2 and returns it. So 5 * 2 = 10.
Look at this Java method:
public static String greet(String name) {
if (name == null) {
return "Hello, Guest!";
}
return "Hello, " + name + "!";
}
public static void main(String[] args) {
System.out.println(greet(null));
}What will be printed when main runs?
public static String greet(String name) { if (name == null) { return "Hello, Guest!"; } return "Hello, " + name + "!"; } public static void main(String[] args) { System.out.println(greet(null)); }
Check what happens when the input is null.
If the input is null, the method returns "Hello, Guest!" directly.
Consider this Java method:
public static int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(4));
}What will be printed when main runs?
public static int factorial(int n) { if (n <= 1) { return 1; } return n * factorial(n - 1); } public static void main(String[] args) { System.out.println(factorial(4)); }
Recall how factorial is calculated recursively.
factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * factorial(1) = 4 * 3 * 2 * 1 = 24.
Given this Java code:
public static int addFive(int num) {
num = num + 5;
return num;
}
public static void main(String[] args) {
int x = 10;
addFive(x);
System.out.println(x);
}What will be printed when main runs?
public static int addFive(int num) { num = num + 5; return num; } public static void main(String[] args) { int x = 10; addFive(x); System.out.println(x); }
Remember Java passes primitives by value.
The method changes only its local copy of num. The original x remains 10.
Which of the following Java methods will cause a compilation error because the return type does not match the returned value?
Check if the returned value type matches the declared return type exactly.
Method getNumber declares return type int but returns a double literal 3.14, causing a compilation error.
