George
George

Reputation: 4674

Does JOptionPane.showInputDialog() return a different String

Is the String returned by JOptionPane.showInputDialog() different from a regular String? When I try to compare it with "2", it returns false and go to the else block.

        // Prompt user for the month
        String monthString = JOptionPane.showInputDialog(
                "Enter which month are you looking for: "); 

        // SMALL Months, ie: 2, 4, 6, 9, 11
        else {
            // Special case on February
            if (monthString == "2" && isLeap) 
                            result += "29 days!";
            else if (monthString == "2")
                result += "28 days!";
            // Everytime my code to go to this block instead
            else
                result += "30 days!";
        }

Only work if I parse month to Int and then compare it with literal 2. Why do my original version does not work?

int month = Integer.parseInt(monthString);
if (month == 2 && isLeap) ...

Upvotes: 1

Views: 1963

Answers (2)

Juned Ahsan
Juned Ahsan

Reputation: 68715

Use equals to compare string and not ==

Change this:

monthString == "2"

to

"2".equals(monthString) 

in your if blocks

Equals compare the string contents while == compares the object equality. Read more from the related post here:

Java String.equals versus ==

Also note the reverse comparision "2" against the monthStirng. This will prevent null pointer exception in case monthString is null.

Upvotes: 3

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14313

Never use == to compare Strings. Strings are reference types, meaning that when you write:

monthString == "2"

You are not testing whether monthString represents the character sequence "2". You are actually testing whether monthString is excatly the same obect in memory as the "2" literal that follows it. This may or may not be true, depending on how the Strings are declared, but in general it is always better to use the equals method instead. This should solve your problem:

if (monthString.equals("2"))

Here is a much more complete overview of the differences between == and .equals.

Upvotes: 2

Related Questions