Day 11 : Function

Chi-Tse Chiang
2022-09-26 13:22:10

Intro

The first seven chapters introduce the basic syntax of Java, and then introduce another important concept: functions.

Whether you are a novice or an engineer writing a program, you will encounter a very long code with many functions and variables to design. The solution at this time is to cut these requirements into different sub-blocks in the program. These sub-blocks may be the integration of functions or content that is constantly called. We call this a function.
When a problem needs to be solved, the corresponding function can be called directly, and these functions must belong to a class. There are two types of methods according to their usage:

1. static execution method

2. object execution method
The main difference between the two is that static methods do not require the creation of an object and can be accessed directly through the class. In contrast, an object must be created through the class before it can be called.

Function

Here, we will continue to introduce several important concepts:

1. Return value (return value)
After calling a function, the function returns the content. The return value type must be set when the function needs to be notified.

2. Arguments and Parameters (Arguments and Parameters)
Arguments are the values passed in when a function is called, and parameters are the variables in the function that receive the arguments.

3. Access Type
Static or object implementation method

Access_Type Return_Value_Type Function_Name (Parameters){
		/*.................
		...Description...
		.................*/
		return value;       //Not necessary
}

static void MyFirstMethod(){
	System.out.println("Hello World!");
}

Program analysis: Looking at the above code, we can see that there are no parameter values or return contents. Because when we call this function in the main program or other functions, if no arguments are passed in, it means that this part does not need to receive any variables. And because we declare the return value type of this function as void, we don't need to return anything to the variables that originally called this function.

Return Value Type : void byte short int long float double String char
Access Type : public private default protected static

public class Main{
	static int Compare(int Agrade,int Bgrade){
		int winner;
		winner = Math.max(Agrade,Bgrade);
		return winner;
	}
	public static void main(String[] args){
		int[] student={0,0};
    int temp,winner;
		for(temp=0 ; temp<2 ; temp++){
			student[temp] = (int)(Math.random() * 101 );
		}
		winner = Compare(student[0],student[1]);
		System.out.println("The highest grade is : " + winner);
	}
}

Program analysis: Using the concept of a function to compare the magnitudes of two random variables, two arguments are passed in, stored in the Agrade and Bgrade parameters, and finally returned to the main program's winner to receive.