🎛 Flow Control#
Branch Statements#
- Single Branch
- Double Branch
- Multiple Branches
if-else#
switch-case#
switch (x) {
case y:
zzz;
break;
case a:
bbb;
break;
default:
ccc;
}
x
can be of type byte
, short
, int
, or char
Starting from Java SE 7, it also supports the String
type, and the case labels must be string constants or literals.
If break
is not used, case fall-through will occur.
Loop Statements#
Three elements
- Initial value
- Termination condition
- Step size
Counting Loop#
for (initial value; termination condition; step size) {
}
The initial value is executed first (only once), followed by the termination condition. The loop terminates when the condition is false
.
Conditional Loop#
while () {
}
do {
} while ()
At least one iteration is guaranteed.
Jump Statements#
- continue: Skips the current iteration of the loop
- break: Terminates the current loop
outfor: for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == 3) {
// continue a;
break outfor;
}
System.out.print(0 + " ");
}
System.out.println();
}
🍂 Methods#
A collection of code that creates a space to store and name it, which can be accessed by its name. The purpose is to achieve code reuse, easy maintenance, easy extension, and flexibility. Multiple modifiers can be set.
Modifier List#
Optional, can have multiple modifiers (some cannot appear together). The order of multiple modifiers does not matter.
Access Control#
- public
- private
- protected
- blank (default package access)
Choose one of the four
static
indicates static, if not added, it is a member method
final
and abstract
cannot appear together
Return Value#
Purpose of return#
- Terminate the execution of the method
- Return data to the caller
If there is no return value and there is a return statement, the method execution will only be terminated without returning any data.
Types#
- Static Method: A variable in the class body that is modified by
static
- Member Method: A variable in the class body that is not modified by
static
- Constructor Method
Invocation#
Prefix.methodName(parameters)
The method is executed when it is called, and the result is returned to the caller.
- Static Method:
ClassName.methodName(parameters)
. If calling a static method in the current class, the class name can be omitted. - Member Method:
object.methodName(parameters)
Overloading#
The same method name with different parameter lists (different number or type of parameters)
Recursion#
Recursion is equivalent to iteration (looping)
Recursion and iteration are equivalent, iteration is a basic idea of looping
Recursion can do what loops can do, but loops cannot do what recursion can do
Generally, tree structures can be traversed, queried, and other operations using recursion
Recursion requires frequent stack pushing and popping, which consumes a lot of memory and is inefficient, so if loops can do it, recursion should not be used
If loops can do it, recursion should not be used, unless loops cannot do it
For example: Get all files in a directory (including files in subdirectories)
For example, tree structures and directory traversal all need to be done using recursion
There must be initial value, termination condition, and step size, otherwise it will cause an infinite loop (stack overflow, no stack popping)
- Direct Recursion
- Indirect Recursion
📚 Arrays#
Placed in heap memory, reference type, built-in object
Fast memory address lookup, modification
Continuous storage, array length cannot be changed
Data Structure#
The way data is stored and organized in a computer. Data structure is a collection of data elements that have a certain logical relationship, apply a certain storage structure in a computer, and encapsulate the corresponding operations. It includes three aspects: logical relationship, storage relationship, and operations.
Declaration#
- Static Declaration
data type[] variable name = {value, value, value, value}
data type variable name[] = {value, value, value, value}
- Dynamic Declaration
data type variable name[] = new data type[length]
Not recommended
data type[] variable name = new data type[length]
data type[] variable name = new data type[length]{value, value, value, value}
Array Usage#
Length: array.length
Query: array[index]
Traversal: fori
Pass by Value and Pass by Reference#
Pass by Reference
Array Copy#
Replace and Merge
System.arraycopy(source array, starting position of source array, target array, starting position of target array, number of elements to copy)
Sorting#
Bubble Sort#
Algorithm Steps#
- Compare adjacent elements. If the first is greater than the second, swap them.
- Repeat the above step for each pair of adjacent elements, from the first pair to the last pair. After this step, the largest element will be at the end.
- Repeat the above steps for all elements except the last one.
- Continue the steps until no more swaps are needed, indicating that the list is sorted.
import java.util.Arrays;
public class BubbleSort {
public int[] sort(int[] sourceArray) {
// Make a copy of the array to avoid modifying the original array
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
for (int i = 1; i < arr.length; i++) {
// Set a flag, if true, it means no swaps were made in this iteration, indicating that the sorted sequence is already completed.
boolean flag = true;
for (int j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}
}
Selection Sort#
Algorithm Steps#
- Find the minimum (or maximum) element in the unsorted part of the list and swap it with the first element in the unsorted part.
- Move the boundary of the sorted part one element to the right.
- Repeat the above steps until the entire list is sorted.
public class SelectionSort {
public void sort(int[] arr) {
int minIndex;
for(int i = 0;i < arr.length;i++) {
minIndex = i;
// Traverse to find the index of the minimum value in the unsorted part
for(int j = i;j < arr.length;j++) {
if(arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// If the index of the minimum value is not the same as the leftmost index in the unsorted part, swap them
if(minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
}
Searching#
Linear Search#
Binary Search#
Also known as binary search
Search Steps#
Compare with the middle element each time
If the target value is greater than the middle value, the ending index remains the same, and the starting index is set to the middle index + 1, then generate the middle index again.
If the target value is less than the middle value, the starting index remains the same, and the ending index is set to the middle index - 1.
When the starting index is greater than the ending index, terminate the search, indicating that the data does not exist.
- Disadvantage: It must be based on a sorted list.
- Advantage: Because each time only half of the data is selected, the efficiency is relatively high, and the query performance is relatively balanced regardless of whether the data is near the beginning or the end.
public class Search {
public int binarySearch(int[] array, int target) {
// Default starting index
int startIndex = 0;
// Default ending index
int endIndex = array.length - 1;
// Default middle index
int index = (startIndex + endIndex) / 2;
for (int i = 0; i < array.length; i++) {
// If the target value is greater than the middle value, the ending index remains the same, the starting index is set to the middle index + 1, then generate the middle index again.
if (target > array[index]) {
startIndex = index + 1;
// If the target value is less than the middle value, the starting index remains the same, the ending index is set to the middle index - 1.
} else if (target < array[index]) {
endIndex = index - 1;
} else if (target == array[index]) {
return index;
}
index = (startIndex + endIndex) / 2;
}
return -1;
}
}