== operator behaves strange in java

23 07 2009

Yesterday I was helping my sister to write one java program. I don’t know java, I was working on php, python, javascript from long time. But I could figure out the logic by seeing any code. So I am checking my sister java code. She wrote one if statement like this.

if(input_data == "Y"){
// some code
}

There is nothing wrong but the if condition is failing every time even I give the value “Y” for the input_data. This is correct syntax and correct logic, but it is still failing. It is looking very strange and weired for me. When I google for how to compare 2 strings in java then I figured out that “==” operator compare the object references not the content of the variables. In my case if write I should write if condition like this.

if(input_data.equals("Y")){
// it works fine
}

This is much difference from other languages. Why it is like this I could not understand.

Advertisements