001package algs11; 002import stdlib.*; 003/* *********************************************************************** 004 * Compilation: javac java 005 * Execution: java Autoboxing 006 * 007 * Headaches with autoboxing. Why does the following code behave 008 * the way it does? 009 * 010 * % java Autoboxing 011 * 42 and 42 are incomparable 012 * 43 == 43 013 * 142 and 142 are incomparable 014 * 015 * Explanation: 016 * - cmp(new Integer(42), new Integer(42)) 017 * first and second refer to different objects holding the value 42; 018 * thus, first != second. 019 * The expressions (first < second) and (first > second) autounbox 020 * the Integer values to 42, so neither expression is true. 021 * 022 * - cmp(43, 43) 023 * the values 43 are autoboxed to the same Integer object because 024 * Java's Integer implementation caches the objects associated with 025 * the values -128 to 127 and the valueOf() method uses the cached 026 * values (and valueOf() gets called by the autoboxing). 027 * 028 * - cmp(142, 142) 029 * the values 142 are autoboxed to different Integer objects. 030 * 031 * 032 * 033 *************************************************************************/ 034 035public class XAutoboxing { 036 037 public static void cmp(Integer first, Integer second) { 038 if (first < second) StdOut.format("%d < %d\n", first, second); 039 else if (first == second) StdOut.format("%d == %d\n", first, second); 040 else if (first > second) StdOut.format("%d > %d\n", first, second); 041 else StdOut.format("%d and %d are incomparable\n", first, second); 042 } 043 044 public static void main(String[] args) { 045 cmp(new Integer(42), 43); 046 cmp(new Integer(42), new Integer(42)); 047 cmp(Integer.valueOf(42), Integer.valueOf (42)); 048 cmp(43, 43); 049 cmp(142, 142); 050 051 double x1 = 0.0, y1 = -0.0; 052 Double a1 = x1, b1 = y1; 053 //StdOut.println(x1 == y1); /* eclipse warns: comparing identical expression */ 054 StdOut.println(a1.equals(b1)); 055 056 double x2 = 0.0/0.0, y2 = 0.0/0.0; 057 Double a2 = x2, b2 = y2; 058 StdOut.println(x2 != y2); 059 StdOut.println(!a2.equals(b2)); 060 } 061 062}