Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanjeevshrestha/8df9a0e248ca94b223437bae207f8f35 to your computer and use it in GitHub Desktop.
Save sanjeevshrestha/8df9a0e248ca94b223437bae207f8f35 to your computer and use it in GitHub Desktop.
Swapping two numbers without third variable in java
public static void swap1(int a, int b) {
System.out.println("The intital value " + a + " " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("The swapped value " + a + " " + b);
}
public static void swap2(int a, int b) {
System.out.println("The intital value " + a + " " + b);
a = a * b;
b = a / b;
a = a / b;
System.out.println("The swapped value " + a + " " + b);
}
public static void swap3(int a, int b) {
System.out.println("The intital value " + a + " " + b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("The swapped value " + a + " " + b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment