Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Java  Module 27 – Java for DSA, placements and online assessments

Java setup for coding rounds and judges

A judge-ready Java Main template with fast input and one flush, how to check which JDK a judge runs first, and the compile errors judges report most.

  • Intermediate
  • 20 minutes
  • Examples run with Java 25.0.4.1 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Write a judge-ready Main class template with fast input, buffered output and helpers
  • Check which JDK an online judge or assessment uses before relying on new syntax
  • Avoid the compile failures judges report most, from class names, package lines and imports
  • Avoid stale static state between the test cases of one input without clearing whole arrays

Before you start

What you’ll learn · Before you start

What you will learn

  • Write a judge-ready Main class template with fast input, buffered output and helpers
  • Check which JDK an online judge or assessment uses before relying on new syntax
  • Avoid the compile failures judges report most, from class names, package lines and imports
  • Avoid stale static state between the test cases of one input without clearing whole arrays

Before you start

On this page

An online judge compiles your Java file with its own JDK, runs it once for every test input, and compares what it prints with the expected output. A setup that survives every judge is small: a public class Main in Main.java with no package line, the classic public static void main(String[] args), input read through one BufferedReader and cut into tokens with a StringTokenizer, output collected in one PrintWriter that is flushed once at the end, and nothing newer than the judge’s JDK. This lesson builds that template, sends it through a small local judge, and reproduces the compile errors and wrong answers that judges report most often. The algorithms themselves belong to MySmartCoPilot’s DSA and coding-patterns tracks; this module covers the Java around them.

A judge compiles Main.java once, runs it once per test file and compares the output; each step can end in its own verdict.Main.javayour submission1. Compile oncewith the javac of the judge's JDK fails: compilation error2. Run once per test filejava with the judge's flags,standard input from the file exception or exit status not 0: runtime errortoo slow: time limit exceeded3. Compare the outputwith the expected output differs: wrong answersame text: acceptedclass filesstandard output

What a judge does with your file, and where each verdict comes from

Text description of the diagram

The diagram is a column of four boxes, from top to bottom.

  1. Your submission, Main.java.
  2. "1. Compile once", with the javac of the judge's own JDK. If javac fails, the verdict is compilation error.
  3. The class files go to "2. Run once per test file": java starts with the judge's flags, and standard input comes from the test file. An exception or an exit status other than 0 gives runtime error; running too long gives time limit exceeded.
  4. The program's standard output goes to "3. Compare the output with the expected output". If it differs, the verdict is wrong answer; if it is the same text, the verdict is accepted.

What a judge does with your file

Every judge works in three steps, and each step can end a submission with a verdict of its own.

  1. Compile once. The judge stores your code, often under a file name it chooses, and compiles it with the javac of its own JDK. If javac fails, the verdict is compilation error, usually shown with the first error message.
  2. Run once per test file. The judge starts java once for each test input, with flags it chooses. Kattis and the ICPC World Finals both set the heap to the problem’s memory limit with -Xms and -Xmx and give the thread a 64 MB stack with -Xss64m. Standard input comes from the test file, so no one is there to type. An uncaught exception or an exit status other than 0 gives runtime error; going past the time limit gives time limit exceeded; using too much memory gives memory limit exceeded.
  3. Compare. The judge compares your standard output with the expected output. Any difference gives wrong answer; the same text gives accepted. Judges differ in how strict the comparison is about spaces at the end of a line, so print exactly the format that the statement shows.

Two rules follow for every program. It reads only from standard input and writes only to standard output, and it has printed everything before it exits.

A template that works on every judge

Here is the template. Its solve method is an example task: each test case is a count n followed by n whole numbers, and the program prints their minimum, their maximum and their sum.

Main.java: the template Java · Main.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

// A judge-ready template: no package line, a public class named Main in Main.java, the classic main, buffered input
// and one buffered output that is flushed once. The solve method is an example: replace it with your solution.
public class Main {
    static final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static final PrintWriter out = new PrintWriter(System.out);
    static StringTokenizer tokens = new StringTokenizer("");

    public static void main(String[] args) throws IOException {
        int t = nextInt(); // the number of test cases in this input
        for (int test = 1; test <= t; test++) {
            solve();
        }
        out.flush(); // without it, the judge receives no output at all
    }

    // Example task: each test case is n followed by n whole numbers; print their minimum, maximum and sum.
    static void solve() throws IOException {
        int n = nextInt();
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        long sum = 0; // n values up to 10^9 each can pass the int range long before the end
        for (int i = 0; i < n; i++) {
            int x = nextInt();
            min = Math.min(min, x);
            max = Math.max(max, x);
            sum += x;
        }
        out.println(min + " " + max + " " + sum);
    }

    // The next token, whatever the line breaks; null once the input has ended.
    static String next() throws IOException {
        while (!tokens.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) return null;
            tokens = new StringTokenizer(line);
        }
        return tokens.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}

Each choice in it has a reason:

  • No package line, and public class Main in Main.java. Some judges store your file as Main.java whatever you called it, and others keep your name and look for the class that holds main. A public Main without a package works on both kinds.
  • The classic public static void main(String[] args) throws IOException. It is the one entry point every JDK accepts. Declaring IOException keeps readLine short, and on a judge an input error is a runtime error whatever you write.
  • One BufferedReader, read through next(). next() fetches a new line whenever the current one has no tokens left, so the numbers may be spread over the lines in any way. nextInt and nextLong convert each token with Integer.parseInt and Long.parseLong.
  • One PrintWriter called out, flushed once at the end of main. It collects the text in memory, where System.out.println hands every line to the operating system at once. Without the flush, a short output never reaches the judge at all, and a long one arrives cut off.
  • long for the sum. Five values of 10^9 already add up to 5 × 10^9, more than the 2,147,483,647 that an int can hold.
  • A loop over the test cases in main. Most statements give the number of test cases first, and solve handles one of them.

The next lesson measures these readers and writers against the alternatives, on a million numbers. The local judge used on this page is a short shell script, submit.sh. It stores the submission as Main.java in a new folder, compiles it with javac --release, and runs class Main on one input file:

submit.sh: a small local judge Shell · submit.sh
#!/bin/sh
# A small local judge: it saves the submission as Main.java in a fresh folder, compiles it the way many judges do,
# for the Java release in $RELEASE (25 when it is not set), and runs class Main on one input file.
# Usage: sh submit.sh Solution.java input.txt        RELEASE=21 sh submit.sh Solution.java input.txt
rm -rf judged && mkdir judged && cp "$1" judged/Main.java || exit 2
cd judged || exit 2
javac --release "${RELEASE:-25}" -encoding UTF-8 -d . Main.java || exit 1
java -Xss64m -cp . Main < "../$2"
The template on the sample input, checked, and on an input that ends early Python · template_session.py
from session import run

# The template, submitted to the local judge of submit.sh: the sample input, the output, a check against the
# expected output, and an input that ends one test case too early.
run("""
cat sample.txt
sh submit.sh Main.java sample.txt
sh submit.sh Main.java sample.txt | diff expected.txt - && echo PASS
sh submit.sh Main.java short.txt
""", expect_failure=("sh submit.sh Main.java short.txt",))

Output

# JDK in use: openjdk version "25.0.4.1" LTS
$ cat sample.txt
3
4
7 -2 19 5
1
1000000000
5
1000000000 1000000000 1000000000 1000000000 1000000000
$ sh submit.sh Main.java sample.txt
-2 19 29
1000000000 1000000000 1000000000
1000000000 1000000000 5000000000
$ sh submit.sh Main.java sample.txt | diff expected.txt - && echo PASS
PASS
$ sh submit.sh Main.java short.txt
Exception in thread "main" java.lang.NumberFormatException: Cannot parse null string
	at java.base/java.lang.Integer.parseInt(Integer.java:527)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at Main.nextInt(Main.java:48)
	at Main.solve(Main.java:24)
	at Main.main(Main.java:17)
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 template_session.py

The third test case printed 5000000000, which needs the long. The diff against the expected output printed nothing, so the command went on to print PASS: that is the judge’s comparison, done on your own computer. The last input promises two test cases but holds only one. The second call to next() returned null, Integer.parseInt threw a NumberFormatException, and the exit status was 1. A judge reports exactly that as a runtime error, so the stack trace you get locally, with its line numbers, is the best clue you will have.

Check the judge’s JDK before you use new syntax

Judges move to new JDKs slowly, and the Java on your computer may be newer than theirs. Four platforms document these versions:

  • Kattis documents javac and java 25.0.3, so compact source files compile there, and it runs the class that holds your main.
  • The ICPC World Finals list OpenJDK 21.0.4: only the classic main works, and there is no IO class.
  • AtCoder lists Java24 (OpenJDK 24.0.2) and compiles Main.java, so the public class must be Main; compact source files were still a preview feature in Java 24.
  • HackerRank lists Java 7, 8, 15, 17 and 21, the newest being OpenJDK 21.0.4. Choose Java 21 when you can; none of these versions compiles a compact source file.

Compact source files and instance main methods became a final feature in JDK 25 with JEP 512, after previews in JDK 21 to 24, and IO.readln and IO.println came with them. Library methods follow the same rule: getFirst() and getLast() on a List arrived in Java 21 with sequenced collections (JEP 431). Platforms do update their JDKs, so read the platform’s own page before a contest or an assessment, and trust it over any list, this one included.

You do not need the judge’s JDK on your computer to see what it would say. javac --release N compiles your code by the language rules of Java release N and against the API of that release, and the javac of JDK 25 accepts every release from 8 to 25. For local practice the template also fits in a compact source file, because such a file imports the whole java.base module by itself and needs no class around its methods:

Practice.java: the same solution as a compact source file Java · Practice.java
// The same solution as a compact source file, for practice on JDK 25 or later: the java.base packages are imported
// by themselves, and main needs no class, no public and no static. Most judges cannot compile it (see the lesson).
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer tokens = new StringTokenizer("");

void main() throws IOException {
    int t = nextInt();
    for (int test = 1; test <= t; test++) {
        int n = nextInt();
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        long sum = 0;
        for (int i = 0; i < n; i++) {
            int x = nextInt();
            min = Math.min(min, x);
            max = Math.max(max, x);
            sum += x;
        }
        out.println(min + " " + max + " " + sum);
    }
    out.flush();
}

String next() throws IOException {
    while (!tokens.hasMoreTokens()) {
        String line = in.readLine();
        if (line == null) return null;
        tokens = new StringTokenizer(line);
    }
    return tokens.nextToken();
}

int nextInt() throws IOException {
    return Integer.parseInt(next());
}
One task, compiled for Java 25, 21 and 17

newer/Main.java · newer/Main.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

// The example task again, written with methods that List gained in Java 21: after sorting, the first value is
// the minimum and the last one the maximum.
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        int t = Integer.parseInt(in.readLine().trim());
        for (int test = 0; test < t; test++) {
            int n = Integer.parseInt(in.readLine().trim());
            List<Integer> values = new ArrayList<>();
            StringTokenizer tokens = new StringTokenizer(in.readLine());
            long sum = 0;
            for (int i = 0; i < n; i++) {
                int x = Integer.parseInt(tokens.nextToken());
                values.add(x);
                sum += x;
            }
            values.sort(null);
            out.println(values.getFirst() + " " + values.getLast() + " " + sum);
        }
        out.flush();
    }
}

The session · release_session.py

from session import run

# The same tasks compiled for older Java releases with javac --release, the way a judge on that JDK would see them.
run("""
java Practice.java < sample.txt
RELEASE=21 sh submit.sh Practice.java sample.txt
RELEASE=17 sh submit.sh newer/Main.java sample.txt
RELEASE=21 sh submit.sh newer/Main.java sample.txt
""", expect_failure=(
    "RELEASE=21 sh submit.sh Practice.java sample.txt",
    "RELEASE=17 sh submit.sh newer/Main.java sample.txt",
))

Output

# JDK in use: openjdk version "25.0.4.1" LTS
$ java Practice.java < sample.txt
-2 19 29
1000000000 1000000000 1000000000
1000000000 1000000000 5000000000
$ RELEASE=21 sh submit.sh Practice.java sample.txt
Main.java:3: error: implicitly declared classes are not supported in -source 21
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
^
  (use -source 25 or higher to enable implicitly declared classes)
1 error
[exit status 1]
$ RELEASE=17 sh submit.sh newer/Main.java sample.txt
Main.java:27: error: cannot find symbol
            out.println(values.getFirst() + " " + values.getLast() + " " + sum);
                              ^
  symbol:   method getFirst()
  location: variable values of type List<Integer>
Main.java:27: error: cannot find symbol
            out.println(values.getFirst() + " " + values.getLast() + " " + sum);
                                                        ^
  symbol:   method getLast()
  location: variable values of type List<Integer>
2 errors
[exit status 1]
$ RELEASE=21 sh submit.sh newer/Main.java sample.txt
-2 19 29
1000000000 1000000000 1000000000
1000000000 1000000000 5000000000

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 release_session.py

On JDK 25, java Practice.java ran the compact version and printed the right answers. Compiled for release 21, the same file failed at its very first declaration, the field in, because a file without a class around its members did not exist in Java 21. The classic program in newer/Main.java compiled for release 21 and printed the same answers, but compiled for release 17 it failed twice, at getFirst() and at getLast(), which Java 17’s List does not have. When a platform documents only “Java 17”, compile with --release 17 before you submit.

The compile errors judges report most, reproduced

This session makes three copies of the working template, each with one change, and sends each to the local judge:

A class name, a package line and a missing import Python · errors_session.py
from session import run

# Three copies of the working template, each with one change that judges punish: another class name, a package
# line and a missing import.
run("""
sed 's/^public class Main/public class Solution/' Main.java > Solution.java
sh submit.sh Solution.java sample.txt
(echo 'package practice;'; echo; cat Main.java) > WithPackage.java
sh submit.sh WithPackage.java sample.txt
sed '/^import java.io.PrintWriter;/d' Main.java > NoImport.java
sh submit.sh NoImport.java sample.txt
""", expect_failure=(
    "sh submit.sh Solution.java sample.txt",
    "sh submit.sh WithPackage.java sample.txt",
    "sh submit.sh NoImport.java sample.txt",
))

Output

# JDK in use: openjdk version "25.0.4.1" LTS
$ sed 's/^public class Main/public class Solution/' Main.java > Solution.java
$ sh submit.sh Solution.java sample.txt
Main.java:9: error: class Solution is public, should be declared in a file named Solution.java
public class Solution {
       ^
1 error
[exit status 1]
$ (echo 'package practice;'; echo; cat Main.java) > WithPackage.java
$ sh submit.sh WithPackage.java sample.txt
Error: Could not find or load main class Main
Caused by: java.lang.ClassNotFoundException: Main
[exit status 1]
$ sed '/^import java.io.PrintWriter;/d' Main.java > NoImport.java
$ sh submit.sh NoImport.java sample.txt
Main.java:10: error: cannot find symbol
    static final PrintWriter out = new PrintWriter(System.out);
                 ^
  symbol:   class PrintWriter
  location: class Main
Main.java:10: error: cannot find symbol
    static final PrintWriter out = new PrintWriter(System.out);
                                       ^
  symbol:   class PrintWriter
  location: class Main
2 errors
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 errors_session.py

  • class Solution is public, should be declared in a file named Solution.java. The judge stored the code as Main.java, and the Java Language Specification allows javac to require that a public class sits in a file of its own name, which it does. Code pasted from a platform whose template names its class Solution fails this way. Rename the class to Main.
  • Could not find or load main class Main. The copy with package practice; compiled without complaint, but its full name is now practice.Main, and with -d . the class file went to practice/Main.class. The judge starts class Main, which does not exist. Delete the package line, which an IDE often adds by itself.
  • cannot find symbol for PrintWriter. Without its import, javac knows neither the type of out nor its constructor, so it reports both places. An IDE adds imports as you type; a judge’s editor does not. Keep the template’s imports, or write import java.io.*; and import java.util.*;, which bring in every public class of both packages.

Together with the runtime error of the short input above, these are the failures that have nothing to do with the algorithm, and every one of them shows up in seconds on your own computer.

Static state survives between test cases

A judge starts a new JVM for each test file, but one test file often holds many test cases, and a static field keeps its value from one test case to the next. This program counts the different values of each test case with a static array seen:

Distinct.java Java · Distinct.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

// For each test case (n, then n values from 1 to 1,000,000), print how many different values it has.
// The array seen is static, so it lives for the whole run, across all test cases.
// java Distinct.java runs it as first written; java Distinct.java reset clears what each test case marked.
public class Distinct {
    static final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static final PrintWriter out = new PrintWriter(System.out);
    static StringTokenizer tokens = new StringTokenizer("");
    static final boolean[] seen = new boolean[1_000_001];
    static boolean reset;

    public static void main(String[] args) throws IOException {
        reset = args.length > 0 && args[0].equals("reset");
        int t = nextInt();
        for (int test = 1; test <= t; test++) solve();
        out.flush();
    }

    static void solve() throws IOException {
        int n = nextInt();
        int[] values = new int[n];
        int distinct = 0;
        for (int i = 0; i < n; i++) {
            values[i] = nextInt();
            if (!seen[values[i]]) {
                seen[values[i]] = true;
                distinct++;
            }
        }
        out.println(distinct);
        if (reset) {
            for (int v : values) seen[v] = false; // undo only what this test case marked: O(n), not O(1,000,000)
        }
    }

    static int nextInt() throws IOException {
        while (!tokens.hasMoreTokens()) tokens = new StringTokenizer(in.readLine());
        return Integer.parseInt(tokens.nextToken());
    }
}
Three test cases, without and with the reset Python · distinct_session.py
from session import run

# Three test cases in one input, run with the static array as first written and with the reset.
run("""
cat cases.txt
java Distinct.java < cases.txt
java Distinct.java reset < cases.txt
""")

Output

# JDK in use: openjdk version "25.0.4.1" LTS
$ cat cases.txt
3
3
5 1 5
4
1 2 5 2
2
7 7
$ java Distinct.java < cases.txt
2
1
1
$ java Distinct.java reset < cases.txt
2
3
1

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 distinct_session.py

The first test case, 5 1 5, has 2 different values, and the program said 2. The second, 1 2 5 2, has 3, but the program said 1: seen[1] and seen[5] were still true from the first test case, so only the 2 counted as new. Run with reset, the program unmarks the values each test case marked, and all three answers are right.

Clearing the whole array after every test case, with Arrays.fill, would be correct too, but its cost is the array’s length times the number of test cases. Statements often allow up to 100,000 test cases in one file, as long as their total size stays small. ResetCost.java runs the same task on 100,000 test cases of four values each, and resets its static array of 1,000,001 counters both ways:

ResetCost.java Java · ResetCost.java
import java.lang.management.ManagementFactory;
import java.util.Arrays;

// The task of Distinct.java on 100,000 small test cases of 4 values each, with two ways to reset a static array of
// 1,000,001 counters between the test cases. Both give the same total; the CPU time of each way is printed.
public class ResetCost {
    static final int[] count = new int[1_000_001];

    public static void main(String[] args) {
        var os = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        for (String way : new String[] {"Arrays.fill after each test case", "undo only what each test case marked"}) {
            boolean fill = way.startsWith("Arrays");
            long start = os.getProcessCpuTime();
            long total = 0;
            int[] values = new int[4];
            long seed = 2026;
            for (int test = 0; test < 100_000; test++) {
                for (int i = 0; i < values.length; i++) {
                    seed = seed * 6364136223846793005L + 1442695040888963407L; // a fixed sequence of values
                    values[i] = 1 + (int) ((seed >>> 33) % 1_000_000);
                }
                for (int v : values) if (count[v]++ == 0) total++;
                if (fill) Arrays.fill(count, 0);
                else for (int v : values) count[v] = 0;
            }
            long ms = (os.getProcessCpuTime() - start) / 1_000_000;
            System.out.println(way + ": total " + total + ", " + ms + " ms of CPU time");
        }
    }
}
Two ways to reset, timed Python · reset_session.py
from session import run

# The task of Distinct.java on 100,000 small test cases, with the two ways to reset the static array.
run("""
java ResetCost.java
""")

Output

# JDK in use: openjdk version "25.0.4.1" LTS
$ java ResetCost.java
Arrays.fill after each test case: total 400000, 2961 ms of CPU time
undo only what each test case marked: total 400000, 14 ms of CPU time

This output changes from run to run: CPU times depend on the computer and on what else it was doing; the totals are the same in every run.

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 reset_session.py

Both ways counted the same 400,000 values. Clearing a million counters 100,000 times took about 3 seconds of CPU time on this track’s build machine, an Apple M5 Pro, which is more than many whole time limits, while undoing only what each test case marked took well under a tenth of a second. Undo only what a test case changed, or create the arrays inside solve, sized for that test case. Counters, lists and maps kept in static fields need the same care.

Practise the way the judge runs

Keep each sample input and its expected output in files, and check every change with the command the template session used: sh submit.sh Main.java sample.txt | diff expected.txt - && echo PASS. On Windows, run it in Git Bash or WSL, or type the script’s commands yourself. When the outputs differ in a way you cannot see, such as a space at the end of a line, paste both into a diff tool that marks each changed character.

Text Diff Paste the expected output and your program's output to see which characters differ, as a judge's comparison sees them.

Test a large input too. A judge’s biggest test can be a thousand times longer than the samples, and that is where an int overflows, a slow reader runs out of time and a forgotten reset of static state finally shows.

Online assessments

If a campus placement test runs on a hosted coding platform, its Java may be older than yours: HackerRank, for example, lists versions from Java 7 to Java 21. Open the test’s instructions or practice round before the day, note the newest Java it offers, and compile your template with javac --release for that version.

Exercise: make three solutions judge-ready

The folder exercise holds three working solutions, each written for another setup: one in an IDE project with a package, two pasted from a platform whose template names the class Solution, and three as a compact source file for JDK 25. Make all three acceptable to a judge that runs Java 21 and compiles Main.java: a public class Main, no package line, the classic main, and input and output in the style of the template. What each program prints must stay exactly the same.

The three solutions

one: marks of 40 or more · exercise/one/Main.java

package rounds;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

// Written in an IDE project: count the marks of 40 or more. Input: n, then n marks from 0 to 100.
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(in.readLine().trim());
        StringTokenizer marks = new StringTokenizer(in.readLine());
        int passed = 0;
        for (int i = 0; i < n; i++) {
            if (Integer.parseInt(marks.nextToken()) >= 40) passed++;
        }
        System.out.println(passed);
    }
}

two: the longest word · exercise/two/Main.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// Pasted from a platform whose template names the class Solution: print the longest word of one line
// (the first of them when several are equally long).
public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String longest = "";
        for (String word : in.readLine().trim().split("\\s+")) {
            if (word.length() > longest.length()) longest = word;
        }
        System.out.println(longest);
    }
}

three: sums of pairs · exercise/three/Main.java

// A compact source file for JDK 25: t lines follow, each with two whole numbers from -10^18 to 10^18;
// print the sum of each pair.
void main() {
    int t = Integer.parseInt(IO.readln().strip());
    for (int i = 0; i < t; i++) {
        String[] pair = IO.readln().strip().split(" ");
        IO.println(Long.parseLong(pair[0]) + Long.parseLong(pair[1]));
    }
}

Each sample test sends one solution to the local judge for release 21, runs it on its sample input and compares the output with diff. As given, all three fail, each in its own way:

The sample tests before you start Python · exercise_session.py
from session import run

# The exercise's sample tests: each solution goes to the local judge as a Java 21 judge would compile it, and its
# output is compared with the expected output. As given, all three fail.
run("""
RELEASE=21 sh submit.sh exercise/one/Main.java exercise/one/input.txt > got.txt; diff exercise/one/expected.txt got.txt && echo PASS
RELEASE=21 sh submit.sh exercise/two/Main.java exercise/two/input.txt > got.txt; diff exercise/two/expected.txt got.txt && echo PASS
RELEASE=21 sh submit.sh exercise/three/Main.java exercise/three/input.txt > got.txt; diff exercise/three/expected.txt got.txt && echo PASS
""", expect_failure=(
    "RELEASE=21 sh submit.sh exercise/one/Main.java exercise/one/input.txt > got.txt; diff exercise/one/expected.txt got.txt && echo PASS",
    "RELEASE=21 sh submit.sh exercise/two/Main.java exercise/two/input.txt > got.txt; diff exercise/two/expected.txt got.txt && echo PASS",
    "RELEASE=21 sh submit.sh exercise/three/Main.java exercise/three/input.txt > got.txt; diff exercise/three/expected.txt got.txt && echo PASS",
))

Output

# JDK in use: openjdk version "25.0.4.1" LTS
$ RELEASE=21 sh submit.sh exercise/one/Main.java exercise/one/input.txt > got.txt; diff exercise/one/expected.txt got.txt && echo PASS
Error: Could not find or load main class Main
Caused by: java.lang.ClassNotFoundException: Main
1d0
< 3
[exit status 1]
$ RELEASE=21 sh submit.sh exercise/two/Main.java exercise/two/input.txt > got.txt; diff exercise/two/expected.txt got.txt && echo PASS
Main.java:7: error: class Solution is public, should be declared in a file named Solution.java
public class Solution {
       ^
1 error
1d0
< submission
[exit status 1]
$ RELEASE=21 sh submit.sh exercise/three/Main.java exercise/three/input.txt > got.txt; diff exercise/three/expected.txt got.txt && echo PASS
Main.java:3: error: implicitly declared classes are not supported in -source 21
void main() {
^
  (use -source 25 or higher to enable implicitly declared classes)
1 error
1,3d0
< 3
< 0
< 1999999999999999999
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 exercise_session.py

First hint: read each check’s first error line. The first solution needs one line deleted and the second one word changed. The third needs a class around its code, a classic main, and a BufferedReader and a PrintWriter in place of IO.readln and IO.println. Each check prints PASS once its solution is right.

Check yourself

5 questions about this lesson. Every answer and why it is right is on the page, behind “Show the answer”. Your score stays in this browser.

  1. Question 1 of 5 A judge stores every submission as Main.java and compiles it with javac. Which declaration compiles there?

    Choose one answer.

    Show the answer to question 1

    Answer: public class Main

    javac requires a public class to sit in a file of its own name, and names are case-sensitive, so only Main fits Main.java. The session showed the error for Solution: class Solution is public, should be declared in a file named Solution.java.

  2. Question 2 of 5 Your submission starts with package practice;. It compiles on the judge, which then runs java Main. What happens?

    Choose one answer.

    Show the answer to question 2

    Answer: The JVM cannot find a class called Main, because its full name is now practice.Main

    A package line changes the class's full name, and javac -d writes the class file to a matching folder, practice/Main.class. The local judge printed Could not find or load main class Main, and a judge reports the same failure as a runtime error. Delete the package line before submitting.

  3. Question 3 of 5 You have only JDK 25. Which command shows whether your solution compiles on a judge that runs Java 17?

    Choose one answer.

    Show the answer to question 3

    Answer: javac --release 17 Main.java

    --release 17 compiles by the language rules of Java 17 and against the Java 17 API, so it reports newer syntax and newer library methods. In the lesson it caught getFirst() and getLast(), which Java 17's List does not have. A plain javac of JDK 25 accepts them, and the judge would not.

  4. Question 4 of 5 A solution resets a static array of 1,000,001 counters with Arrays.fill after each test case, and the input holds 100,000 small test cases. What did the lesson measure?

    Choose one answer.

    Show the answer to question 4

    Answer: About 3 seconds of CPU time for the resets alone, against well under a tenth of a second for undoing only the marked entries

    Arrays.fill writes every one of the 1,000,001 entries, 100,000 times. ResetCost.java measured about 3 seconds of CPU time for that, while undoing only the four entries each test case marked took well under a tenth of a second. The JVM resets nothing between the test cases of one input; a new JVM starts only for each test file.

  5. Question 5 of 5 The template prints three short lines, but out.flush() was deleted. What does the judge receive?

    Choose one answer.

    Show the answer to question 5

    Answer: Nothing at all, so the verdict is wrong answer

    A PrintWriter keeps its text in a buffer until it is flushed, and nothing flushes a writer you created when the program ends. A short output is still entirely in the buffer, so nothing arrives; a long output arrives cut off at a buffer boundary.

Interview questions

Fresher · Why do online judges usually want a class named Main and no package declaration?

A judge compiles your file and then starts a class by name, so it must know the name and where the class file lands. Many judges store the submission under a fixed file name such as Main.java, and javac requires a public class to sit in a file of its own name, so any other public class name fails to compile. A package line changes the class’s full name, to practice.Main for example, and javac -d writes the class file to a matching folder, so a judge that runs java Main finds no such class. Judges that look for the class holding main, as Kattis does, are more forgiving, but a public Main without a package works on all of them. That is why judge templates start that way.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    Your Java solution passes every sample, but on the judge's file with 100,000 test cases it gives wrong answers from the second case on. After you add Arrays.fill to reset a static array of a million entries after each case, it gets time limit exceeded instead. Explain both verdicts and the fix.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    A platform documents only "Java 17", and your template and helpers were written on JDK 25. How do you make sure they compile and behave the same there before the test, and which of your Java 21 and later habits are the likely failures?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A judge compiles once with its own JDK, runs your class once per test file with its own flags, and compares the output; each step has a verdict of its own.
  • Submit a public class Main in Main.java, with no package line and the classic public static void main(String[] args).
  • Read the platform’s Java page first: the four platforms above document versions from Java 7 to Java 25, and only JDK 25 compiles compact source files.
  • javac --release N shows on your own computer what a Java N judge would report, for syntax and for library methods alike.
  • Read through one BufferedReader cut by a StringTokenizer, print through one PrintWriter, and flush it once at the end.
  • static fields keep their values across the test cases of one input: undo what each test case changed instead of clearing whole arrays.
  • Check every change against the sample files with diff, and try a large input before you submit.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.