I wrote following code.
class String {
private final java.lang.String s;
public String(java.lang.String s){
this.s = s;
}
public java.lang.String toString(){
return s;
}
public static void main(String[] args) {
String s = new String("Hello world");
System.out.println(s);
}
}
When I execute it, get following error
The program compiled successfully, but main class was not found.
Main class should contain method: public static void main (String[] args).
Why is it so?... though main method is defined why system is not reading/ recognizing it ?
public static void main(String[] args) {
Becuase you must use a java.lang.String
, not your own. In your main method, the String
you're using is actually the custom String
that was defined, not a real java.lang.String
.
Here is the code, clarified a bit:
class MyString {
private final String s;
public MyString(String s){
this.s = s;
}
public String toString(){
return s;
}
public static void main(MyString[] args) { // <--------- oh no!
MyString s = new MyString("Hello world");
System.out.println(s);
}
}
So, the lesson that you can learn from this puzzle is: don't name your classes as other commonly used classes!
Why is it so?
Because the String[]
you are using at the point is not a java.lang.String[]
. It is an array of the String
class that you are defining here. So your IDE (or whatever it is) correctly tells you that the main
method as a valid entry point.
Lesson: don't use class names that are the same as the names of commonly used classes. It makes your code very confusing. In this case, so confusing that you have confused yourself!
Because the signature of the main method must be
public static void main(java.lang.String[] args) {
and not
public static void main(mypackage.String[] args) {
Usually, java.lang
is implied. In this case, your personal String
is used instead. Which is why you should never name your classes as those already in java.lang
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With