0

I have the following code:

String tmp = "cif";
String control = tmp.substring(1);


if(control == "if") {

append = "if( ";

}

However, despite control being "if", the test will still fail. Any solutions?

MrD
  • 4,986
  • 11
  • 48
  • 90

5 Answers5

5

== compares object references whereas .equals() compares actual value

if(control.equals("if") {
   append = "if( ";
}
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
2

For string compare use equals()

Joan
  • 427
  • 3
  • 6
2

The "==" operator will compare the memory address of two strings, not their values. You need to use equals(). In your case, do something like "if".equals(control);.

Vitaly
  • 2,760
  • 2
  • 19
  • 26
kronion
  • 711
  • 4
  • 14
1
String tmp = "cif";
String control = tmp.substring(1);

if(control.equals("if")) {
   append = "if( ";
}
gkiko
  • 2,283
  • 3
  • 30
  • 50
0

You cannot compare Strings via the == operator as Strings are objects.

Being objects, it does give the extra functionality of them having various methods inside of their classes. One such method which may come in handy is the equals() method.

The code you will therefore want would be:

String tmp = "cif";
String control = tmp.substring(1);

if("if".equals(control) {

...
Vitaly
  • 2,760
  • 2
  • 19
  • 26
Mike
  • 99
  • 2
  • 3
  • 13