Here is the Java program you ran from Setup, with some comments added. I've put the equivalent Python program here for comparison.
|
|
There are a few obvious differences from Python:
//
instead of Python's #
.{ }
. That is, you can tell if code is inside a class or method because it'll be inside its { }
.;
(but don't put semicolons after { }
).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.
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.
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?
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?
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.
Change the name of the class to printhelloworld
, all lowercase. What happens when you compile or run?
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")
?
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!");
}
}