Java Programming · Practice by type
Java Programming Programs for Practice with Output
Practice programs for every Java Programming topic, each with a full solution, its real output and an explanation. Try writing each one yourself first.
- 280 questions
- 28 topics
- Answers checked on a real compiler
Java Basics, Syntax and Data Types 10 questions
- Simple and compound interest calculator in Java Easy
- Celsius to Fahrenheit and Kelvin table in Java Easy
- BMI calculator with category in Java Easy
- Swap two numbers with and without a temp variable in Java Easy
- Convert seconds to days, hours, minutes and seconds in Java Easy
- Sum of digits and reverse of a number in Java Easy
- Print an ASCII table of letters and digits in Java Easy
- Electricity bill with slab rates in Java Medium
- Report the size and range of every primitive type in Java Easy
- Shopping bill with GST and discount using printf in Java Medium
Operators and Expressions 10 questions
- Leap year check with logical operators in Java Easy
- Largest and smallest of three with the ternary operator Easy
- Convert decimal to binary using bit operations in Java Medium
- Count set bits three ways in Java Medium
- Simple calculator with operators and switch in Java Easy
- Check if three sides form a triangle and classify it in Java Easy
- Swap nibbles and reverse bits of a byte in Java Hard
- Grade and result calculator with relational operators Easy
- Sum of even and odd numbers using bitwise checks in Java Easy
- Loan EMI calculator with operators and Math.pow in Java Medium
Control Flow Statements 10 questions
- Print prime numbers in a range in Java Easy
- Fibonacci series up to N terms in Java Easy
- Find Armstrong numbers in Java Medium
- GCD and LCM using Euclid's algorithm in Java Easy
- Menu-driven program with do-while and switch in Java Medium
- Number pyramid and diamond patterns in Java Medium
- Perfect, abundant and deficient numbers in Java Medium
- Number guessing game with a binary-search strategy in Java Medium
- Multiplication table grid with nested for loops in Java Easy
- Strong numbers and palindromic primes in Java Medium
Arrays in Java 10 questions
- Remove duplicates from a sorted array in place in Java Easy
- Two-sum: find two numbers that add up to a target in Java Medium
- Merge two sorted arrays into one in Java Easy
- Move all zeros to the end keeping order in Java Easy
- Matrix multiplication with 2D arrays in Java Medium
- Find the missing number from 1 to N in Java Easy
- Find leaders in an array in Java Medium
- Print a matrix in spiral order in Java Hard
- Count occurrences and find the most frequent element in Java Easy
- Maximum subarray sum with its start and end (Kadane) in Java Hard
Strings and StringBuilder 10 questions
- Character frequency in insertion order in Java Easy
- First non-repeating character in a string in Java Medium
- Compress a string with character counts in Java Medium
- Convert a sentence to title case in Java Easy
- Toggle case and count letter types in Java Easy
- Reverse each word but keep the word order in Java Easy
- Longest common prefix of an array of strings in Java Medium
- Count words, sentences and characters in a paragraph in Java Medium
- Remove duplicate characters from a string in Java Easy
- Caesar cipher encryption and decryption in Java Medium
Methods and Recursion 10 questions
- Recursive binary search in Java Medium
- All permutations of a string with recursion in Java Hard
- Generate all subsets of a set recursively in Java Hard
- Convert a number to words with helper methods in Java Medium
- Merge sort with recursion in Java Hard
- Count islands in a grid with recursive flood fill in Java Hard
- Temperature utility class with overloaded methods in Java Easy
- Digital root and persistence with recursion in Java Easy
- Pascal's triangle with a recursive method in Java Medium
- Validate user registration with small methods in Java Medium
Classes and Objects 10 questions
- Student report card using a class in Java Easy
- Shopping cart with Product and CartItem objects in Java Medium
- Rectangle and Circle classes with area and perimeter in Java Easy
- Movie seat booking with a Theatre class in Java Medium
- Inventory manager with low-stock alerts in Java Medium
- Singly linked list built from Node objects in Java Hard
- To-do list manager with Task objects in Java Easy
- Bank transfers between Account objects in Java Medium
- Employee payroll and department summary in Java Medium
- Parking lot with Vehicle objects and fees in Java Hard
Constructors and the this Keyword 10 questions
- Rectangle with overloaded constructors in Java Easy
- A validated Date class with leap years in Java Medium
- Deep copy constructor for a class with a list in Java Medium
- Fraction class that normalises in its constructor in Java Medium
- Pizza order using the builder pattern in Java Medium
- Thread-safe singleton with a holder class in Java Hard
- Employee objects with auto-generated IDs in Java Easy
- Temperature with named static factory methods in Java Medium
- Matrix class with several constructors in Java Hard
- Bank account with opening-balance rules in Java Medium
Static and Final Keywords 10 questions
- Count objects created with a static counter in Java Easy
- Unit converter utility class with constants in Java Easy
- Immutable Money class with currency checks in Java Medium
- Application config loaded in a static block in Java Medium
- Singleton logger using an enum in Java Medium
- Static math helpers: GCD, LCM, primes and factorial in Java Easy
- A final template method in a report generator in Java Hard
- Caching static factory for colour objects in Java Medium
- Thread-safe static counters with AtomicInteger in Java Hard
- Immutable 2D vector class with static constants in Java Medium
Access Modifiers and Packages 10 questions
- Student marks with private fields and validation in Java Easy
- User password with a private hash and policy in Java Medium
- Discount rules with protected hook methods in Java Medium
- Inventory with private map and read-only views in Java Medium
- Rate limiter with private state in Java Hard
- Library members with access levels in Java Easy
- Immutable API response with private constructor in Java Medium
- Game characters with protected stats in Java Medium
- Fully qualified names instead of imports in Java Easy
- Feature flags with private storage in Java Hard
Encapsulation 10 questions
- Encapsulated bank account with transaction log in Java Easy
- Shopping cart that hides its items in Java Medium
- Employee salary with controlled raises in Java Easy
- Library card with fines and borrowing limits in Java Medium
- Temperature log with private readings and statistics in Java Medium
- Voting machine that prevents double voting in Java Medium
- Immutable student record with defensive copies in Java Hard
- Digital wallet with PIN and transfer limits in Java Medium
- Parking meter with private time and coins in Java Easy
- Smart bulb with encapsulated state and brightness in Java Easy
Inheritance 10 questions
- Savings and current accounts with inheritance in Java Easy
- Shape hierarchy with area and perimeter in Java Easy
- Multilevel inheritance: Vehicle, Car and ElectricCar in Java Medium
- Library items: books, DVDs and magazines in Java Medium
- Notification channels sharing a send template in Java Medium
- Hierarchical inheritance: employee bonuses in Java Easy
- Composition: building a computer from parts in Java Medium
- Zoo feeding schedule with instanceof checks in Java Medium
- Game characters with shared base stats in Java Hard
- Person, Student and Teacher with super calls in Java Easy
Polymorphism and Method Overriding 10 questions
- Payment gateway with overridden fee rules in Java Easy
- Overloaded area and volume calculator in Java Easy
- Food delivery fees with polymorphic partners in Java Medium
- Sort mixed shapes by area using polymorphism in Java Easy
- Multi-channel notifications through one interface in Java Medium
- Salaried, hourly and commission pay in Java Medium
- Evaluate an expression tree with polymorphism in Java Hard
- Logger hierarchy overriding format and filter in Java Medium
- Invoice line totals with a sealed type and switch in Java Hard
- Rock-paper-scissors strategy players in Java Medium
Abstraction 10 questions
- Abstract Shape with circle, square and triangle in Java Easy
- Vehicle rental pricing with an abstract base in Java Medium
- Document parsers sharing a parse pipeline in Java Medium
- Abstract Employee with permanent and contract staff in Java Easy
- Abstract board game with a fixed play loop in Java Hard
- Bank accounts with abstract interest rules in Java Medium
- Report generator with abstract data source in Java Medium
- Cache with abstract eviction policy in Java Hard
- Exam grading with abstract marking schemes in Java Easy
- Smart home devices with an abstract base in Java Medium
Interfaces 10 questions
- Payment gateways behind one interface in Java Easy
- Sort products several ways with Comparator in Java Easy
- Event listeners with a functional interface in Java Medium
- Discount strategies chosen at run time in Java Medium
- Shapes that are both Comparable and Drawable in Java Medium
- A Range class that implements Iterable in Java Medium
- Text-processing plugins through an interface in Java Medium
- Repository interface with two implementations in Java Hard
- Smart devices with segregated interfaces in Java Easy
- Form validators combined with default methods in Java Hard
Object Class and Wrapper Classes 10 questions
- Remove duplicate employees with equals and hashCode in Java Easy
- Parse a mixed list of numbers safely in Java Easy
- Number base converter using wrapper methods in Java Easy
- Text statistics with the Character class in Java Easy
- Deep copy of an order with a copy constructor in Java Medium
- GST invoice with exact BigDecimal arithmetic in Java Medium
- Grid points as HashMap keys in Java Medium
- Null-safe totals over Integer data in Java Medium
- Big factorials and digit sums with BigInteger in Java Medium
- Check the equals and hashCode contract in Java Hard
Exception Handling 10 questions
- Safe calculator that handles bad input in Java Easy
- CSV import with a per-line error report in Java Medium
- Ticket booking with custom checked exceptions in Java Medium
- Read records with try-with-resources in Java Medium
- Sign-up form validation with exceptions in Java Easy
- Bank transfer with rollback on failure in Java Hard
- Ask again until the input is a valid number in Java Easy
- Translate low-level errors at a service layer in Java Hard
- Checking internal invariants with assertions in Java Medium
- Count and group exceptions from many tasks in Java Medium
Collections Framework 10 questions
- Top K highest scores with a PriorityQueue in Java Medium
- Undo and redo for a text editor with two stacks in Java Medium
- Bank counter queue simulation in Java Medium
- Sliding window maximum with a deque in Java Hard
- Task scheduler by priority and deadline in Java Medium
- Merge two sorted lists without duplicates in Java Easy
- Recently viewed products list (max 5, no repeats) in Java Medium
- Sort an inventory list several ways in Java Easy
- Josephus elimination game with a queue in Java Medium
- Students common to courses using set operations in Java Easy
HashMap and TreeMap 10 questions
- Word frequency with the top three words in Java Easy
- First non-repeating character with LinkedHashMap in Java Easy
- Group anagrams using sorted keys in Java Medium
- Grade and scholarship bands with TreeMap in Java Medium
- LRU cache with hit and miss statistics in Java Hard
- Phone book with prefix search using TreeMap in Java Medium
- Top visitors from an access log in Java Medium
- Merge warehouse stock maps in Java Easy
- Count subarrays with a given sum using prefix sums in Java Hard
- Event timeline queries with TreeMap in Java Medium
Generics 10 questions
- Generic singly linked list with iteration in Java Medium
- Generic min, max and clamp utilities in Java Easy
- Generic key-value cache with a loader in Java Medium
- Type-safe event bus with Class keys in Java Hard
- Generic binary search with a comparator in Java Medium
- Zip, unzip and group with a generic Pair in Java Medium
- Generic bounded circular queue in Java Medium
- Generic binary search tree in Java Hard
- Generic validation rules that collect errors in Java Medium
- Generic numeric operations with a strategy in Java Hard
Lambda Expressions 10 questions
- Write your own filter and map with lambdas in Java Easy
- Pluggable discount rules with lambdas in Java Medium
- Retry an operation using a Supplier lambda in Java Medium
- Button click listeners with Consumer lambdas in Java Easy
- Password validation with a list of named predicates in Java Medium
- Text cleaning pipeline with composed functions in Java Medium
- Sort employees in several orders with lambdas in Java Easy
- Memoise any function with a lambda wrapper in Java Hard
- Traffic light state machine with lambda transitions in Java Medium
- Run Callable lambdas and collect results in Java Medium
Streams API 10 questions
- Student result analysis with streams in Java Easy
- Top words in a text with groupingBy in Java Medium
- Department salary report with collectors in Java Medium
- Web server log analysis with streams in Java Medium
- Prime numbers and twin primes with IntStream in Java Medium
- Parse CSV inventory and report with streams in Java Medium
- Flatten customer orders and find best sellers in Java Hard
- Temperature readings: partition, stats and streaks in Java Medium
- Price range and spread with Collectors.teeing in Java Hard
- Group anagrams with a single stream in Java Medium
Records, Enums and Sealed Classes 10 questions
- Vending machine with an enum of products in Java Easy
- Invoice built from validated records in Java Medium
- Payment results as a sealed hierarchy in Java Medium
- Pizza pricing with enums and a record in Java Easy
- Traffic violations and fines with an enum in Java Medium
- A tiny JSON model with sealed records in Java Hard
- Chess piece moves with a sealed interface in Java Hard
- Leave request workflow with enums and records in Java Medium
- Shipping charges by zone and parcel type in Java Medium
- A deck of cards with Suit and Rank enums in Java Easy
File Handling, IO and NIO 10 questions
- Word, line and character count of a file in Java Easy
- Read a CSV file and write a summary report in Java Medium
- Copy a binary file with a byte buffer in Java Medium
- Read a key=value configuration file in Java Medium
- Filter errors from a log file into a new file in Java Medium
- Summarise a folder by file extension in Java Medium
- Save and load student records in a binary file in Java Hard
- Merge several text files with headers in Java Easy
- Safely update a file via a temporary file in Java Hard
- Letter frequency histogram from a file in Java Easy
Serialization 10 questions
- Save and load a list of contacts to a file in Java Easy
- Game save with transient runtime state in Java Medium
- Adding a field without breaking old saved data in Java Hard
- Compact custom format with Externalizable in Java Medium
- Block unexpected classes with an ObjectInputFilter in Java Hard
- User session with a transient cache in Java Medium
- Serialization-safe configuration with an enum in Java Easy
- Serialize a circular doubly linked list in Java Hard
- Bank ledger with checksum validation in Java Medium
- Java serialization versus a simple text format Easy
Multithreading 10 questions
- Print odd and even numbers with two threads in Java Medium
- Concurrent ticket booking without overselling in Java Medium
- Count words in several documents in parallel in Java Medium
- Two-stage pipeline with a bounded buffer in Java Hard
- Cancellable countdown timer thread in Java Easy
- Concurrent bank transfers that conserve money in Java Hard
- ThreadLocal for a non-thread-safe formatter in Java Medium
- Multiply matrices with one thread per row in Java Medium
- Limited parking slots with wait/notify in Java Hard
- Background worker with a progress monitor in Java Medium
Concurrency and Executors 10 questions
- Process files in parallel with a thread pool in Java Easy
- Enrich an order with parallel async lookups in Java Medium
- Order processing pipeline with BlockingQueue in Java Medium
- Limit concurrent API calls with a Semaphore in Java Medium
- Start services in parallel and wait with a latch in Java Medium
- Count words in a large text with Fork/Join in Java Hard
- Simulated web crawl with virtual threads in Java Medium
- Step-by-step simulation with a CyclicBarrier in Java Hard
- Fetch from the fastest mirror with invokeAny in Java Medium
- Thread-safe price cache with a ReadWriteLock in Java Hard
Data Structures in Java 10 questions
- Generic linked-list stack with an iterator in Java Medium
- Queue implemented with two stacks in Java Medium
- Merge two sorted linked lists and remove duplicates Medium
- Binary min-heap from scratch with heap sort in Java Hard
- Deleting from a binary search tree: all three cases Hard
- Left view, right view and level sums of a tree Medium
- Course order with topological sort (Kahn's algorithm) Hard
- Shortest path through a grid maze with BFS in Java Hard
- Sliding-window maximum temperature with a deque Hard
- Minimum spanning tree with Kruskal and union-find Hard
Ready to test your Programming?
Timed online tests with instant scores and explanations.