Java Basics
This article is designed for beginners and introduces the basic usage of Java, including control statements and common data structures from the standard library, to help you quickly get started with problem-solving.
Standard Output
Java's standard output is System.out.println
, which is used to print content to the console followed by a newline. System.out.print
can be used for output without a newline.
int a = 10;
// output: 10
System.out.println(a);
// can concatenate output
// output: Hello, World!
System.out.println("Hello" + ", " + "World!");
String s = "abc";
// output: abc 10
System.out.println(s + " " + a);
// formatted output
// output: abc 10
System.out.printf("%s %d\n", s, a);
Control Statements
Control statements in programming languages are generally straightforward. The most common ones are conditional statements and loops. Here's a brief introduction.
Conditional Statements: if else
int a = 10;
if (a > 5) {
System.out.println("a > 5");
} else if (a == 5) {
System.out.println("a == 5");
} else {
System.out.println("a < 5");
}
// output: a > 5
Loops: for/while
Both for
and while
can be used for loops. The for
loop is typically used when the number of iterations is known, while the while
loop is generally used when the number of iterations is unknown.
// output: 0 1 2 3 4
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
}
System.out.println();
int num = 100;
// output: 100 50 25 12 6 3 1
while (num > 0) {
System.out.print(num + " ");
num /= 2;
}
System.out.println();
Basic Data Structures
Java's standard library offers a variety of commonly used data structures, such as ArrayList
, LinkedList
, HashMap
, and HashSet
. Below is an introduction to some of these common data structures and how to use them.
Dynamic Array ArrayList
ArrayList
is an implementation of a dynamic array in Java's standard library. Unlike fixed-size arrays, ArrayList
can dynamically adjust its size as needed.
Initialization method:
import java.util.ArrayList;
// initialize an empty ArrayList nums
ArrayList<Integer> nums = new ArrayList<>();
// initialize an ArrayList nums with elements 1, 3, 5
ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 3, 5));
ArrayList
offers numerous methods. Here are examples of some commonly used methods:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
int n = 10;
// Initialize ArrayList with size 10, all elements are 0
ArrayList<Integer> nums = new ArrayList<>(Collections.nCopies(n, 0));
// Output: false
System.out.println(nums.isEmpty());
// Output: 10
System.out.println(nums.size());
// Insert an element 20 at the end of the array
nums.add(20);
// Output: 11
System.out.println(nums.size());
// Get the last element of the array
// Output: 20
System.out.println(nums.get(nums.size() - 1));
// Remove the last element of the array
nums.remove(nums.size() - 1);
// Output: 10
System.out.println(nums.size());
// Can access or modify values directly by index
nums.set(0, 11);
// Output: 11
System.out.println(nums.get(0));
// Insert an element 99 at index 3
nums.add(3, 99);
// Remove the element at index 2
nums.remove(2);
// Swap nums[0] and nums[1]
Collections.swap(nums, 0, 1);
// Traverse the array
// Output: 0 11 99 0 0 0 0 0 0 0
for(int num : nums) {
System.out.print(num + " ");
}
System.out.println();
}
}
The above are the common methods of Java ArrayList
, mainly including accessing elements by index and methods for adding or removing elements. In algorithm problems, these methods of ArrayList
are sufficient.
Doubly Linked List LinkedList
LinkedList
is a doubly linked list implementation in the Java standard library. Compared to ArrayList
, LinkedList
performs better when inserting and removing elements at the head and tail.
Common methods of LinkedList
:
import java.util.Arrays;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
// initialize the linked list
LinkedList<Integer> lst = new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5));
// check if the linked list is empty, output: false
System.out.println(lst.isEmpty());
// get the size of the linked list, output: 5
System.out.println(lst.size());
// insert element 0 at the head of the linked list
lst.addFirst(0);
// insert element 6 at the tail of the linked list
lst.addLast(6);
// get the first and last elements of the linked list, output: 0 6
System.out.println(lst.getFirst() + " " + lst.getLast());
// remove the head element of the linked list
lst.removeFirst();
// remove the tail element of the linked list
lst.removeLast();
// insert an element in the linked list
// move to the third position
lst.add(2, 99);
// remove a specific element from the linked list
lst.remove(1);
// traverse the linked list
// output: 1 99 3 4 5
for(int val : lst) {
System.out.print(val + " ");
}
System.out.println();
}
}
Generally, when we want to add or remove elements at the head, we use LinkedList
because it is more efficient than ArrayList
for these operations. However, when we need to frequently access elements by index, we use ArrayList
.
Queue
Queue
is an interface in the Java Standard Library, with common implementations like LinkedList
and PriorityQueue
. Here, we take LinkedList
as an example.
import java.util.Queue;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
// initialize an empty integer queue q
Queue<Integer> q = new LinkedList<>();
// add elements to the end of the queue
q.offer(10);
q.offer(20);
q.offer(30);
// check if the queue is empty, output: false
System.out.println(q.isEmpty());
// get the size of the queue, output: 3
System.out.println(q.size());
// get the front element of the queue
// output: 10
System.out.println(q.peek());
// remove the front element of the queue
q.poll();
// output the new front element: 20
System.out.println(q.peek());
}
}
Stack
A stack is a data structure that follows the Last In, First Out (LIFO) principle. Java provides the Stack
class to implement stack functionality:
import java.util.Stack;
public class Main {
public static void main(String[] args) {
// initialize an empty integer stack s
Stack<Integer> s = new Stack<>();
// push elements to the top of the stack
s.push(10);
s.push(20);
s.push(30);
// check if the stack is empty, output: false
System.out.println(s.isEmpty());
// get the size of the stack, output: 3
System.out.println(s.size());
// get the top element of the stack, output: 30
System.out.println(s.peek());
// remove the top element of the stack
s.pop();
// output the new top element of the stack: 20
System.out.println(s.peek());
}
}
Hash Table HashMap
HashMap
is a hash table implementation in the Java standard library. It provides storage based on key-value pairs, enabling efficient operations for adding, deleting, searching, and updating key-value pairs.
Common methods of HashMap
are as follows:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// initialize the hashmap
HashMap<Integer, String> hashmap = new HashMap<>();
hashmap.put(1, "one");
hashmap.put(2, "two");
hashmap.put(3, "three");
// check if the hashmap is empty, output: false
System.out.println(hashmap.isEmpty());
// get the size of the hashmap, output: 3
System.out.println(hashmap.size());
// check if a specific key exists
// output: Key 2 -> two
if(hashmap.containsKey(2)) {
System.out.println("Key 2 -> " + hashmap.get(2));
} else {
System.out.println("Key 2 not found.");
}
// get the value for a specific key, returns null if not found
// output: null
System.out.println(hashmap.get(4));
// get the value for a specific key, return default value if not found
// output: defaultVal
System.out.println(hashmap.getOrDefault(4, "defaultVal"));
// insert a new key-value pair
hashmap.put(4, "four");
// get the newly inserted value, output: four
System.out.println(hashmap.get(4));
// remove a key-value pair
hashmap.remove(3);
// check if key 3 exists after removal
// output: Key 3 not found.
if(hashmap.containsKey(3)) {
System.out.println("Key 3 -> " + hashmap.get(3));
} else {
System.out.println("Key 3 not found.");
}
// iterate over the hashmap
// output (order may vary):
// 1 -> one
// 2 -> two
// 4 -> four
for(Map.Entry<Integer, String> pair : hashmap.entrySet()) {
System.out.println(pair.getKey() + " -> " + pair.getValue());
}
}
}
HashSet
HashSet
is an implementation of a hash set in the Java Standard Library, used to store unique elements. A common use case is to eliminate duplicates from a collection of elements.
Common methods of HashSet
:
import java.util.Arrays;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// initialize the hash set
HashSet<Integer> hashset = new HashSet<>(Arrays.asList(1, 2, 3, 4));
// check if the hash set is empty, output: false
System.out.println(hashset.isEmpty());
// get the size of the hash set, output: 4
System.out.println(hashset.size());
// check if a specific element exists
// output: Element 3 found.
if(hashset.contains(3)) {
System.out.println("Element 3 found.");
} else {
System.out.println("Element 3 not found.");
}
// insert a new element
hashset.add(5);
// remove an element
hashset.remove(2);
// output: Element 2 not found.
if(hashset.contains(2)) {
System.out.println("Element 2 found.");
} else {
System.out.println("Element 2 not found.");
}
// iterate over the hash set
// output (order may vary):
// 1
// 3
// 4
// 5
for(int element : hashset) {
System.out.println(element);
}
}
}
Summary
The foundational knowledge covered above is sufficient for you to start practicing problems.
Java also offers many other data structures with various methods and APIs that are not introduced in this article. Advanced data structures will be gradually introduced in later sections, and the API for each structure can be looked up as needed, so there's no need to memorize everything initially.
Next, I will guide you through some LeetCode algorithm problems to quickly apply these data structures and familiarize yourself with the problem-solving system.