Core Java

Java puzzlers from OCA part 1

I’m reading Oracle Certified Associate Java SE Programmer book from Mala Gupta in my spare time and I’m surprised with some of the new things I learn. Some of the time they really don’t make sense, some of the time they make sense but really surprising to see. So in this article series, I wanted to share them as “Java Puzzlers” which sounded much cooler than “Java Surprises”.

Lets check the below code and see what happens when we call an empty object reference’s static method or field.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
public class Puzzler {
 
    public static int field = 1;
 
    public static void printField() {
        System.out.println(field);
    }
 
    public static void main(String[] args){
        /*
        * Lets see what happens when the
        * reference is null.
        * */
 
        Puzzler puzzler = null;
        puzzler.printField(); // prints 1
        System.out.println(puzzler.field); // prints 1
    }
 
}

When you try to guess what will happen, you can think that we will get NullPointerException while doing the method and field calls as the reference does not have an object attached to it. But remember that static methods and fields belong to the class itself and not to the instance. So without the need of an associated object you can use them and won’t get an exception for doing that. An also the way we call the static method are usually in Puzzler.printField() form which tells more.

Published on Java Code Geeks with permission by Sezin Karli, partner at our JCG program. See the original article here: java puzzlers from oca part 1

Opinions expressed by Java Code Geeks contributors are their own.

Sezin Karli

Mathematics Engineer & Computer Scientist with a passion for software development. Avid learner for new technologies. Currently working as Senior Software Engineer at Sahibinden.com.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button