search
HomeJavajavaTutorialWhy in Java, we get ClassNotFoundException when the class exists?

Why in Java, we get ClassNotFoundException when the class exists?

Sep 11, 2023 pm 06:21 PM
Explanation of classnotfoundexception exception in javaClass Loading Mechanism (Class Loading Mechanism)classpath problem (classpath problem)

Why in Java, we get ClassNotFoundException when the class exists?

Whenever we try to load a class, if the class loader cannot find the class at the specified path, a ClassNotFoundException will be generated.

This may happen when executing a java program, using the forName() method of the class named Class or the loadClass()## of the ClassLoader class # Method to explicitly load the class. These two classes accept a string value representing the class name and load the specified class.

When passing class names to these methods, you need to ensure that -

    The class names passed to these methods should be accurate.

  • The specified class (along with the package) should be located in the current directory or its path should be listed in the environment variable classpath.

Example

Suppose we create a file named

Sample in the directory D:// and compile as follows -

package myPackage.example;
public class Sample {
   static {
      System.out.println("The class named Sample loaded successfully.........");
   }
}

Compile

D:\>javac -d . Sample.java

This will create a package in the current directory myPackage.example and build ## in it

.class file of the #Sample class. So when loading this class you need to put it in the same directory and pass the absolute class name to Class.forName() or loadClass()Example p>

Live Demonstration

public class ClassNotFoundExample {
   public static void main(String args[]) {
      try {
         Class.forName("myPackage.exampl.Sample");
      }catch (ClassNotFoundException ex) {
         ex.printStackTrace();
      }
   }
}

Exception

While executing the above program, you will get the following exception due to the misspelling of the name of the package.

D:\>java ClassNotFoundExample
java.lang.ClassNotFoundException: myPackage.exampl.Sample
   at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
   at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
   at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
   at java.base/java.lang.Class.forName0(Native Method)
   at java.base/java.lang.Class.forName(Unknown Source)
   at ClassNotFoundExample.main(ClassNotFoundExample.java:4)

If you are trying to access a specific class from another directory, you need to set the classpath -

    A folder containing the following content (the outermost package) .class document.
  • Or,

  • The jar file containing the class.
  • Assume we have corrected the spelling problem and try to load the class from a Java file in the E:// directory

Example

Live demonstration

public class ClassNotFoundExample {
   public static void main(String args[]) {
      try {
         Class.forName("myPackage.example.Sample");
      }catch (ClassNotFoundException ex) {
         ex.printStackTrace();
      }
   }
}

Exception

You will still encounter the same exception because the package containing the .class file for the specified class (or the jar file containing it) is neither in the current directory nor in the path list environment variable classpath.

E:\>java ClassNotFoundExample
java.lang.ClassNotFoundException: myPackage.example.Sample
   at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
   at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
   at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
   at java.base/java.lang.Class.forName0(Native Method)
   at java.base/java.lang.Class.forName(Unknown Source)
   at ClassNotFoundExample.main(ClassNotFoundExample.java:4)

In the current scenario, set the classpath to the directory containing the package of the required class, i.e. "

D://

" and execute the above java program to make it work.

E:\>javac ClassNotFoundExample.java
E:\>java ClassNotFoundExample
The class named Sample loaded successfully.........

The above is the detailed content of Why in Java, we get ClassNotFoundException when the class exists?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software