The First Exercise — Hello World
Write a simple Java program to demonstrate
- Creating a project
- Creating a package
- Creating a class
- Declaring variables : String
- Console output
- 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.
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).
Creating a Class
- Right-click on “LabAssignments” in the package explorer window, or go to “File → New → Class”.
- Select the package as “lab1”.
- Type the name of the class as “HelloWorld”.
- Select the “public” class modifier.
- Check “public static void main(String[] args)” to automatically create an empty main function.
- Click on finish.
The HelloWorld.java file is created in the “src” directory in the project location, and is displayed in the editor window.
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.
- 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.
- 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.
- Hover the mouse cursor over the red mark to see the explanation of the error.
- Program output will be displayed in the console window.