-2

Having an issue when trying to compare strings in If statement.

private String browser = XMLreader.getData("browser");

if (browser == "chrome"){
    System.out.println(browser);
} // Will not print anything

if (browser != "chrome"){
    System.out.println(browser);
} // Will print chrome 

Any idea what am I missing?

Thanks

  • 1
    show us your code, see: [minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example) – Josh W. Oct 14 '19 at 16:38

1 Answers1

2

It is because string in Java is not possible to compare with "==" operator. When you are using the "==" operator, you are compare the object reference related to string. So when you get the real compared to "!=", In fact the return will print "chrome"because the object references being different and actually resulting.

When you wish compare string in Java you could use the equals string method. Like here:

if("chrome".equals(browser)){ ... }

You also can use some utils library to compare these strings, like StringUtils of Apache Commons.

if(StringUtils.equals("chrome", browser)) { ... }

The advantage is the treatments that these libs already provide, such as validation of null and empty values, for example.

Juliano Pacheco
  • 521
  • 1
  • 5
  • 13
  • I already tried what you suggested if("chrome".equals(browser)){ ... } The same issue remains. It doesn't print anything – doron pnini Oct 14 '19 at 17:15
  • Did you ever test using StringUtils? Where is the browser variable being declared? Is it out of the method, right? Can you print browser variable, during the execution, to see if it actually contains the string "chrome" as a value? – Juliano Pacheco Oct 14 '19 at 17:34
  • 1
    I manage to find the issue, thank you for your help. There was redundant space in the XML file and also needed to run equalsIgnoreCase – doron pnini Oct 14 '19 at 17:36