Write a Java Program Swap Two Numbers using function

By | 19.01.2017

Write a Java Program Swap Two Numbers using function


SOURCE CODE: :

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 ::

 

Enter first  number: 1
    Enter second number: 2
    After swapping  a: 2, b: 1

 

4 1 vote
Article Rating
Category: Basic Programs Java Programming Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments