</>CodexBash
Java
JavaBeginner10 min

Operators and reading input

Arithmetic, remainder and increment, comparisons, logical operators, the == trap with objects, and reading input with Scanner and BufferedReader.

Taking a number apart with % and /step 1/6
4
0
7
1
n = 4071digit = -
Start with n = 4071. n % 10 gives the last digit; n / 10 (// in Python) drops it.

Arithmetic#

+, -, *, / and %. With two integers, / drops the fraction, rounding towards zero: 7 / 2 is 3. % gives the remainder and takes the sign of the left side: -7 % 2 is -1. For a remainder that is never negative, use Math.floorMod(-7, 2), which gives 1.

n % 10 and n / 10 take a number apart one digit at a time.

There is no power operator. Math.pow(2, 10) returns a double; for whole powers, multiply in a loop.

Shorthand#

i++;          // add one
total += x;   // total = total + x
total *= 2;

Comparisons and logic#

==, !=, <, >, <=, >= produce a boolean. && (and), || (or) and ! (not) combine them, and && and || stop as soon as the answer is known:

if (i < nums.length && nums[i] == target) { ... }

Java will not let you write if (x = 5): a condition must be a boolean, so the classic C mistake is a compile error here.

The == trap#

For primitives, == compares values. For objects, including String, it compares whether two references point at the same object, not whether they have the same contents:

String a = "hello";
String b = new String("hello");
a == b          // false: two different objects
a.equals(b)     // true: same characters

Always compare strings with equals. The same goes for Integer and other wrapper objects: Integer values above 127 compared with == are usually false even when equal.

Reading input with Scanner#

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        System.out.println(a + b);

        String word = in.next();        // one word
        in.nextLine();                  // finish the current line
        String line = in.nextLine();    // a whole line
    }
}

Mixing nextInt with nextLine catches people out: after nextInt, the rest of the line, often just the newline, is still waiting, so the next nextLine returns an empty string. Call in.nextLine() once to skip it, as above.

Reading until the input ends:

long total = 0;
while (in.hasNextInt()) {
    total += in.nextInt();
}

Faster input#

Scanner is convenient but slow for very large inputs. BufferedReader reads lines quickly, and you split them yourself:

import java.io.*;
import java.util.*;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());

On CodexBash the judge reads the input for you and calls your method, so this matters mainly for programs that read their own input.

Key points#

  • Integer / drops the fraction; % keeps the left side's sign; Math.floorMod does not.
  • Conditions must be boolean, so if (x = 5) will not compile.
  • Compare strings with equals, never ==.
  • After nextInt, call nextLine() once before reading a full line.

Next: strings and StringBuilder.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedReads the same backwardsEasy
  2. Not startedTurn the digits aroundEasy
Create a free account to track your progress