Methods strengthen practice
This requirement and code are at the bottom of the article.
1. Method parameter transfer
1.1 what is method parameter transfer
Concept: when using a method, the passed in value or variable is the parameter transfer.
1.2 essence of parameter transfer:
Java parameter passing:
The basic data type passes the value itself.
The reference data type passes the reference address of the variable in the heap.
1.3 value transfer
/** * Stack analysis: * The basic type is the passing of "value" * A reference type is the passing of a reference address */ public class _04StackHeap { public static void main(String[] args) { int a = 1; System.out.println("Before change:" + a); // 1 // Call the change method change(a); System.out.println("After change================ : " + a); // 1 } public static void change(int a) { a = 2; System.out.println("Changing-------: " + a); // 2 } }
Memory analysis diagram:
1.4 reference address transfer
/** * Stack analysis: * The basic type is the passing of "value" * Reference type is the passing of reference address */ public class _05StackHeap { public static void main(String[] args) { int[] arr = {1, 2}; System.out.println("Before change:" + arr[0]);// 1 System.out.println("Before change:" + arr[1]);// 2 // Call the change method change(arr); System.out.println("After change================ : " + arr[0]);// 6 System.out.println("After change================ : " + arr[1]);// 9 } public static void change(int[] arr) { arr[0] = 6; arr[1] = 9; System.out.println("Changing-------: " + arr[0]);// 6 System.out.println("Changing-------: " + arr[1]);// 9 } }
Memory analysis diagram:
2. Variable parameters
Let's first look at some requirements
Demand: 2 int The sum of variables, and return, design a method implementation /** * Find the sum of variables a and b * @param a int parameter * @param b int parameter * @return Return and */ public static int getSum(int a, int b) { return a + b; } Demand: 3 int The sum of variables, and return, design a method implementation /** * Find the sum of variables a, b and c * @param a int parameter * @param b int parameter * @param c int parameter * @return Return and */ public static int getSum(int a, int b, int c) { return a + b + c; }
You can see that the requirements for summation are similar. If there are many such requirements, we need to declare many corresponding methods to deal with them according to our previous processing method. In this way, there will be some disadvantages, such as code repetition, poor readability, and programmers need to take time to remember, so we need to optimize the code with arrays.
public class _03ChangeMethod { public static void main(String[] args) { // Requirements: find the sum of two int variables and return, and design a method implementation // Requirements: find the sum of three int variables and return, and design a method implementation // Call getSum(int[] arr) method int[] arr; arr = new int[]{1, 2}; // Find the sum of three int parameters. Now the parameters are equivalent to a statically created array int sum2 = getSum(new int[]{1, 2, 3}); System.out.println(sum2); // Find the sum of the four int parameters. Now the parameters are equivalent to a statically created array int sum3 = getSum(new int[]{1, 2, 3, 69}); System.out.println(sum3); } /** * Find the sum of all elements of int [] * @param arr int[]parameter * @return Return and */ public static int getSum(int[] arr) { int sum = 0; for (int e : arr) { sum += e; } return sum; } }
Now, although the number of parameters is uncertain, there is another problem. When passing in parameters, it is very troublesome for our programmers to create an array with parameters as elements. Therefore, we will use variable parameters to finally solve these problems.
1. Concept: a syntax that simplifies the requirement of an indefinite number of method parameters. Its essence is an array.
2. Function: simplify the code and hand over the creation of array to the compiler.
3. Syntax:
Modifier return value type method name (other data types, variables, data types... Variables){ Method body } |
Code case:
public class _03ChangeMethod { public static void main(String[] args) { // Call the getSum(int... arr) method // Find the sum of three int parameters. Now the parameters are equivalent to a statically created array int sum = getSum(1, 2); System.out.println(sum); // Call the getSum(int... arr) method // Find the sum of three int parameters. Now the parameters are equivalent to a statically created array int sum2 = getSum(1, 2, 3);// Now the array creation is handed over to the compiler, which will temporarily and statically create an array according to the passed parameters System.out.println(sum2); // Find the sum of the five int parameters. Now the parameters are equivalent to a statically created array int sum3 = getSum(1, 2, 3, 4, 5);// Now the array creation is handed over to the compiler, which will temporarily and statically create an array according to the passed parameters System.out.println(sum3); } /** * Variable parameter syntax: Modifier return value type method name (other data type variables, data type... Variables){ Method body } * Find the sum of multiple int type parameters * @param arr Variable parameters * @return Return and */ public static int getSum(int... arr) { System.out.println(arr);// address System.out.println(arr.length);// Array length int sum = 0; for (int e : arr) { System.out.println("Element:" + e); sum += e; } return sum; } }
matters needing attention:
1. Variable parameters are essentially an array, but this array is created by the compiler for our programmers.
2. A method can only have one variable parameter and can only be at the end of the formal parameter list.
3. Arrays tool class & use of API documents
3.1 what are tools
- Concept: simply think that it is just the classes that JDK or other programmers have written for us.
- Function: it can be regarded as a ready-made wheel and can be used directly, which saves programmers' time in designing classes and improves development efficiency.
Arrays is a tool class designed by JDK to specifically operate arrays.
3.2 how to use tools?
The best way to use a class designed by others is to learn how to use it through its own API manual (that is, equivalent to the manual) or Baidu.
Steps for using API Manual:
1. Click the index and enter the class Arrays to be used in the search column 2. Take a brief look at this kind of introduction. If you can understand it, you can read it. If you can't understand it, you don't care 3. Directly look at the methods in this class, and then look at the introduction and usage of the methods Modifier (modifier) has static calling method: class name Method name (argument); Type (return value type): determines what type of variable can be used to accept the result of method call Method (method name): look at the formal parameter list. When calling, you must pass in the corresponding argument Description (description and introduction of the method) 4. If you don't understand the description of the method, call the method directly to see the effect See if there is static modification. If useful: class name Method name (argument); See if there is a static modifier. If not, the object name Method name (argument); |
Common methods in Arrays class:
1. public static String toString(int[] arr) splicing elements in array, format: [value 1, value 2...] 2. public static void sort(int[] arr) sorts the elements in the array in ascending order by default. from small to large 3. public static int # binarySearch(int[] arr,int # a) queries the subscript of variable a in array arr for the first time. Returns a negative number if not found. Note: it is recommended that the array be arranged in good order and not repeated, otherwise the query results are inaccurate (both ascending and descending can be used) 4. Expansion and reduction methods of public static int [] copyof (int [] arr, int {newLength) array Capacity expansion: if the newLength is greater than the length used in the arr array, it is capacity expansion. After capacity expansion, all elements of the arr array have been copied to the new array Shrink: if the newLength is less than the length used in the arr array, it is shrink. After shrink, the arr array shrinks from back to front 5. static int[] copyOfRange(int[] arr, int from, int to) Copy the elements of the specified subscript range of the specified array arr from from to to the new array. [including head but not tail] 6. public static void fill(int[] arr,int {a) initializes the elements in array arr to a in batch |
Code case:
public class _06API { public static void main(String[] args) { // 1. Call public static String toString(int[] arr) in the Arrays class to splice elements in the array, format: [value 1, value 2...] int[] arr = {1, 69, 33, 12, 5}; // toString is called. Because it is a static modification, it is called with the array class name. The return value is of String type. Therefore, the String variable is used to receive the result String str = Arrays.toString(arr);// The error is reported because such Arrays cannot be found and the package needs to be imported // Print the return value str System.out.println(str); // Sort: 2 Public static void sort (int [] ARR) sorts the elements in the array in ascending order by default. from small to large Arrays.sort(arr); // Reassemble sorted array strings String str2 = Arrays.toString(arr); System.out.println("After sorting:" + str2); /* * 3. public static int binarySearch(int[] arr,int a)Query the subscript of variable a in array arr. Returns a negative number if not found. Note: it is recommended that the array should be arranged in order without repeating elements (both ascending and descending can be used) [1, 5, 12, 33, 69] */ int binarySearch = Arrays.binarySearch(arr, 12);// [1, 5, 12, 33, 69] System.out.println("Subscript:" + binarySearch); /* * 4. public static int[] copyOf (int[] arr, int newLength)Expansion and reduction methods of array Capacity expansion: if the newLength is greater than the length used in the arr array, it is capacity expansion. After capacity expansion, all elements of the arr array have been copied to the new array Shrink: if the newLength is less than the length used in the arr array, it is shrink. After shrink, the arr array shrinks from back to front The capacity is expanded or reduced from subscript 0 */ int[] arr2 = {1, 69, 33, 12, 5}; // Capacity expansion int[] newArr = Arrays.copyOf(arr2, 7);// Because 7 > arr2 Length, so it is capacity expansion // Splice the array newArr into strings and receive it with the String variable str3 String str3 = Arrays.toString(newArr); System.out.println("New array after capacity expansion:" + str3); // Volume reduction int[] newArr2 = Arrays.copyOf(arr2, 3);// Because 3 < arr2 Length, so it is volume reduction // Splice the array newArr2 into a String and receive it with the String variable str4 String str4 = Arrays.toString(newArr2); System.out.println("====New array after shrinking:" + str4); /* * 5. static int[] copyOfRange(int[] arr, int from, int to) Copy the elements of the specified subscript range of the specified array arr from from to to the new array. [including head but not tail] */ int[] arr3 = {1, 69, 33, 12, 5}; int[] newArr3 = Arrays.copyOfRange(arr3, 1, 3);// Intercept the elements between array arr3 with subscript 1 and array arr3 without subscript 3, and return to the new array // Splice the array newArr3 into a String and receive it with the String variable str5 String str5 = Arrays.toString(newArr3); System.out.println("Copy specified subscript 1~3 New array of intervals:" + str5); // 6. public static void fill(int[] arr, int a) initializes the elements in array arr in batch to a Arrays.fill(arr3, 996);// Batch modify all elements in array arr3 to 996 // Concatenate array arr3 into strings and receive them with String variable str6 String str6 = Arrays.toString(arr3); System.out.println("Array after batch initialization:" + str6); } }
Methods strengthen practice (demand)
/** * Method exercises */ public class _01Homework { public static void main(String[] args) { // 1. Define a method getMax, receive two int parameters and return the maximum number (low level). It is recommended to use ternary operation /* * 2 Method invocation: (most important) See whether the method to be called has static modification: 1 With static modifier, use: current class name Method name (argument (variable / value)); 2 No static modifier, use: the object name of the current class Method name (argument (variable / value)); exceptional case: If the caller (currently refers to the main method) and the callee are in the same class, and both have or do not have static modification, it can be abbreviated as: Method name (argument (variable / value)); */ int max = getMax(1, 2); System.out.println(max); System.out.println(getMax(2, 3));// You can print a method directly, but the return value type of the method must not be void. // 2. Define a method, receive three int parameters and return the smallest number (low level) // 3. Design a method to find the product of three int types and return the product (low level) // 4. Design a method to pass in an int array and return the largest value in the array (intermediate) int[] arr = {1, 9, 96, 9, 6, 66}; // Call the getMaxInArray method int maxInArray = getMaxInArray(arr); System.out.println("Maximum value in array:" + maxInArray); // 5. Design a method, pass in a parameter name and a parameter hobby, and print out a sentence: name's hobby is: hobby // ===============================Choose to do========================== /* * 6.Design a method to query and return the position of the first occurrence of a character in the character array (Advanced) char[] arr2 = {'a', 'b', 'c', 'a', 'g'}; char c = 'a'; Four elements: Return value type: int Method name: getIndexInArray() Formal parameter list: char c, char[] arr Method body: Traverses the entire array, returns the subscript i if c and arr[i] are equal If not found after traversal, return - 1 subscript range: 0,n */ char[] arr2 = {'a', 'b', 'c', 'a', 'g'}; char c = 'g'; int indexInArray = getIndexInArray(arr2, c); System.out.println("Subscript:" + indexInArray); // 7. Design a method to count the number of times a character appears in the character array (Advanced) // 8. Design a method to return the odd sum of the integer array int[] arr = {1,2,3,4,5,6,7,8,9,11,12} int[] arr3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12}; // Calling method: getOddSum int oddSum = getOddSum(arr3); System.out.println("Odd sum:" + oddSum); /* * 9.Now there is an array double[] scores = {11,34,76,77,88,99,58,97,56}; Define a method to count and print out the students at each stage * Number (segmentation method: 0-60; 60-80; 80-100) (Advanced) */ double[] scores = {11, 34, 76, 77, 88, 99, 58, 97, 56}; printScores(scores); // The return value is void, which can be called and executed directly // 10. Design a method to pass in an int array, flip the elements in the array, and return the inverted array (cowhide) // Calling method: reverse int[] reverse = reverse(arr3); for (int e : reverse) { System.out.println(e); } // Printing arrays is meaningless. So, with this requirement // 11. Requirements: please design a method toString, pass in an int [], and splice the array into strings. The format is as follows: [element 1, element 2, element 3...], Returns the spliced string System.out.println(reverse); // Calling: toString method String str = toString(reverse); System.out.println(str); } /** * 1.Define a method getMax, receive two int parameters and return the maximum number (low level). It is recommended to use ternary operation * Method declaration (definition): (most important) 1. In the current class, under the main method, write public + alt + / and select the third one 2. According to the four elements of the demand analysis method: 1. Return value type: int 2. Method name: getMax 3. Formal parameter list: int a, int b 4. Method body: three eye operation, find the maximum value, and return 3. Modify the four elements of the method according to the actual needs * @return */ public static int getMax(int a, int b) { // If you use an if else statement // if (a > b) { // return a; // } else { // return b; // } return a > b ? a : b;// It is the operation with the lowest priority. Return will be executed after performing the trinomial operation to return the result } /** * 4.Design a method to pass in an array of int and return the maximum value in the array (intermediate)] * Method declaration (definition): (most important) 1. In the current class, under the main method, write public + alt + / and select the third one 2. According to the four elements of the demand analysis method: 1. Return value type: int 2. Method name: getMaxInArray 3. Formal parameter list: int[] arr 4. Method body: foreach Traverse the array arr, find a temporary variable to save the maximum value max, and each cycle is compared with the array element e. if it is larger than max, re assign Max to e. after the cycle ends, find the maximum value, and then return the maximum value max 3. Modify the four elements of the method according to the actual needs * @return */ public static int getMaxInArray(int[] arr) { // Judge whether the parameter arr is not null first. If it is not null, the execution can continue // Declare an int type max, assign the first element arr[0], and save the maximum value traversed int max = arr[0]; // foreach traversal array arr for (int e : arr) { // Each loop max is compared with the array element e if (e > max) {// If e is greater than max, re assign Max to E max = e; } } // After the loop ends, the maximum value is found, and then the maximum value max is returned return max; } /** * 6.Design a method to query and return the position of the first occurrence of a character in the character array (Advanced) * @return */ public static int getIndexInArray(char[] arr, char c) { // First judge whether the parameter arr is non null. If it is non null, the execution can continue. Otherwise, a null pointer exception may occur. if (arr == null) { return -1;// Any negative number means not found } // Traversal array for (int i = 0; i < arr.length; i++) { // Judge whether each element arr[i] is equal to parameter c if (c == arr[i]) { return i;// If equal, returns the current subscript directly } } // If the end of the loop is not returned, the certificate is not found, and - 1 is returned return -1; } /** * 8.Design a method to return the odd sum of int[] arr = {1,2,3,4,5,6,7,8,9,11,12} * @return */ public static int getOddSum(int[] arr) { // Non null judgment can be solved by throwing exceptions in the future. It doesn't matter now int sum = 0; // Traversal array arr for (int e : arr) { // Determine whether the current e is an odd number if (e % 2 != 0) { sum += e; } } return sum; } /** * 9.Now there is an array double[] scores = {11,34,76,77,88,99,58,97,56}; Define a method to count and print out the students at each stage * Number (segmentation method: 0-60; 60-80; 80-100) (Advanced) * @return */ public static void printScores(double[] scores) { // Non null judgment is not written int countC = 0;// Declare 0-60 counters int countB = 0;// Claim 60-80 counters int countA = 0;// Claim 80-100 counters // Traverse array scores for (double e : scores) { // Determine which stage element e belongs to if (e >= 0 && e < 60) { countC++; } else if (e >= 60 && e < 80) { countB++; } else if (e >= 80 && e <= 100) { countA++; } else { System.out.println("Wrong score!"); } } System.out.println("0-60 Number of persons:" + countC + " 60-80 Number of persons:" + countB + " 80-100 Number of persons:" + countA); } /** * 10.Design a method to pass in an int array, flip the elements in the array, and return the inverted array (cowhide) * @return */ public static int[] reverse(int[] arr) { // Non null judgment is not written // Ordinary for loop traverses array arr for (int i = 0; i < arr.length / 2; i++) {// The number of cycles is known by drawing // Through drawing, we can know the subscript relationship of exchange // Just swap the closed elements int temp = arr[i];// Declare a temporary variable temp and assign it as arr[i] arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } // Return array arr return arr; } /** * 11.Requirements: please design a method toString, pass in an int [], and splice the array into strings, * The format is as follows: [element 1, element 2, element 3...], Returns the spliced string * Idea: to traverse the array, string splice the array elements * Steps: * 1. Declare a String type str with a value of "[", which is used to splice strings * 2. Traverse the array num, initialize the condition, start with subscript 0, and end the condition to the penultimate element * In each loop, the obtained element nums[i] is spliced into str, and then a comma is spliced * 3. After the loop is completed, splice the last element num [num.length - 1] to the end of the splice] * @param arr * @return */ public static String toString(int[] arr) { // Non null judgment is not written // 1. Declare a String type str, with a value of "[", which is used to splice the String String str = "["; // 2. Traverse the array arr, initialize the condition, start with subscript 0, and end the condition to the penultimate element for (int i = 0; i <= arr.length - 2; i++) { // In each loop, the obtained element arr[i] is spliced into str str += arr[i] + ", "; } // System.out.println(str); // 3. After the cycle ends, splice the last element arr[arr.length - 1], and the splicing ends] str += arr[arr.length - 1] + "]"; return str; } }
The next chapter is object oriented