Java Examples Library with Explained Programs

This Java examples library groups short, complete programs by the skill they demonstrate.

Lesson 116 of 127Beginner13 min read

This Java examples library groups short, complete programs by the skill they demonstrate. Each program has a defined input, visible output, and an explanation of the steps producing that output. Use the examples as starting points for variations, not as formulas to paste into an unrelated project. The first solves an arithmetic-and-remainder problem, the second processes a sequence while preserving its order, and the third models valid state in a small object. All three use Java 17 without external libraries.

Example one: pack items into trays

A bakery needs trays holding six pastries each. Dividing the item count by six gives complete trays, and a nonzero remainder requires another tray. Zero items need no trays; negative counts are invalid. The program below uses division and a remainder check rather than rounding a floating-point approximation. Its contract returns tray count, not spare capacity. Keeping those results distinct matters when a caller later asks how many positions remain empty in the final tray.

Read the arithmetic before changing it

For fourteen items, integer division produces two complete trays and the remainder is two. One additional tray gives three. For twelve items, the remainder is zero, so two trays suffice. An expression adding five before division can also round upward for many values, but that addition can overflow at very large int inputs. The remainder-based approach avoids that extra addition and states the packaging rule directly.

Example two: retain first appearances

A list can contain repeated visitor names, but a welcome report should display each equal name only at its first appearance. LinkedHashSet combines uniqueness with insertion order for this task. Converting the input into that set retains Asha, Ben, and Cara in first-seen order. HashSet would satisfy uniqueness without promising the same displayed order. Treat the ordering requirement as part of the result, not an accidental detail of one run.

Specify the normalization policy

The unique-name example uses exact String equality. Asha and ASHA are therefore different values. A real registration report may trim whitespace or compare normalized identifiers, but it should not silently merge different people sharing a display name. Use stable IDs when identity matters. The small example teaches collection behavior; its meaning does not authorize a broader identity policy. Test variations under the rule you actually choose.

Example three: encapsulate a counter limit

A meeting-room counter stores a current visitor count and a capacity. Its enter method returns false when no space remains and leaves the count unchanged. The state is private so a caller cannot simply assign an impossible number. Constructor validation rejects negative capacity. The prototype is local and single-threaded; a shared concurrent room service would need coordination and a stronger identity model for entry and exit events.

Turn an example into a useful experiment

First predict the supplied output, then change one input or contract and explain the new outcome. For trays, test zero, an exact multiple, and one beyond a multiple. For first appearances, test duplicates at the end and an empty list. For the room, test capacity zero and repeated entry after full. Continue to topic exercises when you can explain these boundaries without relying on the output panel alone.

Practice tasks and checks

Generalize trays to accept a capacity and reject capacities of zero or less. Test an exact multiple and one extra item for capacities four and six. Extend the encounter report to use normalized IDs while keeping display names separate, and explain why that avoids merging people just because their names match. Add a leave method to Room that refuses to reduce visitors below zero. Test an empty room, a full room, a failed entry, and a failed exit. Keep those acceptance cases beside the source so later extensions preserve its contract. Finally, explain each output without executing the program; a correct explanation should mention the operation responsible for every displayed value.

Java Summary

  • State each example’s input and return contract before adapting it.
  • Collection order and uniqueness are separate requirements.
  • A rejected operation should preserve valid state.
  • Continue with topic exercises when these examples are clear.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Calculate tray count

Save this program as TrayExample.java. Compile it with javac TrayExample.java and run it with java TrayExample.

Expected output:

The method validates before arithmetic. Fourteen divides into two full groups with leftover items, so the conditional adds one. Twelve divides exactly and adds zero. Zero likewise has no remainder and produces zero. The return value counts containers, not items or money. If you change the tray capacity, extract it as a positive parameter and validate it before division to avoid dividing by zero.

Java
public class TrayExample {
    static int trays(int items) {
        if (items < 0) throw new IllegalArgumentException("Negative count");
        return items / 6 + (items % 6 == 0 ? 0 : 1);
    }
    public static void main(String[] args) {
        System.out.println(trays(14));
        System.out.println(trays(12));
        System.out.println(trays(0));
    }
}
Output
3
2
0
Example 2

Keep unique values in encounter order

Save this program as EncounterExample.java. Compile it with javac EncounterExample.java and run it with java EncounterExample.

Expected output:

The set processes the list in encounter order and ignores later equal names. Printing it follows LinkedHashSet's insertion order, making the three-name result deterministic. The source list still contains five entries because creating another collection does not remove its duplicates. This contrast separates an input history from a derived unique report. Adding an already present element does not normally move it to the end.

Java
import java.util.LinkedHashSet;
import java.util.List;
public class EncounterExample {
    public static void main(String[] args) {
        List<String> arrivals = List.of("Asha", "Ben", "Asha", "Cara", "Ben");
        LinkedHashSet<String> firstSeen = new LinkedHashSet<>(arrivals);
        System.out.println(firstSeen);
        System.out.println(arrivals.size());
    }
}
Output
[Asha, Ben, Cara]
5
Example 3

Reject entry when capacity is reached

Save this program as RoomExample.java. Compile it with javac RoomExample.java and run it with java RoomExample.

Expected output:

The first call sees available capacity, increments visitors, and returns true. The second sees the limit and returns false without incrementing. The final getter confirms the rejected operation did not corrupt the state. this.capacity distinguishes the field from the constructor parameter. Keeping the visitor field private makes enter the controlled mutation path, although concurrent calls would require an additional protection rule.

Java
public class RoomExample {
    static class Room {
        private final int capacity;
        private int visitors;
        Room(int capacity) {
            if (capacity < 0) throw new IllegalArgumentException("Negative capacity");
            this.capacity = capacity;
        }
        boolean enter() {
            if (visitors == capacity) return false;
            visitors++;
            return true;
        }
        int visitors() { return visitors; }
    }
    public static void main(String[] args) {
        Room room = new Room(1);
        System.out.println(room.enter());
        System.out.println(room.enter());
        System.out.println(room.visitors());
    }
}
Output
true
false
1

Java FAQ

Can I run these in the site editor?

These are Java source programs. Run them with a suitable local JDK or a Java environment you control; the site's browser runner is for its supported browser languages. Each example supplies its source filename and terminal commands.

Should examples include every production feature?

No. A focused example should make one contract visible and state its limits. Add input handling, persistence, or concurrency only when studying those responsibilities, while preserving the behavior already demonstrated.

What is the best way to learn from example programs?

Run each program as written, then predict what a small change will do before trying it. Change one input, one condition or one data structure at a time and explain any surprise. Typing an example yourself and then modifying it teaches far more than reading it.

Which Java version do these examples need?

They are written for Java 17 and run on any later version, such as Java 21 or 25. Save each program in a file named after its public class, then compile and run it with javac and java, or use source-file mode with java FileName.java.

Where can I find more Java examples?

Each topic lesson in this course includes its own worked examples, and the beginner, intermediate and advanced project lessons combine several topics. The official dev.java site also publishes tutorials with examples.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

How many six-item trays are needed for seven items?

Multiple choicemedium

Which collection preserves first-seen uniqueness here?

Java Quiz

2 questions to check what you learned.

  1. What does a rejected room entry change?

    • Nothing in visitors
    • It increases capacity
    • It resets visitors
  2. Why does arrivals still have five entries?

    • The derived set does not modify the list
    • Sets always store five values
    • The list is automatically deduplicated