1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/* Swap Numbers Java Example This Swap Numbers Java Example shows how to swap value of two numbers using java. */ public class SwapElementsExample { public static void main(String[] args) { int num1 = 10; int num2 = 20; System.out.println("Before Swapping"); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num2 is :" +num2); //swap the value swap(num1, num2); } private static void swap(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; System.out.println("After Swapping"); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num2 is :" +num2); } } /* Output of Swap Numbers example would be Before Swapping Value of num1 is :10 Value of num2 is :20 After Swapping Value of num1 is :20 Value of num2 is :10 */ |
[code]
num1 = num1 + num2;
num2 = num1 – num2;
num1 = num1 – num2;
[/code]
a=a^b;
b=a^b;
a=a^b;
This is crap code how can it be swap??
once the function returns the variable will have their original values not the changed one.
hai friends please help me for below program in java:
input :88,96,76,33,42
output:89,67,63,34,28
main function num1 and num2 value wont change after executing swap fucntion
Hello,
As you commented that – main function num1 and num2 value wont change after executing swap function, because the scope for Main function is within in that block only and same for the Swap function, so after executing the Swap function, the scope will get finish there and control will return back to main, so no changes will be reflected in Main function.Therefore, Main function num1 and num2 value wont change after executing swap function.
Regards,
Usha Naidu.
This is not quite real swap like C++ can do, by passing variables as reference…