user1993177
user1993177

Reputation: 593

Java - returning int from function(String)?

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:

Thanks guys.

Upvotes: 1

Views: 3184

Answers (2)

ylnsagar
ylnsagar

Reputation: 644

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.

Upvotes: 1

kosa
kosa

Reputation: 66657

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.

Upvotes: 11

Related Questions