Swapping numbers program
Write a program to swap two numbers using a temporary variable.
Write a program to swap two numbers using a temporary variable.
public class swap1
{
public static void main()
{
int temp;
int a=3;
int b=9;
temp=a;
a=b;
b=temp;
System.out.println("After swapping, a="+a);
System.out.println("After swapping, b="+b);
}
}<tbody>
After swapping,a will be=9
After swapping,b will be=3
</tbody>
Write a program to swap two numbers without using a temporary variable.
public class swap2
{
public static void main()
{
int a=3;
int b=9;
a=a+b;
b=a-b;
a=a-b;
System.out.println("After swapping, a="+a);
System.out.println("After swapping, b="+b);
}
}<tbody>
After swapping,a will be=9
After swapping,b will be=3
</tbody>
rite a program
Related Posts
Continue learning with these related articles

Pattern Programs in Java for ICSE Class 9: 8 Solved Patterns with Explanations
ICSE Class 9 Computer Applications pattern programs in Java using nested loops: number and star triangles, inverted triangles, Floyd's triangle, a pyramid, letter and word patterns and a 0-1 pattern, each with output and the logic explained.
Sum of First n Natural Numbers in Java (Loop and Formula)
Find the sum of the first n natural numbers in Java with a for loop, a while loop and the formula n(n + 1)/2, with a dry run and the sums of even numbers, odd numbers, squares and cubes.
Prime Number Program in Java: Check a Number and Print Primes in a Range
Check whether a number is prime in Java by counting its factors, a faster square-root method with isPrime(), and a program that prints all prime numbers in a range.