实例
1.无参数无返回值类型:
public class Demo {
public static void main(String[] args) {
fun();
}
public static void fun() {
System.out.println("你好世界");
}
2.没有参数有返回值类型(注意:return返回值的数据类型与定义方法的返回值类型有关):
public class Demo {
public static void main(String[] args) {
String fun01 = fun01();
System.out.println(fun01);
}
public static String fun01() {
return "你好世界";
}
3.有参数没有返回值类型:
public class Demo {
public static void main(String[] args) {
fun04("苹果");
}
public static void fun04(String food) {
System.out.println("吃" + food);
}
4.有参数有返回值类型:
public class Demo {
public static void main(String[] args) {
String fun05 = fun05("苹果");
System.out.println(fun05);
}
public static String fun05(String food) {
return "吃" + food;
}
5.两个参数没有返回值类型:
public class Demo {
public static void main(String[] args) {
fun06(3, "苹果");
}
public static void fun06(int a, String food) {
System.out.println("吃了" + a + "个" + food);
}
6.两个参数有返回值类型:
public class Demo {
public static void main(String[] args) {
int sum = fun08(2, 3);
System.out.println(sum);
}
public static int fun08(int a, int b) {
return a + b;
}
遍历数组
public class Demo {
public static void main(String[] args) {
fun09(new int[]{1, 2, 3, 4});
}
public static void fun09(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i < arr.length - 1) {
System.out.print(arr[i] + ", ");
} else {
System.out.print(arr[i]);
}
}
System.out.println("]");
}
可变参数写法(注意:可变参数必须放在参数的最后一个位置):
public class Demo {
public static void main(String[] args) {
fun10(1,2,3,4,5);
}
public static void fun10(int a,int... arr) {
System.out.println(a);
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i < arr.length - 1) {
System.out.print(arr[i] + ", ");
} else {
System.out.print(arr[i]);
}
}
System.out.println("]");
}
}
运行结果如下:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)