Skip to main content
OCA Java Programmer 1Z0-803

Your First Java Program

To make are start learning Java we will build a program with the ubiquitous “Hello World” output but we can then add a little extra to display the current user name. Java is cross platform so any code that you write on your OS should be able to run on any other OS within the Java Virtual Machine. I will use Linux as my development platform OS but you may use the OS that is most convenient to you with Java 7 SE installed. We we build our program mostly with plain text editors, in Linux I will use vi. Integrated Design Environments or IDEs are very useful but when you are starting out with a language the repetition of typing in a text editor is good rather than relying on the code  completion features of IDEs that can auto-complete for you.

First we create the source file HelloWorld.java; note that JAVA is case-sensitive and it is normal to create the java files based on the class that will be created. In the JAVA file we will create a class definition, in this case, we want to call it HelloWorld. The source file then ius names after the class that it contains.

Within the HelloWorld.java file we define the CLASS:

public class HelloWorld {
}

Within the class we define a method, if the class will be run directly it must contain a main method.

public class HelloWorld {
public static void main(String[] args) {
  }
}

Within the method we use the System object to write output to the screen, Hello World. The System object is part if the inherent package java.lang :

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

Notice the semi-colon at the end of the line of code within the method!

Now we can save the file and from the same directory as the .java file we can run the java compliler. This will make the class file which is the java binary.

javac HelloWorld.java

We can run the class file with

java HelloWorld

If we would like to extend the program to display the users name we can use the System object again to retrieve the name of the user. Modify the code so that it reads similar to this

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello " + System.getProperty("user.name"));
  }
}

You must compile the code again and rerun the class file, your output should be similar to this: