0

I was checking System.out.println to understand composition of Java and i tried to make a similar of it like this;

FakeSystem class

public class FakeSystem {
public final static Print out = null;
}

Print class

public class Print {
public void print(String text){
    System.out.println(text);
 }
}

Main class

public class Main {
public static void main(String[] args) {
    FakeSystem.out.print("my text");
 }
}

It gives NullPointerException when i do this but it has null when i check "out" variable of original System class at java.lang package. It gives "my text" output when i change "out" variable to this;

public final static Print out = new Print();

I wanna understand why doesn't it work when i make it null.

krystal
  • 35
  • 1
  • 8
  • Please read this (https://stackoverflow.com/questions/2707322/what-is-null-in-java). null means your field doesn't point to an actual object. How do you expect to call a method on a nonexistent value? – user May 18 '20 at 18:21
  • but original out variable of System class is like - PrintStream out = null; – krystal May 18 '20 at 18:22
  • It is later set to something else, depending on where your code executes – user May 18 '20 at 18:23
  • In FakeSystem class initialize the Print object as Print out = new Print(); – Chitraveer Akhil May 18 '20 at 18:23
  • @ChitraveerAkhil Yeah, the OP did that, they were just wondering why setting it to null worked in java.lang.System but not in their own class – user May 18 '20 at 18:25
  • @krystal If you go to the source code (https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/lang/System.java) you'll see there's a static block that looks like `static { registerNatives(); }`. I'm fairly certain that's where `out` is set – user May 18 '20 at 18:27
  • @user oh thank you, i didnt think of it is later set to something else. – krystal May 18 '20 at 18:28

0 Answers0