Java Course - Creating a Java Application with Eclipse

This free online course will walk you through creating a Java project in Eclipse, including compiling, packaging into a jar file, and running the application from the command line. It assumes you have already installed Eclipse on your system and have completed the Eclipse Tutorial - Installing and Running Eclipse.

Creating a Java Project

A Java project in Eclipse will contain all of the .java class files that our application needs, along with any .jar file libraries that our application might depend on.

Start Eclipse and select File - New - Project from the main menu. You'll see the New Project wizard where you'll select Java Project. We'll choose the name assign01, since this is the lesson exercise I give students on the first week of class.

Click "Finish" to accept the remaining default settings for a new Java project.

Creating a Java class

We'll create a math utility application that calculates the average value of a set of numeric values. Nothing complex, but enough to gain a good understanding of how to use Eclipse to create and package a Java application.

Select File - New - Class from the main menu. You'll see a New Java Class wizard which will ask for the name and location of the new source code file. Enter MathUtil as the file name and cis as the package (short for Computer Information Systems). NOTE: Be sure to check the option to create a public static void main method, since this will be the entry point to our application when we run it from the command line.

At this point you should see the following code module in your Eclipse project. You may need to select the Package Explorer tab in order to see a hierarchical view of your Java source files and packages.

Inside the public static void main method, type the following line of Java code:

System.out.println("I did it!");

We'll come back later and add the math calculation logic, but for now let's focus on compiling, packaging, and running our application.

Compiling the Code

Eclipse automatically compiles Java source code each time a source file is saved. It even goes a step further and automatically compiles your code in the background as you type, which enables it to indicate programming errors before you even save the file.

If you’ve made a programming error, Eclipse will display a red underline at the point where the error was made. You’ll also notice a yellow light bulb icon in the left margin. Click this icon and Eclipse will give you a list of options you can choose to automatically correct your mistake (e.g. if you forgot to include an import statement for an object you’re trying to reference, Eclipse will offer to add the import statement for you). I really like this feature!

Packaging the Application

Most real-world Java applications consist of more than one .java source code file, and include multiple packages. Java provides a way to bundle these files together into a single .jar file – JavaARchive – with a zip file format. These files can also be opened using Winzip or comparable unzipping utility.

Select your project in Eclipse, and then select the File -- Export menu. Choose the “JAR file” export destination and click Next to identify the files that will be included in the .jar file.

In the JAR Export dialog shown below, be sure to check the options for exporting generated class files, as well as java source files. Be sure to use the Browse button to identify the name and location of the .jar file.

Click "Next" and check the option to save the description of this jar in the workspace. Eclipse will save the settings you have chosen for this export in a file of your choosing, ending with a .jardesc file extension. Then the next time you want to package your application, you can simply right-click on the .jardesc file and select "Create JAR".

NOTE: Always use the Browse button if one is available. Eclipse is not always consistent with its use of relative verses absolute paths.

Click Next to define the manifest file settings. Java uses a manifest.mf file to determine the entry point to your application (a .java file containing a public static void main method). Check the options to save the manifest in the workspace, and use the Browse button to identify the main class.

The last remaining step is to click the Finish button and let Eclipse create the .jar file. You’ll notice that the manifest.mf and a .jardesc file are displayed in Eclipse, and possibly your .jar file if you saved it in the same location as your project files.

After you have packaged the application, if you make additional changes and wish to repackage the jar file, simply right-click on the jardesc file and select “Create JAR”. Eclipse will use your previous settings to repackage your project files into a jar file.

Running the Packaged Application from the Command Line

Open a command prompt window and navigate to the folder containing the packaged jar file. Use the java command with the –jar parameter to execute the jar file:

Values can be passed to your application by typing them on the command line and separating them with spaces:

These values are passed into the public static void main method in the form of a String array called args. The code sample below iterates through each value passed in from the command line and prints them back out to the command line (System.out).


public static void main(String[] args) {

   for (int i = 0; i < args.length; i++) {
     System.out.println("Arg" + i + ": " + arg[i]);
   }

}



Congratulations - you've just created your first Java application, compile it, packaged it, and ran it from the command line! You're ready now to use Eclipse to build a real world Java application, such as the MathUtil program that will calculate the average of command-line input parameters.

Here's the MathUtil exercise, and please feel free to use the forum to post any questions you may have while you work through the assignment:

Exercises:

  1. Create a new Java project in Eclipse.
  2. Add a Java class called MathUtil to the project, in a cis package. Create a public static void main(String[] args) method, so that it can be run as a stand-alone application from within Eclipse or from the command-line. The MathUtil class should accept from 0 to 5 command-line arguments representing numbers, and should calculate the average (mean) and print it to System.out.
  3. Configure your Eclipse project so that it contains a src folder for .java source files, and compiles .class files into a classes folder.
  4. Use the File -> Export menu option in Eclipse to package your application in a jar file, including all .java source files and compiled .class files. Be sure to also include a manifest.mf file that allows your jar file to be run from the command line using the command java -jar YourJarFile.jar.

Additional Exercises:

  1. Consider adding exception handling logic in case the input parameters are not numeric.
  2. Consider also checking the number of inputs and adding "user-friendly" responses that help the user understand how to use the program.
  3. Be sure to add plenty of code comments in your source code, so that someone else looking at your code will be able to quickly understand what your code is attempting to do.

DiskCopy and Clean - Download

DiskCopy and Clean - Download

Safely Copy Everything to Your New Drive & Permanently Erase Data from Your Old Drive Are you purchasing a new hard drive? Disk Copy & Clean is the perfect solution for upgrading from your old hard drive to your new hard drive. DiskCopy & Clean moves all your data, applications and Windows to your new hard in one easy step. Plus, if you have partitions on your old hard drive, they can be moved and expanded proportionally to your new hard drive.

Special Offer: Save 20% with Coupon Code AFDCC20

Regarding Error in using jar file for accepting commandline para


I followed all the instructions you gave to create a jar file and I created a jar file. When I am trying to use it in command line , it showing error as Unable to use jar file.....

Can you let me know what mistake i did?

File is
public class MyEcho {
public static void main(String[] args){
if(args.length>0)
System.out.println("echoing:"+args[0]);
else
System.out.println("Usage: 'java MyEcho '");
}
}

Usage in commandline as
C:\projects> java -jar MyEcho.jar Hello...

Thanks

Good lecture notes


Good lecture notes (Powerpoint format) - wish I had this level of information back when I was first learning Tomcat.

How do I package


How do I package dependencies (other JARs) into the JAR and make it run?

You can't bundle dependent jars in the same jar


Unfortunately there's no out-of-the-box way to package dependencies into a single jar file and be able to run it from the command line.

There's an open soure project called One-Jar that has an excellent description of the reasons for this limitation, and a solution as well.

Development Tools


Just curious to know what are some of the other tools commonly used for development
other than Eclipse?

Thanks
Biruntha

IntelliJ IDEA is popular too, but Eclipse rules


IntelliJ IDEA is probably the second most widely used IDE:
http://www.jetbrains.com/idea/

IBM's WebSphere (now called RAD for Rapid Application Developer) is based on Eclipse.

JBuilder is also used (Borland), but Eclipse does most everything
JBuilder does and for free. I worked at a shop about 3 years ago
that switched from JBuilder's $3000 per license to Eclipse's free
licenses, and we all liked Eclipse a lot better.

I have never seen NetBeans used at a company in my entire career,
although it's come a LONG way and looks to be very feature packed.
Unfortunately, they missed the boat at a time when Eclipse and IntelliJ
were snatching up the market share... and it's a big thing for a company
to switch IDEs (we're talking major turf wars between developers, heated
arguments, dirty looks, the whole works ;-) )