Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

(Difference between revisions)

How to swap variable values in Java ME using bitwise operations

From Wiki
Jump to: navigation, search
vkmunjpara (Talk | contribs)
hamishwillee (Talk | contribs)
m (Automated deletion of category:Level-Intermediate. (This category is too subjective.))
Line 1: Line 1:
[[Category:Java ME]][[Category:How To]][[Category:Code_Examples]][[Category:Level-Intermediate]]
[[Category:Java ME]][[Category:How To]][[Category:Code_Examples]]
Heres a sample code that swaps 2 variable values
Heres a sample code that swaps 2 variable values
<code java>
<code java>

Revision as of 00:06, 24 March 2011


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();
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.

121 page views in the last 30 days.