转译自http://pages.cs.wisc.edu/~bahls/cs302/PrimitiveVsReference.html
这是一篇关于Java语言的好文,简短明了,涉及到Java语言的赋值、比较、参数传递和返回值等概念。
提示:Primitives:在Java语言中,遵从多数人的习惯将其翻译为基本。
Primitives vs. References(基本与引用)
Assignment(赋值)
Comparisons (e.g. ==) (比较(例如 ==))
Passing Parameters(传递参数)
Returning Values(返回值)
附、Oracle官方文档中对于Java参数传递方式的介绍 https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html 节选如下:
Passing Primitive Data Type Arguments
传递基本数据类型参数
Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. Here is an example:
基本数据类型的参数,如 int 或 double,是通过值传递到方法中的。这意味着参数值的任何更改只存在于方法的作用域内。当方法返回时,参数消失了,对它们的任何更改也随之丢失。这里有一个例子:
public class PassPrimitiveByValue {
public static void main(String[] args) {
int x = 3;
// invoke passMethod() with
// x as argument
passMethod(x);
// print x to see if its
// value has changed
System.out.println("After invoking passMethod, x = " + x);
}
// change parameter in passMethod()
public static void passMethod(int p) {
p = 10;
}
}
When you run this program, the output is:
当你运行这个程序时,输出是:
After invoking passMethod, x = 3
Passing Reference Data Type Arguments
传递引用数据类型参数
Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.
For example, consider a method in an arbitrary class that moves Circle objects:
引用数据类型的参数,如对象,也是通过值传递到方法中的。这意味着当方法返回时,传入的引用仍然指向与之前相同的对象。然而,如果对象的字段具有适当的访问级别,那么这些字段的值可以在方法中被改变。
例如,考虑在任意类中移动Circle对象的方法:
public void moveCircle(Circle circle, int deltaX, int deltaY) {
// code to move origin of circle to x+deltaX, y+deltaY
circle.setX(circle.getX() + deltaX);
circle.setY(circle.getY() + deltaY);
// code to assign a new reference to circle
circle = new Circle(0, 0);
}
Let the method be invoked with these arguments:
让该方法通过以下参数调用:
moveCircle(myCircle, 23, 56)
Inside the method, circle initially refers to myCircle. The method changes the x and y coordinates of the object that circle references (that is, myCircle) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called.
在方法内部,circle最初引用(指向)myCircle。该方法将circle引用的对象(即myCircle)的x坐标和y坐标分别更改23和56。当方法返回时,这些更改将持续存在。然后 circle 被赋予了一个新的 Circle 对象的引用,x = y = 0。但是,这个重赋值没有持久性,因为引用是按值传入的,不能更改。在方法中(内部),circle所指向的对象已经改变,但是,当方法返回时,myCircle仍然引用与调用该方法之前相同的circle对象。