# Android Code SnippetSwap without extra variable

Here's a reminder that we don't need an extra variable for swapping integer values:
B4X:
``````Dim a = 120, b = 110 As Byte 'Short / Int / Long
Log(a & " | " & b) 'Output: 120 | 110
a = a + b
b = a - b
a = a - b
Log(a & " | " & b) 'Output: 110 | 120``````

It works for doubles and floats as well, but you might lose precision (12.2 becomes 12.1999998), so beware.

#### Emme Developer

##### Well-Known Member
Longtime User
Another way
B4X:
``````Dim a = 120, b = 110 As Byte 'Short / Int / Long
Log(a & " | " & b) 'Output: 120 | 110
a = Bit.Xor(a,b)
b = Bit.Xor(a,b)
a = Bit.Xor(a,b)
Log(a & " | " & b) 'Output: 110 | 120``````

#### wonder

##### Expert
Longtime User
Another way
B4X:
``````Dim a = 120, b = 110 As Byte 'Short / Int / Long
Log(a & " | " & b) 'Output: 120 | 110
a = Bit.Xor(a,b)
b = Bit.Xor(a,b)
a = Bit.Xor(a,b)
Log(a & " | " & b) 'Output: 110 | 120``````
Can you use it for floats and doubles without loosing precision?

#### Emme Developer

##### Well-Known Member
Longtime User
Can you use it for floats and doubles without loosing precision?
B4X:
``````    Dim a = 120.2, b = 110.7 As Float 'Short / Int / Long
Log(a & " | " & b) 'Output: 120.19999694824219 | 110.69999694824219
a = Bit.Xor(a,b)
b = Bit.Xor(a,b)
a = Bit.Xor(a,b)
Log(a & " | " & b) 'Output: 110 | 120``````

This is the log, bit.xor return an int so you lost the decimal values

#### Emme Developer

##### Well-Known Member
Longtime User
Ahh... if I remember, the arguments for Bit.Xor() are integers, right?
Yes, also the value got from Xor is an Int

#### Emme Developer

##### Well-Known Member
Longtime User
Using strings
B4X:
``````Dim a = "A", b =  "B" As String
Log(a & " | " & b) 'Output: A | B
a = A&B
b = A.replace(B,"")
a = A.replace(B,"")
Log(a & " | " & b) 'Output: B | A``````

Replies
5
Views
2K
Replies
4
Views
2K
Replies
3
Views
2K
Replies
29
Views
3K
Android Code Snippet NB6 class - additional functions
Replies
11
Views
9K