Java How To
›Short versionOpen if you only have a minute.
- Each recipe below is the happy path. The note under it is the input that still compiles and gives the wrong answer.
- int addition wraps. int division drops the remainder. A sort writes into the array the caller still holds.
- Math.random() never returns 1. A cast of Math.random() * 100 stops at 99.
- A single pass finds a maximum. Sorting the array to read the last index is a different cost, and it reorders the data.
Short programs for a job you already know how to name. Read the snippet, then the bound it assumes: the type, the empty input, and whether the method mutates what you passed in.
Strings
Reverse a string
String original = "Hello";
String reversed = new StringBuilder(original)
.reverse()
.toString();
System.out.println(reversed); // olleHreverse swaps char values. A character stored as a surrogate pair, including many emoji, comes back with the two halves exchanged. Building the reverse with += copies the whole string on every character.
Count words
String text = "Java is fun";
String[] words = text.trim().split("\\s+");
System.out.println(words.length); // 3split(" ") counts the empty token between two spaces. "".split("\\s+") still returns one element, so an all-blank string has to return 0 before the split.
Numbers
Even or odd
int num = 10;
if (num % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}Zero is even. In Java -3 % 2 is -1, so n % 2 == 1 misses every negative odd int. Test odd with n % 2 != 0.
A random int from 0 through 100
int randomNum = (int) (Math.random() * 101);
System.out.println(randomNum);Math.random() is in [0.0, 1.0). Multiplying by 100 and casting never returns 100. The 101 is the inclusive width.
Arrays
Largest value
int[] nums = {3, 7, 2, 9};
int max = nums[0];
for (int n : nums) {
if (n > max) {
max = n;
}
}
System.out.println(max); // 9Starting max at 0 returns 0 for {-5, -1, -8}, and 0 is not in the array. An empty array has no first element. Sorting just to read the last index is O(n log n) and reorders the array a linear scan would have left alone.
Sort
import java.util.Arrays;
int[] nums = {5, 1, 3};
int[] ordered = nums.clone();
Arrays.sort(ordered);
System.out.println(Arrays.toString(ordered)); // [1, 3, 5]
System.out.println(Arrays.toString(nums)); // [5, 1, 3]Arrays.sort on an int[] writes into that array. Clone first when the caller still needs the original order. println on the array itself prints a type and a hash, not the elements.
Why is the multiplier 101, not 100, for a roll from 0 through 100?
Math.random() * 100 lands in [0.0, 100.0). The cast to int keeps 0 through 99.
Math.random() * 101 lands in [0.0, 101.0), so the cast keeps 0 through 100. Random.nextInt(101) documents that exclusive bound without the double.