Recently I just got an error in java that

Exception in thread "main" java.lang.NoSuchMethodError: main

Even if my class was just of 3 line of code.

public class Test{
    public static void main(String[] args){
    System.out.println("hello");
    }
}

I was wondering why this happens, but later on i get to know there was a public class String which i had tried & created in same package.

so now new question arise is what happen in this kind of situation though String is not a keyword defined in java (you can use in your code)

Then I just deleted String.java & String.class file from the package but it sounds odd that you could not use String class as well.

Question: Does java gives major priority to our custom class?

有帮助吗?

解决方案

Your main method needs to match

 public static void main(java.lang.String[] args){ ... }

If you create your own String class in the same package where the class with your main method is, it will become

 public static void main(your.own.package.String[] args){ ... }

which is valid, but will not allow the runtime launcher to find a main method anymore, since it expects java.lang.String[] as parameter.

The classes from java.lang are imported automatically by default, so you don't need an explicit import statement - that probably made it even more confusing to you.

As a rule of thumb, I would avoid to name my own classes the same as classes from the Java Runtime, whenever possible - especially from java.lang.

See also the JLS: Chapter 7. Packages:

A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.

其他提示

You can always use a fully qualified name:

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

The story you are telling says that we can use String as the name for one of our classes. But, like in real life, if there are two people named "John" around, you sometimes need to disambiguate them.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top