Sunday, May 15, 2016

Writing your First Java Program in Eclipse

Step 0: Launch Eclipse
  1. Start Eclipse by running "eclipse.exe" in the Eclipse installed directory.
  2. Choose an appropriate directory for your workspace (i.e., where you would like to save your files).
  3. If the "Welcome" screen shows up, close it by clicking the "close" button.
Step 1: Create a new Java Project
 
For each Java application, you need to create a project to keep all the source files, classes and relevant resources.
To create a new Java project:
  1. Choose "File" menu ⇒ "New" ⇒ "Java project".
  2. The "New Java Project" dialog pops up.
    1. In the "Project name" field, enter "FirstProject".
    2. Check "Use default location".
    3. In the "JRE" box, select "Use default JRE (currently 'JDK1.x')". But check the JDK version, you should be using JDK 1.5 and above.
    4. Click "Finish".
Step 2: Write a Hello-world Java Program
  1. In the "Package Explorer" (left panel) ⇒ Right-click on "FirstProject" (or use the "File" menu) ⇒ New ⇒ Class.
  2. The "New Java Class" dialog pops up.
    1. In "Name" field, enter "Hello".
    2. In "package" field, delete the content if it is not empty.
    3. Check "public static void main(String[] args)" box.
    4. Click "Finish".
  3. The source file "Hello.java" opens on the editor panel. Enter the following codes:
    public class Hello {   // "Hello.java"
       public static void main(String[] args) {
          System.out.println("Hello, world!");
       }
    }
Step 3: Compile & Execute the Java Program
  1. There is no need to compile the Java source file explicitly. It is because Eclipse performs the so-called incremental compilation, i.e., the Java statement is compiled as and when it is entered.
  2. To run the program, right-click anywhere on the source file "Hello.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application".
  3. The output "Hello, world!" appears on the "Console" panel.
NOTES:
  • You should create a new Java project for each of your Java application.
  • Nonetheless, Eclipse allows you to keep more than one programs in a project, which is handy for writing toy programs (such as your tutorial exercises). If you have more than one files with main() method in one project, you need to right-click the source and choose "Run As" ⇒ "Java Application" to run that particular source. Clicking the "Run" button runs the recently-run program (based on the previous configuration). Try clicking on the "down-arrow" besides the "Run" button.

No comments:

Post a Comment