2.当通过return语句从方法返回信息时,基本数据类型的变量总是以值的形式返回(即返回拷贝),而对象总是以应用的方式返回。
方法调用过程:
1.为调用方法的内存中开辟空间。
2.将实参传递给形参。
3.程序流程跳转到方法里,并执行方法。
4.执行完方法,程序流程跳转到main方法,带回返回值如果有的话,为方法开辟的空间被销毁。
列如:
public class Test {
public static void main(String args[]) {
int a = 10, b = 20
String str1 = "abc"
String str2 = "def"
swap(a, b)
swap(str1, str2)
System.out.println(a + "/t" + b)
System.out.println(str1 + "/t" + str2)
}
public static void swap(int a, int b) {
int temp = a
a = b
b = temp
}
public static void swap(String str1, String str2) {
String temp = str1
str1 = str2
str2 = temp
}
}
结果:
10 20
abc def
注意结果中整型和字符串都没有交换。
在一个类中,程序的作用体现在方法中。方法是JAVA创建一个有名字的子程序的方法。1、方法的实现包括两部分内容:方法声明和方法体。
[public | protected | private ] [static]
[final | abstract] [native] [synchronized]
returnType methodName([paramList])
[throws exceptionList] //方法声明
{statements} //方法体
——方法体是对方法的实现,它包括局部变量的声明以及所有合法的Java指令。方法体中声明的局部变量的作用域在该方法内部。若局部变量与类的成员变量同名,则类的成员变量被隐藏。
—— 方法声明中的限定词的含义:
static: 类方法,可通过类名直接调用
abstract: 抽象方法,没有方法体
final: 指最后一个方法
方法声明包括方法名、返回类型和外部参数。其中参数的类型可以是简单数据类型,也可以是复合数据类型(又称引用数据类型)。
对于简单数据类型来说,java实现的是值传递,方法接收参数的值,但不能改变这些参数的值。如果要改变参数的值,则用引用数据类型,因为引用数据类型传递给方法的是数据在内存中的地址,方法中对数据的操作可以改变数据的值。