Namespaces
Variants
Actions
Revision as of 09:04, 19 July 2012 by hamishwillee (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

How to swap variable values in Java ME using bitwise operations

Jump to: navigation, search
SignpostIcon Code 52.png
Article Metadata

Article
Created: giridharn (23 May 2007)
Last edited: hamishwillee (19 Jul 2012)


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.

160 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved