java中的方法
-
什么是方法?
方法是类行为的体现,是具体实现某项功能的地方。
-
方法的语法及声明格式
访问符 修饰符 <返回值类型>方法名(参数列表){
//方法体
}
返回值类型表示该方法运行到最后所返回的值的数据类型,如果方法没有返回值则其返回值类型为void(访问符,修饰符不是必须的可写可不写)。如
String name;
public static String test(){
return name
}
当无返回值时
public void test(){
//方法体
}
方法的参数
方法参数的传递机制
****当数据类型为基本数据类型时实参和形参是按照值传递
public class Test{
//该方法的形参为int类型,调用该方法需要传递一个int类型的实参
public void T(int i){
System.out.println(i);
//i=2;
}
public static void main(String []args){
Test test=new Test();
test.T(2);//括号内可接受int类型的数,这里顺便传一个2
}
}
形参是在声明方法时给方法定义形式上的参数如上文的int i,没有具体的数值,等待接受实参。
(2)test.T;表示调用T方法,T方法需要一个int类型的实参因此调用时需要传递一个int类型的实参。调用T方法时将2的值赋给了i。
值传递时实参和形参在内存中占用不同的空间,完成传递后二者互不影响
具体演示
public class Test{
//声明一个t方法,a,b此时为形参
public void t(int a,int b){
//自定义变量实现a与b的值相交换
//a的值赋值给c
int c=a;
//把b的值赋值给a
a=b;
//把c的值赋值给a
b=c;
//分别打印a,b,c的值
//在t方法中因为交换了值所以结果为a=4;b=2
System.out.println(a);
System.out.println(b);
}
public static void main(String[]args){
int a=2;
int b=4;
//a,b值未交换前,a=2,b=4;
System.out.println(a);
System.out.println(b);
//调用t方法
Test test=new Test();
test.t(a,b);
//值传递完成后的a和b的值为a=2,b=4;
System.out.println(a);
System.out.println(b);
}
}
在未完成传递前a=2,b=4;
在t方法中 a=4,b=2;
脱离t方法再次打印值时 a=2,b=4;
****当数据类型为引用数据类型时,值会采用引用传递(形参的值会改变实参的值)
public class Test {
public void change(String str,char[] ch){
形参中的String str用于接收main方法中s=world的值;
str="hello";
//str原本指向常量池中的‘world’现在指向‘hello’
//在change方法中输出str的结果为hello
ch[0]='5';
//参数接收的类型为char类型( 引用数据类型采用引用传递,将main方 法 中的char【】ch的地址传给chang方法,
//所以在change方法体外输出其值会改变 )
}
public void gr(){
System.out.println();
}
public static void main(String[] args) {
String str =new String("world");
//创建String类型的对象s位于堆中,s指向常量池中的’world‘;
char[]ch={'a','b','c'};
Test t=new Test();
t.change(s,ch);
//调用change方法并传参
System.out.println(s);
System.out.print(ch);
}
}