MOCKSTACKS
EN
Questions And Answers

More Tutorials




How to swap two numbers in Kotlin

To Swap 2 numbers in Kotlin we can declare a third temporary variable.

Assuming we have a = 1, b =2

And Temporary variable called x

1- We set value of temporary from first variable. x = 1 (a)
2- We set value of First variable from Second variable. a = 2 (b)
3- We set value of second variable from temporary variable b = 1 (x)

Example

import java.util.*


fun main(arg: Array<String>) {
    
    var first = 1;
    
    var second = 2;    
    
    println("Numbers Before Swap : first = $first second = $second ")
    
    var temp = first
    first = second
    second = temp
    
    println("Numbers After  Swap : first = $first second = $second ")
}

Output

Numbers Before Swap : first = 1 second = 2
Numbers After Swap : first = 2 second = 1

Conclusion

In this page (written and validated by ) you learned about How to swap two numbers in Kotlin . What's Next? If you are interested in completing Kotlin tutorial, we encourage you simply to start here: Kotlin Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.