Hello World Program in Java

The following is the most basic example of a Java program. You need the Java Development Kit installed in order to compile source code you write. If you don't have JDK installed on your computer, go here and click the link for your operating system for directions on how to install it. The following code contains many comments. Anything after two slashes // is ignored by the compiler. Programmers use comments to help themselves and each other keep track of what their code is meant to do. Be sure to read all comments in the code below:
  1. public class hello //declares name of the class. you must save this file as hello.java for it to run
  2.  
  3. {
  4.  
  5.         public static void main(String[] args) //this is the start of the main method. I will cover what everything here means in the second beginner tutorial.
  6.  
  7.         {
  8.  
  9.                 System.out.println("Hello, world!"); //this displays on the screen "Hello, world!"
  10.  
  11.         } //ends the main method
  12.  
  13. } //end of the class
In order to get the program running, first save it as hello.java. Open a command line or terminal, and type "cd" (without quotes) followed by the path to where you saved the file. If you saved it in Documents, type "cd Documents" and hit enter. Now, type "javac hello.java" and hit enter, then "java hello". Hit enter one last time and the program will run. You may notice that all it does is display "Hello, world!" in the terminal. This is called a console program. We could modify our program a bit so that it creates its own window. This is what is called a GUI (graphical user interface) program. Below is an example of a basic GUI program. Comments are only displayed on lines that were changed from above:
  1. import javax.swing.JOptionPane; //this imports java GUI elements from a pre-defined class. JOptionPane is necessary for GUI components
  2.  
  3. public class gui //changed the name to gui so it could be saved in the same directory as hello.java
  4.  
  5. {
  6.  
  7.         public static void main(String[] args)
  8.  
  9.         {
  10.  
  11.                 JOptionPane.showMessageDialog(null, "Hello, world!"); //this creates a window and displays "Hello, world!" in it
  12.  
  13.         }
  14.  
  15. }
That's all for today. If the GUI elements seem confusing now, don't worry! In the second beginner's tutorial, we will work with this same code and build upon it so that it can do more. Happy coding!

Add new comment