Thursday, April 2, 2015

Interesting java codes

Most of the software engineers are living with java programs daily for their big projects. But the real fact is, we all are doing Copy Paste job, because mostly your working projects will be well designed. As we are very busy with Copy Paste job, some times we failed to understand the some basic interesting things in java. Some of us might be experienced with interesting things in java programs. I am sharing few things here which i have learned.

Some of us might though that, below code will not compile. But below code will compile and execute

     public class Curiosity {
           public static void main (String[ ] args) {
                System.out.println ("A curiosity");
                http://google.com
                System.out.println ("compile Ok!");
          }
     }
Output:
A curiosity
compile Ok!

Reason is simple, many of us aware of label statement in java. So here "http:" is label and // is comment line.

The next one is strange. Is is possible to call any method or field by null reference?. Most of us will give answer as NO. We have seen NullPointerException many times, so we thought that, below code will give run time exception. But below code will compile and execute successfully.

     public class Foo {
           static int fubar = 30;
           public static void main(String args[]) {
                Foo foo = null;
                System.out.println(foo.fubar);
           }
     }
Output:
30

Reason: Here, we have to notice variable declaration of "fubar". "fubar"is declared as static, so this will be stored in Method Area. Static variables are accessed via class and though the object is null, the type Foo is what is used to determine reference to the variable.

No comments:

Post a Comment