Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

the "!"(not) in string conditions  RSS feed

 
Howard Tan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,
i recently encountered a problem with "!"(not) and strings. Does this work?
ex. if (!(strName == ""))
It doesn't give me a compiliation error. I played around with it and
I think "!"(not) with strings do not work. This condition is treated as if there was no "!"(not)....
Am i right? Is there an alternative way to solve this?
thanks in advance.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howard,
The ! operator is boolean complement and doesn't work for strings.
Try
if( strName != "" )
Regards,
Manfred.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, so i'm embarassed to ask this, but why would this not work?
doesn't (strName == "") return a boolean? so (!(strName == "")) should just return the complement of (strName == "")
granted, i've had no coffee yet this morning, but now i'm confused!!!
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did i miss something???

C:\fred_temp>java stringTest
false
true
C:\fred_temp>
It seems to work just fine from where i'm sitting...
 
Peter Kristensson
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
Brush up on String.equals(), where I think your problem really is.
The == construct is really a comparison of references.
/Peter
 
Jason Menard
Sheriff
Posts: 6450
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use equals() to compare the value of objects, and == to check for the same object reference.
1)
String s = new String("test");
String t = new String("test");
The following hold for #1 above:
s == t : false
s != t : true
s.equals(t) : true
!s.equals(t) : false
2)
String s = "test";
String t = "test";
Because of the way Java handles Strings internally, in #2 above, "s == t" may evaluate to true, but this is not something you want to count on.
3)
String s = "test";
String t = s;
The following would hold for #3, where you are making t point to the same object as s.
s == t : true
s.equals(t) : true
To quote Ernest Friedman-Hill, comparing Strings with "==" is like running with scissors.
 
Howard Tan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thanks guys.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!