Showing posts with label Long Caching. Show all posts
Showing posts with label Long Caching. Show all posts

Friday, 5 February 2016

Java - Interning

public static void main(String[] args) {

    Long long1 = new Long(1234);
    Long long2 = long1;

    // Does this compare references or actual values? 
    if (long1 == long2) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }
 
    // Displays "Equal"
 
    long2 = new Long(1234);

    // Let's create a new object with the same value to see if this works.
    if (long1 == long2) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }

    // Displays "Not Equal" 
 
    // Let's compare the Long wrapper with its equivalent primitive. 
    if ((new Long(1234) == 1234) && (Long.valueOf(1234) == 1234)) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }

    // Displays "Equal" 

    long1 = Long.valueOf(1234);
    long2 = Long.valueOf(1234);

    // We've now used valueOf() instead of creating a new Long, just to see if it works. 
    if (long1 == long2) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }

    // Displays "Not Equal"   
 
    // Numbers in the range [-128, 127] are cached. 
    long1 = (Long.valueOf(127);
    long2 = (Long.valueOf(127);

    if (long1 == long2) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }

    // Displays "Equal" 

    // So let's prove it for numbers greater than 127. 
    if ((Long.valueOf(128) == Long.valueOf(128))) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }
 
    // Displays "Not Equal" 
 }