| Author |
IF statement ptoblem
|
Micheal Smith
Greenhorn
Joined: Apr 08, 2006
Posts: 4
|
|
hi 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 Micheal
|
 |
Muhammad Saifuddin
Ranch Hand
Joined: Dec 06, 2005
Posts: 1318
|
|
try to change ur code with this.. i m not sure about it but may be ur problem is solve.. just try it.. code: String t1s; t1s = Thread.currentThread().getName().toString(); if (t1s.equals(Thread.currentThread().getName().toString())) { System.out.println("YES EQUALS"); } else { System.out.println("t1s: "+t1s); System.out.println("thread:"+Thread.currentThread().getName().toString()); }  [ April 08, 2006: Message edited by: saif uddin ]
|
Saifuddin..
[Linkedin] How To Ask Questions On JavaRanch My OpenSource
|
 |
Micheal Smith
Greenhorn
Joined: Apr 08, 2006
Posts: 4
|
|
A REAL BI THANKS MY FRIEND! YOU SOLVED MY PROBLEM. 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: 1318
|
|
hi, == 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() Regards SAif uddin [ July 25, 2006: Message edited by: saif uddin ]
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9950
|
|
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.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Jackie Davis
Greenhorn
Joined: Mar 04, 2006
Posts: 23
|
|
Thanks for the explanation! This has just solved my problem too
|
 |
 |
|
|
subject: IF statement ptoblem
|
|
|