JPad
Snippets
Download
Help
Contact
new vs valueOf()
new vs valueOf()
Code
Integer a = new Integer("1"); Integer b = new Integer("2"); System.out.println(a == b); // false Integer c = 1; Integer d = 1; System.out.println(c == d); // true - because autoboxing uses valueOf() which use cached immutable values between -128..127 Integer e = 1000; Integer f = 1000; System.out.println(e == f); // false because outside the cached values range
Result
Console
false true false
Bytecode
Compiled from "RunnContainer.java" public class io.jpad.scratch.RunnContainer { public io.jpad.scratch.RunnContainer(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String...) throws java.lang.Exception; Code: 0: new #2 // class java/lang/Integer 3: dup 4: ldc #3 // String 1 6: invokespecial #4 // Method java/lang/Integer."<init>":(Ljava/lang/String;)V 9: astore_1 10: new #2 // class java/lang/Integer 13: dup 14: ldc #5 // String 2 16: invokespecial #4 // Method java/lang/Integer."<init>":(Ljava/lang/String;)V 19: astore_2 20: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream; 23: aload_1 24: aload_2 25: if_acmpne 32 28: iconst_1 29: goto 33 32: iconst_0 33: invokevirtual #7 // Method java/io/PrintStream.println:(Z)V 36: iconst_1 37: invokestatic #8 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 40: astore_3 41: iconst_1 42: invokestatic #8 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 45: astore 4 47: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream; 50: aload_3 51: aload 4 53: if_acmpne 60 56: iconst_1 57: goto 61 60: iconst_0 61: invokevirtual #7 // Method java/io/PrintStream.println:(Z)V 64: sipush 1000 67: invokestatic #8 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 70: astore 5 72: sipush 1000 75: invokestatic #8 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 78: astore 6 80: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream; 83: aload 5 85: aload 6 87: if_acmpne 94 90: iconst_1 91: goto 95 94: iconst_0 95: invokevirtual #7 // Method java/io/PrintStream.println:(Z)V 98: return }
Jpad Version:1.07
viewCount:2022
Creator:
graemeg
Latest Editor:
graemeg
Tags
java
Download
Copy As Markdown:
**code [new vs valueOf().java](/example/1P/new-vs-valueof-)** Integer a = new Integer("1"); Integer b = new Integer("2"); System.out.println(a == b); // false Integer c = 1; Integer d = 1; System.out.println(c == d); // true - because autoboxing uses valueOf() which use cached immutable values between -128..127 Integer e = 1000; Integer f = 1000; System.out.println(e == f); // false because outside the cached values range **Result:** false true false