CodingNeed.

1 · Values and control flow · 25 MIN

Types, methods and conditions

A method turns a declared input type into a declared result type.

Java checks types before running a program. A static method can be called without creating an instance and makes a useful starting point for pure calculations. The conditional here includes the boundary score of 60. String is a reference type; use equals for content comparison rather than ==. Keep your output separate from decisions so tests can call the decision method directly. Primitive int is fixed-width and overflow is not automatically reported by ordinary arithmetic.

Write down the interval for each grade before writing branches.

Read the example

public class Main {
  static String result(int score) { return score >= 60 ? "Pass" : "Try again"; }
  public static void main(String[] args) {
    System.out.println(result(60));
    System.out.println(result(59));
  }
}
Check the expected output
Pass
Try again

Your challenge

Add a grade method that returns A for at least 90, B for at least 75 and C otherwise; reject scores outside 0–100.

Solution cost: O(1) comparisons. time · O(1) auxiliary state. space

Common trap

Order overlapping conditions from most specific to least specific.

Study the project implementation
public class Main {
  static String result(int score) { return score >= 60 ? "Pass" : "Try again"; }
  public static void main(String[] args) {
    System.out.println(result(60));
    System.out.println(result(59));
  }
}

Further reading: Official documentation

Next lesson: Lists, loops and independent results

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.