-2

I am comparing two strings in if else block..if it is true if block should be executed and if it is false else block should execute..but my code is always executing else block for both true & false condition..here is my code

if(deckey==keystr)
{
.
.
}
else
{
System.out.println("your unauthorised person");
System.exit(0);
}

my deckey is containing string value abc123 and for keystr i am getting the value from this which is also abc123(i am getting through arraylist)..

ArrayList<Integer> listfkey= new ArrayList<Integer>();
String keystr=" ";
for (int i = 0; i < listfkey.size(); i++) {
dech=(char)listfkey.get(i).intValue();
keystr+=dech;
}

please help me out..

user1717259
  • 2,717
  • 6
  • 30
  • 44
  • 1
    Comparing strings like this will not end well: all you're doing is comparing the references. Use .equals method instead. – Bathsheba Mar 13 '15 at 15:32
  • 1
    possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Florent Bayle Mar 13 '15 at 15:33
  • Please don't downvote well-posed questions that are duplicates (unless of course the answer could easily be attained with a search). Vote to close instead. – Bathsheba Mar 13 '15 at 15:42

3 Answers3

3

Strings need to be tested for equality using the .equals method:

deckey.equals(keystr)

Not the == operator, which tests if two string instances are the same:

deckey==keystr
mk.
  • 11,360
  • 6
  • 40
  • 54
  • 2
    you can also use `deckey.equalsIgnoresCase(keystr)` so it doesn't care about upper/lower case. Also its a good idea to do a empty/null check before working with any String: `StringUtils.isEmpty(deckey) || StringUtils.isEmpty(keystr)`. – Code Whisperer Mar 13 '15 at 15:35
0

primatives are a different matter, but with Java objects, == will only return true if the object is being compared to itself (same memory location). For Objects, use the equals method or the Comparator interface

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

== is use for compare memory location, it will be right on some primitive data

String is object, so for compare it we need to use .equals() method It come from Comparator

TienHoang
  • 21
  • 1
  • 6