This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I just want to know why the compiler allow to continue the program normally in the first condition:
public void ButtonOnClickDirectoryList(View v){
try {
if (!spnOptionSelectedDepartment.equals(null) && !spnOptionSelectedCities.equals(null)) {
if (!spnOptionSelectedTypes.equals(null)) { //code....}
the spnOptionSelectedDepartment and spnOptionSelectedTypes are Strings and are defined at the begining of the class like this:
private String spnOptionSelectedDepartment = null;
private String spnOptionSelectedCities = null;
private String spnOptionSelectedTypes = null;
so when I press the button, it call this method and this are the values that I have in the moment:
spnOptionSelectedDepartment = "9999"
spnOptionSelectedCities = null
spnOptionSelectedTypes = null
so when I put a break point on this condition it just continue validating the rest of the code inside that if...
Could anybody explain me why this behavior?
Let me edit the question, Yes it throws nullpointer exception on the second if...
if (!spnOptionSelectedTypes.equals(null)) {
but why it allows the first IF when spnOptionSelectedCities = null...?
It shouldn't continue, it should throw a NullPointerException that you may intercept in the catch block.
When you try
if (!spnOptionSelectedTypes.equals(null))
it should throw this exception because spnOptionSelectedTypes is null so it is not a String and does not have any equals() method.
Edit:
It allows the first if to pass because it has 2 tests
if (A OR B) {
If A is true, the B condition is not tested because only one is required to continue, because of the OR operator.
Edit 2:
With:
if (A AND B) {
If A is true, B will also be tested and throw a NullPointerException if spnOptionSelectedCities is null.
Definitive answer:
Null tests in Java
if (x != null && y != null) {
x.doSomething();
y.doSomethingElse();
}
Related
This question already has answers here:
Try Catch Performance Java
(4 answers)
Closed 3 months ago.
First of all, I want to describe that there are more than five thousand records. Please let me know the best method for best performance from the following:
String hmVALUE = "";
try
{
hmVALUE = hashmapRECORDS.get(key).toString();
}
catch(Exception ex)
{
hmVALUE = "";
}
// Second method:
String hmVALUE = "";
if(Module.hmQUEUED_REQUESTS.containsKey(key))
{
hmVALUE = hashmapRECORDS.get(key).toString();
}
else
{
hmVALUE = "";
}
I am using try-catch and want to know which method is best.
Neither is ideal. Better to call get() and check if the result is null:
String hmVALUE = "";
Object value = hashmapRECORDS.get(key);
if (value != null) {
hmVALUE = value.toString();
}
Generally speaking, exceptions are much heavier operations for Java to generate (they need to collect stack traces, etc...) so in this specific case, I would say that if-statement is much better than try-catch.
However, for the question in general, those are completely different mechanisms - the 1st one should handle an unexpected error, while the other one is flow control.
Moreover, you can use the short condition ? if true : if false syntax and have the entire code like this:
String hmVALUE = Module.hmQUEUED_REQUESTS.containsKey(key) ? hashmapRECORDS.get(key).toString() : ""
And more specifically in your case, you can just use the getOrDefault() method:
String hmVALUE = hashmapRECORDS.getOrDefault(key, "");
This question already has answers here:
Null check chain vs catching NullPointerException
(19 answers)
Check if last getter in method chain is not null
(3 answers)
Closed 5 years ago.
I have an object and i want to check if this object or nested fields are null. I want to print this neted field, but i should check if there is null in some level, otherwise i will get null pointer exception .
I know i can do this:
if( object != null && object.A != null && object.A.B != null && object.A.B.C != null && object.A.B.C.D != null) { doSomething( object.A.B.C.D);}
but its so long. Do you know better way to check it ?
Optional is a good way in Java 8.
String value = foo.getBar().getBaz().toString();
With optional it will be:
String value = Optional.ofNullable(foo)
.map(Foo::getBar)
.map(Bar::getBaz)
.map(Baz::toString)
.orElse("EmptyString");
You could implement an interface on all objects with method that returns all child objects and create a method that calls itself recursively to verify that all objects are set.
Let assume that this is a check to prevent misuse of a method, so this should not occurs too many time.
Simply catch this exception, this will invalidate the value.
private boolean isValid(YourObject object){
try{
return object.A.B.C.D != null;
} catch (NullPointerException npe){
return false;
}
}
Of course, don't use this solution if you are doing a lot of validation and those return false to often, exception are an heavy process.
EDIT :
As Fildor point it out, there is a cost to use a try-catch even without exception. But using this answer I can assume this will be limited and there is not much optimization to do on this unique line.
This question already has answers here:
Null check chain vs catching NullPointerException
(19 answers)
Closed 6 years ago.
I have a complex model structure in my project.
Sometimes I have to get a deep placed value from it. It looks like following:
something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
The problem is that each of those methods could return null, and I will get NullPointerException in case if it does.
What I want to know is should I write long if like
if(something != null && something.getSomethongElse() != null && something..getSomethongElse().getSecondSomething() != null && something.getSomethongElse().getSecondSomething().getThirdSomething() != null && omething.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething() != null) {
//process getFourthSomething result.
}
Or it is OK just to use try..catch like following:
SomethingFourth fourth = null;
try {
fourth = something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
} catch (NullPointerException e) { }
if(fourth != null) {
///work with fourth
}
I know that NPE is a thing to be avoided, but isn't it overhead to avoid it in my case?
If you can refactor the code and make each method return Optional. It will be possible to avoid null checks and try ... catch.
Optional<Result> result = something.getSomethingElse()
.flatMap(e -> e.getSecondSomething())
.flatMap(x -> x.getThirdSomething())
.flatMap(e -> e.getFourthSomething());
// at the end to check if result is present
result.ifPresent(..some_logic_here..); // or result.orElse(...);
so getSomethingElse() returns Optional<SomethingElse>, getThirdSomething() - Optional<ThirdSomething> and so on. We have to use here flatMap(Function<? super T,Optional<U>> mapper) because if the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with an additional Optional. In other words if map on map(e -> e.getSecondSomething()) the result type will be Optional<Optional<SecondSomething>> and we will have to do unnecessary get() call - map(...).get().map(...).
I hope this helps.
UPDATED
You can do the same thing using method references.
Optional<Result> result = something.getSomethongElse()
.flatMap(SomethongElse::getSecondSomething)
.flatMap(SecondSomething::getThirdSomething)
.flatMap(ThirdSomething::getFourthSomething);
This question already has answers here:
Why do I get a NullPointerException when comparing a String with null?
(4 answers)
Closed 8 years ago.
if(status.equals(null))
{
status="Pass";
}
from above code it throws NullPointerException, please give solution for comparing value with null.
Looks like status itself is null. So when you do:
status.equals("null")
You're actually doing:
null.equals("null")
Which causes NPE. You should do:
if(status == null) //Now you're checking if the reference is null
//So you'll never dereference a null pointer
You might find this link useful.
Related topics:
What is null in Java?
Java null check why use == instead of .equals()
In Java "null" is a string. You want to compare the reference to null. Do the following:
if(status == null){
// code here
}
Keep in mind that String is class in Java.So whenever you call a method with unitialized object (which is a null object) then it will throw NullPointerException.In your case, there is possibility that your String status is not initialized So you need to make it sure.
BTW you should check null without using equals() method because it doesn't make sense that you are checking a null object's method for its null value.
You must do like this
if(status == null)
//Do something
only use equals method when you want to compare a String and at the stage where you are quiet sure that your String is initialized.Let say String status = ""; is a intialized String and now it is not null.Just for the info while using equals() , try to use it like "anyValue".equals(status) instead of status.equals("anyValue") because by using like "anyValue".equals(status), it will be more safe in case of null string and you wont get NullPointerException
if(status.equals("null")) //Just checking if string content/value is same
{
status="Pass";
}
By this you are just checking if value(content) of status variable is "null" String or not. IF you want to do a null check you need to do the following
if(null == status)
{
status="Pass";
}
You are not suppose to make it null as "null"! in your case compiler consider it as string.
if(stringVariable!=null)
{
//ur Code
}
(OR)
if(stringVariable.equals(null))
{
//Ur code
}
In case if ur working with string array you can do it as following
if(stringArray.isEmpty())//checks length of String array
{
//ur code
}
You cannot use .equals with a null . Use :
if(status == null) {
//Do something
}
This is exactly the reason why the HashMap cannot store more than one null values . Because it always compares the key with other valuues and if a null is inputted the second time , it throws NPE .
You are getting this error since status is null.
Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.
String lastGroup = "";
menuTevekenysegekGrouped = new ArrayList<MenuElem>();
for(MenuElem me : menuA) {
// double checked that me objects are never null
// double checked that menuA is never null
if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE!!! */
lastGroup = me.getGroup();
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)
Are you sure that me itself is not, in fact, null?
From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...
If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.
The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:
String lastGroup = "";
for(MenuElem me : menuA) {
String thisGroup = me.getGroup();
if(thisGroup != null && !thisGroup.equals(lastGroup)) {
lastGroup = thisGroup;
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.