userimage
Moe

Java all strung out

Let"s start with a basic java code where my code have class name but don"t have any package name.

public class Output {
    public static void main(String[] args){
        String s = new String("Hi, I am gonna amaze you...");
        System.out.println(s);
    }
}

class String {
    private final java.lang.String s;
    
    public String(java.lang.String s) {
        this.s = s;
    }
    
    public java.lang.String toString(){
        return s;
    }
}


This is one of the most simple program where Output class have no package and having a subclass String. Now if we see the program it will compile without any problem. And if we try to run it, we probably think that will print "Hi, I am gonna amaze you...". But this will not happened. It will give you exception at runtime like :

Error: Main method not found in class Output, please define the main method as:
   public static void main(String[] args)

   
Now the point is why this happened:

The problem is clear that the VM not able to find main method although it"s present in Output class. The signature we have mentioned in main method is wrong. Now vm expecting a main method with java.lang.String[] where we provided the subclass String which we created in the same class. So we should give any class name which are belongs to package java.lang.*. Else we should manually mentioned the class with package name.

To solve the above problem we have two choices like:

1: Either we can go and specify the String class with package name:

public class Output {
    public static void main(java.lang.String[] args) {
        String s = new String("Hi, I am gonna amaze you...");
        System.out.println(s);
    }
}

class String {
    private final java.lang.String s;

    public String(java.lang.String s) {
        this.s = s;
    }

    public java.lang.String toString() {
        return s;
    }
}


2: Don"t use the class name which are belongs to java library.