The First Exercise — Hello World

Write a simple Java program to demonstrate

  1. Creating a project
  2. Creating a package
  3. Creating a class
  4. Declaring variables : String
  5. Console output
  6. Compiling and running a program

Creating a Project

Go to “File → New → Java Project”. Set “LabAssignments” as the new project name. Check the default JRE being used.

Project Creation

Creating a Package

Go to “File → New → Package”. Set the name of the package as “lab1”. (Note the use of lowercase for the package name).

Package Creation

Creating a Class

  1. Right-click on “LabAssignments” in the package explorer window, or go to “File → New → Class”.
  2. Select the package as “lab1”.
  3. Type the name of the class as “HelloWorld”.
  4. Select the “public” class modifier.
  5. Check “public static void main(String[] args)” to automatically create an empty main function.
  6. Click on finish.

The HelloWorld.java file is created in the “src” directory in the project location, and is displayed in the editor window.

Class Creation

Declaring variables : String

Inside the main function, declare and initialize a string to contain “Hello World”.

  String str = "Hello World";

Console Output

Use

  System.out.println(str);
to print “Hello World” to the console.

Compiling and Running the program

Whenever the Java file is saved in Eclipse, it gets compiled.

  1. Go to “Run → Run” (hotkey: F11) to compile and run the Java program. The “arrow in red circle” button in the toolbar can also be used.
  2. Check the problems window for any errors/warnings. If there are any compiler errors, they will be displayed in the editor window, and with a red mark on the left side of the corresponding line.
  3. Hover the mouse cursor over the red mark to see the explanation of the error.
  4. Program output will be displayed in the console window.