The following will describe how to create a minimal Java program using Eclipse. It will be the classical "Hello World" program. Our program will write "Hello Eclipse!" to the console.
Select from the menu File -> New-> Java project. Maintain "de.vogella.eclipse.ide.first" as the project name. Select "Create separate source and output folders".
Press finish to create the project. A new project is created and displayed as a folder. Open the folder "de.vogella.eclipse.ide.first"
Create now a package. A good convention is to use the same name for the top package as the project. Create therefore the package "de.vogella.eclipse.ide.first".
Select the folder src, right mouse click on it and select New -> Package.
Right click on your package and select New -> Class
Create MyFirstClass, select the flag "public static void main (String[] args)"
Maintain the following code.
package de.vogella.eclipse.ide.first;
public class MyFirstClass {
public static void main(String[] args) {
System.out.println("Hello Eclipse!");
}
}
Now run your code. Right click on your Java class and select Run-as-> Java application
Finished! You should see the output in the console.
To run your Java program outside of Eclipse you need to export it as a jar file. Select your project, right click on it and select "Export".
Select JAR file, select next. Select your project and maintain the export destination and a name for the jar file. I named it "myprogram.jar".
Press finish. This will create a jar file in your select output directory.
Open a command shell, e.g. under Microsoft Windows select Start -> Run and type in cmd. This should open a consle.
Switch to your output directory, e.g. by typing cd path, e.g. if you jar is located in "c:\temp" type "cd c:\temp".
To run this program you need to include the jar file into your classpath. See Classpath and Java JAR Files for details.
java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass
Congratulations! You created your first Java project, a package a tiny Java program and you ran this program inside Eclipse and outside
0 comments:
Post a Comment