10111
10111

Reputation: 47

Not able understand the error in java

I was trying to know what would happen if I have two classes with the main function. I used the following code:

class A {
  public static void main(String[] args){
    System.out.println("Hello,World!");
  }
}
class Hello {
  public static void main(String[] args){
    System.out.println("Hello,World!");
  }
}

I compiled it using javac First.java (since no class is specified as public , I named the file as First.java); it got compiled without any error and i ran only the class A.Expecting the Hello class to run itself. DIDN'T HAPPEN(?),maybe the program ran out of scope.

So,

I tried compiling the following java code(I am a beginner) but i got the following error. Code:

class Hello {
  public static void main(String[] args) {
    System.out.println("Hello,World!");                                                 
  }
}
class A {
  public static void main(String[] args) {
    System.out.println("Hello,World!");
    Hello.main();
  }
}

I compiled it through javac First.javaand got the following error:

method main in class Hello cannot be applied to given types;

    Hello.main();
         ^

I wanted the program to run first the class A's main function and then class Hello's. What's going wrong here?

Upvotes: 0

Views: 126

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503839

Look at the declaration of Hello.main:

public static void main(String[] args)

Now you're trying to call it like this:

Hello.main();

What would you expect the value of args to be, within the method? You need to provide it with a value for args... and fortunately, you already have one, as you're within a method which uses args as a parameter, also of type String[]. So you should just be able to change your code to:

Hello.main(args);

Note that the two args parameters - one for Hello.main and one for A.main are entirely separate. We happen to use pass the value of one to the provide the initial value for the other, but we could easily have written:

Hello.main(null);

or

Hello.main(new String[] { "Some", "other", "strings" });

instead.

Upvotes: 5

Jops
Jops

Reputation: 22715

Do this in your second class:

public static void main(String[] args) throws IOException {
    MyOtherClass.main(args);
}

Upvotes: 0

Related Questions