1. Method
java methods are collections of statements that together perform a function
- Method is an ordered combination of steps to solve a class of problems
- Method contained in class or object
- Methods are created in programs and referenced elsewhere
Principle of design method: Only one function is accomplished by one method, which is beneficial to our later expansion.
Definition of method
Modifier return type Method Name(Parameter Type Parameter Name){ ... Method Body ... return Return value; }
package com.kuang.method; public class Demo01 { //main method public static void main(String[] args) { int sum = add(1,2); System.out.println(sum); } //addition public static int add(int a,int b){ return a + b; } }
Note: Method return values are implemented by the return statement. If there is no return value and the return value type is set to void, return can be omitted.
Method invocation using: "Class name."
package com.kuang.method; public class Demo02 { public static void main(String[] args) { int a = max(10,10); System.out.println(a); System.out.println("==========="); //Use class name. Method call int b = Demo02.max(26,78); System.out.println(b);//78 System.out.println("==========="); System.out.println(Demo02.max(10,20));//20 } //Ratio Size public static int max(int num1,int num2){ int result; if (num1 == num2){ System.out.println("num1 == num2"); return 0;//Termination Method } if (num1 > num2){ result = num1; }else { result = num2; } return result; } }
2. Method overload overlord
An overload is a function in a class that has the same function name but different parameters
Rules for method overload:
- In the same class and method names must be the same
- The list of parameters must be different (different numbers of parameters, different types of parameters, different order of parameters)
//Example: Method overload simplifies output statements public class s{ public static void p(){ System.out.println(); } public static void p(byte b){ //Output byte type System.out.println(b); } public static void p(short s){ //Output short type System.out.println(s); } public static void p(int i){ //Output int type System.out.println(i); } public static void p(long l){ //Output long type System.out.println(l); } public static void p(float f){ //Output float type System.out.println(f); } public static void p(double d){ //Output double type System.out.println(d); } public static void p(Boolean b){ //Output boolean type System.out.println(b); } public static void p(char c){ //Output char type System.out.println(c); } public static void p(String s){ //Output String Type System.out.println(s); } } /*Result achieved: System.out.println("Hello World!") s.p("Hello World!") The purpose of method overloading: Functionally similar methods use the same name, are easier to remember, and therefore are easier to call. */
3. Variable parameters (Understanding)
JDK1.5 Beginning, java supports passing variable parameters of the same type to a method
In the method declaration, add an ellipsis (...) after specifying the parameter type
Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any common parameter must be declared before it.
package com.kuang.method; public class Demo04 { public static void main(String[] args) { Demo04 demo04 = new Demo04(); demo04.test(1,2,3,4,5); } // public void test(int...i,int x) will fail ///public void test(int a,int...i) can public void test(int...i){ System.out.println(i[0]); } }
4. Recursion
Recursion is the method itself calling itself
The recursive structure consists of two parts:
- Recursive header: When to not call its own method. If there is no head, it will fall into an endless loop.
- Recursive body: When you need to call your own method.
package com.kuang.method; public class Demo05 { public static void main(String[] args) { System.out.println(f(5));//120 } //Factorial //1! 1 //2! 2*1 //5! 5*4*3*2*1 public static int f(int n){ if (n == 1) {//End condition return 1; }else { return n * f(n-1); //If 2:2 2 2 * f(1) is passed //If 3:3 3 3 * f((2) } } }
Use recursive calculation 1~N And Public static void main(String[] args){ Int revalue = sum(3); System.out.println(reValue); } Public static int sum(int n){ if(n == 1){//End condition return 1; } return n + sum(n - 1); }
Note: When using recursion, an end condition must be added or a stack memory overflow (StackOverflowError) will occur.
Reason: Stacked all the time, no stack, not enough stack memory
What about a stack memory overflow caused by recursion in actual development?
- Check that the end condition is correct
- If correct, you can adjust the stack memory size of the JVM (java-X)
5. Arrays
-
An array is an ordered collection of data of the same type. Arrays describe several data of the same type, arranged and combined in a certain order. Each data is called an array element, and each array element can be accessed through a subscript.
-
Element memory addresses in arrays are contiguous
-
The memory address of the first element in the array is the memory address of the entire array object
Array variables must be declared before they can be used in programs. Here is the syntax for declaring array variables:
dataType[] arrayRefVar;//Preferred method //or dataType arrayRefVar[];//The effect is the same, but not the preferred method //The java language uses the new operator to create arrays with the following syntax: dataType[] arrayRefVar = new dataType[arraySize];
Each element in the array has a subscript, starting at 0, increasing by 1, and the last element has a subscript of length-1
Get the length of the array: arrays.length
package com.kuang.array; public class ArrayDemo01 { public static void main(String[] args) { int[] nums;//1. Declare an array //int nums2[]; The style of early java favoring C and c++. //2. Create an array nums = new int[10];//Here you can store 10 int s of numbers //3. Assigning values to array elements nums[0] = 1; nums[1] = 2; nums[2] = 3; System.out.println(nums[0]);//1 System.out.println(nums[1]);//2 System.out.println(nums[2]);//3 System.out.println(nums[3]);//0, no assignment will be the default //Calculate the sum of all elements int sum = 0; //Get the length of the array: arrays.length for (int i = 0; i < nums.length; i++) { sum += nums[i]; } System.out.println("The sum is:" + sum);//The sum is: 6 } }
//String Array //Strings are reference types, so we define an array of strings: String[] names = { "ABC","XYZ","Zoo" };
Advantages and disadvantages of arrays
Advantages: It is extremely efficient to query/find/retrieve elements on a subscript
Reason:
-
The memory address of each element is continuous in spatial storage
-
Each data type is the same, so it takes up the same amount of space
-
Knowing the memory address of the first element, the size of space occupied by each element, and the subscript, you can calculate the memory address of a subscript element by a mathematical expression and locate the element directly by the memory address
Disadvantages: Random additions and deletions are inefficient
Reason:
-
To ensure that the memory address of each element in the array is continuous, it is inefficient to randomly delete or add elements to the array because random addition or deletion of elements involves the forward or backward displacement of subsequent elements.
-
Arrays cannot store large amounts of data because it is difficult to find an extremely large contiguous block of memory space
Java Memory Analysis
- Heap: Objects and arrays that hold new, which can be shared by all threads, without other object references
- Stack: The variable that holds the basic variable type (containing the specific value of the basic type), the variable that references the object (the specific address inside the reference heap)
- Method area: can be shared by all threads, including all class and static variables
Three initializations of arrays: static, dynamic, and default
package com.kuang.array; public class ArrayDemo02 { public static void main(String[] args) { //Static Initialization: Create + Assign int[] a = {1,2,3,4,5,6,7,8}; System.out.println(a[0]);//1 //Dynamic Initialization: Include Default Initialization int[] b = new int[10];//Manual assignment or default b[0] = 10;//assignment System.out.println(b[0]);//10 System.out.println(b[1]);//0 } }
//Declare an array of type int, using static initialization int[] a = {1,100,10,20,55,689}; //All array objects have a length property System.out.println("Number of elements in the array:" + a1.length);//6 //Each element in the array has a subscript //Store and fetch elements in an array with Subscripts //Take (Read) System.out.println("First element=" + a[0]);//1 System.out.println("Last element=" + a[5]);//689 System.out.println("Last element=" + a[a.length - 1]);//689 //Save (change), change the first element to 111 a[0] = 111; //Modify the last element to zero a[a.length - 1] = 0; System.out.println("First element=" + a[0]);//111 System.out.println("Last element=" + a[5]);//0
Four basic characteristics of arrays
- The length is fixed, and once the array is created, the size cannot be changed
- Its elements must be of the same type, no mixed type allowed
- Elements in an array can be of any data type, including basic and reference types
- Arrays are of reference type and can also be considered objects. Each element in the array corresponds to a member variable of the object. The array object itself is stored in the heap.
Array Boundary
Subscript's legal range: [0,length - 1], error if out of bounds
ArrayIndexOutOfBoundsException: Array subscript out of bounds exception!
Use of arrays
Normal for Loop and For-Each Loop
Ordinary for loop traversal
package com.kuang.array; public class ArrayDemo03 { public static void main(String[] args) { int[] arrays = {1,2,3,4,5}; //Print all array elements for (int i = 0; i < arrays.length; i++) { System.out.println(arrays[i]); } System.out.println("=============="); //Calculate the sum of all elements int sum = 0; for (int i = 0; i < arrays.length; i++) { sum += arrays[i]; } System.out.println("sum = " + sum); //Find the largest element int max = arrays[0]; for (int i = 1; i < arrays.length; i++) { if (arrays[i] > max){ max = arrays[i]; } } System.out.println("max = " + max); } }
foreach traversal
package com.kuang.array; public class ArrayDemo04 { public static void main(String[] args) { int[] arrays = {1,2,3,4,5}; //foreach traversal, no Subscripts for (int array: arrays) { System.out.println(array); } } }
Multidimensional Array
Multidimensional arrays can be viewed as arrays of arrays. For example, a two-dimensional array is a special one-dimensional array, each element of which is a one-dimensional array.
2-D Array
int a[][] = new int[2][5]; //Parse: The two-dimensional array a above can be seen as a two-row, five-column array
package com.kuang.array; public class ArrayDemo05 { public static void main(String[] args) { //[3][2]:3 rows and 2 columns /* 1,2 a[0] 3,4 a[1] 5,6 a[2] */ int[][] a = {{1,2},{3,4},{5,6}}; System.out.println(a[0][0]);//1 System.out.println(a[0][1]);//2 System.out.println(a[1][0]);//3 System.out.println("=========="); System.out.println(a.length);//3: Represents 3 rows System.out.println(a[0].length);//2: Represents 2 columns System.out.println("=========="); //Two-dimensional array traversal for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.println(a[i][j]); } } } }
One-dimensional array expansion
Expansion is to create a new large-capacity array and then copy the data from the small-capacity array one by one into the large array.
Note: Array expansion efficiency is extremely low
public class ArrayTest08 { public static void main(String[] args) { //Copy methods in java //System.arraycopy(5 parameters); int[] src = {1,11,22,3,4};//Source Copy int[] dest = new int[20];//Copy target, dynamically initializing an array of length 20 //Call arraycopy method System.out.println(src,srcPost:1(Copy Source Start Location),dest,destPos:3(Copy to location),length:2(Copy Length)); //foreach for(int i = 0; i < dest.lentgh; i++){ System.out.rptinln(dest[i]);//0 0 0 11 22...0 } //Source Copy String[] strs = {"hello","world!","java","oracle","mysql","jdbc"}; //Copy Target String[] newStrs = new String[20]; System.arraycopy(strs,0, newStrs, 0, strs.length); for (int i = 0; i < newStrs.length; i++) { System.out.println(newStrs[i]); } } }
6.Arrays class
Array's tool class java.util.Arrays
Methods in the Arrays class are static methods decorated with static, which can be called directly with the class name when used
It has the following common functions:
- Assigning values to arrays: through the fill method
- Sort arrays in ascending order using the sort method
- Compare arrays: Compare the values of elements in an array by the equals method
- Find Array Elements: Binary search on sorted arrays using binarySearch
package com.kuang.array; import java.util.Arrays; public class ArrayDemo06 { public static void main(String[] args) { int[] a = {1,2,3,4,9090,31231,543,21,3,23}; System.out.println(a);//[I@154617c //Print array elements: Arrays.toString System.out.println(Arrays.toString(a));//[1, 2, 3, 4, 9090, 31231, 543, 21, 3, 23] Arrays.sort(a);//Sort arrays: ascending System.out.println(Arrays.toString(a));//[1, 2, 3, 3, 4, 21, 23, 543, 9090, 31231] Arrays.fill(a,0);//Array Fill System.out.println(Arrays.toString(a));//[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Arrays.fill(a,2,4,1);//Fill elements between subscripts 2 and 4 with 1 System.out.println(Arrays.toString(a));//[0, 0, 1, 1, 0, 0, 0, 0, 0, 0] } }
7. Bubble sort
Bubble sorting is undoubtedly one of the most famous sorting algorithms, with a total of eight sorts
package com.kuang.array; import java.util.Arrays; //Bubble sort /* 1.Comparing two adjacent elements in an array, if the first number is larger than the second, we swap their positions 2.Each comparison produces a maximum or minimum number 3.Ordering may occur less often in the next round 4.Loop in turn until the end */ public class ArrayDemo07 { public static void main(String[] args) { int[] a = {6,4,2,1,26,78}; int[] sort = sort(a); System.out.println(Arrays.toString(a));//[1, 2, 4, 6, 26, 78] } public static int[] sort(int[] array){ //Temporary variable int temp = 0; //Outer loop, judge how many times we're going to go here for (int i = 0; i < array.length - 1; i++) { //Inner loop, compare and judge two numbers, swap positions if the first number is larger than the second for (int j = 0; j < array.length - 1 - i; j++) { if (array[j + 1] < array[j]){//From large row to small, just change <to> temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } return array; } }