Skip to content

Instantly share code, notes, and snippets.

@ygolecha
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ygolecha/9136643 to your computer and use it in GitHub Desktop.
Save ygolecha/9136643 to your computer and use it in GitHub Desktop.
Source code for example showing Autoboxing and Unboxing
/*
* Author : Yashwant Golecha (ygolecha@gmail.com) *
* http://idlebrains.org/tutorials/java-tutorials/primitives-boxed-primitives-autoboxing-unboxing/
*/
package oracle.apps;
import java.util.Comparator;
import java.util.Date;
public class SlowAutoboxing {
public SlowAutoboxing() {
super();
}
public static void main(String[] args) {
autoBoxingInLopp();
withoutAutoBoxingInLopp();
autoBoxingInLopp2();
// Uncomment following line to see NPE.
//shocking();
// compare();
// improvedCompare();
}
public static void autoBoxingInLopp() {
Date startTime = new Date();
Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println("Sum : " + sum);
Date endTime = new Date();
long timeDiff = endTime.getTime() - startTime.getTime();
System.out.println("With Autoboxing in loop : " + timeDiff + " ms");
}
public static void withoutAutoBoxingInLopp() {
Date startTime = new Date();
long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println("Sum : " + sum);
Date endTime = new Date();
long timeDiff = endTime.getTime() - startTime.getTime();
System.out.println("Without Autoboxing in loop : " + timeDiff + " ms");
}
public static void autoBoxingInLopp2() {
Date startTime = new Date();
Long sum = 0L;
for (Long i = 0L; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println("Sum : " + sum);
Date endTime = new Date();
long timeDiff = endTime.getTime() - startTime.getTime();
System.out.println("With Autoboxing in loop : " + timeDiff + " ms");
}
static Integer i;
public static void shocking() {
if(i == 1)
System.out.println("Shocking !!");
else
System.out.println("Expected !!");
}
public static void compare() {
Comparator<Integer> naturalOrder = new Comparator<Integer>() {
public int compare(Integer first, Integer second) {
return first < second ? -1 : (first == second ? 0 : 1);
}
};
Integer i = new Integer(21);
Integer j = new Integer(21);
System.out.println(naturalOrder.compare(i, j));
}
public static void improvedCompare() {
Comparator<Integer> naturalOrder = new Comparator<Integer>() {
public int compare(Integer first, Integer second) {
int f = first; int s = second;
return f < s ? -1 : (f == s ? 0 : 1);
}
};
Integer i = new Integer(21);
Integer j = new Integer(21);
System.out.println(naturalOrder.compare(i, j));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment