Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Puzzler- What is the reason? [closed]

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 ?

like image 971
Just_another_developer Avatar asked Jun 12 '13 12:06

Just_another_developer


3 Answers

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!

like image 96
tckmn Avatar answered Nov 18 '22 19:11

tckmn


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!

like image 6
Stephen C Avatar answered Nov 18 '22 19:11

Stephen C


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

like image 2
tucuxi Avatar answered Nov 18 '22 19:11

tucuxi