Swap Without Variable Example in Java
On this page (9sections)
Introduction
Swap Without Variable is a classic Java console program that demonstrates the concept with complete source code and sample output. Calculation programs apply formulas to solve geometry, statistics and numeric problems.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
The act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory.
Swap Without Variable Example Program
import java.util.Scanner;
class SwapWithoutVariable{
public static void main(String args[]){
int num1,num2;
System.out.println("Enter num1 and num2");
Scanner in = new Scanner(System.in);
num1 = in.nextInt();
num2 = in.nextInt();
System.out.println("Before Swapping num1 = "+num1+" and num2 = "+num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After Swapping num1 = "+num1+" and num2 = "+num2);
}
}
Sample Output
Enter num1 and num2
67
78
Before Swapping num1 = 67 and num2 = 78
After Swapping num1 = 78 and num2 = 67
When to use
Use these formulas in homework tools, engineering calculators or anywhere repeated numeric computation is needed.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
println/printcall writes text to the console — part of the sample output below. -
A
Scannerreads typed input from the keyboard (System.in). -
num1 = in.nextInt();updates a variable used in the calculation or output. -
num2 = in.nextInt();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.