×
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
hamishwillee (Talk | contribs)
hamishwillee (Talk | contribs)
m (Hamishwillee - Fix categories)
Line 1: Line 1:
 +
[[Category:Java ME]][[Category:Code Snippet]][[Category:Math]]
 
{{ArticleMetaData <!-- v1.1 -->
 
{{ArticleMetaData <!-- v1.1 -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
Line 23: Line 24:
 
}}
 
}}
  
[[Category:Java ME]][[Category:How To]][[Category:Code Snippet]]
+
 
 
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 08:24, 13 July 2012

Article Metadata
Article
Created: giridharn (23 May 2007)
Last edited: hamishwillee (13 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.

173 page views in the last 30 days.
×