What Is Classpath And How To Set That In Java

In java, the source file is written in normal text and saved with .java  extension.
The compiler upon invoked by the command javac creates a .class file for the corresponding .java file.

The JVM during run time reads the .class file ,performs certain checks and execute the same.

if the .class file is placed under ...../java/bin/ folder . It is not required to mention classpath. But when our project becomes larger, it is required to create some folder structure and place all the necessary .class file at one place,it is extremely required for JVM to know where the .class files resides.

This post will talk about the different settings how to set classpath in different way.

Classpath settings
How to set classpath for java...
  • In my previous post here, I have shown how to set classpath permanently from environment variable
  • Temporary for a command session
    set classpath=%classpath%;E:\myPrograms\
    //%classpath% is to keep what ever is already present in the classpath;Now provide the required classpath followed by a semi colon(;)
    This command is valid for the command prompt it has been set. If you open another command prompt the java command will not work.

  • One more option is also available for setting classpath, valid for a single command.
    java -cp <<full classpath>> <<name of the class>>
    like-java -cp E:\myProgram Test123
The scope of the process:
  • Set globally--across the command prompts
  • Set classpath at command prompt--only for that command prompt session
  • Set classpath on command level-only for that command
While going for the 3rd option there are things to remember:
  • -cp will not consider present working directory by default. We need to include dot(.) to get present working directory into classpath
  • Always use full path while working with -cp
  • if the same class file available in different directories then JVM will read from left to write for the -cp command and whenever the first occurrence of the class is available JVM will pick that and execute. But the next sequence will not be picked again.
 so in drive C,D,E three test class is available.
Now if we provide
java -cp C:;D:;E: test 
only C: drives test will be executed,D and E will be ignored.
similarly if we provide
java -cp D:;C:;E: test 
only D: drives test will be executed,C and E will be ignored.
What Is Classpath And How To Set That In Java What Is Classpath And How To Set That In Java Reviewed by Animesh Chatterjee on May 08, 2013 Rating: 5

No comments:

Powered by Blogger.