Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to swap two variables in one line in Java?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 358
    Comment on it

    How to swap two variables in one line in Java?

    // Java program to swap two variables in single line
    
    class Demo
    {
       public static void main (String[] args)
       {
          int a = 6, b = 11;
          a = a ^ b ^ (b = a);
          System.out.println("After Swapping values of a and b are "
                              + a + " " + b);
       }
    }
    

    Output:

    After Swapping values of x and y are 11 6

    Explanation of above program:

    Java always evaluate operands from left to right.

    The left-hand operand of a binary operator in this case a ^ b appears to be fully evaluated before any part of the right-hand operand (b = a) is evaluated. Therefore,

    Flow of evaluation:

    a ^ b = 6 ^ 11 = 13

    After this again a binary operation ^ is performed but for that right hand side of ^ is to be evaluated thereby assigning value of a to b and assign result of 13 ^ b to a.

    a = 13 ^ b = 13 ^ 6 = 11

    Now a is having value 11 and in the expression b is already ssigned with previous value of a i.e 6.

    But a = (b=a) ^ b ^ a will not swap values because if the operator is a compound-assignment operator on left hand side, then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: