×
Namespaces

Variants
Actions
(Difference between revisions)

How to swap variable values in Java ME using bitwise operations

From Nokia Developer Wiki
Jump to: navigation, search
njzk2 (Talk | contribs)
hartti (Talk | contribs)
m (some formatting, added a category)
Line 1: Line 1:
[[Category:Java]][[Category:Java ME]][[Category:How To]][[Category:Code_Examples]]
+
[[Category:Java]][[Category:Java ME]][[Category:How To]][[Category:Code_Examples]][[Category:Level-Intermediate]]
 
+
How to swap variable values using bitwise operations.
+
 
+
 
Heres a sample code that swaps 2 variable values
 
Heres a sample code that swaps 2 variable values
 
<code java>
 
<code java>
Line 23: Line 20:
 
</code>
 
</code>
  
The above code can be considered as much more optimized in terms of other swapping code it does not use any temp variables,secoundly it uses bitwise operators which also do internally require temp varibales to do the operation and thirdly it will be faster then the normal swap operations as bitwise operations are considered to be faster then other normal operations.
+
The above code can be considered quite optimized. It does not use any temporary variables. Secoundly it uses bitwise operators which also do internally require temp varibales to do the operation. And thirdly it will be faster than the normal swap operations as bitwise operations are considered to be faster then other normal operations.

Revision as of 01:26, 28 October 2008

Heres a sample code that swaps 2 variable values

class test 
{
public static int a = 10,b = 20;
public static void main(String[] args)
{
test t = new test();
t.swap();
}
 
public void swap(){
a= a^b;
b = b^a;
a = a^b;
System.out.println("a "+a+" b "+b);
}
}

The above code can be considered quite optimized. It does not use any temporary variables. Secoundly it uses bitwise operators which also do internally require temp varibales to do the operation. And thirdly it will be faster than the normal swap operations as bitwise operations are considered to be faster then other normal operations.

154 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×