Java examples become useful when a learner can type the source, compile it, predict the output and explain why it appears. These five small programs demonstrate output, input, decisions, arrays and maps. Run each one separately in a file named Main.java; a file containing public class Main must use the same base name. The examples work with a modern supported JDK and require no third-party dependencies.
Prepare a repeatable compile-and-run workflow
Install a current supported JDK, open a terminal in the folder containing Main.java, and check both java -version and javac -version. The first command reports the runtime; the second establishes that the compiler is available. Running java Main looks for the compiled class. If Java reports that it cannot find the main class, check the working directory, file spelling and compilation errors before changing code.
javac Main.java
java Main
Compile a program after every edit. A program may run successfully from an old Main.class even when the current source contains a typo, so do not ignore compiler diagnostics. Use one code example at a time and compare its actual output with the example shown below.
Example 1: print a message and a calculated value
public class Main {
public static void main(String[] args) {
int price = 12;
int quantity = 3;
System.out.println("Order total: " + price * quantity);
}
}
Expected output: Order total: 36. The multiplication happens before string concatenation, so Java computes the total and then appends it to the message. For financial calculations involving fractional currency values, do not automatically switch to double; consider BigDecimal with explicit rounding rules.
Example 2: read a number and classify it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("Enter an integer: ");
int value = input.nextInt();
if (value > 0) {
System.out.println("Positive");
} else if (value < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
}
}
}
When the user enters -4, the program prints Negative. When the user enters 0, it prints Zero. nextInt() throws an input-mismatch exception for non-integer text; production input handling should validate and recover instead of displaying a stack trace. The try block closes the scanner when it is no longer used.
Example 3: count even numbers with a loop
public class Main {
public static void main(String[] args) {
int count = 0;
for (int n = 1; n <= 10; n++) {
if (n % 2 == 0) {
count++;
}
}
System.out.println("Even numbers: " + count);
}
}
Expected output: Even numbers: 5. The remainder operator % makes parity visible: even integers have a remainder of zero when divided by two. A frequent beginner error is using n < 10 when the requirement includes 10; test the boundaries rather than only the middle of a loop.
Example 4: find the largest value in an array
public class Main {
public static void main(String[] args) {
int[] scores = {8, 12, 5, 17, 9};
int largest = scores[0];
for (int score : scores) {
if (score > largest) {
largest = score;
}
}
System.out.println("Largest: " + largest);
}
}
Expected output: Largest: 17. Initializing from the first element handles all-negative arrays correctly, unlike initializing a maximum to zero. It also assumes the array is nonempty. For reusable code, reject empty input or return an optional result explicitly rather than accessing index zero without checking.
Example 5: count repeated words with a map
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String[] words = {"java", "python", "java", "go", "java"};
Map<String, Integer> counts = new HashMap<>();
for (String word : words) {
counts.merge(word, 1, Integer::sum);
}
System.out.println("java appears: " + counts.get("java"));
}
}
Expected output: java appears: 3. A map associates each distinct word with a count, and merge increments its value. A HashMap does not promise iteration order, so avoid comparing a printed whole-map representation as though the key order were guaranteed.
Practice problems and debugging
- Change the loop bound to 9 and predict the even-number count before running the code.
- Replace the array with only negative numbers and verify the maximum still works.
- Add a new word to the map and display its count.
- Enter nonnumeric input in the scanner example; note which exception occurs and design a user-friendly retry.
The goal is not to memorize console screenshots but to reason about inputs, state changes, and expected outputs. If classes and object construction still feel unfamiliar, the existing explanation of Java classes and objects provides useful conceptual context. For language changes and current JDK tooling, refer to the official Dev.java learning material rather than relying on outdated applet-era examples.