You want to write a method that returns the larger of two integers. Which method correctly returns the larger value?
hard📝 Application Q8 of 15
Java - Methods and Code Reusability
You want to write a method that returns the larger of two integers. Which method correctly returns the larger value?
Apublic int max(int a, int b) { if (a > b) return b; else return a; }
Bpublic int max(int a, int b) { return (a > b) ? a : b; }
Cpublic int max(int a, int b) { if (a > b) System.out.println(a); else System.out.println(b); }
Dpublic void max(int a, int b) { if (a > b) return a; else return b; }
Step-by-Step Solution
Solution:
Step 1: Check return type and return statements
Method must return int and return the larger value.
Step 2: Evaluate each option
public int max(int a, int b) { return (a > b) ? a : b; } uses ternary operator correctly. public void max(int a, int b) { if (a > b) return a; else return b; } has void return type but returns values (error). public int max(int a, int b) { if (a > b) System.out.println(a); else System.out.println(b); } prints values but does not return (error). public int max(int a, int b) { if (a > b) return b; else return a; } returns smaller value incorrectly.
Final Answer:
public int max(int a, int b) { return (a > b) ? a : b; } -> Option B
Quick Check:
Return type and returned value must match and be correct [OK]
Quick Trick:Use ternary for simple return decisions [OK]
Common Mistakes:
Using void but returning value
Printing instead of returning
Returning wrong value
Master "Methods and Code Reusability" in Java
9 interactive learning modes - each teaches the same concept differently