通过代码完成2个整数内容的交换

通过代码完成2个整数内容的交换

不磨叽了,直接上代码:

 

package com.hylink.common;

public class Swap {

	/** 
	 * @function 2个整数内容交换
	 * @author ylchou@qq.com
	 * @param args
	 */
	public static void main(String[] args) {
		//method one 不用额外的变量来交换,不过可能回溢出
		int i = 23;
		int j = 55;
		System.out.println("i,j:"+i+","+j);
		i = i + j;//右边为i和j之和  可能回溢出
		j = i - j;//右边为为i的值
		i = i - j;//右边为j的值
		System.out.println("i,j:"+i+","+j);
		
		//method two 用额外的变量来临时存储交换,不会发生溢出
		int x = 44;
		int y = 77;
		System.out.println("x,y:" + x + "," + y);
		int tmp = 0;
		tmp = x;
		x = y;
		y = tmp;
		tmp = 0;
		System.out.println("x,y:" + x + "," + y);
		System.out.println(tmp);
	}
}


console print:

i,j:23,55
i,j:55,23
x,y:44,77
x,y:77,44
0

 

 ----------------------------------------------------------------------------------------

 

 

扩展:要是字符串交换,用method two,示例如下:

package com.hylink.common;

public class Swap {

	/** 
	 * @function 字符串内容交换
	 * @author ylchou@qq.com
	 * @param args
	 */
	public static void main(String[] args) {
		//字符串交换 用额外的变量来临时存储交换
		String str3 = "abc";
		String str4 = "xyz";
		System.out.println("str3,str4:"+str3+","+str4);
		String tmpStr = null;
		tmpStr = str3;
		str3 = str4;
		str4 = tmpStr;
		tmpStr = null;
		System.out.println("str3,str4:"+str3+","+str4);
		System.out.println(tmpStr);
	}
}


console print:

str3,str4:abc,xyz
str3,str4:xyz,abc
null

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值