Exploring CLASSPATH
CLASSPATHrepresents the path where class files, package s, or JAR files are available.- By default, you can access the classes from the same location where they are available.
Example
Consider the above CASE 3:
java com.JavaWorldIndia.Hello
➡ Gives an error.
- When you want to access classes from another location in the file system, then you need to specify the location of the class file by setting the
CLASSPATH.
Option 1: Temporarily for Current Execution
java-cp E:\app\class es com.JavaWorldIndia.Hello
➡ Runs Successfully
Option 2: Temporarily for Current Command Prompt
setCLASSPATH=%CLASSPATH%;E:\app\class es;
java com.JavaWorldIndia.Hello
➡ Runs Successfully
Option 3: Permanently in System Environment Variables
Steps
- Right Click on My Computer and select Properties
- Select Advanced tab
- Click on Environment Variables button
- Click on New button in the User Variable
- Provide the required information
Variable Details
Variable name : CLASSPATH
Variable value : %CLASSPATH%;E:\app\class es;
- Click on OK button in all the windows.
Quick Understanding of CLASSPATH
Important Commands Summary
| Purpose | Command |
|---|---|
| Compile with package | javac -d location File.java |
| Run package d class | java package Name.ClassName |
| Run with custom classpath | java -cp path package Name.ClassName |
| Set temporary classpath | set CLASSPATH=path |
Lab454.java
class Lab454{
public static void main(String str[]){
System.out.println("Hello Guys!");
}
}
package com.javaindia.p1;
class Hello{}
❌ Not possible
Package statement must be the first statement in source file.
Lab455.java
package com.javaindia.p1;
class Lab455 {
public static void main(String str[]) {
System.out.println("Hello Guys!");
}
}
class Hello {}
✅ Possible
Lab456.java
package com.javaindia.p1;
package com.javaindia.p2;
class Lab456{
public static void main(String str[]){
System.out.println("Hello Guys!");
}
}
❌ Not allowed
Only one package declaration is allowed in a source file.
Lab457.java
package com.javaindia.p1;
public class Lab457 {
public static void main(String str[]) {
System.out.println("Hello Guys!");
}
}
class Hello {}
class Hai {}
✅ Valid
Lab458.java
package com.javaindia.p1;
public class Lab458 {
public static void main(String str[]) {
System.out.println("Hello Guys!");
}
}
public class Hello {}
❌ Not allowed
A source file cannot contain more than one public class.
Lab459.java
package com.javaindia.p1;
class Lab459 {
public static void main(String str[]) {
System.out.println("Hello Guys!");
}
}
public class Hello {}
✅ Possible
But the file name must be
Hello.java.