2. Hello world

Your first Java program

Here is the Java program you ran from Setup, with some comments added. I've put the equivalent Python program here for comparison.

// java
class PrintHelloWorld { // a class called PrintHelloWorld
    public static void main(String[] args) { // the main method
        System.out.println("Hello world!");
    }
}
# python
 
def main():
    print("Hello world!");
 
main()

There are a few obvious differences from Python:

Methods?

You may have noticed that I called Java's main function a main method. A method is simply a function that's inside a class. Java requires all functions to be inside classes, so all Java functions are referred to as methods.

It's good to get used to the vocabularly Java programmers use because it will make it easier to search for help later on. Make an effort to adopt the terminology.

Exercises

Each section will have exercises at the end of it. It's very important to actually do them. You can't learn a programming language just by reading code; you have to actually write it.

These exercises will help you see some of the other ways Java is different from Python. Remember to recompile with javac every time you make a change to your code.


  1. Move the print statement outside of the PrintHelloWorld class, like this:

    System.out.println("Hello world!"); 
    class PrintHelloWorld {
        public static void main(String[] args) {
        }
    }

    Try recompiling. What happens? Now keep the print statement inside the class, but move it outside of the main method. What happens now?

  2. Try removing the class entirely so your program looks like this:

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

    Does the program still work? What about without the main method?

  3. Rename the main method to something else. Does your program still compile? Change the name back to main but remove some of the keywords from the main method declaration (like public or static). Try compiling/running your program.

  4. Change the name of the class to printhelloworld, all lowercase. What happens when you compile or run?

  5. Add another print statement that prints out your first and last name like this: System.out.println("FirstName" + " LastName"). Can you use a comma to separate strings like you would in Python: print("FirstName", "LastName")?

  6. If you deindent the print statement, the program will still work:

    class PrintHelloWorld {
        public static void main(String[] args) {
    System.out.println("Hello world!"); // deindented
        }
    }

    How much indentation can you remove before the program won't run or compile? Can you even put statements on the same line, like this:

    class PrintHelloWorld {
        public static void main(String[] args) { System.out.println("Hello world!");
        }
    }