1

my case:

I try to get a value from my MySQL database. This data is defined as a VARCHAR. This is done in java with a prepared statement and resultset.

String add1 =rs.getString("include");

according to this website table 5.1 states "Can always be converted to these Java types".

therefore a VARCHAR should be able to be converted in a java.lang.string. When i check the data type in java it indeed gives java.lang.string. So for so good.

My issue is when i try to compare this obtained "String" value to a in java defined String value they don't seem to be equal.

Let's give a simple example. I get the (VARCHAR) value "1" from the database and store in in String add1

I want to check if this value is indeed "1" and therefore I use the following statement

if(add1=="1")
{
      /* do something */   
}    

Only the values are , according to java, not the same. So I was curious about why this is.

I started searching why those two "Strings" are not equal.

First of I checked the length of both strings. Both came out to be 1 in length as expected.

Afterwards I checked the value of both. To see if both values where indeed the same i wanted to check their hexadecimal representance. Both came out with the value 0x31. Still as expected.

But then why isn't my if statement accepted by java if both seem to represent the same string-hex-bin-you name it value.

In short: Why is my VARCHAR "String" obtained from a MySQL databse in java not the same as a String defined in java.

ravisvi
  • 149
  • 2
  • 9
s0ulmaster
  • 13
  • 3

3 Answers3

3

Compare values, not memory references:

if(add1.equals("1"))
{
      /* do something */   
} 

Please see this post best answer.

Community
  • 1
  • 1
drgPP
  • 926
  • 2
  • 7
  • 22
1

You must always compare strings with the .equals method in your case it will be

add1.equals("1")

"==" or equality operator in Java is a binary operator It is good for compairing primitives like boolean, int, float "==" works fine but when it comes to compare objects it creates confusion with equals method in Java. "==" compare two objects based on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.

String comparison is a common scenario of using both == and equals method. Since java.lang.String class override equals method, It return true if two String object contains same content but == will only return true if two references are pointing to same object.

Read more: http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html#ixzz3PdLbOre0

kirti
  • 4,499
  • 4
  • 31
  • 60
0

You need to compare the Strings with .equals() method. because == checks for object reference.

What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56