不利用临时变量,交换两个变量的值

本文介绍了一种在Java中不借助第三个变量来交换两个整数变量的方法。通过五种不同的方式实现这一目标,包括使用算术运算、位运算、字符串拼接等技巧,这些方法不仅适用于基本类型也适用于引用类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者“zyy-jay-163-com”

public class ChangeValue 
{ 
     
    /** 
     * <不用第三个变量,交换两个变量的值>
     */ 
    public static void main(String[] args) 
    { 
        //方法一  精简,一行代码搞定  
        int x = 3, y = 7, t = 123; 
        System.out.printf("x = %d, y = %d\n", x, y); 
        x = y + 0 * (y = x);  
        System.out.printf("x = %d, y = %d\n", x, y); 
         
        //方法二   简单明了  
        int p = 4, q = 9; 
        System.out.printf("p = %d, q = %d\n", p, q); 
        p = p + q; //7 
        q = p - q; // 7-5=2  q == p 
        p = p - q; //7-2   
        System.out.printf("p = %d, q = %d\n", p, q); 
         
        //方法三  兼容,支持Integer.MAXVALUE的+操作   
        int a = 2, b = 5; 
        System.out.printf("a = %d, b = %d\n", a, b); 
        a ^= b; 
        b ^= a; 
        a ^= b; 
        System.out.printf("a = %d, b = %d\n", a, b); 
         
        //方法四  字符串 数组 
        String s1 = "111", s2 = "222"; 
        System.out.printf("s1 = %s, s2 = %s\n", s1, s2); 
        s1 = s1 + "," + s2; 
        s2 = s1; 
        s1 = s1.split(",")[1]; 
        s2 = s2.split(",")[0]; 
        System.out.printf("s1 = %s, s2 = %s\n", s1, s2); 
         
        //方法五  字符串 表达式(类似方法一) 
        String str1 = "aaa", str2 = "bbb"; 
        System.out.printf("str1 = %s, str2 = %s\n", str1, str2); 
        str1 = str2 + ((str2 = str1) == "" ? "" : ""); 
        System.out.printf("str1 = %s, str2 = %s\n", str1, str2); 
    } 
     
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值