First Java Program - Exercise

Contact Us or call 1-877-932-8228
First Java Program - Exercise

First Java Program

Duration: 5 to 15 minutes.
  1. Create a file called
  2. Enter the following code:
    public class Hello {
    	public static void main(String[] args) {
    		System.out.println("Hello World");
  3. Save the file.
  4. In a command prompt window, change to the directory where is stored and type the following:
    1. A prompt on the next line without any error messages indicates success.
  5. Type:
    java Hello
  6. Press Enter.
    1. You should see the message Hello World print in the window.
public class Hello
  • All Java code must be within a class definition.
  • A class defines a type of object.
  • A public class can be accessed by any other class.
  • A public class must be in its own file, whose name is the name of the class, plus a dot and an file extension of java (e.g., ).
    	. . .
  • Curly braces denote a block of code (the code inside the braces).
  • Code within braces usually belongs to whatever immediately precedes them.
    public static void main(String[] args) {
  • Words followed by parentheses denote a function.
  • To be executable by itself, a class must have a function defined in this fashion; the name main means that execution will start with the first step of this function, and will end when the last step is done.
  • It is public because it needs to be executed by other Java objects (the JVM itself is a running Java program, and it launches your program and calls its main function).
  • It is static because it needs to exist even before one of these objects has been created.
  • It does not return an answer when it is done; the absence of data is called void.
  • The String[] args represents the additional data that might have been entered on the command line.
System.out.println("Hello World!");
  • System is an class within the JVM that represents system resources.
  • It contains an object called out, which represents output to the screen (what many environments call standard out).
  • Note that an object's ownership of an element is denoted by using the name of the object, a dot, and then the name of the element.
  • out in turn contains a function, println, that prints a line onto the screen (and appends a newline at the end).
  • A function call is denoted by the function name followed by parentheses; any information inside the parentheses is used as input to the function (called arguments or parameters to the function).
  • The argument passed to println() is the string of text "Hello World!".
  • Note that the statement ends in a semicolon (as all do Java statements).