[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 190
  • Last Modified:

Irritating problem with a easy easy concept

Take a look at this code

    private boolean ParseResponse(String strResponse) throws InvalidResponseException{
        strResponse = strResponse.toUpperCase();
        if (strResponse == "Y" || strResponse == "N"){
            if (strResponse == "Y"){
                return true;
            }
            else{
                return false;
            }
        }
        else{
            System.out.println(strResponse);
            throw new InvalidResponseException();
        }
    }

When the method is called I pass it a string with the value of y.  The method then converts it to upper case Y.  Why is this statement failing and going to the else? if (strResponse == "Y" || strResponse == "N")

Thanks for your help.
0
BofADev
Asked:
BofADev
2 Solutions
 
objectsCommented:
== tests objects equality, not string equality
use equals() instead

        if (strResponse.equals("Y") || strResponse.equals("N")){
            if (strResponse.equals("Y")){
0
 
hoomanvCommented:
When you compare two instances using ==, you are actually comparing their memory addresses to see if they are references to the same object

also this way is more efficient as it has 1 comparison for Y and 2 for N and 2 for non-of-them
but yours, 2 comparison for Y, 3 for N and 2 for non-of-them

if (strResponse.equals("Y")
    return true;
else if(strResponse.equals("N"))
    return false;
else {
    System.out.println(strResponse);
    throw new InvalidResponseException();
}

0
 
BofADevAuthor Commented:
Now it makes sense!  I was thinking last night...how stupid of Java.  But I remember now that the memory address of a string just holds the memory address of the actual text.  That would make sense why it isn't evaluating the way I think it should.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
objectsCommented:
> But I remember now that the memory address of a string just holds the memory address of the actual text.

== compares the memory address of the object, not the address of the text. they are different things really
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Somehow that recommendation was not followed.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now