Bird
0
0

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:
  1. Step 1: Check return type and return statements

    Method must return int and return the larger value.
  2. 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.
  3. Final Answer:

    public int max(int a, int b) { return (a > b) ? a : b; } -> Option B
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes