-
Using strings inside of "if" statements
I am trying to use an if statement to compare strings and it doesn't appear to be working. The format I am using is:
if (stringname = "value")
do this;
However this doesn't seem to work, unless I'm missing something it it looks like it pretty much ignores the if statement altogether despite ways I change it around. Any help would be appreciated.
-
Two things. First, what you should use for checking String equality is:
Code:
if (stringname.equals("value")) {
// stuff!
}
If you use the == operator, it actually compares the address of the String objects which isn't what you want.
Second, using a single = means assignment. So in your original if statement, it sets the variable stringname's value to "value", and the if statement evaluates to true because it was successful. A little wierd I know.
When doing a compare, use two ==. Here is how an if comparing two ints would look:
Code:
int a = 0;
int b = 1;
if (a == b) {
// more stuffs!
}
-- Steven
-
Thanks, it works now. I meant to put the "==" in the example as it was what I was using I just keep forgetting little stuff like that without the compiler to scream at me .
-
just remember:
primitives start with a lowercase letter:
int boolean byte short float double long char
and you compare those with ==
if( myInt == 1)
--------------------------------------
Objects start with an Uppercase Letter:
String s = "hello";
File f;
System.out.println //System is an object
Character c;
Integer i; //the primitives all have Object equivalents, for special uses.
you compare the CONTENT of 2 objects with .equals():
object1.equals(object2)
you compare MEMORY ADDRESSES of 2 objects, with ==
this is used occasionally, say for if a button handler is handling 10 buttons, and it is told which button generated the event :
if buttonThatGeneratedTheEvent == saveButton{
save()
}
else if buttonThatGeneratedTheEvent == quitButton{
quit()
}
-------------
simple rule is: use == for primitives and .equals for objects
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks