How to set path and classpath in java




Classpath in Java is the path to directory or list of the directory which is used by ClassLoadersto find and load class in Java program. Classpath can be specified using CLASSPATH environment variable which is case insensitive, -cp or -classpath command line option or Class-Path attribute in manifest.mf file inside JAR file in Java. 



  If  you  want  to set  path and  classpath   using  a  batch file .  open notepad Save the  file  path.bat

 And   type  the following command   to set your  path through command line .
On Windows 98/ME systems, do this by editing your autoexec.bat file in your c:\ directory, or create it if it doesn't exist. Add the following line:

Set    PATH=%PATH%;
c:\ …Java\JavaVirtualMachines\jdk1.8.0_221.jdk\Contents
 \Home\bin

(make sure the directory name matches where you installed the JDK). If there are no other lines setting PATH then you can simply use:

set   PATH=c:\ …Java\JavaVirtualMachines\jdk1.8.0_221.jdk\Contents
 \Home\bin

 Here … means   the directory where your java folder located.




Setting the CLASSPATH
--------------------------- 

SET CLASSPATH=.;

As you start using Java, especially if you use third-party class libraries, you may also need to set your CLASSPATH environment variable. On Windows 98/ME, this is done by editing your autoexec.bat file (as above) and adding a line like:

SET CLASSPATH=.;c:\someclasses\stuff.jar

or, if a CLASSPATH entry already exists then a new line like

SET CLASSPATH=%CLASSPATH%;c:\someclasses\stuff.jar


Use your own path rather than the example given. As many paths as you need can be added, with each separated by a semi-colon.
Save  the  path.bat    and  start  command prompt then type path . Then you can  use javac and java command .

It is useful to set the PATH environment variable permanently so it will persist after rebooting. To make a permanent change to the PATH variable, use the System icon in the Control Panel. The precise procedure varies depending on the version of Windows:
Windows XP
  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Windows Vista:
  1. From the desktop, right click the My Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced tab (Advanced system settings link in Vista).
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Windows 7:
  1. From the desktop, right click the Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced system settings link.
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.

Setting Classpath  in Windows


 To set the classpath for the Windows XP Command Prompt:
  • Select Start -> Control Panel -> System -> Advanced -> Environment Variables -> System Variables -> CLASSPATH.
  • If the Classpath variable exists, prepend .;C:\introcs to the beginning of the CLASSPATH varible.
  • If the CLASSPATH variable does not exist, select New. Type CLASSPATH for the variable name and .;C:\introcs for the variable value.
  • Click OK three times.

Classpath in  OX

To set the classpath for the bash shell in OS X:
  • Use your favorite text editor (e.g., TextEdit) to add the following line to the file /Users/username/.bashrc.
export CLASSPATH=.:/Users/username/introcs/
If the file doesn't exist, create a new one.
  • Close the Terminal and open a new one. If it does not work, in addition, try repeating the same instructions with the file /Users/username/.profile or /Users/username/.bash_profile.


Update the PATH Variable (Solaris and Linux)
You can run the JDK just fine without setting the PATH variable, or you can optionally set it as a convenience. However, you should set the path variable if you want to be able to run the executables (javac, java, javadoc, and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:
% /usr/local/jdk1.7.0/bin/javac MyClass.java
To find out if the path is properly set, execute:
% java -version
This will print the version of the java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set.
To set the path permanently, set the path in your startup file.
For C shell (csh), edit the startup file (~/.cshrc):
set path=(/usr/local/jdk1.7.0/bin $path)
For bash, edit the startup file (~/.bashrc):
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH
For ksh, the startup file is named by the environment variable, ENV. To set the path:
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH
For sh, edit the profile file (~/.profile):
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH
Then load the startup file and verify that the path is set by repeating the java command:
For C shell (csh):
% source ~/.cshrc
% java -version
For ksh, bash, or sh:
% . /.profile
% java -version
Checking the CLASSPATH variable (All platforms)
The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)
The preferred way to specify the class path is by using the -cp command line switch. This allows the CLASSPATH to be set individually for each application without affecting other applications. Setting the CLASSPATH can be tricky and should be performed with care.
The default value of the class path is ".", meaning that only the current directory is searched. Specifying either the CLASSPATH variable or the -cp command line switch overrides this value.
To check whether CLASSPATH is set on Microsoft Windows NT/2000/XP, execute the following:
C:> echo %CLASSPATH%
On Solaris or Linux, execute the following:
% echo $CLASSPATH
If CLASSPATH is not set you will get a CLASSPATH: Undefined variable error (Solaris or Linux) or simply %CLASSPATH% (Microsoft Windows NT/2000/XP).
To modify the CLASSPATH, use the same procedure you used for the PATH variable.
Class path wildcards allow you to include an entire directory of .jar files in the class path without explicitly naming them individually. For more information, including an explanation of class path wildcards, and a detailed description on how to clean up the CLASSPATH environment variable, see the Setting the Class Path technical note.

Errors related to Classpath in Java
If you are working in Java, you must have faced some errors and exception related to the classpath in java, two most common issues related to java classpath is ClassNotFoundException and NoClassDefFoundError. I have seen that many 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 this 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 Java class at Runtime and don’t find the corresponding class file on the classpath. Two keywords here “dynamically” and “runtime”. A classic example of these errors is whey you try to load JDBC driver by using Class.forname(“driver name”) andgreeted with java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. So this error essentially comes when Java try to load a class using forName() or by loadClass() method of ClassLoader. The 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. A classic example of this error is using log4j.jar for logging purpose and forgot to include log4j.jar on the classpath in java during run-time. to read more about logging in Java see. The keyword here is,  the class was present at compile time but not available at run-time.  This is normally occurring due to any method invocation on a particular class which is part of the library and not available on the classpath in Java. This is also asked as common interview questions as  
“When do you see NoClassDefFoundError and ClassNotFoundException Exception in Java”. By the way, NoClassDefFoundError can also come due to various other reason like static initializer failure or class not visible to Classloaders in the J2EE environment. Read 3 ways to resolve NoClassDefFoundError in Java for complete details.




Summary of CLASSPATH in Java
1.      Classpath in Java is an environment variable used by Java Virtual machine to locate or find  class files in Java during class loading.

2.      You can override the 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 the 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 the 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 the directory with colon “:”separated, On Windows Java Classpath will be  semicolon “;” 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 the 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 the manifest file is not absoluteinstead 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.











How to set path and classpath in java How to set  path and classpath in java Reviewed by Mukesh Jha on 4:39 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.