Register

Java for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Operators and conditionals

Control flow and methods11 min readLesson 1 of 4

1.1 Arithmetic, comparison, and boolean results

Operators combine values. The familiar +, -, *, /, and % work on numbers. Parentheses control precedence, so (2 + 3) * 4 gives 20 while 2 + 3 * 4 gives 14.

Comparison operators (==, !=, >, <, >=, <=) produce a boolean. A boolean is either true or false. Use == to test equality of numbers and other primitive values. For text, use the equals method, which compares the characters inside the string.

Assignment and comparison are different operations. x = 5 stores 5 in x; x == 5 asks whether x already holds 5. Java rejects a comparison used where a statement is expected, which catches this mistake early.

java
public class Main {
    public static void main(String[] args) {
        int total = 23;
        int parts = 4;
        System.out.println(total / parts);
        System.out.println(total % parts);
        System.out.println(total > 20 && parts != 0);
    }
}

Output

5
3
true

1.1.1 Choosing with if and else

An if statement runs a block when its condition is true. An optional else runs when the condition is false. An else if chain tests conditions in order and stops at the first match, so put the most specific or highest band first.

The condition must be a boolean. Java does not treat 0 or a non-empty string as false. Braces are optional for a single statement, but keeping them makes later edits safer.

When several bands share the same result, group them carefully. A score of 90 or more can print A, a score from 75 to 89 can print B, and every lower score can fall through to a final else. Order the tests from the highest boundary down, and each later test can assume the earlier ones failed.

java
public class Main {
    public static void main(String[] args) {
        int score = 78;
        if (score >= 90) {
            System.out.println("A");
        } else if (score >= 75) {
            System.out.println("B");
        } else if (score >= 60) {
            System.out.println("C");
        } else {
            System.out.println("Needs practice");
        }
    }
}

Output

B

1.1.2 Combining conditions

&& means both sides must be true. || means at least one side must be true. ! reverses a boolean. These operators also short-circuit: with &&, Java skips the right side when the left is false; with ||, it skips the right side when the left is true.

Short-circuiting is useful when the right side would be unsafe. In name != null && name.length() > 0, the length call runs only when name is not null. Parentheses make a mixed condition easier to read and remove doubt about precedence.

A common range check combines two comparisons: age >= 13 && age <= 19. Writing 13 <= age <= 19 does not work in Java because the first comparison produces a boolean, and a boolean cannot be compared with < and a number.

java
public class Main {
    public static void main(String[] args) {
        int age = 16;
        boolean hasTicket = true;
        if (age >= 13 && hasTicket) {
            System.out.println("Entry allowed");
        } else {
            System.out.println("Entry denied");
        }
        System.out.println(age < 13 || !hasTicket);
    }
}

Output

Entry allowed
false

1.1.3 switch for fixed choices

A switch statement compares one value against several labels. It works with integers, characters, and strings. Each case is a candidate value, and default handles the values that match none of them.

Without break, execution falls through into the next case. A deliberate fall-through can group several labels that share one action, as when Saturday and Sunday both mean "Weekend." An accidental missing break runs code from a later case and is a common bug. Java 17 also supports the arrow form, case 1 -> ..., which does not fall through; the classic form is worth recognising in existing code.

java
public class Main {
    public static void main(String[] args) {
        int day = 6;
        switch (day) {
            case 6:
            case 7:
                System.out.println("Weekend");
                break;
            default:
                System.out.println("Weekday");
        }
    }
}

Output

Weekend

1.1.4 The conditional operator

The conditional operator chooses one of two values:

String status = stock >= wanted ? "Ready" : "Short";

The part before ? must be a boolean. If it is true, the expression produces the value before :; otherwise it produces the value after :. Both branches should have compatible types because the whole expression has one type.

Use it for small, obvious choices. A full if statement usually reads better when a branch calls several methods or changes state. Nesting conditional operators makes the order hard to follow.

java
public class Main {
    public static void main(String[] args) {
        int stock = 4;
        int wanted = 3;
        String status = stock >= wanted ? "Ready" : "Short";
        System.out.println(status);
    }
}

Output

Ready

1.1.5 Mistakes that change the flow

Putting a semicolon directly after if (condition) creates an empty body. The braces after it then run unconditionally, so the program prints a result even when the condition is false. The compiler allows this because it is valid syntax.

Using = in a condition is another common error. if (x = 5) tries to assign a value and then use it as a boolean, which fails for an int. if (x == 5) is the comparison you intended.

Boundary choices deserve a test. Check the value just below, at, and above each limit. A grade rule written with > can put a score of exactly 90 in the wrong band; use >= when the boundary belongs to the higher band. Add a few print statements or a small set of test values while the rule is new.

1.1.6 Practice

  1. Write a program that prints a ticket price from an age: free under 5, half price from 5 to 17, full price at 18 or older.
  2. Combine a membership flag with a purchase total and print a discount message only when both conditions hold.
  3. Convert a number from 1 to 7 into a day name with switch.
  4. Replace a simple if/else with the conditional operator, then decide which version reads better.
  5. Test the age program with 4, 5, 17, 18, and a negative age. Decide what a negative age should do.

Do not ignore the negative case. Add a guard at the top that prints an error and does nothing else for implausible input.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between `=` and `==`?

    `=` assigns a value to a variable. `==` compares two values and produces a boolean.

  • 02Why does `&&` sometimes skip its right operand?

    It short-circuits when the left side is false, because the whole expression must then be false. The skipped expression is never evaluated.

  • 03When should you use `switch`?

    Use `switch` when one value must choose among several fixed labels. Use `if` for ranges, combined conditions, or more complex logic.

Quiz

Check: Java operators and if statements

Four questions on precedence, boolean comparisons, short-circuit operators and the condition type in an if.

4 questions

Question 1 of 4

0/4 answered

What is the value of 2 + 3 * 4 in Java?

Answer all you can, then submit.