108
Swap Two Numbers in Java Using Function
In this section, we will create Java programs to swap two numbers using functions with different logic.
- STEP 1: START
- STEP 2: DEFINE x, y, t
- STEP 3: ENTER x, y
- STEP 4: PRINT x, y
- STEP 5: t = x
- STEP 6: x= y
- STEP 7: y= t
- STEP 8: PRINT x, y
- 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
Next TopicCullen Number in Java