Write a Java Program Swap Two Numbers using function
SOURCE CODE: :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.util.*; class SwapTwoNumbersFunc { int a,b; public void swap(SwapTwoNumbersFunc swp) { int temp; temp=swp.a; swp.a=swp.b; swp.b=temp; } public static void main(String s[]) { SwapTwoNumbersFunc objSwp= new SwapTwoNumbersFunc(); try { Scanner sc=new Scanner(System.in); System.out.print("Enter first number: "); objSwp.a=sc.nextInt(); System.out.print("Enter second number: "); objSwp.b=sc.nextInt(); objSwp.swap(objSwp); System.out.println("After swapping -a: " + objSwp.a + ", b: " + objSwp.b); } catch(Exception E) { System.out.println("Exception: " + E.toString()); } } } |
OUTPUT ::
1 2 3 |
Enter first number: 1 Enter second number: 2 After swapping a: 2, b: 1 |