Swap two variables without using third variable

Write a program to swap the data of two variables A and B without using third variable in java.
There is no input taken at runtime by user. The A and B is declared and initialized in the program.

class swap
{
          public static void main(String ars[])
          {
                    int A = 10;
                    int B = 20;

                    System.out.println("A Before Swap = "+A);
                    System.out.println("B Before Swap = "+B);

                    A = A + B;

                    B = A - B;
                    A = A - B;


                    System.out.println("A After Swap = "+A);
                    System.out.println("B After Swap = "+B);
          }

}


0 Comments:

Post a Comment