Java 中的传值和传应用

来源:互联网 发布:如何做淘宝网红店 编辑:程序博客网 时间:2024/05/22 04:52
Java中在函数调用传递参数时,

 *   传递的若是基于基本类型的JAVA数据类型, 都是传值. 

             如 8 种基本数据类型 int, float, double, long, char, byte, short, boolean 分别对应 Integer, Float, Double, Long, String, Byte, Short, Boolean.

             此外,数组也是传值,和C/C++中不一样(验证了 byte 数组)

 *   传递的若是普通类的对象, 则是传引用.

测试代码:

package string;/** * 测试Java中的函数参数传值. * 传值、传引用. * 函数参数是普通类型、对象等. * 在函数调用传递参数时, *    传递的若是基于基本类型的JAVA数据类型, 都是传值. 如 8 种基本数据类型 int, float, double, long, char, byte, short, boolean 分别对应 Integer, Float, Double, Long, String, Byte, Short, Boolean. *    传递的若是普通类的对象, 则是传引用. * @author zhankunlin * */public class TestTransfValueFunction {/** * 测试 String 类型. * String 对应基本类型 char. */private void testString() {System.out.println("测试 String");String src = new String("world");  System.out.println(src);procsString(src);System.out.println(src);}/** * 该方法中处理参数 src * @param src */private void procsString(String src) {src += "hello";}/** * 测试 Integer 类型. * Integer 对应基本类型 int. */private void testInteger() {System.out.println("测试 Integer");Integer src = new Integer(500);//Integer src = 500;  System.out.println(src);procsInteger(src);System.out.println(src);}/** * 该方法中处理参数 src * @param src */private void procsInteger(Integer src) {src += 500;}/** * 测试 Float 类型. * Float 对应基本类型 float. */private void testFloat() {System.out.println("测试 Float");Float src = new Float(123.45);  System.out.println(src);procsFloat(src);System.out.println(src);}/** * 该方法中处理参数 src * @param src */private void procsFloat(Float src) {src += 500.00;}/** * 测试参数是普通类的对象的情况. * 此时是传递的是引用. */private void testT() {System.out.println("测试 普通类对象");T src = new T();  src.num = 100;src.str = "hello";System.out.println(src.str + ", " + src.num);procsT(src);System.out.println(src.str + ", " + src.num);}/** * 该方法中处理参数 src * @param src */private void procsT(T src) {src.num = 500;src.str = "hello world";}public static void main(String []argv) {TestTransfValueFunction test = new TestTransfValueFunction();test.testString();test.testInteger();test.testFloat();test.testT();}}class T {public String str;public Integer num;public void setStr(String str) {this.str = str;}public String getStr() {return this.str;}public void setNum(Integer num) {this.num = num;}public Integer getNum() {return this.num;}}

运行结果:

测试 Stringworldworld测试 Integer500500测试 Float123.45123.45测试 普通类对象hello, 100hello world, 500


原创粉丝点击