Take the 2-minute tour ×

When I run the program and enter a rank & gender it yells at me and tells me it is an invalid gender. I cannot see why if I enter "male" into the console, it does not equal the string "male"? Can please explain to me why this doesn't work and perhaps some suggestions on how to fix it? Thanks!

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class BabyNames {

    Scanner input = new Scanner(System.in);
    System.out.print("Enter male or female: ");
    String gender1 = input.next();
    System.out.print("Enter rank: ");
    int rank = input.nextInt();         
    while (!(gender1 == "female" || gender1 == "male")){
            System.out.println("Please try again with a valid gender.");
            System.out.println("Enter male or female: ");
            gender1 = input.next();
    while (rank <= 0 || rank > 1000){
        System.out.println("Please try again with a valid rank.");
        System.out.println("Enter rank: ");
        rank = input.nextInt();

    findRank(gender1, rank);

public static void findRank(String gender2, int rank) throws IOException {
    File babyNames = new File("/home/skatty14/Downloads/BabyNames.txt");
    Scanner input = new Scanner(babyNames);
    int rankCount = 0;
    while (input.hasNextLine()){
        if (gender2 == "male"){
            String name = input.next();
        if (gender2 == "female"){
            String name = input.next();
share|improve this question
use a case-insensitive string comparison. –  zerodin Oct 27 '10 at 2:05

3 Answers 3

up vote 4 down vote accepted

To compare Strings, you need to use .equals() so change all of your String comparisons with == to use .equals() instead.

if(gender1 == "male") { ... }

would become,

if(gender1.equals("male")) { ... }

So on and so forth.

share|improve this answer
Just to be that much more 'efficient' should you change the second if to else if? –  Glenn Nelson Oct 27 '10 at 2:05

The '==' operator tests for equivalence of references to Strings, not contents of Strings, hence why your code is not giving you the expected results.

Try using the form

if (gender1.equals("female"))

etc. instead.

share|improve this answer
Thanks! It is fixed now, at least that problem! :) I will select your answer in 10min or so, it won't let me quite yet. –  Mr_CryptoPrime Oct 27 '10 at 2:11

Anthony Forloney answer is the best

but you can skip the equals, if you want, with intern() function provided by String API.

if( gender1.intern() == "male".intern() ) { ... }


public String intern() Returns a canonical representation for the string object.




share|improve this answer
if (gender1.intern() == "male") will work as well as string literals are already interned. –  cgull Oct 27 '10 at 3:31

Your Answer


