Wednesday, March 11, 2015

Java using in Reverse Number and Swap Numbers program



Reverse Number using Java

public class ReverseNumber
{  
public static void main(String[] args)
{
int number = 1234;
int reversedNumber = 0;
int temp = 0;              
while(number > 0)
{
temp = number%10;
reversedNumber = reversedNumber * 10 + temp;
number = number/10;                       
}
System.out.println("Reversed Number is: " + reversedNumber);
   }
}

Swap Numbers Java

public class SwapElements
{
public static void main(String[] args)
{               
int num1 = 10;
int num2 = 20;             
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
swap(num1, num2);
}
private static void swap(int num1, int num2)
{       
int temp = num1;
num1 = num2;
num2 = temp;         
System.out.println("After Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);             
   }
}

Swap Numbers without Using Third Variable

public class SwapElementsWithoutThirdVariable
 {
public static void main(String[] args)
{
int num1 = 10;
int num2 = 20;      
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
   }
}

No comments:

Post a Comment