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.
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.
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.
- Your submission, Main.java.
- "1. Compile once", with the javac of the judge's own JDK. If javac fails, the verdict is compilation error.
- 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.
- 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.
- Compile once. The judge stores your code, often under a file name it chooses, and compiles it with the
javacof its own JDK. Ifjavacfails, the verdict is compilation error, usually shown with the first error message. - Run once per test file. The judge starts
javaonce 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-Xmsand-Xmxand 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. - 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.
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
packageline, andpublic class MaininMain.java. Some judges store your file asMain.javawhatever you called it, and others keep your name and look for the class that holdsmain. A publicMainwithout 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. DeclaringIOExceptionkeepsreadLineshort, and on a judge an input error is a runtime error whatever you write. - One
BufferedReader, read throughnext().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.nextIntandnextLongconvert each token withInteger.parseIntandLong.parseLong. - One
PrintWritercalledout, flushed once at the end ofmain. It collects the text in memory, whereSystem.out.printlnhands 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. longfor the sum. Five values of 10^9 already add up to 5 × 10^9, more than the 2,147,483,647 that anintcan hold.- A loop over the test cases in
main. Most statements give the number of test cases first, andsolvehandles 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:
#!/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" 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
javacandjava25.0.3, so compact source files compile there, and it runs the class that holds yourmain. - The ICPC World Finals list OpenJDK 21.0.4: only the classic
mainworks, and there is noIOclass. - AtCoder lists Java24 (OpenJDK 24.0.2) and compiles
Main.java, so the public class must beMain; 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:
// 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());
} 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:
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 asMain.java, and the Java Language Specification allowsjavacto 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 classSolutionfails this way. Rename the class toMain.Could not find or load main class Main. The copy withpackage practice;compiled without complaint, but its full name is nowpractice.Main, and with-d .the class file went topractice/Main.class. The judge starts classMain, which does not exist. Delete thepackageline, which an IDE often adds by itself.cannot find symbolforPrintWriter. Without itsimport,javacknows neither the type ofoutnor 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 writeimport java.io.*;andimport 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:
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());
}
} 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:
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");
}
}
} 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.
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.
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:
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.
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.
-
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.
-
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?
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 MaininMain.java, with nopackageline and the classicpublic 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 Nshows on your own computer what a Java N judge would report, for syntax and for library methods alike.- Read through one
BufferedReadercut by aStringTokenizer, print through onePrintWriter, and flush it once at the end. staticfields 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
- Java SE 25 API: java.io.BufferedReader (Oracle)
- Java SE 25 API: java.io.PrintWriter (Oracle)
- Java SE 25 API: java.util.StringTokenizer (Oracle)
- The Java Language Specification, Java SE 25: 7.6, Top Level Class and Interface Declarations (Oracle)
- The javac Command (JDK 25 tool reference) (Oracle)
- JEP 512: Compact Source Files and Instance Main Methods (OpenJDK)
- JEP 431: Sequenced Collections (OpenJDK)
- Java (Kattis language reference) (Kattis)
- ICPC World Finals Programming Environment (ICPC Foundation)
- AtCoder Rules (language list) (AtCoder)
- HackerRank Execution Environment (HackerRank)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress