VOOZH about

URL: https://www.javacodegeeks.com/2020/04/java-puzzlers-from-oca-part-1.html

⇱ Java puzzlers from OCA part 1 - Java Code Geeks


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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

👁 Photo of Sezin Karli
Sezin Karli
April 22nd, 2020Last Updated: April 21st, 2020
0 74 1 minute read

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

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

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz