Java Trick: Swap two Numbers without using third Variable!

Pubblicato il: 01 maggio 2023
sul canale di: Techie coding
213
5

Interview Question : Write a Java Program to swap two numbers without using the third variable.

This video explains about how you can use the concept of swapping of values within a variable without using the third variable. Here third variable means, without using temporary variable.
First of all you have to create a class having a name 'Swapping'. Within this class, the main() method, create two integer variables 'a' and 'b' and takes its input from user and perform calculation as :

a = a + b ;
b = a - b ;
a = a - b ;

First variable is first added to the second variable and stored in first variable. Then the second variable is subtracted from first variable and stored in second variable.
Lastly, the value of 2nd variable is subtracted from 1st and stored in first variable.

This is how the values of one variable get swapped to another and vice versa,
i.e. : a becomes 20 and b becomes 10.

Finally, the swapped value gets printed using the System.out.println() method.

Example :
Before Swapping : a = 10, b = 20
After Swapping : a = 20, b = 10

====================================

Learn Java Programming :
👉    • Java Tutorials  

====================================

Learn Data Structures and Algorithms in Java :
👉    • DS & Algorithms + Implementation in Java  

====================================

Thank you for Watching :

Happy coding Keep Learning 😊

====================================

subscribe for more videos :

/ @techie_coding

/ @techie_coding

/ @techie_coding

====================================

#java #javaprogramming #swapping #javainterviewquestions #swappingprogram
#swaptwonumbers #javacoding #javacodinginterviewquestions #techiecoding


In questa pagina del sito puoi guardare il video online Java Trick: Swap two Numbers without using third Variable! della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Techie coding 01 maggio 2023, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 213 volte e gli è piaciuto 5 spettatori. Buona visione!