This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,
visit the help center.
Closed 7 years ago.
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
The problem is that your class is named String
, like the String
class of Java. That's really bad, you shouldn't do that.
Because of that, when you write the declaration of main :
public static void main(String[] args) {
String []
doesn't refer to Java String
class, but to your own class, so java can't find it.
If you want java to be able to find it, you would have to write :
public static void main(java.lang.String[] args) {
But really, it's not what you want, find an other name for your class.