0

[![enter image description here][1]][1]In my opinion,the first output should be "hello",but why the first output is "world" ?

    public static void main(String[] args) {
        System.out.println("hello");
        test();
    }
    public static void test() {
        System.out.println("world");
        main(null);
        System.out.println("!");
    }
   }


  [1]: https://i.stack.imgur.com/SXSHY.png
super_man
  • 21
  • 2

1 Answers1

1

The main method is run by default. It is run first. Inside the main method, it:

  • prints "hello"
  • calls the test() method

In the test() method, it:

  • prints "world"
  • calls the main() method

And the process repeats, resulting in a StackOverflowError.

The main method was run first, so the order of events is as so:

  • prints "hello"
  • calls the test() method
  • prints '"world"`
  • calls the main() method

Therefore it prints "hello" first.

Spectric
  • 30,714
  • 6
  • 20
  • 43