相信大家经常在Java编写过程中遇到main方法,那main方法究竟是什么呢,在这里我就给大家简单讲解一下
方法就是用来解决某一个问题的代码集合,它可以被多次调用
此处的hello只是一个示例,是这个hello方法
public class method1 {
/*
main方法==c语言main函数,启动程序,一个程序只需要一个main方法
在c语言中被称为函数
在面向对象语言中称为方法
方法:
用来解决某一个问题的代码集合,可以多次调用
定义方法的语法:
访问权限修饰符public
修饰符static
方法返回值
*/
public static void main(String[] args) {
/*
定义一个无参,无返回值的方法
public static 是固定写法
void表示此方法没有返回值
hello方法名
()参数列表,可以为空
{
System.out.printlrn("你好");//方法做的事
*/
}
}
接下来是方法的另一种调用,此处可以用String数据类型用来声明
public class method2 {
public static void main(String[] args) {
method2.hello("张三",30);
String n = "李四";
method2.hello(n,30);
}
/*
String数据类型
name参数的名字 可以自定义,本质就是一个变量
*/
public static void hello(String name,int age){
System.out.println("你好");
}
}
接下来用到的是return关键字。
可以用在有参数有返回值的方法,用于返回方法处理之后的结果
当然也可以用在没有返回的方法中,但是后面不能有其他表达式,其目的就是为了终止方法
public class method3 {
public static void main(String[] args) {
/*
int m = method3.max(10,5);
System.out.println(m);
*/
method3.hello("洞洞拐",19);
}
/*
有参数有返回值的方法:
int——————>定义的是方法的返回值类型
return max;通过return关键字返回方法处理后的结果
*/
public static int max(int a,int b){
int max = (a>b)?a:b;
return max;
}
public static void hello(String name,int age){
if(name ==null){
return;
//在没有返回的方法中,也可以使用return关键字,但是return后面不能有其他表达式,作用就是终止方法 //名字输入为空,则无法说出你好
}
System.out.println("你好!"+name+" "+"年龄:"+age+"岁");
}
}