Friday, 10 July 2015

Swap value of two variable without using third varibale (Core JAVA)

Save File as swapVariables.java


package myFirstProject;

public class swapVariables {

 public static void main(String[] args) {
  
   int firstVariable = 10; 
   int secondVariable = 5;
   
   // Code to swap 'firstVariable' and 'secondVariable'
   firstVariable = firstVariable + secondVariable;   // firstVariable now becomes 15
   secondVariable = firstVariable - secondVariable;   // secondVariable becomes 10
   firstVariable = firstVariable - secondVariable;   // firstVariable becomes 5
   
   System.out.println("Value of firstVariable is: "+firstVariable);
   System.out.println("Value of secondVariable is: "+secondVariable);
 }
}

No comments:

Post a Comment