Skip to content
Tutorials Center
My learning

Topics

Lesson 196 of 201 ยท Practice and Review

Java Programs: 40 Classic Examples

40 classic Java programs you can run - primes, palindromes, factorials, Fibonacci, GCD, Armstrong numbers, anagrams, matrices, patterns, sorting and more.

Some programs show up again and again: in textbooks, in coding interviews, in university exams and in the first weeks of every new job. Checking whether a number is prime, reversing a string, finding the second largest value in an array, printing Pascal's triangle. They're small, but each one trains a specific skill, from loops and integer arithmetic to strings, arrays, recursion and collections.

This page collects 40 of those classics, plus extra conversion, pattern, basic math and extra string programs (numbered 41-50 near the end), written from scratch in clean, modern Java 25. They're grouped by topic, and each one has a short explanation of the idea that makes it work plus a link to the lesson it practices. Every program is a live editor: press Run to see the output, then change the input values and run it again. Programs that read input have it preset in the Input box, so they work right away.

Most examples use the short compact form (void main() with no class around it), which Getting Started introduces. The logic would be identical inside a classic public class Main. When you're ready for practice without the answers in front of you, move on to the exercises.

Number programs

These practice arithmetic operators, loops and methods. Most of them rely on two tricks: n % 10 gives the last digit of a number and n / 10 removes it.

1. Even or odd, positive or negative

The remainder after dividing by 2 decides parity. Use != 0 rather than == 1, because in Java -7 % 2 is -1, not 1.

Java Program 1: Even or odd

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

2. Leap year

A year is a leap year if it's divisible by 4, except century years, which must also be divisible by 400. The library agrees: Year.isLeap(year) gives the same answers.

Java Program 2: Leap years

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

3. Sum of digits

Peel off the last digit with % 10, add it, then drop it with / 10 until nothing is left. Math.abs makes negative numbers work too.

Java Program 3: Sum of digits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

4. Reverse a number and check for a palindrome

Building the reversed number digit by digit (reversed * 10 + digit) avoids converting to a string. A number is a palindrome when it equals its reverse.

Java Program 4: Reversed numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that 120 reverses to 21: leading zeros disappear in a number.

5. Prime check

A number is prime if no divisor from 2 up to its square root divides it. Testing only up to โˆšn (written i * i <= n to stay in integers) and skipping even numbers makes the check fast.

Java Program 5: Is it prime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

6. All primes up to N (Sieve of Eratosthenes)

To find many primes at once, cross out the multiples of each prime instead of testing every number. Starting at p * p works because smaller multiples were already crossed out by smaller primes.

Java Program 6: Sieve of Eratosthenes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The sieve is covered with other classic algorithms in Searching and Sorting Algorithms.

7. Factorial

n! grows so fast that long overflows after 20!, so this program shows a loop with long and an exact version with BigInteger, which has no upper limit. See BigInteger and BigDecimal.

Java Program 7: Factorials

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

8. Fibonacci sequence

Each Fibonacci number is the sum of the two before it. The loop keeps just two variables, which is far faster than the naive recursive version, as Recursion explains.

Java Program 8: Fibonacci numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

9. GCD and LCM

Euclid's algorithm replaces the pair (a, b) with (b, a % b) until the remainder is 0; the last nonzero value is the greatest common divisor. The least common multiple follows from it. Dividing before multiplying keeps the LCM from overflowing.

Java Program 9: GCD and LCM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

10. Armstrong numbers

An Armstrong number equals the sum of its digits, each raised to the power of the number of digits: 153 = 1ยณ + 5ยณ + 3ยณ. Integer powers are computed with a loop, because Math.pow returns a double.

Java Program 10: Armstrong numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

11. Perfect numbers

A perfect number equals the sum of its proper divisors: 6 = 1 + 2 + 3. Divisors come in pairs (i and n / i), so checking up to the square root is enough.

Java Program 11: Perfect numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Math and conversions

12. Decimal to binary and back

The manual method divides by 2 and collects remainders in reverse. The library does both directions in one call each, and also handles hex and any other base. See Bitwise and Shift Operators.

Java Program 12: Binary conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

13. Roman numerals

A greedy algorithm works: repeatedly subtract the largest value that still fits. Including the subtractive pairs (900 = CM, 4 = IV) in the table means no special cases.

Java Program 13: Roman numerals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

14. Quadratic equation

For axยฒ + bx + c = 0, the discriminant bยฒ โˆ’ 4ac decides whether there are two real roots, one, or two complex ones. See The Math Class and Formatting Strings.

Java Program 14: Quadratic roots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

15. Simple calculator

A switch expression maps each operator to its result, and default throws for anything unknown. The program reads one calculation per line from the Input box until it runs out.

Java Program 15: Calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

16. Tower of Hanoi

Moving n disks means: move n โˆ’ 1 disks out of the way, move the biggest disk, then move the n โˆ’ 1 disks on top of it. The recursion mirrors that sentence exactly and always needs 2โฟ โˆ’ 1 moves.

Java Program 16: Tower of Hanoi

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

String programs

These practice Strings, String Methods, StringBuilder and HashMap.

17. Reverse a string

StringBuilder.reverse() is the practical answer; the two-pointer swap shows what happens underneath and is what interviewers usually want to see.

Java Program 17: Reverse a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both versions work on UTF-16 chars. StringBuilder.reverse() keeps surrogate pairs (most emoji) intact; the manual swap would split them.

18. Palindrome string

Compare characters from both ends, skipping anything that isn't a letter or digit, so sentences like "Never odd or even" count.

Java Program 18: Palindrome check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

19. Anagram check

Two words are anagrams if they use the same letters the same number of times. Counting letters in one array (add for the first word, subtract for the second) runs in linear time; sorting both strings also works.

Java Program 19: Anagrams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The 26-slot array assumes the English letters a to z. For any alphabet, count with a Map<Character, Integer> instead.

20. Count vowels and consonants

A small string of vowels plus indexOf classifies each letter. Character.isLetter skips spaces, digits and punctuation. See Characters and Booleans.

Java Program 20: Vowels and consonants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

21. Character frequency

A TreeMap keeps the characters sorted, and merge(c, 1, Integer::sum) is the standard one-line counter. See TreeMap and TreeSet.

Java Program 21: Character frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

22. First non-repeated character

Count first, then scan the string again in order. A LinkedHashMap would also work, because it remembers insertion order. See LinkedHashMap and LinkedHashSet.

Java Program 22: First unique character

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

23. Remove duplicate characters

A LinkedHashSet keeps the first occurrence of each character and drops later ones, all while preserving order. See HashSet.

Java Program 23: Remove duplicates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

24. Word count and title case

strip() plus split("\\s+") handles extra spaces between words. Capitalizing means upper-casing the first character and lower-casing the rest of each word.

Java Program 24: Words and title case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

25. Run-length compression

Replace each run of repeated characters with the character and its count: aaabcc becomes a3b1c2. Keep the original when the "compressed" form is longer.

Java Program 25: Run-length encoding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Array programs

These practice Arrays, Looping Through Arrays and The Arrays Class.

26. Largest, smallest and average

Start from the first element (not from 0, which breaks for all-negative arrays) and update as you go. Cast to double before dividing so the average keeps its decimals.

Java Program 26: Min, max and average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

27. Second largest element

One pass with two variables does it. The n != largest check makes duplicates of the maximum count once, so {7, 7, 3} gives 3.

Java Program 27: Second largest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

28. Find duplicates in an array

Set.add returns false when the element is already there, which detects every repeat in a single pass.

Java Program 28: Duplicate values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

29. Reverse an array in place

Swap the first and last elements, then move both indexes inward until they meet. No second array needed.

Java Program 29: Reverse in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

30. Rotate an array

To rotate right by k, reverse the whole array, then reverse the first k elements and the rest separately. It's O(n) time with no extra memory. k % length handles rotations larger than the array.

Java Program 30: Rotate right

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

31. Merge two sorted arrays

Walk both arrays with one index each and always take the smaller front element; then copy whatever is left. This is the heart of merge sort.

Java Program 31: Merge sorted arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

32. Find the missing number

An array holds every number from 1 to n except one. The sum of 1 to n is n(n + 1) / 2, so the missing number is that total minus the actual sum.

Java Program 32: Missing number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

33. Pairs with a given sum (two sum)

For each number, check whether its partner target โˆ’ n was seen earlier. A HashMap from value to index turns an O(nยฒ) double loop into a single O(n) pass.

Java Program 33: Two sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Matrices and patterns

These practice Multidimensional Arrays and nested loops.

34. Matrix addition and transpose

Adding visits each cell once with two nested loops. A transpose swaps rows and columns, so a 2ร—3 matrix becomes 3ร—2.

Java Program 34: Add and transpose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

35. Matrix multiplication

Cell [i][j] of the product is the dot product of row i of the first matrix and column j of the second. The inner dimensions must match: (2ร—3) ร— (3ร—2) gives 2ร—2.

Java Program 35: Multiply matrices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

36. Number and star pyramids

Pattern programs are all about the relationship between the row number and how many spaces and symbols that row gets. repeat keeps them short. See String Methods.

Java Program 36: Pyramids

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

37. Pascal's triangle

Each value is the sum of the two above it. Computing a row from the previous one with C(n, k+1) = C(n, k) ร— (n โˆ’ k) / (k + 1) needs no 2D array at all.

Java Program 37: Pascal's triangle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Searching, sorting and collections

These practice Searching and Sorting Algorithms, HashMap and Streams.

On sorted data, compare with the middle element and throw away the half that can't contain the target. low + (high - low) / 2 avoids the overflow that (low + high) / 2 can cause on huge arrays.

Java Program 38: Binary search

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

For a missing value, Arrays.binarySearch returns -(insertion point) - 1 instead of a plain -1, which tells you where the value would go.

39. Bubble sort

Repeatedly swap neighbors that are out of order; each pass bubbles the largest remaining value to the end. The swapped flag stops early once a pass makes no swaps. It's O(nยฒ) and for learning only: real code calls Arrays.sort.

Java Program 39: Bubble sort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

40. Word frequency, most common first

Split the text into words with a regex, count them with a stream collector, and sort the entries by count (then alphabetically to break ties). This one program uses regex, maps, streams and comparators together. See Collecting Stream Results and Comparable and Comparator.

Java Program 40: Word frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The Text Analyzer project grows this idea into a complete program.

Conversion programs

Converting between representations is a favorite exercise because every conversion has a failure mode: a digit that doesn't belong, a number that doesn't fit, a view that is not a copy. See Type Casting and String Comparison and Conversion for the rules behind them.

41. Binary, octal, hex and any other base

Converting by hand means repeated division (collect remainders, then reverse) in one direction and "multiply the running value by the base, add the next digit" in the other. The library does both in one call, and Integer.parseInt(text, radix) accepts any radix from 2 to 36 and rejects digits that don't belong.

Java Program 41: Number bases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Going from octal to hexadecimal (or any pair) is the same trick: parse into a plain int, which has no base, then format in the new base.

42. String, number, char and boolean conversions

parseXxx turns text into a primitive and throws NumberFormatException for anything that isn't exactly a number: no spaces, no empty string, and for byte nothing outside -128 to 127. String.valueOf goes the other way for every type. Characters are numbers in disguise, so '7' - '0' is the digit 7. Boolean.parseBoolean never throws: anything but "true" (ignoring case) is false, which surprises people who expect "yes" to work.

Java Program 42: Parsing and converting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

43. Arrays, lists, sets, maps and streams

The important question for every collection conversion is whether you get a view or a copy. Arrays.asList(array) is a fixed-size view that writes through to the array; new ArrayList<>(...) is an independent copy. Putting a list into a TreeSet removes duplicates and sorts. An Iterator can be drained with forEachRemaining, Vector and LinkedList have copy constructors that accept any collection, and readAllBytes turns an InputStream into a String (always name the charset).

Java Program 43: Collection conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

More pattern programs

Every pattern is the same question asked row by row: how many spaces, and how many symbols? The outer loop is the row, the inner loop (or repeat) is the column. When a shape depends on the border (hollow shapes), test row == 0 || row == last || col == 0 || col == last instead of counting.

44. Triangles, hollow square and diamond

A diamond is a pyramid followed by the same pyramid upside down without repeating the widest row.

Java Program 44: Triangles and a diamond

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

45. Number and letter patterns

Floyd's triangle needs a counter that keeps running across rows. Letter patterns use (char) ('A' + k). The butterfly is two triangles with a gap that shrinks by two per row. For a spiral, see the spiral matrix in Multidimensional Arrays.

Java Program 45: Floyd, letters, butterfly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

More basic math programs

46. Swaps, simple formulas and small classes

Swapping with a temporary variable is the version to write in real code. The arithmetic and XOR tricks avoid the temp but are famous only as puzzles: the arithmetic one can overflow, and neither is faster on a modern JIT. A Neon number equals the digit sum of its own square (9 squared is 81, and 8 + 1 = 9). Compound interest is P ร— (1 + r/n)^(nยทt). A record is a neat way to model a complex number: it is immutable, and plus and times return new values. The last program, the sum of even Fibonacci numbers up to four million, shows that you never need to store the sequence, only the last two terms.

Java Program 46: Swap, interest, complex numbers, Neon

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Printing the primes up to N is Program 6; the largest of three could also be Collections.max(List.of(x, y, z)), but Math.max twice is faster and needs no boxing.

More string programs

Strings come up so often in interviews that one section was not enough. These four programs cover the smaller classics: pangrams, sorting a string, comparing strings the way a dictionary does, swapping, inserting, splitting, regex tricks and Unicode code points. They build on String Methods, StringBuilder and Regular Expressions.

47. Pangram, sort a string and compare strings

A pangram uses every letter of the alphabet at least once. Keep a boolean[26], mark each letter you see (c - 'a' turns 'a'..'z' into 0..25) and count the first time each one appears. To sort the characters of a string, move them into a char[], call Arrays.sort, and build a new String. Strings themselves are immutable, so every "change" produces a new string.

compareTo compares two strings the way a dictionary does, character by character using their UTF-16 values. It returns a negative number when the first string comes first, zero when they are equal and a positive number otherwise. The exact size of the number is not part of the contract (it is the difference of the first two characters that differ, or the difference of the lengths), so only ever test its sign.

Java Program 47: Pangram, sort and compareTo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

For a locale-aware order (accents, German "รค") use java.text.Collator instead of compareTo.

48. Swap pairs, replace and insert characters, remove leading zeros

Four small string edits, each one a different tool. Swapping neighbouring characters is a loop over a char[] with a step of 2 (an odd leftover character stays where it is). To replace the character at one index, StringBuilder.setCharAt is the shortest route because a String has no setter. StringBuilder.insert(position, text) puts one string inside another. Removing leading zeros is a loop that stops one digit early, so "0000" becomes "0" instead of an empty string; a regex does the same in one line.

Java Program 48: Swap, replace, insert and trim zeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The regex ^0+(?!$) means "zeros at the start that are not followed by the end of the string", which is exactly why the last zero of "0000" survives.

49. Split into pieces, even-length words, first letters and code points

Splitting a string into fixed-size chunks is a loop with substring; Math.min keeps the last, shorter chunk from running past the end. Picking words with an even number of letters is a stream over split(" "). The first letter of every word is \b\w in a regex (a word boundary followed by a word character), and replaceAll with a capture group can do the same job by keeping only group 1.

The last part is a reminder that length() counts UTF-16 code units, not characters a person sees. An emoji takes two code units (a surrogate pair), so "Hi ๐Ÿ˜€!" has length 6 but only 5 code points. Use codePointCount and codePoints() when you work with text that may contain such characters.

Java Program 49: Chunks, filters, regex and code points

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

50. Reverse a string with a stack

A stack hands items back in the opposite order from which they went in, so pushing every character and then popping them all reverses the string. It is not the fastest way (StringBuilder.reverse() is), but it is the classic way to show you understand last-in, first-out. ArrayDeque is the stack to use in modern Java; the old Stack class is synchronized and legacy (Queues and Deques).

Java Program 50: Reverse with a stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

How to practice with these programs

Reading a solution feels like understanding it, but the real test is writing it yourself. A routine that works well:

  1. Read only the heading and the one-line idea, then close the code in your mind and write the program in an empty editor (any TryIt will do: select all and replace).
  2. Run it against the same values as ours and compare the output.
  3. Change the inputs to break it: empty arrays, zero, negative numbers, one-element strings, huge values. Programs 5, 26 and 27 show the kind of edge cases interviewers love.
  4. Rewrite it in a different style: a loop version of a recursive program, a stream version of a loop, or the reverse.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Program 1, why does the even/odd test use n % 2 != 0 instead of n % 2 == 1?

    In Java the remainder takes the sign of the left operand, so -7 % 2 is -1. Testing != 0 is correct for every int.
  2. 2. Program 7 prints a negative number for 21! computed as a long. Why?

    20! (about 2.4 ร— 10^18) still fits, but 21! is about 5.1 ร— 10^19, beyond Long.MAX_VALUE (about 9.2 ร— 10^18). Java integer arithmetic wraps around without an error; BigInteger avoids that.
  3. 3. Why does the prime check in Program 5 stop at i * i <= n?

    Divisors come in pairs d and n / d, and one of each pair is at most the square root. Writing i * i <= n also avoids floating-point rounding from Math.sqrt.
  4. 4. Which data structure lets Program 33 (two sum) run in a single O(n) pass?

    Looking up "have I seen target - n?" in a HashMap takes O(1) on average, so one pass over the array is enough. A TreeSet would work too, but in O(n log n).

Summary

  • Number programs rely on % 10 and / 10 to work digit by digit, on i * i <= n for divisor searches, and on long or BigInteger when values grow fast.
  • String programs combine charAt, toCharArray, StringBuilder, character tests like Character.isLetterOrDigit, and maps or sets for counting and uniqueness; test only the sign of compareTo, and use code points when text may contain emoji.
  • Array programs use one-pass scans, two-pointer swaps, the reverse trick for rotation, merging, and a HashMap to replace nested loops.
  • Matrix and pattern programs are nested loops where the row and column indexes decide what goes where.
  • Always know the library shortcut too (Year.isLeap, Integer.toBinaryString, Arrays.sort, Arrays.binarySearch), and know the edge cases that break the naive version.

Next: File and Directory Programs, practice with files, folders and ZIP archives, and then the exercises.