PrimalScientist
PrimalScientist

Reputation: 861

Boolean test returning false when it should be true?

I am going through a list of questions on a past examination paper. One of the questions is of type boolean.

It should return false if the name is not Thomas, and true if it is.

Here is my code:

public class QuestionTwo
{   
String name;

public static void main(String [] args){

    System.out.println(nameTest("Thomas"));   
}
public static boolean nameTest(String name){
    if(!name.equals("Thomas"));
    return false; 
 }
}

As you can see my code should return true, but it keeps returning false? Can someone tell me where I seem to have gone wrong with my code please? Please forgive any silly errors found as I am still learning. Many thanks.

Upvotes: 3

Views: 2687

Answers (5)

blagae
blagae

Reputation: 2402

The best thing to do is to return exactly whether the name equals Thomas. There is no need to do an if statement

public static boolean nameTest(String name){
  return name.equals("Thomas"); 
}

The other proposed solution:

if(!name.equals("Thomas")) return false;

won't compile, because there is no return value in case the name isn't Thomas.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

[the method] should return false if the name is not Thomas, and true if it is.

You do not need an if at all:

 public static boolean nameTest(String name){
     return name.equals("Thomas");
 }

In general, boolean expressions are easier to read without ifs and == true / == false around them. Every time you see returning true or false from a branch of an if, you should consider rewriting it without the if statement.

Upvotes: 3

Jeevan Patil
Jeevan Patil

Reputation: 6089

Putting semicolon after if and return statements makes them separate statements. Code should be like :

public class QuestionTwo {   
    String name;

    public static void main(String [] args){
        System.out.println(nameTest("Thomas"));   
    }

    public static boolean nameTest(String name){
        if(!"Thomas".eqauals(name)) {
            return false;
        }
        return true;
    }
}

Upvotes: 1

PermGenError
PermGenError

Reputation: 46438

remove the semicolon at the end of if statement.

 if(!name.equals("Thomas"))

Also good practice is to do equals test this way:

 if(!"Thomas".equals(name))

In this case, if name is null you wouldn't get NPE.

Upvotes: 6

Zutty
Zutty

Reputation: 5377

Remove the semicolon

    if(!name.equals("Thomas")) return false; 

The way you have written it, it is two separate statements. First, if name not equals Thomas then do nothing. Then second, return false.

Upvotes: 6

Related Questions