1

I am trying to create a function that takes a string as function and returns an int.

public int convert (String input) {
    int x = -1;
    if (input == "one") {
        x = 1;
    }

    else if (input == "two") {
        x = 2;
    }

    else if (input == "three") {
        x = 3;
    }
    return x;
}

The problem is, (assuming inputs will always be one of the three inputs), the function always returns -1. Ive tried:

  • returning 0 instead of x
  • and:

    public int convert (String input) {
    
      if (input == "one") {
         return 1;
      } 
      else if (input == "two") {
         return 2;
      }
      else if (input == "three") {
         return 3;
      }
      return -1;
    }
    

Thanks guys.

1
  • 2
    The first method will always return 0, not -1. I've edited it Commented Jan 20, 2013 at 5:25

2 Answers 2

11

One issue is:

if (input == "one") 

should be

if  ("one".equals(input)) 

String/Object equality check should use equals() method instead of == (except the case of String literal comparison)

== checks for reference equality.

equals() checks for object content equality based on equals() implementation.

Sign up to request clarification or add additional context in comments.

Comments

1

when you are comparing two String for equality never use "==" operator. because "==" operator checks for address equality i.e if you are comparing "x == y" you are checking whether value of x and value of y is at the same memory location. It means that == operator compares references.

Since String is an object and when you are comparing 2 objects never use == operator as they compare whether the 2 references are pointing to same object or not.

in your case input points to one object and you are comparing input to other object which is at a different location.

for example your string "input" contains value "one" at address location 123456 and your new string "one" is created at address location 12347. so input == "one" compares the address locations of input and one which are not the same.

so for your example use

public int convert (String input) {
int x = -1;
if (input.equals("one")) {
    x = 1;
}

else if (input.equals("two")) {
    x = 2;
}

else if (input.equals("three")) {
    x = 3;
}
return x;
}

.equals method compare objects equality and not references equality. so you will get the desired output if you compare two objects using .equals() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.