Return Type Boolean in Java

29,732

Solution 1

As @DR says, Java does not force you to assign the result of a method call. A void or non-void method call is valid as a complete statement in Java.

I would surmise that the reasons Java is designed this way include the following:

  • Convenience: most developers would find it a nuisance if the result of every non-void method call had to be assigned.

  • Tradition: C, C++ and almost no other language force you to do this. (I have vague recollections of some language that did ... but that was long ago.)

  • Futility: you cannot stop the developer from assigning the result to a temporary variable and then ignoring it. Or writing a wrapper method that does the same thing.

  • Better alternatives: if you want to encourage the developer to pay attention to an error in Java, throw an appropriate checked exception.

Solution 2

Java never forces you to assign the return value of a function call. There must be something wrong with your other code (you might post it here, too)

PS: This reminds me of good old Turbo Pascal, where you had to enable the Extended Syntax to get this behaviour.

Share:
29,732
gmhk
Author by

gmhk

Bangalore, India, Dream to Develop a Web Eco System where all Internet users can interact and exchange Ideas. Always work on New innovative Ideas with latest technology

Updated on September 17, 2020

Comments

  • gmhk
    gmhk over 3 years

    I have a question on boolean return types. Check the following code:

    Code Sample 1

    boolean flag = sampleMethod();
    
    public boolean samplemethod(){
        return false;
    }
    

    Code Sample 2

    sampleMethod();
    
    public boolean samplemethod(){
        return false; 
    }
    

    In the above two examples, the code compiles properly without any compile time or run time exceptions. My doubt is, Java doesn't make it mandatory for the boolean return type to be assigned in the calling program, where for the other data types the program does not work. Can you please explain the reason for this to me?

  • gmhk
    gmhk about 14 years
    I am not focusing on whether it compiles or not, main question is the calling program doesnot make it mandatory to assign the return boolean value from the method.
  • Bozho
    Bozho about 14 years
    the answer was pretty clear that Java never forces you to assign the return value.
  • Nyerguds
    Nyerguds over 12 years
    This still doesn't compile unless sampleMethod(); is called from inside an actual function though. Otherwise it's seen as illegal function definition without a return type set.
  • Saurabh
    Saurabh over 12 years
    @Nyerguds, of course. I assume it is obvious from context that the call to sampleMethod(); is within another method somewhere. The same applies to the code sample in the question.