Tuesday, February 5, 2008

Quick Java Setup Tut

Being bred in C/C++, my eventual move to Java wasn't a smooth experience. Setting up the Java environment was something i found difficult to understand initially coming from C++, where essentially there was no such setting up required. The online tutorials I found were either too verbose and I could never find my way through the tones of literature, or they were on the complete opposite end of the spectrum, where I could never understand why I was doing whatever was asked to be done for setup. So here is my quick tut on setting up the Java environment..

1) Install Java SDK for your OS from sun's website
2) Setting the Environment Variables

JAVA_HOME: This is the root directory of the Java installation i.e., something that ends like jdk1.5.0

PATH: This is the list of directories the OS searches for the commands you invoke. If you want to be able to call java from anywhere, you need to make sure the OS can find it.. In other words, the java executable needs to be in the list of directories the OS looks in. The java exectuable and other dev tools are in the JAVA_HOME/bin directory. So edit the PATH variable to include the JAVA_HOME/bin directory

CLASSPATH: This was something i could never digest initially during my move from the C world. Unlike C/C++, you need to tell java where to look for the compiled source files a.k.a classes. And this is exactly what the CLASSPATH variable tells. I think Classpath defaults to current directory and the standard directories (under JAVA_HOME). If your code uses classes from other direcories/.jar files, you will need to include them in the CLASSPATH variable. Note that you need to fully specify the jar files, not just stopping with the containing directory.

Quick Example:

Assume I have installed Java at /home/yoda/jdk1.5.0. And the java source files (.java) I wrote are under /home/yoda/src. Also, my source files import the mysql-java.jar file(located under /home/yoda) and use classes under /home/yoda/ReusableClasses

I will be using bash for the e.g. Use appropriate modifications for setting and exporting environmental variables in your Shell.

vim ~/.bash_profile

JAVA_HOME=/home/yoda/jdk.1.5.0
PATH=$JAVA_HOME/bin:$PATH
CLASSPATH=/home/yoda/mysql-java.jar:/home/yoda/ReusableClasses

export JAVA_HOME PATH CLASSPATH

source ~/.bash_profile

Make sure the environment variables are set by echoing e.g. echo $PATH.

Now cd /home/yoda/src
Compiling: javac *.java
Running: java MyMain.java

1 comment:

Unknown said...

Heya¡­my very first comment on your site. ,I have been reading your blog for a while and thought I would completely pop in and drop a friendly note. . It is great stuff indeed. I also wanted to ask..is there a way to subscribe to your site via email?








Java Training Courses