Return True in Java

This article discusses the methods to return true in Java. The article discusses general approach to return a boolean variable from a function in Java.

Boolean Values in Java

The boolean values in Java represent a truth or fallacy. To denote the truth boolean true is used while boolean false denotes the fallacy.

You should also note that the boolean values are negation of each other. Therefore the statement ‘not true’ is equivalent to ‘false’ and vice verse.

You would come across the boolean values in Java at multiple places. These values are used to check conditions in conditionals and loops.

Other uses of the boolean values might be to mark a state as processed usually working with trees and graphs.

Returning a Boolean Value From a Method

If you want your method to return a boolean value, its declaration should contain a boolean keyword before the name of the method.

For example, the code snippet given below defines a boolean method named isEven().

You should note the following points in the above declaration.

  • public: This is the modifier that represents the fact that this method is accessible from anywhere using the class object. There are other modifiers as well.
  • boolean: This is the most important keyword of discussion. It represents the type that method returns. Therefore the above method returns a boolean type data.
  • The keywords discussed above are followed by name of the method and the parameters to the method.

Let us see the example that returns a boolean value.

Output:

true
false

Using a Returned Boolean Value in a Loop

You can use a boolean value returned by a method in the loop to check the loop condition.

Let us see an example that breaks the loop when a number divisible by 10 is found.

Note the exclamation before the method invocation. It reverse the value returned by method.

So if the number passed is 10, method returns true which on reversing becomes false and hence the loop breaks.

Output:

1 2 3 4 5 6 7 8 9

Returning a Boolean Value by Checking a List

You can return a boolean true or a boolean false by checking the conditions on the elements of a list.

For example, the code given below checks whether the elements in a list are negative or positive. It returns true if the element is positive otherwise it returns false.

Note that to traverse an ArrayList you must use the index inside the get() method of the list.

Output:

1 3 5 7

Conclusion

This is all about returning the true (or boolean value) from a method in Java. You can use the other data structures in place of list as given in the example according to your need.

Hope you enjoyed reading the article. Stay tuned for more such articles. Happy Learning!

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *