English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

consider str is a variable of type String.

(1)if( str.toLowerCase() == "answer" )
will ALWAYS NO MATTER WHAT return FALSE.

(2)if( str.equalsIgnoreCase ( "answer" ) )
will return TRUE if the condition is met.

The above is the code I have written for a program. Unfortunately, when I try statement (1) it ALWAYS return false. In other language (I've learned C), the statement is correct. Why is Java interpreting it wrongly?

What is the difference between condition (1) and (2)?
Why is that condition in (1) will always return False?

A long and detailed explanation is highly appreciated. Thx.

2007-10-23 22:54:04 · 5 answers · asked by Akira Matsushima 3 in Computers & Internet Programming & Design

Please note that I know about the java syntax. I just need the explanation of why statement (1) is incorrect and statement (2) is correct!

2007-10-23 23:14:10 · update #1

5 answers

The test == SHOULD only be used for number equality. And then mostly only for integer testing.
Testing for float or double should be tested within a range due to the rounding error in double or float.

When using the == test with objects (including Strings) the test is equating the address, i believe, of the object and not the value of the object.
To test an object you should always use the equals() method.

2007-10-23 23:05:46 · answer #1 · answered by AnalProgrammer 7 · 0 1

Try

if( str.toLowerCase().equals("answer" ))

This statement
(1)if( str.toLowerCase() == "answer" )
will return false because the objects are unequal because it's comparing an objects reference.

2007-10-24 06:04:18 · answer #2 · answered by shallowG 3 · 0 0

It's because (1) is not doing a string comparison but rather a reference check (are they the same object).

Try:

"answer".equals( str.toLowerCase() )

2007-10-24 06:01:55 · answer #3 · answered by SadButTrue 4 · 0 0

For statement 1

if("answer".equals(str.toLowerCase()))

will return true.

use the .equals() method for comparing strings.

2007-10-24 06:05:51 · answer #4 · answered by joelmcleish 2 · 0 0

Use the equals() method then you will get the correct return clause. its java! not c++ so try this.

2007-10-24 07:42:46 · answer #5 · answered by Namita 3 · 0 0

fedest.com, questions and answers