Algorithms
In short: A fixed sequence of steps to solve a specific problem — in Java often implemented as a method that processes a collection or an array.
In more detail: Java already ships with many standard algorithms built in, e.g. Collections.sort(), Collections.binarySearch(), or Collections.max() — for common tasks it’s rarely worth reimplementing them. For your own algorithms, time and space complexity (Big-O notation) are the central benchmarks.
In Depth
An algorithm is language-independent to begin with — the same sorting logic can be implemented in Java, Python, or C++. However, Java makes working with standard algorithms particularly convenient, since the java.util.Collections class (for lists) and java.util.Arrays (for arrays) already come with the most important ones built in:
List<Integer> numbers = new ArrayList<>(List.of(5, 3, 8, 1, 9));
Collections.sort(numbers); // [1, 3, 5, 8, 9]
int index = Collections.binarySearch(numbers, 8); // 3 - only valid on sorted lists!
int max = Collections.max(numbers); // 9
Collections.reverse(numbers); // [9, 8, 5, 3, 1]For your own algorithms, time complexity (Big-O notation) is the central benchmark: a linear search (O(n)) searches through every element once in the worst case, a binary search (O(log n)) on sorted data halves the search space at every step and is drastically faster for large amounts of data — but requires the data to be sorted beforehand (which itself costs time again, usually O(n log n)). For very frequent lookups on the same data, a suitable data structure like HashSet/HashMap (O(1) on average) is often worth it instead of an algorithm that iterates over a list anew every time.
Implementing your own algorithms
If no standard algorithm fits, you can usually implement your own iteratively or recursively. A linear search as an example:
static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return i;
}
return -1; // not found
}For recursive algorithms (e.g. quicksort or your own Fibonacci implementation), the same caution applies as for recursion in general: without a clear base case, a StackOverflowError looms.
Common pitfalls
A classic beginner mistake is calling Collections.binarySearch() on an UNsorted list — the method then returns an undefined, usually wrong result, without throwing an exception. Equally common: trying Collections.sort() on an immutable list created with List.of(...), which triggers an UnsupportedOperationException (which is why the example above takes the detour via new ArrayList<>(List.of(...))).
Comparison to related concepts
An algorithm describes HOW a problem is solved, a data structure HOW the data is organised in the process — the two are closely related, since the choice of structure often directly determines the possible efficiency of the algorithm (e.g. search in a sorted array vs. in a HashMap).
See also: Sorting, Recursion, Data Structures