ADVERTISEMENT
ADVERTISEMENT

Java program to swap two numbers using function

In this program we will swap integer numbers using function, we will design a function to swap two numbers.

Swap Two Numbers by function using Java Program

//Java program to swap two numbers using function.
 
import java.util.*;
 
class SwapTwoNumbersFunc
{
    int a,b;
    //function to swap two numbers
    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

    Complie 	:	javac SwapTwoNumbersFunc.java
    Run		:	java SwapTwoNumbersFunc
    Output
    Enter first  number: 10 
    Enter second number: 20
    After swapping  -a: 20, b: 10 

Java Basic Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.