passed into methods by value java专题

java没有引用传递只有按值传递,没有引用传递只有按值传递,值传递。
因为Primitive类型的值不能改变,所以method不能更改调用方传的primitive 值。因为method更改的是Primitive变量的copy,所以method的更改,调用方是不知道的

因为Reference Data Type的内存地址不能被method中操作更改,所以调用方中Reference Data 对象中的状态 也发生变化。因为method操作的对象,与调用方是相同的,即调用方是知道method中的更改的

只不过Primitive类型传的是实际的数据,Reference Data Type 传的是内存地址。

入参为Reference Data Type的方法中,可以更改这个对象状态的原因,就是因为入参对象的内存地址是不能改变,这样在method中更改这个对象的属性值,调用方的该对象的相关属性值也发生变化

 

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.

import org.junit.Test;

public class CircleTest {
    @Test
    public void moveCircle() throws Exception {
        Circle circle=new Circle(10,10);
        circle.print(circle);
        circle.moveCircle(circle, 20, 20);
        circle.print(circle);
    }

}

输出:

moveCircle:Circle{x=10, y=10},hash code:1252585652
moveCircle:Circle{x=0, y=0},hash code:2036368507
moveCircle:Circle{x=30, y=30},hash code:1252585652

 

Let the method be invoked with these arguments:

moveCircle(myCircle, 20, 20)

 

Inside the method, circle initially refers to myCircle. The method changes the x and y coordinates of the object that circle references (i.e., myCircle) by 20 and 20, 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.

 

public class Circle {
    private int x;
    private int y;

    public Circle(int x, int y) {
        this.x = x;
        this.y = y;
    }

    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); //自这行后,moveCircle方法就丢失入参circle---即不能再操作入参circle。就像连续对一个primitive 变量赋值,后一次操作会覆盖前面的
        print(circle);
    }
    public void print(Circle circle) {
        System.out.println("moveCircle:"+circle+",hash code:"+circle.hashCode());
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "Circle{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

 

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:

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

 

 

 

http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html

 

 

通过下面代码解释:

 1 public class Test {
 2     public static void main(String[] args ){
 3         int var = 1 ;
 4         f(var) ;
 5         System.out.println(var) ;
 6     }
 7     public static void f(int newVar ){
 8         newVar = 2 ;
 9     }
10 }

执行结果: 

1

分析:

当执行 int var = 1 时,jvm在栈中开辟一块空间存放值---1,同时var变量指向值1所对应的内存空间,也就是var变量也有自己的内存空间,不过它的空间里存放的是值1所对应的内存地址。

 

当执行到第七行,要将var的值传递进方法f中时,jvm执行的操作是创建一个新的变量newVar,并将var里存放的值(也就是值1的内存地址)复制一份给newVar。

当执行到第八行时,jvm重新开辟值--2所对应的存储空间来存储值2,并修改了newVar里存放的地址值。

方法返回,执行到第五行,输出var所指向的值,当然是值1,因为var中的地址值根本没有变化。

上面示例用的是int,一个基本数据类型,对于引用数据类型同样适用,因为java中没有引用传递,只有值传递。例如自定义的类UserClass:

 1 class MyClass {
 2     int var1 ;
 3 }
 4 public class Test {
 5     public static void main(String[] args ){
 6         MyClass myClass = new MyClass() ;
 7         myClass.var1 = 1 ;
 8         f(myClass) ;
 9         System.out.println(myClass.var1) ;
10     }
11     public static void f(MyClass newMyClass ){
12         myClass.var1 = 100 ;
13     }
14 }

执行结果:

100

分析:

第六行:在栈中创建一个变量指向在堆中创建的对象。关于堆中对象属性的存储可以理解为每创建一个对象就会在堆中分配一块内存空间给改对象,这块内存空间中记录了该对象属于哪个类,剩下就是存储该对象的属性值。

 

第七行修改对象属性值:

 

下面就是关键的第八行值的传递了,jvm会在栈中在开辟一块空间newMyClass,然后把myClass里的内容拷贝进newMyClass,这样在方法f中对newMyClass的修改就是对MyClass所对应内容的修改,因为newMyClass也是指向与myClass同样的一块内存空间。

第十二行中对newMyClass属性的修改同样会影响myClass所指的内容,因为他们俩指的是同一块内存空间。

最后方法返回myClass所指内容同样被修改。

下面说一个比较特殊的类----String,这是java中的一个特殊的引用类型,使用String传递时会发现在方法中修改不会影响到方法外的值,例如下面这段代码:

 1 public class Test {
 2     public static void main(String[] args ){
 3         String var = "Hello" ;
 4         f(var) ;
 5         System.out.println(var) ;
 6     }
 7     public static void f(String newVar ){
 8         newVar = "World" ;
 9     }
10 }

运行结果:

Hello

在分析这段代码之前需要知道String的底层是怎样实现的,其实String是通过char数组来完成其功能,简单的说String就是对char[]的一个封装。还要明白直接“字符串内容”和使用new String(“字符串内容”)效果是一样的,只不过jvm对这两种创建的字符串存储的地方不同而已。对上面这段代码的分析当然还要使用对引用数据传值方法分析。

第三行jvm在静态存储区存放创建的“Hello”字符串,并在栈中开辟var指向Hello的地址(var中存储的值是Hello字符串的地址)。当将var作为参数传递时,jvm会在栈中新创建一个变量newVar,这时newVar是指向"Hello"内存区的,但是在第八行 newVar = “World”却把newVar中存储的“Hello”地址改为一个新创建的“World”String对象的地址,注意,var内存储的地址仍然是“Hello”,所以在方法返回时输出的仍然是Hello。

终于写完了~~~ 发现自己想和写完全是两码事‘(*>﹏<*)′,其中一定有错误,在内存分配地方没有说清楚,因为我也不太清楚,还有就是关于对象中属性的内存分配,这个我真不知道,哪位知道别忘告诉我~~

http://www.cnblogs.com/caiyao/p/4964176.html

 

时间: 2024-08-03 05:42:40

passed into methods by value java专题的相关文章

实例代码讲解Java连接Oracle数据库的各种方法

oracle|数据|数据库 java与oracle的接口: 在数据库中运行JAVA可以说是ORACLE8i的最令人激动的新特性.在你创建的使用ORACLE8i 数据库的应用程序中,你可以使用与JAVA有关的新特征,轻松的将程序发布到INTERNET或INTRANET上. Methods for Using Java in ORACLE 大家都知道JAVA在跨平台开发与INTERNET开发中已经比较流行,ORACLE8i及以后的版本中都包含了对在数据库中运行JAVA的扩展支持,这里有两种方法可以使

java连接oracle数据库的方法

java与oracle的接口: 在数据库中运行JAVA可以说是ORACLE8i的最令人激动的新特性.在你创建的使用ORACLE8i 数据库的应用程序中,你可以使用与JAVA有关的新特征,轻松的将程序发布到INTERNET或INTRANET上. Methods for Using Java in ORACLE 大家都知道JAVA在跨平台开发与INTERNET开发中已经比较流行,ORACLE8i及以后的版本中都包含了对在数据库中运行JAVA的扩展支持,这里有两种方法可以使用: JDBC:与ODBC类

Spring 4 and MyBatis Java Config

TL;DR With the Java Config enhancements in Spring 4, you no longer need xml to configure MyBatis for your Spring application. Using the @MapperScanannotation provided by the mybatis-spring library, you can perform a package-level scan for MyBatis dom

java程序调用xfire发布的webService服务

昨天用xfire搭好了一个简单的webService的服务,可以在浏览器访问,今天便想要尝试以下如何调用这个服务及相关的方法.在网上查找了一些资料后,实现过程如下. 1.创建一个maven web项目,并创建一个带有main方法的类. 2.导入xfire依赖的一些jar包,为了简单起见,我就把搭建服务端时的jar包都考了过来,放在lib文件夹下,然后如上一篇搭建时一样把jar加入到build path中.                  3.创建一个和服务端一样的接口类,必须要有这个接口类才可

浅谈Java的Fork/Join并发框架

1. Fork/Join是什么   Oracle的官方给出的定义是:Fork/Join框架是一个实现了ExecutorService接口的多线程处理器.它可以把一个大的任务划分为若干个小的任务并发执行,充分利用可用的资源,进而提高应用的执行效率.   Fork/Join实现了ExecutorService,所以它的任务也需要放在线程池中执行.它的不同在于它使用了工作窃取算法,空闲的线程可以从满负荷的线程中窃取任务来帮忙执行.(我个人理解的工作窃取大意就是:由于线程池中的每个线程都有一个队列,而且

JavaCore extends Plugin

/******************************************************************************* 2 * Copyright (c) 2000, 2007 IBM Corporation and others. 3 * All rights reserved. This program and the accompanying materials 4 * are made available under the terms of t

MediaRecorder test

public class MediaRecorder extends Object java.lang.Object    ↳ android.media.MediaRecorder Class Overview Used to record audio and video. The recording control is based on a simple state machine (see below). A common case of using MediaRecorder to r

Dynamic proxy (good-原创)

  import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicProxyTest { public static void main(String[] args) { IHello iHello = new Hello();//被代理的类 InvocationHandler handler = ne

使用plot绘制图形

plot()是最常用 R绘图函数,是一个泛型函数(允许参数类型可变),它产生的图形依赖于第一个参数的类型或者类. > set.seed(1 ); x <- sample(c(1:50),10) > set.seed(2); y <- sample(c(1:50),10) > xt <- ts(x) > xy <- cbind(x, y) > f <- as.factor(c(rep('a',3),rep('b',5),rep('c',2))) &