Running Code Outside of Main

I notice that Mosh often runs code in a class other than Main. I haven’t figured out how to do this. I’ve been adding the class from the lesson to Main and running from there. Is anyone able to explain how to run the from classes other than main. Thank you!

Hi it is a convention in Java that the Main class acts as the entry point to your program so code is mostly run from this class. However, if you just add a main method to another class you could also run it from there like:

public class Secondary {
    public static void main(String[] args) {
        System.out.println("hi");
    }
}
1 Like

If you mean how to actually run the program, try the keyboard shortcuts:

on windows:

-shift + F10 to run Main (only have to do once inside main)
-ctrl+f5 (to rerun main anywhere from other classes etc)

1 Like

Thank you! Both of these answers are helpful :slightly_smiling_face: