Java 中的传值和传应用

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;
	}
}

运行结果:

测试 String
world
world
测试 Integer
500
500
测试 Float
123.45
123.45
测试 普通类对象
hello, 100
hello world, 500


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值