Um momento
0x30Lesson 4 of 6

Choose a path with conditions

Compare values and use if, else if, and else to make decisions.

14 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • Write branches using comparisons and boolean conditions.

An if statement runs a block when a boolean condition is true. else if checks another condition when earlier ones were false, and else handles the remaining case. Comparisons include ==, !=, <, <=, >, and >=. Use && for “and” and || for “or.”

Main.java
1int score = 82;
2if (score >= 90) {
3    System.out.println("A");
4} else if (score >= 80) {
5    System.out.println("B");
6} else {
7    System.out.println("Keep practicing");
8}
Output
B

Conditions are checked from top to bottom, so put more specific or higher thresholds first. For object values such as Strings, use .equals() to compare contents; == compares whether two references identify the same object.

Key takeaways

  • Write branches using comparisons and boolean conditions.

  • Java checks types as it compiles your source.

  • Use compiler messages as clues about what needs fixing.

Lesson quiz

4 questions · pass with 3 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Java

Write Java in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.

Exercise 1

Label a number

+25 XP

Read an integer and print positive, negative, or zero based on its value.

  • Positive value
  • Negative value
  • Zero
Main.java
Loading editor…

Java is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: