Avatar ·

What is null/nil in Java and how to work with it?

Hello everyone! I'm learning Java basics and came across the concept of null. In some languages (e.g., SQL or Go) I'm used to the term nil. Do I understand correctly that Java doesn't have nil, and only null is used? And if so, what exactly is it — an empty reference or a special value?

The problem arose when I wrote a simple code with a User class and tried to call a method on an object that I hadn't initialized:

public class User {\n    String name;\n\n    void printName() {\n        System.out.println(name.length());\n    }\n\n    public static void main(String[] args) {\n        User user = null;\n        user.printName(); // Here a NullPointerException is thrown\n    }\n}\n

I expected th