Exchange of java basic variables

Java basics-exchange of variables

When it comes to the exchange of variables, the first thing we think of is to use third-party variables for exchange, as follows:

public static void main(String[] args) {
    
     
        int a = 40;
        int b = 60;
        int c;   
        c= a;  //c = 40
        a = b;  // a = 60
        b = c;  // b = 40
    }

The above code uses a third-party variable to exchange the values ​​of a and b. However, if the third-party variable is not used, what method can be used to exchange the two variables? This question is often asked in interviews. Let’s see how to exchange the values ​​of two variables without using third-party variables!

The first method: Use mathematical operators
Use addition and subtraction operations:

public static void main(String[] args) {
    
    

        int a = 40;
        int b = 60;

        a = a + b;
        b = a - b;
        a = a - b;

        System.out.println("a为:"+ a);  // 60
        System.out.println("b为:"+ b);  // 40

    }

Or use multiplication and division operations:

public static void main(String[] args) {
    
    

        int a = 40;
        int b = 60;
        
        a = a * b;
        b = a / b;
        a = a / b;
        
        System.out.println("a为:"+ a); // 60
        System.out.println("b为:"+ b); // 40
    }

The first method: use the assignment method The
above code looks bloated, this method can be solved with one code!

public static void main(String[] args) {
    
    

        int a = 40;
        int b = 60;
        
        a = b + (b = a) * 0 ;
        
        System.out.println("a为:"+ a); // 60
        System.out.println("b为:"+ b); // 40
    }

Friends who can't understand the above code need to learn the basics of Java well! We can take a look at the right side: first, b = 60, a = 40, and the code is 60 + (40) * 0. Why is 40 in the brackets needless to say, the value of a is assigned to b, so b Now it is equal to 40, so the inside of the brackets is 40. First calculate the multiplication and division and then add and subtract. The result of 60 + (40) * 0 is equal to 60. In this way, the values ​​of a and b are replaced!
The above are two other ideas besides using third-party variables to exchange values. Do you have any other better ideas?

Guess you like

Origin blog.csdn.net/weixin_47316336/article/details/108944104