温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

In Java, everything is pass-by-value

发布时间:2020-08-06 19:36:19 来源:ITPUB博客 阅读:160 作者:Jewyi 栏目:编程语言
In Java, everything is pass-by-value
Q: Can you provide some authoritative quotation to support the saying "In Java, everything is pass-by-value"?
A:
From The Java Programming Language, by James Gosling et al. 3rd edition (pg. 56):

quote:



Some people will say incorrectly that objects are passed "by reference." In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory. The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.

From The Java Tutorial

quote:


Pass by Value

In Java methods, arguments are passed by value.
When invoked, the method receives the value of the variable passed in. When the
argument is of primitive type, pass-by-value means that the method cannot change
its value. When the argument is of reference type, pass-by-value means that the
method cannot change the object reference, but can invoke the object's methods
and modify the accessible variables within the object.

This is often the
source of confusion--a rogrammer writes a method that attempts to modify the
value of one its arguments and the method doesn't work as expected. Let's look
at such method and then investigate how to change it so that it does what the
programmer originally intended.


Quiz question from Sun:
In Java programming, all method parameters are passed by value.
Answer: true
In Java, everything is pass-by-value, unless you think Dr. James Gosling forgot how he invented Java, AND Sun does not know how Java works.If we all agree those are not the cases. Then the question should change to that how to understand the fact "In Java, everything is pass-by-value".If you go up-and-down a little, you will find a lot of help here.

Two examples to prove:

Example one:(from:http://bobcat.webappcabaret.net/javachina/faq/07.htm#pas_Q2)

// PassByValueTest.java
public class PassByValueTest { 
  public static void main(String [] args) { 
    String arr[]=new String[2]; 
          
    arr[0]="hello"; 
    arr[1]="hi"; 
          
    // nothing will change here
    swap(arr[0], arr[1]); 
    System.out.println(arr[0] + ", " + arr[1]); //hello, hi
          
    // two Strings are actually swapped
    swap(arr, 0, 1); 
    System.out.println(arr[0] + ", " + arr[1]); //hi, hello
  }
        
  // useless swap method, since you swap the copies 
  // of two strings' reference inside the method 
  // Strings outside are not affected.
  public static void swap(String s1,String s2){ 
    String tmp = null;
           
    tmp  = s1; 
    s1   = s2; 
    s2   = tmp; 
  } 
        
  // real practical swap here
  // swap array elements with two indices
  // very useful for sorting algorithm, etc.
  // reference of arr will never change (pass-by-value)
  // but the contents of arr will change permanently
  // since the copy of arr reference still refer to the same object.
  public static void swap(String arr[], int ix1, int ix2) { 
    String tmp = null; 
          
    tmp      = arr[ix1]; 
    arr[ix1] = arr[ix2]; 
    arr[ix2] = tmp; 
  } 
} 

Example two(my code):

public class ParamTest {

/**
* @param args
* @author Jianming
* @version 1.0
*/

public static void main(String[] args){
/*
* Test one:Methods can't modify numeric parameters
*/

System.out.println("Testing tripleValue:");
double percent = 10;
System.out.println("Before: percent = " + percent);
tripleValue(percent);
System.out.println("After: percent = " + percent);

/*
* Test two: Methods can modify the state of object parameters
*/

System.out.println("nTesting tripleSalary:");
Employee harry = new Employee("Harry", 5000);
System.out.println("Before: salary = " + harry.getSalary());
tripleSalary(harry);
System.out.println("After:salary = " + harry.getSalary());

/*
* Test three:Methods can't attach new objects to object parameters
*/

System.out.println("nTesting swap:");
Employee a = new Employee("Jianming", 10000);
Employee b = new Employee("James", 20000);
System.out.println("Before: a = " + a.getName());
System.out.println("Before: b = " + b.getName());
swap(a, b);
System.out.println("After: a = " + a.getName());
System.out.println("After: b = " + b.getName());

}

public static void tripleValue(double x){
x = 3 * x;
System.out.println("End of method:x = " + x);
}

public static void tripleSalary(Employee x){
x.raiseSalary(200);
System.out.println("End of method:salary = "
+ x.getSalary());
}

public static void swap(Employee x, Employee y){
Employee temp = x;
x = y;
y = temp;
System.out.println("End of method: x = " + x.getName());
System.out.println("End of method: y = " + y.getName());
}

}

class Employee{
public Employee(String n, double s){
name = n;
salary = s;
}

public String getName(){
return name;
}

public double getSalary(){
return salary;
}

public void raiseSalary(double bypercent){
double raise = salary * bypercent / 100;
salary += raise;
}

private double salary;
private String name;

}

The result:

Testing tripleValue:
Before: percent = 10.0
End of method:x = 30.0
After: percent = 10.0

Testing tripleSalary:
Before: salary = 5000.0
End of method:salary = 15000.0
After:salary = 15000.0

Testing swap:
Before: a = Jianming
Before: b = James
End of method: x = James
End of method: y = Jianming
After: a = Jianming
After: b = James

Note:

(1):Methods can't modify the parameters of primitive type

(2):Methods can modify the state of object parameters,but methods can't attach new objects to object parameters

an example to explain the question:

电视机和遥控器可以很形象的描叙和解释这个问题。
可以把遥控器看作是电视机的一个引用拷贝,只要电视机存在,也就是用遥控器对准一台电视机,按遥控器上面的各种按扭(function)可以对电视机产生各种影响,但是你换一个遥控器对电视机来说是不会产生影响的,电视机并不会因为遥控器换了而变成别的电视机。同时遥控器也可以不对准原来的电视机,转去对准别的电视机,这对原来的电视机也是不会产生影响的。一台电视机可以有多个遥控器,并且只要某个遥控器对准了这台电视机,这个遥控器就可以通过它上面的按扭改变电视机的状态。

a picture to show how it works:

In Java, everything is pass-by-value

End.

[@more@]

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI