Chapter 7: Conditionals

Computer Fundamentals and Introduction to Programming
Control flowif-elseelse ifswitchExamples
Sercan KÜLCÜ · Giresun University

Introduction

Learning Outcomes

Flow

Distinguish sequential, selection and repetition flow.

Conditions

Write conditions with comparison and logical operators.

Decisions

Write if, else if and else in the right order.

switch

Use switch for discrete choices.

Basics

Three Basic Control Structures

SequenceSelectionLoopstatement 1statement 2statement 3condition?truefalsepath Apath Bonly one path runscondition?truebodyfalserepeats while true
  • Sequence runs statements in the order written; selection picks a path based on a condition.
  • A loop repeats a block of code.
  • Every algorithm is built from these three structures.

Basics

Sequential Statements

double base = 8;
double height = 5;
double area = base * height / 2;
System.out.println(area);
1base8.02height5.03area = 8.0 * 5.0 / 2 = 20.0420.0screenarea needs base and height first
  • Each statement can use values produced by earlier ones.
  • Change the order and you may get an undefined or wrong value.

Basics · Step through the code

Sequential Statements Step by Step

Memory (variables)base8.0double

base = 8 → stored in a double box as 8.0 (widening).

Memory (variables)base8.0doubleheight5.0double

height = 5.0.

Memory (variables)base8.0doubleheight5.0doubleExpressionbase * height / 240.0 / 2

Left to right: first base * height = 40.0.

Memory (variables)base8.0doubleheight5.0doublearea20.0double

40.0 / 2 = 20.0 → stored in area. This line uses the values of the two boxes above.

Memory (variables)base8.0doubleheight5.0doublearea20.0double

20.0 is printed. Had line 3 come before line 1, base would not exist yet → compile error.

double base = 8;
double height = 5;
double area = base * height / 2;
System.out.println(area);

Decisions

Making Decisions

  • A condition produces a boolean value.
  • if defines the true path, else the false path.
  • Every independent if is tested; in an else-if chain, once the first true branch runs the rest are skipped.
  • Example: score = 95. On the right, two versions with different results.
independent ifsscore >= 90 → truegrade='A'score >= 80 → truegrade='B'result: grade = 'B'✗ wrongelse ifscore >= 90 → truegrade='A'score >= 80skippedresult: grade = 'A'✓ correct

Decisions

The if-else Statement

truefalseread scorescore >= 60print "Pass"print "Fail"End
if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
  • The boundary belongs to the condition: 60 → Pass.
  • Every possible value goes to exactly one branch.

Decisions · Step through the code

if-else Step by Step: score = 75, 60, 45

truefalseread scorescore >= 60print "Pass"print "Fail"End

Run 1: the user enters 75.

truefalseread scorescore >= 60print "Pass"print "Fail"End

Condition: score >= 60 → 75 >= 60 → true.

truefalseread scorescore >= 60print "Pass"print "Fail"End

The true branch runs: Pass. The else block is skipped.

truefalseread scorescore >= 60print "Pass"print "Fail"End

Run 2: the user enters 60.

truefalseread scorescore >= 60print "Pass"print "Fail"End

Condition: score >= 60 → 60 >= 60 → true. The boundary is included: >=.

truefalseread scorescore >= 60print "Pass"print "Fail"End

The true branch runs: Pass. The else block is skipped.

truefalseread scorescore >= 60print "Pass"print "Fail"End

Run 3: the user enters 45.

truefalseread scorescore >= 60print "Pass"print "Fail"End

Condition: score >= 60 → 45 >= 60 → false.

truefalseread scorescore >= 60print "Pass"print "Fail"End

The false branch runs: Fail. The if block is skipped.

Scanner in = new Scanner(System.in);
int score = in.nextInt();
if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

Decisions

Multiway Decisions: else-if

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'F';
}
  • Conditions are tested top to bottom; the first true branch runs and the rest are skipped.
  • Put the higher thresholds first: with score >= 70 on top, 95 would also get a C.
  • else runs when no condition holds.

Decisions · Step through the code

else-if Chain: score = 75, 95, 50

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Run 1: score = 75. grade is declared but has no value yet.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Condition 1: score >= 90 → 75 >= 90 → false. Move on to the next one.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Condition 2: score >= 80 → 75 >= 80 → false. Move on to the next one.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Condition 3: score >= 70 → 75 >= 70 → true. This branch is taken.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

grade = 'C'. The rest of the chain is skipped without testing.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

C is printed.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Run 2: score = 95. grade is declared but has no value yet.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Condition 1: score >= 90 → 95 >= 90 → true. This branch is taken.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

grade = 'A'. The rest of the chain is skipped without testing.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

A is printed.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Run 3: score = 50. grade is declared but has no value yet.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Condition 1: score >= 90 → 50 >= 90 → false. Move on to the next one.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Condition 2: score >= 80 → 50 >= 80 → false. Move on to the next one.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

Condition 3: score >= 70 → 50 >= 70 → false. Move on to the next one.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

No condition held → else: grade = 'F'.

truefalsetruefalsetruefalsescore >= 90grade = 'A'score >= 80grade = 'B'score >= 70grade = 'C'grade = 'F'print grade

F is printed.

int score = in.nextInt();
char grade;
if (score >= 90)      grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else                grade = 'F';
System.out.println(grade);

Braces may be omitted when a branch has a single statement.

Decisions · Step through the code

Independent if Statements: score = 95 → 3 lines

score = 95. The three ifs are independent; none is the else branch of another.

95 >= 90 → true → A is printed. Because the ifs are independent, the next one is tested anyway.

95 >= 80 → true → B is printed too. The previous if has no effect on this test.

95 >= 70 → true → C is printed too. Result: 3 lines instead of one grade, which is wrong.

int score = 95;
if (score >= 90) System.out.println("A");
if (score >= 80) System.out.println("B");
if (score >= 70) System.out.println("C");

Decisions · Step through the code

Same score = 95, else-if chain → 1 line

Same score = 95; this time the conditions are chained with else if.

95 >= 90 → true → A is printed.

The first branch ran, so the else if branches are never evaluated; 80 and 70 are not tested.

Result: just 1 line. Independent ifs print 3 lines (A, B, C); the else-if chain prints 1 (A).

int score = 95;
if (score >= 90) System.out.println("A");
else if (score >= 80) System.out.println("B");
else if (score >= 70) System.out.println("C");

Decisions

Nested Decisions

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"
  • A branch can contain another decision: the inner condition is tested only when the outer one is true.
  • Nesting fits cases where the second question only makes sense once the first condition holds.
  • Deep nesting hurts readability; conditions can be combined with &&.

Decisions · Step through the code

Nested Decision: 3 different inputs

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Run 1: age = 20, license = true.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Outer condition: age >= 18 → 20 >= 18 → true. Enter the inner if.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Inner condition: license → true.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Can drive is printed.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Run 2: age = 20, license = false.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Outer condition: age >= 18 → 20 >= 18 → true. Enter the inner if.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Inner condition: license → false.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Get a license first is printed.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Run 3: age = 15, license = true.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

Outer condition: 15 >= 18 → false. The inner if is never tested; license does not matter.

truefalsetruefalseage >= 18licenseprint "Can drive"print "Get a license first"print "Too young"

The outer else runs: Too young.

int age = in.nextInt();
boolean license = in.nextBoolean();
if (age >= 18) {
  if (license)
    System.out.println("Can drive");
  else
    System.out.println("Get a license first");
} else {
  System.out.println("Too young");
}

Decisions · Step through the code

The Dangling else: a = −1

Start: a = -1, b = 5, x = 0. The indentation suggests the else belongs to the outer if, but the compiler ignores indentation.

a > 0 → −1 > 0 → false. The whole body of the outer if (inner if and its else included) is skipped.

else binds to the nearest if (if (b > 0)); that if never ran, so neither did the else. x is unchanged: 0 is printed.

int a = -1, b = 5, x = 0;
if (a > 0)
    if (b > 0)
        x = 1;
    else
        x = 2;
System.out.println(x);

Decisions · Step through the code

Fixing the Dangling else with Braces

Same starting values. This time the inner if is wrapped in braces; the else belongs to the outer if.

a > 0 → false. The inner if block is skipped and control goes to the else block.

The else block runs: x = 2.

2 is printed. Always use braces with nested ifs to remove the ambiguity.

int a = -1, b = 5, x = 0;
if (a > 0) {
    if (b > 0) x = 1;
} else {
    x = 2;
}
System.out.println(x);

Decisions

Decisions with Logical Operators

boolean eligible = age >= 18 && hasDoc;
if (eligible) {
    System.out.println("Application accepted");
}
age >= 18hasDoc&&eligibleboth must be truehasDoctruefalseage >= 18 ↓truefalsetruefalsefalsefalsevalue of eligible
  • && requires both conditions to be true.
  • || requires at least one of them to be true.

Decisions · Step through the code

Deciding with &&: 3 different inputs

age20inthasDoctruebooleanage >= 18&&hasDoc

Run 1: age = 20, hasDoc = true.

age20inthasDoctruebooleanage >= 18true&&hasDoctrue→ true

20 >= 18 → true; the right side is needed: hasDoc → true. true && true → true.

age20inthasDoctruebooleanage >= 18true&&hasDoctrue→ true

Application accepted is printed.

age20inthasDocfalsebooleanage >= 18&&hasDoc

Run 2: age = 20, hasDoc = false.

age20inthasDocfalsebooleanage >= 18true&&hasDocfalse→ false

20 >= 18 → true; the right side is needed: hasDoc → false. true && false → false.

age20inthasDocfalsebooleanage >= 18true&&hasDocfalse→ false

eligible is false → the block is skipped, no output.

age16inthasDoctruebooleanage >= 18&&hasDoc

Run 3: age = 16, hasDoc = true.

age16inthasDoctruebooleanage >= 18false&&hasDocnot evaluated→ false

16 >= 18 → false. Short circuit: hasDoc is not read; the result is already false.

age16inthasDoctruebooleanage >= 18false&&hasDocnot evaluated→ false

eligible is false → the block is skipped, no output.

int age = in.nextInt();
boolean hasDoc = in.nextBoolean();
boolean eligible = age >= 18 && hasDoc;
if (eligible) {
    System.out.println("Application accepted");
}

Decisions

! and De Morgan's Laws

ab!(a && b)!a || !b!(a || b)!a && !b
falsefalsetruetruetruetrue
falsetruetruetruefalsefalse
truefalsetruetruefalsefalse
truetruefalsefalsefalsefalse
// Reject: under 18 or no document
if (!(age >= 18 && hasDoc)) { … }
// Same condition by De Morgan:
if (age < 18 || !hasDoc) { … }
  • Pushing ! inside the parentheses swaps && and || and negates each term.
  • Negated comparisons: >= ↔ <, > ↔ <=, == ↔ !=.

Decisions

Non-Short-Circuit & and |

int a = 10, b = 0;
if (b != 0 && a / b > 1) { … }  // safe: a / b never runs
if (b != 0 &  a / b > 1) { … }  // ArithmeticException: / by zero

The single-character & and | also work on booleans, but they always evaluate both sides.

static int count = 0;
static boolean check(boolean v) { count++; return v; }
Expression (count starts at 0)count
check(false) && check(true)1
check(false) & check(true)2
check(true) || check(true)1
check(true) | check(true)2

Decisions · Step through the code

The Conditional Operator: (a > b) ? a : b

a7intb12inta > b?a:b

a = 7, b = 12.

a7intb12inta > bfalse?anot checked:btrue

Condition: a > b → 7 > 12 → false, so the value after : is chosen.

a7intb12intmax12inta > bfalse?anot checked:btrue→ 12

max = 12. ?: is an expression: it yields a value that can be assigned.

a7intb12intmax12inta > bfalse?anot checked:btrue→ 12

12 is printed. The same if-else takes 4 lines.

int a = 7, b = 12;
int max = (a > b) ? a : b;
System.out.println(max);

Use it for short two-way value choices; nested ?: hurts readability.

Decisions · Step through the code

Comparing Strings: == vs. equals

variablesstring poolheap (via new)s1"java"

The literal "java" is created in the string pool; s1 holds a reference to it.

variablesstring poolheap (via new)s1"java"s2

Writing the same literal again shares the pooled object; s2 points to the same object.

variablesstring poolheap (via new)s1"java"s2s3"java"

new String("java") always creates a new object; s3 points to a separate object on the heap.

variablesstring poolheap (via new)s1"java"s2s3"java"

== compares references (addresses). s1 and s2 point to the same object, so true.

variablesstring poolheap (via new)s1"java"s2s3"java"

s1 and s3 have the same contents but are different objects → different addresses → false.

variablesstring poolheap (via new)s1"java"s2s3"java"

equals compares the contents: "java" = "java" → true. Always compare strings with equals.

String s1 = "java";
String s2 = "java";
String s3 = new String("java");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));

switch

When to Use switch

switch (month)case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"
  • It suits a choice among the discrete values of a single expression.
  • case labels name the fixed options; control jumps directly to the matching case.
  • For ranges and complex logical conditions, if-else is usually a better fit.

switch

The switch Expression

String season = switch (month) {
    case 12, 1, 2 -> "Winter";
    case 3, 4, 5 -> "Spring";
    case 6, 7, 8 -> "Summer";
    case 9, 10, 11 -> "Autumn";
    default -> "Invalid";
};
123456789101112WinterSpringSummerAutumnmonth1..12a value like 13 → default: "Invalid"
  • The arrow form prevents accidental fall-through into the next case.
  • default handles unexpected values. A switch expression (x = switch …) must cover every value, so for int and String default is required; in a switch statement it is optional. This syntax needs Java 14 or later.

switch · Step through the code

switch Expression: month = 4, 12, 13

month = 4case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

Run 1: month = 4.

month = 4case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

switch (month) → 4: 4 is in this case's list. The selected branch yields "Spring".

month = 4case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

The value of the switch expression is assigned: season = "Spring". No other case runs.

month = 4case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

Spring is printed.

month = 12case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

Run 2: month = 12.

month = 12case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

switch (month) → 12: 12 is in this case's list. The selected branch yields "Winter".

month = 12case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

The value of the switch expression is assigned: season = "Winter". No other case runs.

month = 12case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

Winter is printed.

month = 13case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

Run 3: month = 13.

month = 13case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

switch (month) → 13: no case lists 13 → default. The selected branch yields "Invalid".

month = 13case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

The value of the switch expression is assigned: season = "Invalid". No other case runs.

month = 13case 12, 1, 2→ "Winter"case 3, 4, 5→ "Spring"case 6, 7, 8→ "Summer"case 9, 10, 11→ "Autumn"default→ "Invalid"

Invalid is printed.

int month = in.nextInt();
String season = switch (month) {
    case 12, 1, 2 -> "Winter";
    case 3, 4, 5 -> "Spring";
    case 6, 7, 8 -> "Summer";
    case 9, 10, 11 -> "Autumn";
    default -> "Invalid";
};
System.out.println(season);

switch

yield in a switch Expression

int year = 2024, month = 2;
int days = switch (month) {
    case 4, 6, 9, 11 -> 30;
    case 2 -> {
        System.out.println("February");
        yield year % 4 == 0 ? 29 : 28;
    }
    default -> 31;
};
System.out.println(days);

Output: February and 29 (two lines).

  • A single-expression branch gives its value directly; when several statements are needed, wrap the branch in a { } block and give the value with yield.
  • A block that ends without yield is a compile error: switch rule completes without providing a value.
  • Requires Java 14 or later; the leap-year test is simplified here (no 100/400 rule).

switch · Step through the code

Classic switch: Forgetting break

case 1:"Mon"breakcase 2:"Tue"no break!case 3:"Wed"breakdefault:"None"no break!

day = 2.

case 1:"Mon"breakcase 2:"Tue"no break!case 3:"Wed"breakdefault:"None"no break!

switch (day) → 2: control jumps straight to case 2; case 1 is never tested.

case 1:"Mon"breakcase 2:"Tue"no break!case 3:"Wed"breakdefault:"None"no break!

"Tue" is printed. This case has no break!

case 1:"Mon"breakcase 2:"Tue"no break!case 3:"Wed"breakdefault:"None"no break!

Fall-through: the next case's code runs too, without testing its label → "Wed".

case 1:"Mon"breakcase 2:"Tue"no break!case 3:"Wed"breakdefault:"None"no break!

break leaves the switch; default does not run. The arrow (->) form avoids this bug.

int day = 2;
switch (day) {
  case 1: System.out.println("Mon"); break;
  case 2: System.out.println("Tue");
  case 3: System.out.println("Wed"); break;
  default: System.out.println("None");
}

switch

if-else vs. switch

Criterionif-elseswitch
Range conditionGood fitNot directly
Many choices on one valueWorksUsually clearer
Complex logicGood fitLimited
Each branch yields a valueNeeds an assignmentA switch expression can return a value
if-else: range conditionsFailPassExcellent05085100score < 50  ·  score < 85  ·  elseeach branch covers a range of numbersswitch: discrete values1234567case 1, 2, 3, 4, 5"Weekday"case 6, 7"Weekend"fixed values of a single variable

Example

Odd or Even?

int num = 17;
if (num % 2 == 0)
    System.out.println("Even");
else
    System.out.println("Odd");
numnum % 2-40-3-1-20-1-100112031400 → Even1 or -1 → Odd (a negative odd number gives -1: an == 1 test fails)
  • A number is even if dividing by 2 leaves a remainder of 0.
  • This works for negatives too. But in Java -7 % 2 = -1, so testing odd numbers with num % 2 == 1 is wrong.

Example · Step through the code

Odd or Even? num = 17, −4, −7

Memory (variables)num17intExpressionnum % 2 == 0

Run 1: num = 17.

Memory (variables)num17intExpression17 % 2 == 01 == 0

First the remainder: 17 % 2 = 1.

Memory (variables)num17intExpression1 == 0→ false

1 == 0 → false.

Memory (variables)num17intExpression→ "Odd"

Odd is printed.

Memory (variables)num-4intExpressionnum % 2 == 0

Run 2: num = -4.

Memory (variables)num-4intExpression-4 % 2 == 00 == 0

First the remainder: -4 % 2 = 0.

Memory (variables)num-4intExpression0 == 0→ true

0 == 0 → true.

Memory (variables)num-4intExpression→ "Even"

Even is printed.

Memory (variables)num-7intExpressionnum % 2 == 0

Run 3: num = -7.

Memory (variables)num-7intExpression-7 % 2 == 0-1 == 0

First the remainder: -7 % 2 = -1 (in Java the remainder takes the sign of the dividend).

Memory (variables)num-7intExpression-1 == 0→ false

-1 == 0 → false.

Memory (variables)num-7intExpression→ "Odd"

Odd is printed. With the test -7 % 2 == 1 the result would have been false!

int num = in.nextInt();
if (num % 2 == 0)
    System.out.println("Even");
else
    System.out.println("Odd");

Example

Absolute Value

int num = -8;
if (num < 0) {
    num = -num;
}
System.out.println(num);
-10-8-505810num < 0 → num = -num-8 (before)8 (after)0 and positives unchanged
  • Zero and positive values stay unchanged.
  • Integer.MIN_VALUE is a special overflow case.

Example · Step through the code

Absolute Value: num = −8, 5, MIN_VALUE

Memory (variables)num-8int

Run 1: num = -8.

Memory (variables)num-8intExpression-8 < 0→ true

Condition: num < 0 → -8 < 0 → true.

Memory (variables)num8int

num = -num → -(-8) = 8.

Memory (variables)num8int

8 is printed.

Memory (variables)num5int

Run 2: num = 5.

Memory (variables)num5intExpression5 < 0→ false

Condition: num < 0 → 5 < 0 → false. The block is skipped; the value stays.

Memory (variables)num5int

5 is printed.

Memory (variables)num-2147483648int

Run 3: num = -2147483648 (Integer.MIN_VALUE).

Memory (variables)num-2147483648intExpression-2147483648 < 0→ true

Condition: num < 0 → -2147483648 < 0 → true.

Memory (variables)num-2147483648int

-(-2147483648) = 2147483648 does not fit in an int → overflow: the result is -2147483648 again!

Memory (variables)num-2147483648int

-2147483648 is printed. The absolute value came out negative: a special case.

int num = in.nextInt();
if (num < 0) {
    num = -num;
}
System.out.println(num);

Example · Step through the code

Leap Year: 2024, 2023, 1900, 2000

year2024int(year % 4 == 0&&year % 100 != 0)||year % 400 == 0

Run 1: year = 2024.

year2024int(year % 4 == 0true&&year % 100 != 0true)||year % 400 == 0

2024 % 4 = 0 → true; 2024 % 100 = 24 → year % 100 != 0 → true. Parenthesized part: true.

year2024int(year % 4 == 0true&&year % 100 != 0true)||year % 400 == 0not checked→ true

Left side true → || short-circuits: the 400 rule is not checked. leap = true.

year2024int(year % 4 == 0true&&year % 100 != 0true)||year % 400 == 0not checked→ true

2024 is a leap year.

year2023int(year % 4 == 0&&year % 100 != 0)||year % 400 == 0

Run 2: year = 2023.

year2023int(year % 4 == 0false&&year % 100 != 0not checked)||year % 400 == 0

2023 % 4 = 3 → false; && short-circuits. Parenthesized part: false.

year2023int(year % 4 == 0false&&year % 100 != 0not checked)||year % 400 == 0false→ false

Left side false → check the right: 2023 % 400 = 23 → false. leap = false.

year2023int(year % 4 == 0false&&year % 100 != 0not checked)||year % 400 == 0false→ false

2023 is not a leap year.

year1900int(year % 4 == 0&&year % 100 != 0)||year % 400 == 0

Run 3: year = 1900.

year1900int(year % 4 == 0true&&year % 100 != 0false)||year % 400 == 0

1900 % 4 = 0 → true; 1900 % 100 = 0 → year % 100 != 0 → false. Parenthesized part: false.

year1900int(year % 4 == 0true&&year % 100 != 0false)||year % 400 == 0false→ false

Left side false → check the right: 1900 % 400 = 300 → false. leap = false.

year1900int(year % 4 == 0true&&year % 100 != 0false)||year % 400 == 0false→ false

1900 is not a leap year. Century years are leap years only if divisible by 400.

year2000int(year % 4 == 0&&year % 100 != 0)||year % 400 == 0

Run 4: year = 2000.

year2000int(year % 4 == 0true&&year % 100 != 0false)||year % 400 == 0

2000 % 4 = 0 → true; 2000 % 100 = 0 → year % 100 != 0 → false. Parenthesized part: false.

year2000int(year % 4 == 0true&&year % 100 != 0false)||year % 400 == 0true→ true

Left side false → check the right: 2000 % 400 = 0 → true. leap = true.

year2000int(year % 4 == 0true&&year % 100 != 0false)||year % 400 == 0true→ true

2000 is a leap year.

int year = in.nextInt();
boolean leap =
    (year % 4 == 0 && year % 100 != 0)
    || year % 400 == 0;
if (leap)
    System.out.println(year + " is a leap year");
else
    System.out.println(year + " is not a leap year");

Example · Step through the code

Quadratic Equation: Δ > 0, Δ = 0, Δ < 0

1.0x² + (-3.0)x + 2.0

Run 1: a = 1.0, b = -3.0, c = 2.0.

1.0x² + (-3.0)x + 2.0Δ = 1.0

d = Δ = b² − 4ac = 9.0 − 8.0 = 1.0.

1.0x² + (-3.0)x + 2.0Δ > 0 → two roots

1.0 > 0 → true: two distinct real roots.

2.01.01.0x² + (-3.0)x + 2.0two roots

√Δ = 1.0; x1 = (3.0 + 1.0) / 2.0 = 2.0, x2 = 1.0.

2.01.01.0x² + (-3.0)x + 2.0two roots

2.0 and 1.0: the parabola crosses the x-axis at two points.

1.0x² + (-2.0)x + 1.0

Run 2: a = 1.0, b = -2.0, c = 1.0.

1.0x² + (-2.0)x + 1.0Δ = 0.0

d = Δ = b² − 4ac = 4.0 − 4.0 = 0.0.

1.0x² + (-2.0)x + 1.0Δ = 0 → one root

Δ > 0 is false; Δ == 0 → true: one (double) root.

1.01.0x² + (-2.0)x + 1.0one root

x = −b / 2a = 2.0 / 2.0 = 1.0: the parabola touches the axis.

1.0x² + (0.0)x + 1.0

Run 3: a = 1.0, b = 0.0, c = 1.0.

1.0x² + (0.0)x + 1.0Δ = -4.0

d = Δ = b² − 4ac = 0.0 − 4.0 = -4.0.

1.0x² + (0.0)x + 1.0Δ < 0

-4.0 > 0 false, -4.0 == 0 false → else.

1.0x² + (0.0)x + 1.0no roots

No real roots: the parabola never meets the axis. Math.sqrt of a negative would give NaN; the else prevents that.

double a = in.nextDouble();
double b = in.nextDouble();
double c = in.nextDouble();
double d = b * b - 4 * a * c;
if (d > 0) {
  double x1 = (-b + Math.sqrt(d)) / (2 * a);
  double x2 = (-b - Math.sqrt(d)) / (2 * a);
  System.out.println(x1 + " and " + x2);
} else if (d == 0) {
  System.out.println(-b / (2 * a));
} else {
  System.out.println("No real roots");
}

Example · Step through the code

Largest of Three Numbers: 3 different inputs

7a12b5cmax?int

Run 1: 7, 12, 5.

7a12b5cmax7int

Candidate: max = a = 7.

7a12b5cmax7int

b > max → 12 > 7 → true.

7a12b5cmax12int

New candidate: max = b = 12.

7a12b5cmax12int

c > max → 5 > 12 → false; the candidate stays.

7a12b5cmax12int

Max: 12.

3a3b9cmax?int

Run 2: 3, 3, 9.

3a3b9cmax3int

Candidate: max = a = 3.

3a3b9cmax3int

b > max → 3 > 3 → false; the candidate stays. An equal value does not replace it.

3a3b9cmax3int

c > max → 9 > 3 → true.

3a3b9cmax9int

New candidate: max = c = 9.

3a3b9cmax9int

Max: 9.

8a2b4cmax?int

Run 3: 8, 2, 4.

8a2b4cmax8int

Candidate: max = a = 8.

8a2b4cmax8int

b > max → 2 > 8 → false; the candidate stays.

8a2b4cmax8int

c > max → 4 > 8 → false; the candidate stays.

8a2b4cmax8int

Max: 8.

int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int max = a;
if (b > max)
    max = b;
if (c > max)
    max = c;
System.out.println("Max: " + max);

Shortcut: Math.max(a, Math.max(b, c)). The "candidate + compare" pattern generalizes with a loop.

Example · Step through the code

A Calculator with switch: *, /0, %

8.0 * 2.5"+""-""*""/"default

Run 1: the user enters 8.0 * 2.5; next() reads the operator as a string.

8.0 * 2.5"+""-""*""/"default

switch (op) → "*": matches case "*".

8.0 * 2.5"+""-""*""/"default20.0

8.0 * 2.5 = 20.0 is printed. No other case runs.

7.0 / 0.0"+""-""*""/"default

Run 2: the user enters 7.0 / 0.0; next() reads the operator as a string.

7.0 / 0.0"+""-""*""/"default

switch (op) → "/": matches case "/".

7.0 / 0.0"+""-""*""/"defaulty == 0 ?

Check before dividing: y == 0 → true. (With doubles 7.0 / 0 does not throw; it gives Infinity, so we check.)

7.0 / 0.0"+""-""*""/"defaultError!

Error! is printed.

5.0 % 3.0"+""-""*""/"default

Run 3: the user enters 5.0 % 3.0; next() reads the operator as a string.

5.0 % 3.0"+""-""*""/"default

switch (op) → "%": no case matches → default.

5.0 % 3.0"+""-""*""/"defaultInvalid

Invalid: this calculator has no %; default catches unexpected input.

double x = in.nextDouble();
String op = in.next();
double y = in.nextDouble();
switch (op) {
  case "+" -> System.out.println(x + y);
  case "-" -> System.out.println(x - y);
  case "*" -> System.out.println(x * y);
  case "/" -> {
    if (y == 0) System.out.println("Error!");
    else System.out.println(x / y);
  }
  default -> System.out.println("Invalid");
}

Summary

Chapter Summary

  • Sequence runs statements in the order written; selection picks a path based on a condition.
  • A condition must always produce a boolean value.
  • In an else-if chain, conditions are tried top to bottom; the first true branch runs.
  • Use if-else for ranges and complex conditions, switch for discrete values of one expression.

Summary

Review Questions

  1. How do independent if statements differ from an else-if chain?
  2. Why are the thresholds written from highest to lowest when converting scores to letter grades?
  3. When can && replace a nested decision?
  4. Why is default useful in a switch?
  5. Which condition tells you that a number is even?

Summary

Exercises

  1. Print whether an input integer is positive, negative or zero.
  2. Compute body mass index (weight / height²) and print underweight / normal / overweight.
  3. Do three side lengths form a triangle? If so, is it equilateral, isosceles or scalene?
  4. Map a day number 1–7 to a day name with switch; warn on invalid input.
  5. Find the smaller of two numbers with ?:, then extend it to three numbers.
  6. Add an "outside 0–100" check to the letter-grade program. Where in the chain should it go?

Summary

References

The End

Chapter 7: Conditionals
Previous: Chapter 6: Variables, Data Types and Operators · Next: Chapter 8: Loops
1 / 1Sercan KÜLCÜ. All rights reserved.