Michael N Michael N - 6 months ago 14
Java Question

How to check a boolean method return value in java

I am pretty new to Java what I am trying to do may seem really strange but it is a matter of me understanding a little bit about how Java works more than actually accomplishing a set result.

If I have a boolean method for instance:

public class doThings
{

// imagine the intial value of this variable is set
// and or modified using getters and setters between the declaration
// and the following method
private boolean boolVar;


public boolean doSomething()
{
if(boolVar == true)
{
//does things and then returns true
return true;
}
else
{
return false;
}
}
}


And I want to call this method in another class like so...

public class testDoThings
{

doThings someObject = new doThings;
public static void main(String[] args)
{
someObject.doSomething()
}
}


How do I check (in the class
testDoThings
) to see if the method has returned true or returned false and print messages accordingly something like this...

public class testDoThings
{

doThings someObject = new doThings;
public static void main(String[] args)
{

someObject.doSomething()
if (doSomething() returns true) // yes I am aware this is not
//valid
{
// print a statment
}
else if (doSomething() returns false) // yes once again not valid
{
// print a different statement
}
}
}


I am aware that you could put these messages in the class containing the method but if I want different messages depending on where the method is called and what it is a called on then putting things in the original class method is not always going to work.

If I am completely off the track here please let me know, if someone can explain this to me though, that would be great!

Answer

You can try like this:

if (someObject.doSomething()) //So if your function returns true then the below statement will be executed
{ 
   // print a statment
}
else //This will check for the false condition of your function
{
   // print a different statement           
}
Comments