What happens when you define the class name as String?

advertisements
class String
{
public static void main(String[] args) {

}
}

String is not keyword, but still above program gives runtime error. Why is that?


Bad thing happens, when you define a class with the name String you are shadowing a java.lang.String Class that means every declared object must use the full-qualified name java.lang.String if it refers to a "normal String" other than that will point to your defined one..

example is the code you write:

public static void main(String[] args) {

}

if that is the only class you have, then the compiler will complain since the entry point for an application will never be found...

you will be need to define explicit the argument by doing

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

}

this is a very nice pitfall that will break your neck, all the most because the classes in the java lang doesnt need to be imported,your code must be carefully writen and is pretty much error prone..

That code will compile but in any decent code analyzer you will get a lot of complains and rename suggestions..

I will follow that way too, and suggest never name your classes like standart java classes...