All lessons

Making Decisions

8 min · Java

Run different code depending on whether something is true.

Java · Making Decisions0/5 cleared

Enemy 1 of 5

Every program you've written so far runs the exact same lines in the exact same order every time. Real programs need to react differently depending on the situation, and that's what conditionals are for.

An if runs its { } block only when the condition evaluates to true; else covers everything else, so exactly one of the two blocks ever runs. Compare values with > (greater than), < (less than), >= , <= , and == (equal to, for numbers) — Java requires the double equals sign for comparisons, reserving a single = for assignment, exactly like most other languages.

One important Java-specific gotcha worth flagging early: == compares primitive values like int correctly, but for String and other object types, == checks whether two variables point at the literal same object in memory, not whether their contents are equal. Comparing Strings for equality should instead use .equals(), like name.equals("Ada") — a subtlety that catches many Java beginners off guard, since it works fine with small literal strings but breaks in less obvious cases.

You
Memory-Leak Rat

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Cold