LearnFrenzy
Sign in Take a free test

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

  1. Simple and compound interest calculator in Java Easy
  2. Celsius to Fahrenheit and Kelvin table in Java Easy
  3. BMI calculator with category in Java Easy
  4. Swap two numbers with and without a temp variable in Java Easy
  5. Convert seconds to days, hours, minutes and seconds in Java Easy
  6. Sum of digits and reverse of a number in Java Easy
  7. Print an ASCII table of letters and digits in Java Easy
  8. Electricity bill with slab rates in Java Medium
  9. Report the size and range of every primitive type in Java Easy
  10. Shopping bill with GST and discount using printf in Java Medium

Operators and Expressions 10 questions

  1. Leap year check with logical operators in Java Easy
  2. Largest and smallest of three with the ternary operator Easy
  3. Convert decimal to binary using bit operations in Java Medium
  4. Count set bits three ways in Java Medium
  5. Simple calculator with operators and switch in Java Easy
  6. Check if three sides form a triangle and classify it in Java Easy
  7. Swap nibbles and reverse bits of a byte in Java Hard
  8. Grade and result calculator with relational operators Easy
  9. Sum of even and odd numbers using bitwise checks in Java Easy
  10. Loan EMI calculator with operators and Math.pow in Java Medium

Control Flow Statements 10 questions

  1. Print prime numbers in a range in Java Easy
  2. Fibonacci series up to N terms in Java Easy
  3. Find Armstrong numbers in Java Medium
  4. GCD and LCM using Euclid's algorithm in Java Easy
  5. Menu-driven program with do-while and switch in Java Medium
  6. Number pyramid and diamond patterns in Java Medium
  7. Perfect, abundant and deficient numbers in Java Medium
  8. Number guessing game with a binary-search strategy in Java Medium
  9. Multiplication table grid with nested for loops in Java Easy
  10. Strong numbers and palindromic primes in Java Medium

Arrays in Java 10 questions

  1. Remove duplicates from a sorted array in place in Java Easy
  2. Two-sum: find two numbers that add up to a target in Java Medium
  3. Merge two sorted arrays into one in Java Easy
  4. Move all zeros to the end keeping order in Java Easy
  5. Matrix multiplication with 2D arrays in Java Medium
  6. Find the missing number from 1 to N in Java Easy
  7. Find leaders in an array in Java Medium
  8. Print a matrix in spiral order in Java Hard
  9. Count occurrences and find the most frequent element in Java Easy
  10. Maximum subarray sum with its start and end (Kadane) in Java Hard

Strings and StringBuilder 10 questions

  1. Character frequency in insertion order in Java Easy
  2. First non-repeating character in a string in Java Medium
  3. Compress a string with character counts in Java Medium
  4. Convert a sentence to title case in Java Easy
  5. Toggle case and count letter types in Java Easy
  6. Reverse each word but keep the word order in Java Easy
  7. Longest common prefix of an array of strings in Java Medium
  8. Count words, sentences and characters in a paragraph in Java Medium
  9. Remove duplicate characters from a string in Java Easy
  10. Caesar cipher encryption and decryption in Java Medium

Methods and Recursion 10 questions

  1. Recursive binary search in Java Medium
  2. All permutations of a string with recursion in Java Hard
  3. Generate all subsets of a set recursively in Java Hard
  4. Convert a number to words with helper methods in Java Medium
  5. Merge sort with recursion in Java Hard
  6. Count islands in a grid with recursive flood fill in Java Hard
  7. Temperature utility class with overloaded methods in Java Easy
  8. Digital root and persistence with recursion in Java Easy
  9. Pascal's triangle with a recursive method in Java Medium
  10. Validate user registration with small methods in Java Medium

Classes and Objects 10 questions

  1. Student report card using a class in Java Easy
  2. Shopping cart with Product and CartItem objects in Java Medium
  3. Rectangle and Circle classes with area and perimeter in Java Easy
  4. Movie seat booking with a Theatre class in Java Medium
  5. Inventory manager with low-stock alerts in Java Medium
  6. Singly linked list built from Node objects in Java Hard
  7. To-do list manager with Task objects in Java Easy
  8. Bank transfers between Account objects in Java Medium
  9. Employee payroll and department summary in Java Medium
  10. Parking lot with Vehicle objects and fees in Java Hard

Constructors and the this Keyword 10 questions

  1. Rectangle with overloaded constructors in Java Easy
  2. A validated Date class with leap years in Java Medium
  3. Deep copy constructor for a class with a list in Java Medium
  4. Fraction class that normalises in its constructor in Java Medium
  5. Pizza order using the builder pattern in Java Medium
  6. Thread-safe singleton with a holder class in Java Hard
  7. Employee objects with auto-generated IDs in Java Easy
  8. Temperature with named static factory methods in Java Medium
  9. Matrix class with several constructors in Java Hard
  10. Bank account with opening-balance rules in Java Medium

Static and Final Keywords 10 questions

  1. Count objects created with a static counter in Java Easy
  2. Unit converter utility class with constants in Java Easy
  3. Immutable Money class with currency checks in Java Medium
  4. Application config loaded in a static block in Java Medium
  5. Singleton logger using an enum in Java Medium
  6. Static math helpers: GCD, LCM, primes and factorial in Java Easy
  7. A final template method in a report generator in Java Hard
  8. Caching static factory for colour objects in Java Medium
  9. Thread-safe static counters with AtomicInteger in Java Hard
  10. Immutable 2D vector class with static constants in Java Medium

Access Modifiers and Packages 10 questions

  1. Student marks with private fields and validation in Java Easy
  2. User password with a private hash and policy in Java Medium
  3. Discount rules with protected hook methods in Java Medium
  4. Inventory with private map and read-only views in Java Medium
  5. Rate limiter with private state in Java Hard
  6. Library members with access levels in Java Easy
  7. Immutable API response with private constructor in Java Medium
  8. Game characters with protected stats in Java Medium
  9. Fully qualified names instead of imports in Java Easy
  10. Feature flags with private storage in Java Hard

Encapsulation 10 questions

  1. Encapsulated bank account with transaction log in Java Easy
  2. Shopping cart that hides its items in Java Medium
  3. Employee salary with controlled raises in Java Easy
  4. Library card with fines and borrowing limits in Java Medium
  5. Temperature log with private readings and statistics in Java Medium
  6. Voting machine that prevents double voting in Java Medium
  7. Immutable student record with defensive copies in Java Hard
  8. Digital wallet with PIN and transfer limits in Java Medium
  9. Parking meter with private time and coins in Java Easy
  10. Smart bulb with encapsulated state and brightness in Java Easy

Inheritance 10 questions

  1. Savings and current accounts with inheritance in Java Easy
  2. Shape hierarchy with area and perimeter in Java Easy
  3. Multilevel inheritance: Vehicle, Car and ElectricCar in Java Medium
  4. Library items: books, DVDs and magazines in Java Medium
  5. Notification channels sharing a send template in Java Medium
  6. Hierarchical inheritance: employee bonuses in Java Easy
  7. Composition: building a computer from parts in Java Medium
  8. Zoo feeding schedule with instanceof checks in Java Medium
  9. Game characters with shared base stats in Java Hard
  10. Person, Student and Teacher with super calls in Java Easy

Polymorphism and Method Overriding 10 questions

  1. Payment gateway with overridden fee rules in Java Easy
  2. Overloaded area and volume calculator in Java Easy
  3. Food delivery fees with polymorphic partners in Java Medium
  4. Sort mixed shapes by area using polymorphism in Java Easy
  5. Multi-channel notifications through one interface in Java Medium
  6. Salaried, hourly and commission pay in Java Medium
  7. Evaluate an expression tree with polymorphism in Java Hard
  8. Logger hierarchy overriding format and filter in Java Medium
  9. Invoice line totals with a sealed type and switch in Java Hard
  10. Rock-paper-scissors strategy players in Java Medium

Abstraction 10 questions

  1. Abstract Shape with circle, square and triangle in Java Easy
  2. Vehicle rental pricing with an abstract base in Java Medium
  3. Document parsers sharing a parse pipeline in Java Medium
  4. Abstract Employee with permanent and contract staff in Java Easy
  5. Abstract board game with a fixed play loop in Java Hard
  6. Bank accounts with abstract interest rules in Java Medium
  7. Report generator with abstract data source in Java Medium
  8. Cache with abstract eviction policy in Java Hard
  9. Exam grading with abstract marking schemes in Java Easy
  10. Smart home devices with an abstract base in Java Medium

Interfaces 10 questions

  1. Payment gateways behind one interface in Java Easy
  2. Sort products several ways with Comparator in Java Easy
  3. Event listeners with a functional interface in Java Medium
  4. Discount strategies chosen at run time in Java Medium
  5. Shapes that are both Comparable and Drawable in Java Medium
  6. A Range class that implements Iterable in Java Medium
  7. Text-processing plugins through an interface in Java Medium
  8. Repository interface with two implementations in Java Hard
  9. Smart devices with segregated interfaces in Java Easy
  10. Form validators combined with default methods in Java Hard

Object Class and Wrapper Classes 10 questions

  1. Remove duplicate employees with equals and hashCode in Java Easy
  2. Parse a mixed list of numbers safely in Java Easy
  3. Number base converter using wrapper methods in Java Easy
  4. Text statistics with the Character class in Java Easy
  5. Deep copy of an order with a copy constructor in Java Medium
  6. GST invoice with exact BigDecimal arithmetic in Java Medium
  7. Grid points as HashMap keys in Java Medium
  8. Null-safe totals over Integer data in Java Medium
  9. Big factorials and digit sums with BigInteger in Java Medium
  10. Check the equals and hashCode contract in Java Hard

Exception Handling 10 questions

  1. Safe calculator that handles bad input in Java Easy
  2. CSV import with a per-line error report in Java Medium
  3. Ticket booking with custom checked exceptions in Java Medium
  4. Read records with try-with-resources in Java Medium
  5. Sign-up form validation with exceptions in Java Easy
  6. Bank transfer with rollback on failure in Java Hard
  7. Ask again until the input is a valid number in Java Easy
  8. Translate low-level errors at a service layer in Java Hard
  9. Checking internal invariants with assertions in Java Medium
  10. Count and group exceptions from many tasks in Java Medium

Collections Framework 10 questions

  1. Top K highest scores with a PriorityQueue in Java Medium
  2. Undo and redo for a text editor with two stacks in Java Medium
  3. Bank counter queue simulation in Java Medium
  4. Sliding window maximum with a deque in Java Hard
  5. Task scheduler by priority and deadline in Java Medium
  6. Merge two sorted lists without duplicates in Java Easy
  7. Recently viewed products list (max 5, no repeats) in Java Medium
  8. Sort an inventory list several ways in Java Easy
  9. Josephus elimination game with a queue in Java Medium
  10. Students common to courses using set operations in Java Easy

HashMap and TreeMap 10 questions

  1. Word frequency with the top three words in Java Easy
  2. First non-repeating character with LinkedHashMap in Java Easy
  3. Group anagrams using sorted keys in Java Medium
  4. Grade and scholarship bands with TreeMap in Java Medium
  5. LRU cache with hit and miss statistics in Java Hard
  6. Phone book with prefix search using TreeMap in Java Medium
  7. Top visitors from an access log in Java Medium
  8. Merge warehouse stock maps in Java Easy
  9. Count subarrays with a given sum using prefix sums in Java Hard
  10. Event timeline queries with TreeMap in Java Medium

Generics 10 questions

  1. Generic singly linked list with iteration in Java Medium
  2. Generic min, max and clamp utilities in Java Easy
  3. Generic key-value cache with a loader in Java Medium
  4. Type-safe event bus with Class keys in Java Hard
  5. Generic binary search with a comparator in Java Medium
  6. Zip, unzip and group with a generic Pair in Java Medium
  7. Generic bounded circular queue in Java Medium
  8. Generic binary search tree in Java Hard
  9. Generic validation rules that collect errors in Java Medium
  10. Generic numeric operations with a strategy in Java Hard

Lambda Expressions 10 questions

  1. Write your own filter and map with lambdas in Java Easy
  2. Pluggable discount rules with lambdas in Java Medium
  3. Retry an operation using a Supplier lambda in Java Medium
  4. Button click listeners with Consumer lambdas in Java Easy
  5. Password validation with a list of named predicates in Java Medium
  6. Text cleaning pipeline with composed functions in Java Medium
  7. Sort employees in several orders with lambdas in Java Easy
  8. Memoise any function with a lambda wrapper in Java Hard
  9. Traffic light state machine with lambda transitions in Java Medium
  10. Run Callable lambdas and collect results in Java Medium

Streams API 10 questions

  1. Student result analysis with streams in Java Easy
  2. Top words in a text with groupingBy in Java Medium
  3. Department salary report with collectors in Java Medium
  4. Web server log analysis with streams in Java Medium
  5. Prime numbers and twin primes with IntStream in Java Medium
  6. Parse CSV inventory and report with streams in Java Medium
  7. Flatten customer orders and find best sellers in Java Hard
  8. Temperature readings: partition, stats and streaks in Java Medium
  9. Price range and spread with Collectors.teeing in Java Hard
  10. Group anagrams with a single stream in Java Medium

Records, Enums and Sealed Classes 10 questions

  1. Vending machine with an enum of products in Java Easy
  2. Invoice built from validated records in Java Medium
  3. Payment results as a sealed hierarchy in Java Medium
  4. Pizza pricing with enums and a record in Java Easy
  5. Traffic violations and fines with an enum in Java Medium
  6. A tiny JSON model with sealed records in Java Hard
  7. Chess piece moves with a sealed interface in Java Hard
  8. Leave request workflow with enums and records in Java Medium
  9. Shipping charges by zone and parcel type in Java Medium
  10. A deck of cards with Suit and Rank enums in Java Easy

File Handling, IO and NIO 10 questions

  1. Word, line and character count of a file in Java Easy
  2. Read a CSV file and write a summary report in Java Medium
  3. Copy a binary file with a byte buffer in Java Medium
  4. Read a key=value configuration file in Java Medium
  5. Filter errors from a log file into a new file in Java Medium
  6. Summarise a folder by file extension in Java Medium
  7. Save and load student records in a binary file in Java Hard
  8. Merge several text files with headers in Java Easy
  9. Safely update a file via a temporary file in Java Hard
  10. Letter frequency histogram from a file in Java Easy

Serialization 10 questions

  1. Save and load a list of contacts to a file in Java Easy
  2. Game save with transient runtime state in Java Medium
  3. Adding a field without breaking old saved data in Java Hard
  4. Compact custom format with Externalizable in Java Medium
  5. Block unexpected classes with an ObjectInputFilter in Java Hard
  6. User session with a transient cache in Java Medium
  7. Serialization-safe configuration with an enum in Java Easy
  8. Serialize a circular doubly linked list in Java Hard
  9. Bank ledger with checksum validation in Java Medium
  10. Java serialization versus a simple text format Easy

Multithreading 10 questions

  1. Print odd and even numbers with two threads in Java Medium
  2. Concurrent ticket booking without overselling in Java Medium
  3. Count words in several documents in parallel in Java Medium
  4. Two-stage pipeline with a bounded buffer in Java Hard
  5. Cancellable countdown timer thread in Java Easy
  6. Concurrent bank transfers that conserve money in Java Hard
  7. ThreadLocal for a non-thread-safe formatter in Java Medium
  8. Multiply matrices with one thread per row in Java Medium
  9. Limited parking slots with wait/notify in Java Hard
  10. Background worker with a progress monitor in Java Medium

Concurrency and Executors 10 questions

  1. Process files in parallel with a thread pool in Java Easy
  2. Enrich an order with parallel async lookups in Java Medium
  3. Order processing pipeline with BlockingQueue in Java Medium
  4. Limit concurrent API calls with a Semaphore in Java Medium
  5. Start services in parallel and wait with a latch in Java Medium
  6. Count words in a large text with Fork/Join in Java Hard
  7. Simulated web crawl with virtual threads in Java Medium
  8. Step-by-step simulation with a CyclicBarrier in Java Hard
  9. Fetch from the fastest mirror with invokeAny in Java Medium
  10. Thread-safe price cache with a ReadWriteLock in Java Hard

Data Structures in Java 10 questions

  1. Generic linked-list stack with an iterator in Java Medium
  2. Queue implemented with two stacks in Java Medium
  3. Merge two sorted linked lists and remove duplicates Medium
  4. Binary min-heap from scratch with heap sort in Java Hard
  5. Deleting from a binary search tree: all three cases Hard
  6. Left view, right view and level sums of a tree Medium
  7. Course order with topological sort (Kahn's algorithm) Hard
  8. Shortest path through a grid maze with BFS in Java Hard
  9. Sliding-window maximum temperature with a deque Hard
  10. Minimum spanning tree with Kruskal and union-find Hard

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links