Hello World

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

The Hello World problem has been around almost as long as modern programming has. Traditionally, when trying a new programming language or technology, developers and students like to make their new medium say hello. Because of this, the Hello World problem will be your first Java application.

When executed, this application will display a message box saying "Hello World!".

 

Getting Started

Wiki start01.jpg

Solution

The solution is in three steps:

  • Import the JOptionPane library.
  • Create the HelloWorld class and main method.
  • Use JOptionPane's showMessageDialog to display a message.

To start, in a new .java file, import the JOptionPane library. Do this by typing the following:

import javax.swing.JOptionPane;

This tells Java that when we use the showMessageDialog method later, it knows where to look for it.

Next, create a Hello World java class. In your .java file under the import statement, create a public class called "HelloWorld" and a standard main method within the class.

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

Now you are ready to create the body of your program. From the JOptionPane library you imported earlier, reference the showMessageDialog method. This method takes two parameters, a Parent object and a String object. We don't need to worry about a Parent object for this problem so we can just pass the method null instead. As for the String, this is where you will write your message.

JOptionPane.showMessageDialog(null, "Hello World!");

Finally, compile and run your application. Congratulations! You've written your first Java application. It doesn't do much for now but don't worry, you'll learn much more later. Also note that it's a good idea to keep your HelloWorld.java file around since it's a convenient template for future Java applications you may write.

Code

Solution Code

Back to the Program-A-Day homepage