Showing posts with label Java. Show all posts
Showing posts with label Java. 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" 
 }

Thursday, 4 February 2016

Java - Difference between System.gc() and Runtime.getRuntime().gc()

public static void main(String[] args) {
    // Some code here
    // Invoke the Garbage Collector here.
     System.gc();

    // Some more code here
    // Invoke the Garbage Collector again.
     Runtime.getRuntime().gc();
}
 
In the above code, both calls seem to invoke the Garbage Collector. So what is the difference between System.gc() and Runtime.getRuntime().gc()?

Looking at the API documentation for System.gc() it invokes Runtime.getRuntime().gc()which means they are the same and System.gc() is only a convenience method.