Hello World
The structure of this crash course was borrowed from learnjavaonline.org
The Java Crash Course slides cover more areas but in less detail.
A good place to start and test the Java Installation is with the classic Hello World.
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Compiling and running the above code will output Hello, World!.
Lets analyse the parts of the code.
public class Main {...
- Defines a class with the name
Main. - The name of source file has to match the name of the class defined in it. In this case it is
Main.java. - Only one class can be defined per source file.
- Methods can only be defined in a class.
- Statements can only be written in a class definition.
- Unlike C++, there are no header files. One source file will contain your class and method definitions.
publicindicates the class is accessible from other Java Packages. In the context of COS 212 onlypublic classwill be used.
public static void main(String[] args) {...
- This is the entry point for our program. The signature has to match exactly as above.
- The Access Level Modifier
publicspecifies that the method is visible to all classes.privatespecifies that is is accessible only within the class.
staticspecifies that the method can be called without instantiating an instance of the class.- i.e
Main.main()
- i.e
voidspecifies that the method returns no value.String[]is the type for an array ofStrings. We will go over the different types soon.argswill contain the command line arguments used to start the program.
System.out.println("Hello, World!");
Systemis a Java class providing useful class fields and methods.outis a static member variable that represents the "standard" output stream.printlnis a method ofoutthat prints the given string along with a new line character.