File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes IF statement ptoblem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "IF statement ptoblem" Watch "IF statement ptoblem" New topic

IF statement ptoblem

Micheal Smith

Joined: Apr 08, 2006
Posts: 4

this is my first post on these forums hehe

I am a beginner in java.

These days I was trying out some multi-threading and I am going on quite well but I encountered one strange problem with, believe it or not, an if statement.

I have the following code snippet inside my Run() method:

I think at this point the program should display YES EQUALS but it is displaying:

t1s: l
thread: l

Therefore the problem is that if t1s and thread are the same why is it jumping to the else statement?

Thanks alot for your help
Muhammad Saifuddin
Ranch Hand

Joined: Dec 06, 2005
Posts: 1323

try to change ur code with this..
i m not sure about it but may be ur problem is solve.. just try it..


String t1s;

t1s = Thread.currentThread().getName().toString();

if (t1s.equals(Thread.currentThread().getName().toString()))
System.out.println("YES EQUALS");
System.out.println("t1s: "+t1s);

[ April 08, 2006: Message edited by: saif uddin ]

[Blog][Linkedin] How To Ask Questions On JavaRanch My OpenSource
Micheal Smith

Joined: Apr 08, 2006
Posts: 4


but may I ask ... why didnt it work with == and it workd with .equals?

just for curiosity hehe
Muhammad Saifuddin
Ranch Hand

Joined: Dec 06, 2005
Posts: 1323


== this comparesion operator is not for String but for all
because there is a wounderful method to comparing a strings
whenever u compare 2 String values String.equals()

SAif uddin
[ July 25, 2006: Message edited by: saif uddin ]
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11956

the == operator basically compares the value of the variables. tls is a REFERENCE to a string object. what it holds is basically the memory address of where that String is.

the way your code was originally written, you created two distinct Strings, at different places in memory.

Therefore, == returns false.

the equals() method checks the CONTENTS of the objects, to see if they are equivelant.

Note that when you write your own classes, you will have to override the default equals() method with one that makes sense for your class.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jackie Davis

Joined: Mar 04, 2006
Posts: 23
Thanks for the explanation! This has just solved my problem too
I agree. Here's the link:
subject: IF statement ptoblem
It's not a secret anymore!