← 講座に戻る: Java from scratch

Operators and type conversions

動画は近日公開

Operators are the symbols that combine values to produce other values: add, compare, decide. This lesson teaches the everyday ones, the order in which they are evaluated and how Java converts one type into another, which is a classic source of surprises. Understanding this well will save you many hours of debugging.

Arithmetic and assignment

The arithmetic ones are +, -, *, / and % (remainder or modulo). The remainder is very useful: x % 2 == 0 tells you x is even, and a clock wraps around with % 24. To modify an existing variable there are shortcuts: x += 5 equals x = x + 5, and x++ adds one. The difference between x++ (postfix) and ++x (prefix) is that the first returns the old value and the second the new one; use them alone on a line and you will avoid confusion.

java
public class Main {
    public static void main(String[] args) {
        int x = 17;
        System.out.println(x / 5);   // 3  (integer division)
        System.out.println(x % 5);   // 2  (remainder)
        System.out.println(x % 2 == 0); // false: 17 is odd

        x += 3;                      // x is now 20
        x *= 2;                      // x is now 40
        x++;                         // x is now 41
        System.out.println(x);

        int y = 5;
        int a = y++;                 // a gets 5, then y becomes 6
        int b = ++y;                 // y becomes 7, then b gets 7
        System.out.println(a + " " + b + " " + y);

        // Precedence: * and / before + and -
        System.out.println(2 + 3 * 4);   // 14
        System.out.println((2 + 3) * 4); // 20
    }
}

Comparison and logic

To compare you use ==, !=, <, >, <= and >=; the result is always a boolean. Beware of a beginner mistake: = assigns, == compares. To combine conditions there are && (and), || (or) and ! (not). The && and || operators use short-circuit evaluation: if the first operand already decides the result, the second is not even evaluated. That lets you write safe checks like b != 0 && a / b > 2 with no risk of dividing by zero.

java
public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean hasTicket = true;

        boolean canEnter = age >= 18 && hasTicket;
        boolean isChild = age < 12 || age > 65;
        System.out.println(canEnter);   // true
        System.out.println(isChild);    // false
        System.out.println(!canEnter);  // false

        int a = 10, b = 0;
        // Short-circuit: a / b is never evaluated, so no exception
        boolean safe = b != 0 && a / b > 2;
        System.out.println(safe);       // false
    }
}

Type conversions

When you mix types, Java converts automatically to the wider type if no information is lost: an int inside a double is safe (widening). The other way, from double to int, loses the decimal part and Java demands that you ask for it explicitly with a cast: (int) 3.99 gives 3, not 4, because it truncates instead of rounding. If you want rounding use Math.round. Casts can also overflow: converting 300 to byte gives 44.

java
public class Main {
    public static void main(String[] args) {
        int apples = 7;
        double half = apples / 2;        // integer division first: 3.0
        double realHalf = apples / 2.0;  // 3.5
        double cast = (double) apples / 2; // 3.5: cast applies to apples
        System.out.println(half + " " + realHalf + " " + cast);

        double price = 3.99;
        int truncated = (int) price;      // 3
        long rounded = Math.round(price); // 4
        System.out.println(truncated + " " + rounded);

        int big = 300;
        byte small = (byte) big;          // overflow: 300 - 256 = 44
        System.out.println(small);

        int max = Integer.MAX_VALUE;      // 2147483647
        System.out.println(max + 1);      // wraps around to a negative number
    }
}

Evaluation order and good practices

When an expression mixes several operators, Java follows a precedence table: first parentheses, then unary operators such as ! and ++, then * / %, then + -, then comparisons, then && and finally ||. You do not need to memorize all of it. The practical rule is to use parentheses whenever you doubt: (a && b) || c reads better than trusting the table, and your teammates will thank you. Code is written once and read many times.

A common mistake is chaining comparisons as in mathematics: 1 < x < 10 does not compile in Java. You must write x > 1 && x < 10. Another is using single & or | instead of && and ||; they work with boolean, but they do not short-circuit and always evaluate both sides. And remember that an int overflow throws no error: it simply wraps around, so for large quantities choose long.

理解度チェック

問題 1 / 1

What is (int) 7.9?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →