方法是程序中最小的执行单元
看到方法就进入方法,进入完回到调用处
public static void main(String[] args) {
//调用方法
playgame();
}
//定义方法
public static void playgame(){
int a=3;
int b=4;
System.out.println(a+b);
}
public static void main(String[] args) {
gerArea(3.0);
}
public static void gerArea(double raids){
double area=raids*raids*3.14;
System.out.println(area);
}
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-02_15-56-26.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-02_15-57-00.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-02_15-58-17.png)
public static void main(String[] args) {
int sum=getsum(2,4);
System.out.println(sum);
}
public static int getsum(int a,int b){
int result=a+b;
return result;
}
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-02_16-20-30.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-02_16-20-52.png)
方法的重载
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-02_16-31-20.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-02_16-32-42.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-02_16-38-08.png)
public class method_test6 {
public static void main(String[] args) {
compare((byte) 1,(byte) 2);
}
//会把相同功能的方法名起成一样
//好处:定义方法的时候不需要那么多单词,并且调用方法也不需要name麻烦了
public static void compare(byte b1,byte b2){
System.out.println(b1==b2);
}
public static void compare(short b1,short b2){
System.out.println(b1==b2);
}
public static void compare(int b1,int b2){
System.out.println(b1==b2);
}
public static void compare(long b1,long b2){
System.out.println(b1==b2);
}
练习
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_00-27-07.png)
public static void main(String[] args) {
int arr1 []={1,2,3,4,5,6,7,8,9};
int [] arr_new=copy(arr1,2,5);
for (int i = 0; i < arr_new.length; i++) {
System.out.println(arr_new[i]);
}
}
public static int[] copy(int [] arr,int from,int to){
int [ ] new_arr=new int[to-from];
int index=0;
for (int i = from; i < to; i++) {
new_arr[index]=arr[i];
index++;
}
return new_arr;
}
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-32-58.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-35-52.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-38-50.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-41-12.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-41-55.png)
方法的值传递
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-44-20.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-45-54.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-46-51.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-49-03.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-50-23.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-50-48.png)
ipaste_2023-05-03_01-50-23.png)
[外链图片转存中…(img-ItoiNNuH-1683117415215)]!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-50-48.png)
!](C:/Users/Lenovo/Desktop/代码图片/Snipaste_2023-05-03_01-51-23.png)