Home > Java > Javagetting Started > body text

What are the ways to exchange the values ​​of two variables in java?

王林
Release: 2020-11-12 15:25:17
forward
3469 people have browsed it

What are the ways to exchange the values ​​of two variables in java?

Method:

1. Define temporary variables

2. No need to define temporary variables

3. Use bit operators

(Learning video sharing: java course)

Code example:

public class SwapTest {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;

        //方式一:定义临时变量的方式
        //推荐使用方式
        int temp = num1;
        num1 = num2;
        num2 = temp;
        System.out.println("方式一num1:"+num1);
        System.out.println("方式一num2:"+num2);

        //方式二:
        //好处:不用定义临时变量
        //弊端:① 相加操作可能超出存储范围
        //     ② 有局限性:只能适用于数值类型
        num1 = 10;
        num2 = 20;
        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;
        System.out.println("方式二num1:"+num1);
        System.out.println("方式二num2:"+num2);

        //方式三:使用位运算符
        //有局限性:只能适用于数值类型
        num1 = 10;
        num2 = 20;
        num1 = num1 ^ num2;
        num2 = num1 ^ num2;
        num1 = num1 ^ num2;
        System.out.println("方式三num1:"+num1);
        System.out.println("方式三num2:"+num2);
    }

}
Copy after login

Running results:

方式一num1:20
方式一num2:10
方式二num1:20
方式二num2:10
方式三num1:20
方式三num2:10

Process finished with exit code 0
Copy after login

Related recommendations :Getting started with java

The above is the detailed content of What are the ways to exchange the values ​​of two variables in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template