This section provides a tutorial example on how to use JAR files in class paths during Java compilation and execution time.
One advantage of aggregating individual class files into a JAR file is that other Java tools recognize
JAR files as collections of class files and allow you to use them in the class paths.
To test this, I created the following class, TempratureConvertorBean.java:
/**
* TempratureConvertorBean.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
package herong;
public class TempratureConvertorBean {
private double celsius = 0.0;
private double fahrenheit = 32.0;
public double getCelsius() {
return celsius;
}
public void setCelsius(double c) {
celsius = c;
fahrenheit = 1.8*c + 32.0;
}
public double getFahrenheit() {
return fahrenheit;
}
public void setFahrenheit(double f) {
fahrenheit = f;
celsius = (f-32.0)/1.8;
}
public String getInfo() {
return new String("My TempraturConvertorBean - Version 1.00");
}
}
I did the following to create a JAR file, herong.jar:
/**
* F2C.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
import herong.TempratureConvertorBean;
public class F2C {
public static void main(String[] arg) {
TempratureConvertorBean b = new TempratureConvertorBean();
double f = 0.0;
if (arg.length>0) f = Double.parseDouble(arg[0]);
b.setFahrenheit(f);
double c = b.getCelsius();
System.out.println("Fahrenheit = "+f);
System.out.println("Celsius = "+c);
System.out.println(b.getInfo());
}
}
Here is what I did to test using JAR files in a class path:
C:\herong>javac -classpath herong.jar F2C.java
C:\herong>java -cp .;herong.jar F2C 70.0
Fahrenheit = 70.0
Celsius = 21.11111111111111
My TempraturConvertorBean - Version 1.00
This is nice. Right? I can take herong.jar to anywhere on any system.
Just add it to "-classpath" for "javac" command, and "-cp" for "java" command.