1

I got this problem when running the following code in Java:

public class comparison
{
    public static boolean main(String[] args)
    {
        if (0.1 + 0.1 + 0.1 == 0.3) return true;
        else return false;
    }
}

Can anybody tell me why and how to modify the code?

1
  • What are you trying to do by returning boolean from main?
    – partlov
    Mar 30, 2013 at 21:14

2 Answers 2

3

main method should be:

public static void main(String[] args)

and not:

public static boolean main(String[] args)

You probably wanted to do something like this:

 public static boolean check() 
 {
     if (0.1 + 0.1 + 0.1 == 0.3) return true;
        else return false;
 }

and then call it from the static main:

public static void main(String[] args)
{
    boolean result = check();
    //now you can print, pass it to another method.. etc..
}

Why main is void (doesn't return anything)?

  • Think about it. Once the main method finishes, it doesn't mean that the program finished. If it spawns a new thread it might be that these threads are still running.

Why main is public?

  • The main method is called by the JVM to run the method which is outside the scope of project.

Why main is static?

  • When the JVM calls the main method, there is no object existing for the class being called. So it has to have static method to allow this from class.
1
  • Yes, that is what I exactly hope to do! It's perfect.
    – Vic Yu
    Aug 12, 2013 at 18:00
0

To be executable from the commandline, Java classes must implement a static method with signature

public static void main(String[] args) {

Because yours returns "boolean" instead of "void", the JVM doesn't know how to execute it. You'll need to either modify that method, or wrap it in another similar one with return type "void".

1
  • Ah...I see your idea. Does that mean I cannot use boolean whenever in the main function?
    – Vic Yu
    Aug 12, 2013 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.