Hopefully this is an easy fix, but for the moment is is boggling me (Actionscript programmer new to Java programming).
I have a string variable coming from getExtra that I am comparing to a static sting in an if statement:
Bundle extras = getIntent().getExtras();
dir = extras.getString("com.activity.Dir");
Then I am utilizing this in an if statement
if (dir == "content"){
// load page content
} else {
// load a menu
}
I am Toasting the value of dir on the line before it and regardless of the value it will not hit the == statement; ie: if dir == "content", it hits the else; if dir == "foo", it hits the else, etc.
I tried placing dir into another String var and used .toString();
String directive = dir.toString();
That does the same thing. What am I missing here?
SOLVED: Used dir.equals("content");
// Thanks for you being patient with me SO!
You must not compare strings via ==, but via .equals()
Strings are Objects, and to do correct Object equality comparisions, you need to use
dir.equals("content");
or better yet (to avoid possible null pointer exceptions)
"content".equals(dir);
You should use equals for Strings on Java.
2 tips:
Add the string you know it isn't null to avoid nullpointers. Ex: "compare".equals(string)
Use equalsIgnoreCase() instead of equals if you wish to compare strings and ignore the case differences.
Use the equals method instead of ==
"vuqar"=="vuqar" or "vuqar"!="vuqar" not works correct
You have to use
if(vuqar.equals("vuqar")){//action}
OR
if(!"vuqar".equals("vuqar")){//action}
Related
When the parameter *{mydata.value} is enum then how to transform it into String in thymeleaf?
I want to compare
if:*{mydata.value == "aaa"}
It gives error.
I think it is because I should do something like:
if:*{mydata.value.toString() == "aaa"}.
Try using
if:*{mydata.value.toString().equals("aaa")}
I'm not very familiar with thymeleaf, however that is a common issue in Java. Using '==' will compare the reference to the object, but the .equals() will compare the contents of the string.
If 'mydata.value' is already a string, you can remove the '.toString()'.
If it isn't a string already, you can also use:
if:*{String.valueOf(mydata.value).equals("aaa")}
See more examples of why this happens here
Never thought I will be asking such a trifle query!
Please help with this stack:
if(request.getParameter("cl")=="star"){
txtFilePath = session.getServletContext().getRealPath("/cl.json");
}
else
{ txtFilePath = session.getServletContext().getRealPath("/kl.json");
}
Irrespective of passing cl=star in the url parameters, its not bringing any difference, and showing only kl.json
This code is in jsp, and as of now, no other framework is being used. It's being tested on Tom cat container.
NEVER compare strings using ==.
Always compare using the equals method.
request.getParameter("cl").equals("star")
Note that when using == to compare string objects, you are not comparing it's values but it's references.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If statement using == gives unexpected result
Hi I'm using this code to add elements to my ComboBox, and I do not want to add empty elements, here's the code:
public void elrendezesBetoltes(ArrayList<Elrendezes> ElrLista){
int i;
Elrendezes tmp;
model.removeAllElements();
model = new DefaultComboBoxModel(comboBoxItems);
for(i=0; i<ElrLista.size(); i++){
tmp = ElrLista.get(i);
if(tmp.getName()!="")comboBoxItems.add(tmp.getName()); //not working
addButton2(tmp.getSeatnum(),tmp.getCoord(),tmp.getFoglalt());
}
}
My problem is that the if statement is not working, it still adds empty names to my combobox. What am I doing wrong?
Always use equals method to compare Strings: -
if (tmp.getName()!="")
should be: -
if (!tmp.getName().equals(""))
or simply use this, if you want to check for empty string: -
if (!tmp.getName().isEmpty()) {
comboBoxItems.add(tmp.getName());
}
Use equals method to compare string. By using != operator, you are comparing the string instances, which is always going the be true as they(tmp.getName() and "") are not same string instances.
Change
tmp.getName()!=""
to
!"".equals(tmp.getName())
Putting "" as first string in comparison will take care of your null scenario as well i.e. it will not break if tmp.getName() is null.
Use equals():
if (!tmp.getName().equals(""))
Using == or != compares string references, not string contents. This is almost never what you want.
you have to compare Strings with "equals", then it will work
if(!tmp.getName().equals(""))comboBoxItems.add(tmp.getName())
you are comparing for identity (==, !=) but each String instance has its own identity, even when they are equal.
So you need to do !tmp.getName().equals("").
Generally it is considered best practice to start with the constant string first, because it will never be null: !"".equals(tmp.getName())
However, I would recommend to use apache commons lang StringUtils. It has a notEmpty() and notBlank() method that take care of null handling and also trimming.
PS: sometimes identity will work for Strings. but it should not be relied upon as it is caused by compiler or jvm optimization due to String immutability.
Use String#isEmpty()
if(!tmp.getName().isEmpty())
OR:
if(!tmp.getName().equals(""))
Always, check String equality with equals method. == operator only checks if two references point to the same String object.
Another alternative if not on Java 6 and isEmpty is unavailable is this:
if (tmp.getName.length()>0)
Checking for the length is supposed to be quicker than using .equals although tbh the potential gain is so small its not worth worrying too much about.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I know it' a dumb question but why this code doesn't work.
boolean correct = "SampleText" == ((EditText)findViewById(R.id.editText1)).getText().toString();
if(correct) ((TextView)findViewById(R.id.textView1)).setText("correct!");
else ((TextView)findViewById(R.id.textView1)).setText("uncorrect!");
The point is to check if content of "editText1" is equal to "Sample Text"
In Java, two strings (and in general, two objects) must be compared using equals(), not ==. The == operator tests for identity (meaning: testing if two objects are exactly the same in memory), whereas the method equals() tests two objects for equality (meaning: testing if two objects have the same value), no matter if they're two different objects. Almost always you're interested in equality, not in identity.
To fix your code, do this:
String str = ((EditText)findViewById(R.id.editText1)).getText().toString();
boolean correct = "SampleText".equals(str);
Also notice that it's a good practice to put the string literal first in the call to equals(), in this way you're safe in case the second string is null, avoiding a possible NullPointerException.
In Java Strings have to be compared with their equals() method:
String foo = "foo";
String bar = "bar";
if (foo.equals(bar)) System.out.println("correct");
else System.out.println("incorrect");
to compare the values for two strings (for equality), you need to use equals, not == (or use equalsIgnoreCase if you do not care about case sensitivity).
Using equals will check the contents/values of the strings (as opposed to "==" which will only check if the two variables point to the same object - not the same value).
The correct way to compare 2 objects in java is using equals() method of Object class
And as String is an object in java, it should be compared in same way.
The correct way to compare a String is with,
s1.equals(s2)
So you can use this,
boolean correct = "SampleText".equals(((EditText)findViewById(R.id.editText1)).getText().toString());
((TextView)findViewById(R.id.textView1)).setText("SampleTest".equals(((EditText)findViewById(R.id.editText1)).getText().toString()) ? "correct!" : "incorrect!");
It's a bit long and theres probably a better way you could do this. The .toString() feels weird!
This might sound like a real dumb question but please bear with me :)
so I have a if condition in my code like if ((msgBO.getEmpId().equals("") == false )) {
// do something
} My question is, if I make the above statement as msgBO.getEmpId().equals(null) == false
would it make any difference or this way I am trying to compare two different things?
Yes, there is a big difference between "" (the empty String) and null (no String at all).
Any Object reference can point to null. That represents 'no data' or 'nothing.' The empty string "" represents a String with no length.
An example of this is the following:
String one = null;
String two = "";
int oneLength = one.length();
int twoLength = two.length();
The first call to length will throw a NullPointerException. And the second will return 0.
These are different things. In particular, the test
msgBO.getEmpId.equals(null) == false
a.k.a.
!msgBO.getEmpId.equals(null)
is guaranteed to always succeed (at least, if the equals method involved is written according to the standard set of rules), since no object is ever allowed to compare equal to null:
For any non-null reference value x, x.equals(null) should return false.
(Documentation of equals)
So, in other word, if you already know, that msgBO.getEmpId != null, then you also know the outcome of the call to equals. And unless you know that msgBO.getEmpId != null, calling equals is a NullPointerException waiting to happen. So, one often sees:
msgBO.getEmpId != null && msgBO.getEmpId.equals("...stuff...")
or even
"...stuff...".equals(msgBO.getEmpId)
"" (an empty string) and null are not the same. .equals(null) on a String will never return true.
A null reference and String of length 0 are two completely different things in Java. Two other points:
getEmpId is either a getter method missing the braces for method invocation or a public field, which is generally frowned upon (and badly named in this case).
if getEmpId is/returns null, teh calling equals() on it will caus a NullPointerException - which is why you should reverse the comparison when comparing with literal strings: if("foo".equals(variable))
Comparing a boolean expression explicitly using == is ugly. Instead you can use negation: if(!msgBO.getEmpId.equals("")) or if(!msgBO.getEmpId != null)
They are different , what you want is
msgBO.getEmpId == null
for the other case
You are trying to compare two different things. It might still work, but one is checking for an empty string and one is checking if the variable is null.
Also a faster check to see if the string is empty is just to check
if (string.length == 0).
(You will get an exception, however, if the string is null so don't do this if null checking, unless you want to handle the null case with the caught exception).
It does make a difference.
msgBO.getEmpId.equals("") compares msgBO.getEmpId with an empty String
msgBO.getEmpId.equals(null) compares msgBO.getEmpId with a null value. This is wrong because it will throw NullPointerException if msgBO.getEmpId is null. If you want to check if the value is null you should use such a condition instead: msgBO.getEmpId == null.
What is correct in this situation depends on the type of a value returned by msgBO.getEmpId. If it isn't String then only comparing with null makes sense. If it is String both values may have sense and then it depends how you represent an empty value of msgBO.getEmpId. In this case if you use null for an empty value you should compare with null and if you use "" for an empty value you should compare with "".