Javatpoint Logo
Javatpoint Logo

Swap Two Numbers in Java Using Function

In this section, we will create Java programs to swap two numbers using functions with different logic.

Swap Two Numbers in Java Using Function
  1. STEP 1: START
  2. STEP 2: DEFINE x, y, t
  3. STEP 3: ENTER x, y
  4. STEP 4: PRINT x, y
  5. STEP 5: t = x
  6. STEP 6: x= y
  7. STEP 7: y= t
  8. STEP 8: PRINT x, y
  9. STEP 9: END

Java Program to Swap Two Numbers Using Function

Using User-defined Function

SwapNumbers.java

Output:

Enter the first number: 25
Enter the second number: 12
After swapping: a= 12, b= 25

Swap Two Numbers Without Using Third Variable

SwapNumber.java

Output:

Enter the first number: 78
Enter the second number: 45
Before Swapping
x = 78
y = 45
After Swapping
x = 45
y = 78

In the above program, we can replace the swapping logic with the following logic:

Swap Two Numbers Using Bitwise XOR (^) Operator

SwapNumberExample.java

Output:

Before swapping values of x and y are: 12, 18
After swapping values of x and y are: 18, 12

Let's see another logic to swap two numbers.

SwapNumbersExample.java

Output:

Before swapping, values of x and y are: 12, 18
After swapping: x = 18, y = 12






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA