0
votes

I found that when I define two classes with the same name but different case in the same file, the program will crash.

public class Main {

    public static void main(String[] args) {
        TestClass testClass = new TestClass();
    }
}

class TestClass {}
class Testclass {}

These are the output information:

Exception in thread "main" java.lang.NoClassDefFoundError: top/example/study/Testclass (wrong name: top/example/study/TestClass) at java.base/java.lang.ClassLoader.defineClass1(Native Method) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1009) at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174) at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:801) at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:699) at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:622) at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:580) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499) at com.example.study.Main.main(Main.java:6)

I learned that java is case sensitive, so why is this happening? Thanks.

1
I have tried this code and not getting error. please check your package details.GauravRai1512
@GauravRai1512 - You're probably using *nix, then, or at least a case-sensitive file system.T.J. Crowder
Defining multiple top-level classes in the same file is something best avoided anyway. As is defining classes that differ only in their capitalization.Andy Turner

1 Answers

1
votes

I'm guessing you use Windows, or at least a case-insensitive file system.

Java's compiler generates .class files using the name of the class. TestClass.java => TestClass.class, Testclass.java => Testclass.class. But if your file system is case-insensitive, TestClass.class and Testclass.class are the same filename, and one of them overwrites the other.

Instead, make the names different in a way other than just capitalization.