Methods and arrays in Java

Table of contents

1.Methods in Java

1.1 Creation and format of methods

1.2 Method calling format

2.Array

2.1 Basic concepts of arrays

2.2 Array declaration

2.3 Creation of array

2.4 Length of array

3. Array access and iteration

3.1 Access to array elements

3.2 Iteration of array elements

4. Sorting of arrays

4.1 Bubble sort

 4.2 Selection sorting

5. Two-dimensional array

5.1 Creation of two-dimensional array

5.2 Assignment of two-dimensional arrays

5.3 Traversal of two-dimensional arrays


1.Methods in Java

1.1 Creation and format of methods

[访问权限修饰符 修饰符][返回值类型]方法名(形式参数类型 参数名){
        Java语句;
        [return 返回值;]
}
Modifier:         is optional and is used to tell the compiler how to call the method. Defines the access type for this method.
Formal parameters : used to receive external input data when the method is called.
Actual parameters:            The data actually passed to the method when calling the method.
Return value:        The data returned by the method to the environment that called it after completion of execution.
Return value type: The data type of the return value agreed in advance. If there is no return value, the return value type void must be given .
eg:
// 调用时候直接调用方法名
// void:表示无返回值
public static void hello(){
      System.out.println("Hello!");
}

 Define a method with no parameters and no return value.
       Public static is a fixed writing method
       . void means that this method has no return value
       . hello method name
       () parameter list can be empty.

Method: A collection of code used to solve a certain problem, which can be called multiple times.

 Define a method with parameters and return value

 public static int max(int a,int b){
//        比较大小
        int max=(a>b)?a:b;
        return max;
    }

When calling this method, parameters must be input, but it should be noted that the input parameter format needs to be the same as the data type defined in the method.

For example: In this code, the data types of a and b defined are integer types. When you give parameters, you cannot give parameters larger than int type or floating point type or character type, etc., so the system will report an error. .

1.2 Method calling format

When calling a method: use the class name where the method is located + .+ method name.

eg: Call the method created by the above code, let the class be FangFa,

Fangfa.max();

When the code is executed at this time, the method created by you will be called.

public class FangFa {
    public static void main(String[] args) {
        int a=FangFa.max(8,5);//调用比较大小的方法,将方法中返回的值赋给变量a。
        System.out.println(a);
    }
}
public static int max(int a,int b ){
        int max = (a>b)?a:b;
        return max; 
}

return max: Return the result after method processing through the return keyword. One is to terminate the method, and the other is to return the result.

In methods that do not return, you can also use the return keyword, but there cannot be other expressions after return. Its function is to terminate the method.

eg:

public  static void hello(String name){
          if(name==null){
              return;
}

Here, when calling the method, you need to enter name in the console. If you do not enter, you will enter the if statement. The return at this time plays the role of terminating the method.

2.Array

2.1 Basic concepts of arrays

  • An array is a collection of elements of the same data type.
  • The array itself is a reference data type, that is, an object.
  • Arrays can store both basic data types and reference data types.  

2.2 Array declaration

There are two forms of array declaration:

  1. Data type [ ] array name eg: int [ ] a;
  2. Data type array name [ ] eg: int a [ ];

Note: There is actually no difference between these two forms, but in order to avoid confusing the data type of a in Java, the first one is used as much as possible.

eg: int a [ ] b; //a here represents an array, and b represents an integer variable.

2.3 Creation of array

There are three forms of array creation:

  1. When declaring an array, memory is allocated according to the length of the elements in the array, but the element values ​​in the array are all default initialization values ​​eg: int [ ] a = new int [10]; 
  2. Declare the array and allocate memory, while initializing it. eg: int [ ] a = new int [ ]{1,2,3};
  3. The same as the previous method, the syntax is relatively simple. eg: int [ ] a = {1,2,3};

 Note: Once the capacity of an array in Java is determined when it is created, the capacity cannot be modified.

The creation of arrays can also be divided into two forms: dynamic and static:

  1. Dynamically create an array (no array elements are given) eg: int [ ] a = new int [3]; When you do not assign a value to the array, the default element in the array is 0.
  2. Create an array statically (assign a value to the array when creating it)

2.4 Length of array

length attribute:

int a [ ] = {1,2,3,4,5,6};

System.out.println(a.length);//The output is the length of array a.

Output: 6 

3. Array access and iteration

3.1 Access to array elements

Array name [index]; eg: a[0],a[1];

Notice:

  • The index of the array starts from 0.
  • The data type of the index is integer
  • The maximum index value and the array length always differ by 1

3.2 Iteration of array elements

The first type: for loop

int [] a = {1,2,3,4};
for(int i=0;i<a.length;i++){
     System.out.println(Arrays.toString(a[i]));
}

Second type: Enhanced for loop

int [] a = {1,2,3,4};
for(int t:a){
     System.out.println(t);
}

4. Sorting of arrays

4.1 Bubble sort

Principle: Take out two adjacent elements for comparison each time, put the larger one at the back and the smaller one in the front. Sort each time to get the largest element.
Thought:

{5,4,3,2,1}

4,3,2,1,5

3,2,1,4,5

2,1,3,4,5

1,2,3,4,5

code show as below:
int [] a = {5,4,3,2,1};
for(int i = 0;i < a.length-1;i++){   //外循环,表示循环次数
    for(int j = 0;j < a.length-1-i;j++){   //内循环,外循环一次取出当前最大值,在内循环时候就少判断一次
       if(a[j]>a[j+1]){
           int t = a[j];
           a[j] = a[j+1];
           a[j+1] = t; 
      }
   }
System.out.println(Arrays.toString(a));
}

 4.2 Selection sorting

Principle: Selection sorting is to compare two adjacent elements, put the smaller element in front, and then use the smaller element to sort with the next element, and select the current smallest element at a time.

Thought:

          [3 ,1 ,2 ,5 ,4]
          1 ,3 ,2 ,5 ,4
          1 ,2 ,3 ,5 ,4
          1 ,2 ,3 ,5 ,4
          1 ,2 ,3 ,4 ,5

code show as below:

            int [] a = {3,1,2,5,4};
            for (int i = 0; i < a.length-1; i++) {
                for (int j = i+1; j <a.length; j++) {
                    if(a[i]>a[j]){
                        int t = a[i];
                        a[i] = a[j];
                        a[j] = t;
                    }
                }
                System.out.println(Arrays.toString(a));
            }

5. Two-dimensional array

5.1 Creation of two-dimensional array

The creation of a two-dimensional array is similar to a one-dimensional array:

Data type [ ] [ ] array name = new data type [capacity of one-dimensional array] [number of elements in each one-dimensional array];

eg:

int [ ] [ ] a = new int [3][5]; //Once the capacity is determined, it cannot be changed

5.2 Assignment of two-dimensional arrays

There are two types:

  1. int  [] [] a = { {1,2.3},{1,2,3},{1,2,3}};
  2. int [] [] a = new int [] []{ {1,2,3},{1,2,3},{1,2,3}};

5.3 Traversal of two-dimensional arrays

The traversal of a two-dimensional array can also use a for loop, but it requires double nesting:

public static void main(String[] args) {
            int [][] a = {
     
     {1,2,3},{4,5,6},{7,8,9}};
            for (int i = 0; i < a.length; i++) {        //a.length就是二维数组中一维数组的长度
                for (int j = 0; j <a[i].length; j++) {
                    System.out.print(a[i][j]+" ");
                    }
                System.out.println();
                }
            }

Notice:

You need to practice more when learning Java, come on!

Guess you like

Origin blog.csdn.net/weixin_69778508/article/details/130033432