Friday, January 27, 2012

CLASSPATH In Java


CLASSPATH in Java

I have experience in finance and insurance domain and Java is heavily used in this domain for writing sophisticated Equity, Fixed income trading applications. Most of these investment banks have written test for Java and I always fine at least one question related to CLASSPATH in Java on those interview. Java CLASSPATH is one of the most important concepts in java but I must say mostly overlooked. This should be the first thing you should learn while writing java programs because without understanding of Classpath in Java you can't understand how java locates your class files.

So let's start with basic and then we will see some example and improvisation of Classpath in Java. In Fact CLASSPATH is an environment variable which is used by Java Virtual Machine to locate user defined classes. 
This article is in continuation of my articles How HashMap works in Java and Why String is immutable in Java and In this tutorial we will see how to setup classpath for java in windows and Linux , java -classpath example in different scenario and use of java -classpath or java -cp.

Setting Java Classpath in Windows

For setting Java Classpath in Windows (any version either Windows XP or Windows 2000) you need to specify value of environment variable CLASSPATH, name of this variable is not case sensitive and it doesn't matter if name of your environment variable is Classpath, CLASSPATH or classpath in Java.

Here is Step by Step guide for setting Java Classpath in Windows:

    Setting Java Classpath in windows and Unix Linux
  1. Go to Environment variable window in Windows by pressing "Windows + Pause "-->Advanced -->Environment variable " or you can go from right click on my computer than choosing properties and then Advanced and then Environment variable this will open Environment variable window in windows.
  2. Now specify your environment variable CLASSPATH and put the value of your JAVA_HOME\lib and also include current directory by including (dot or period sign).
  3. Now to check the value of Java classpath in windows type "echo %CLASSPATH" in your DOS command prompt and it will show you the value of directory which are included in CLASSPATH

Setting Java Classpath in UNIX or Linux

To set Classpath for Java In Linux you can simply export CLASSPATH="your classpath" from either your .bash_profile or .bashrc script which will run whenever you login into your Linux or Unix Machine.
Now to check value of Java CLASSPATH in Linux type "echo ${CLASSPATH}.
I hope this example for setting classpath in Java will enable to set classpath by yourself let me know if you face any problem while setting up classpath in Java

Overriding Classpath in Java

You can override value of Java classpath defined by environment variable CLASSPATH by providing option "-cp" or "-classpath" while running your program and this is the best way to have different classpath for different application in Java. General way to define classpath is in the startup script of any program. e.g.
CLASSPATH=/home/tester/classes
java -cp $CLASSPATH Test

By default Java CLASSPATH points to current directory denoted by "." and it will look for any class only in current directory.

Different example of using Classpath in Java

In case you have multiple directories defined in CLASSPATH variable, java will look for a class starting from first directory and only look second directory in case it did not find the specified class in first directory. This is extremely useful feature of Classpath in java to understand and it's very useful for patch release kind of stuff. Let's see  java -classpath example

I have my CLASSPATH=/home/tester/first:/home/tester/second
Now I have "Test" class of different version in both first and second directory so when I give a command
"java Test" What will happen ? Which Test class would be picked?
Since JVM search directory in the order they have listed in CLASSPATH variable it will first go to the "first" directory and if it finds "Test" over there it will not go to "/home/tester/second" directory.
Now if you delete Test class from /home/tester/first directory it will go to /home/tester/second directory and will pick "Test" class from there.

I have used this feature of Java Classpath to test my patch releases, we used to have a folder called "patch" listed as first element in Java CLASSPATH and any point of time we want to put any debug statement or want to test any bug we just modify Java source file , compile it and generate class file and put that inside patch folder instead of releasing whole new jar and this comes very handy if you are working in a large project where you don't have development environment setup in Windows and your project only runs on Unix server.
Its also worth noting that when you use the -jar command line  option to run your program as an executable JAR, then the CLASSPATH environment variable will be ignored, and also the -cp and -classpath switches will be ignored. 

In this case you can set your Java classpath in the META-INF/MANIFEST.MF file by using the Class-Path attribute.
Now a common question if I have my CLASSPATH variable pointing to current directory "." and I have class called "Test" inside package "testing" and with below directory structure C:\project\testing\Test.class in my computer.
What will happen if I run command "java Test" from directory "C:\project\testing\" will it run?
No it will not run it will give you Exception in thread "main" java.lang.NoClassDefFoundError: Test
Since name of the class is not Test, instead it's testing. Test even though your classpath is set to current directory.

Now what will happen if I give command "java testing.Test "from" C:\project\testing\, it will again not run and give error?

Exception in thread "main" java.lang.NoClassDefFoundError: testing/Test
Why because now it looking for class called Test which is in package testing, starting from current directory "." but don't find it since there is no directory called "testing after this path "C:\project\testing\".

To run it successfully you need to go back to directory "C:\project" and now run
C:\project>java testing.Test
It will run successfully.

Errors related to Classpath in Java

If you are working in Java you must have faced some errors and exception related to classpath in java, two most common issues related to java classpath is ClassNotFoundException and NoClassDefFoundError. I have seen that most of java developer tries to solve this error by trial and error; they just don't look beyond the hood and try to understand what the reason for these java classpath related errors is. They often misunderstood that these two errors are same also.

Here is the reason of these java classpath errors:

ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries to load a particular Class at Runtime and don't find that on Java classpath. Two keyword here "dynamically" and "runtime". Classic example of these errors is whey you try to load JDBC driver by using Class.forname("driver name"). So this error essentially comes when Java try to load a class using forName() or by loadClass() method of ClassLoader. Key thing to note is that presence of that class on Java classpath is not checked on compile time. So even if those classes are not present on Java classpath your program will compile successfully and only fail when you try to run.


On the other hand NoClassDefFoundError is an Error and more critical than ClassNotFoundException which is an exception and recoverable. NoClassDefFoundError comes when a particular class was present in Java Classpath during compile time but not available during run-time. Classic example of this error is using log4j.jar for logging purpose and forgot to include log4j.jar on classpath in java during run-time. to read more about logging in Java see . Keyword here is "class present at compile time but not available on run-time". This is normally occurring due to any method invocation on a particular class which is part of library and not available on classpath in Java. This is also asked as common interview questions as  
"What is difference between NoClassDefFoundError and ClassNotFoundException Exception in Java"   or
"When do you see NoClassDefFoundError and ClassNotFoundException Exception in Java".


Summary of CLASSPATH in Java

1.      Classpath in Java is an environment variable used by Java Virtual machine to locate or find java classes during class loading.

2.      You can override value of Classpath in Java defined by environment variable CLASSPATH by providing JVM command line option –cp or –classpath while running your application.

3.      If two classes with same name exist in Java Classpath then the class which comes earlier in Classpath will be picked by Java Virtual Machine.

4.      By default CLASSPATH in Java points to current directory denoted by "." and it will look for any class only in current directory.

5.      when you use the -jar command line  option to run your program as an executable JAR, then the Java CLASSPATH environment variable will be ignored, and also the -cp and -classpath switches will be ignored and In this case you can set your java classpath in the META-INF/MANIFEST.MF file by using the Class-Path attribute.

6.      In Unix of Linux Java Classpath contains names of directory with colon ":" separated , On Windows Java Classpath will be  semi colon ";" separated while if you defined java classpath in Manifest file those will be space separated.

7.       You can check value of classpath in java inside your application by looking at following system property "java.class.path"
System.getProperty("java.class.path")

Class-Path attribute is used to contain classpath inside manifest file. Also make sure that your manifest file must end with a blank line (carriage return or new line) , here is an example of java classpath in manifest file.

Main-Class: com.classpathexample.Demo_Classpath
Class-Path: lib/tibco.jar lib/log4j.jar


8.       It's also important to note that path specified in manifest file is not absolute instead they are relative from application jar's path. For example in above if your application jar file is in C:\test directory you must need a lib directory inside test and tibco.jar and log4j.jar inside that.

9.       ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries to load a particular Class at Runtime and don't find that on Java classpath due to result of Class.forName() or loadClass() method invocation.
10. NoClassDefFoundError comes when a particular class was present in Java Classpath during compile time but not available during runtime on Classpath in Java.


No comments:

Post a Comment