Java Language Java Pitfalls - Language syntax Pitfall - Declaring classes with the same names as standard classes

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


Sometimes, programmers who are new to Java make the mistake of defining a class with a name that is the same as a widely used class. For example:

package com.example;

 * My string utilities
public class String {

Then they wonder why they get unexpected errors. For example:

package com.example;

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello world!");

If you compile and then attempt to run the above classes you will get an error:

$ javac com/example/*.java
$ java com.example.Test
Error: Main method not found in class test.Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Someone looking at the code for the Test class would see the declaration of main and look at its signature and wonder what the java command is complaining about. But in fact, the java command is telling the truth.

When we declare a version of String in the same package as Test, this version takes precedence over the automatic import of java.lang.String. Thus, the signature of the Test.main method is actually

void main(com.example.String[] args) 

instead of

void main(java.lang.String[] args)

and the java command will not recognize that as an entrypoint method.

Lesson: Do not define classes that have the same name as existing classes in java.lang, or other commonly used classes in the Java SE library. If you do that, you are setting yourself open for all sorts of obscure errors.

Got any Java Language Question?