Skip to main content

Exploring CLASSPATH

  • CLASSPATH represents 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

  1. Right Click on My Computer and select Properties
  2. Select Advanced tab
  3. Click on Environment Variables button
  4. Click on New button in the User Variable
  5. Provide the required information

Variable Details

Variable name : CLASSPATH
Variable value : %CLASSPATH%;E:\app\class es;
  1. Click on OK button in all the windows.

Quick Understanding of CLASSPATH

Important Commands Summary

PurposeCommand
Compile with packagejavac -d location File.java
Run package d classjava package Name.ClassName
Run with custom classpathjava -cp path package Name.ClassName
Set temporary classpathset 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.