How to Set Path and Classpath for Java on Unix, Linux and Windows?
PATH is one of fundamental Environment variable on shell or DOS but it’s commonly associated with Java mainly because if we try to run a java program which doesn't include Java executable in PATH then we say PATH is not set for Java and we need to set path for Java. I have also seen developer getting confused over path and classpath in java. Though both path and classpath provides run-time settings for any java environment which is required to compile and execute Java program they are completely different to each other.
Classpath is usually used to find out classes and mostly associated with lib part while PATH is used to find the executable or command to be executed. In order to compile and run java program from command line your PATH environment variable must have "javac" and "java" on it. In this Java PATH tutorial we will see what is PATH for Java, How to Set Path for Java and how to troubleshoot PATH related issues.
What is Path in Java
First of all PATH is not specific to java it’s a shell concept and also available in Windows and DOS. It’s represented by Environment variable called "PATH" and that's why it’s known as path. Whenever you type a command in shell in UNIX or Linux or in command prompt in windows machine, command will be looked on PATH and if shell is not able to find the command in PATH it says "not recognized" or wrong command. Now for compiling and running we use two java commands "javac" and "java" and these commands doesn't come by default with windows or Unix instead they comes when you install JDK in your machine. Now to successfully compile and run a java program in either windows or Linux you must have these two commands or executable in your PATH environment variable and that is called Setting Path for Java.
Setting Path for Java in Unix/Linux and Windows
How to check if "java" or "javac" is in PATH
Javac and Java command resides under /bin directory or your Java installation directory. In my machine its "C:\Program Files\Java\jdk1.6.0_26\bin"
If you have this bin directory in path it means java and javac will be in path and Path is set to run Java Program. There are two ways you verify whether java is in path or not.
1) Simple and easy way
Open a command prompt window by pressing start -->run-->cmd and then typing "java" or "javac" in command prompt as shown in below example
C:\Documents and Settings>java
Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file)
where options include:
-client to select the "client" VM
-server to select the "server" VM
-hotspot is a synonym for the "client" VM [deprecated]
If it displays lot of output means Java is in your path and similarly you can check for "javac”, on the other hand if java is not in your system's path you will get below output in UNIX
stock_trader$ javac
javac: not found
and in windows
C:\Documents and Settings>javac
'javac' is not recognized as an internal or external command,
operable program or batch file.
If java or javac is not in your path then you can add them into path by adding "bin" directory or your JDK installation directory into environment variable "PATH". Both windows and UNIX use same name.
How to set PATH for Java in windows
I say pretty easy just add bin directory of your JDK installation directory into PATH environment variable. You can do this either from command prompt or by using windows advanced environment editor
1) Setting Java PATH using command prompt in windows
Use "set" command to set value of PATH environment variable as shown in below example:
C:\Documents and Settings>set PATH=%PATH%;
C:\Program Files\Java\jdk1.6.0_26\bin
%PATH% is actually representing current path and we are appending java bin directory into PATH. Note that every path in windows is comma (;) separated while in UNIX it would be colon (:) separated
2) Setting Java PATH using windows environment variable editor
Use short cut "window key + pause/break" --> Advanced --> Environment Variables -->PATH
Just append the path of java installation directory here and you are done. Open a command prompt and type java or javac and you can see the output.
How to set Java PATH in UNIX or Linux
Setting PATH for java in UNIX is similar to the way we did for it on windows using command prompt. In UNIX just open any shell and execute below command
set PATH=${PATH}:/home/opt/jdk1.6.0_26/bin
Remember here each element in PATH is colon separated.
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.
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:
- 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.
- 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).
- 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 when 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. 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.