Null check + dereference on the same line - java

Are there any dangers in checking for null and dereferencing on the same line?
If myObj is in fact null, how would this code behave?
Are there differences in how different languages handle situations like these (ie C# vs Java)
For example, something like below
if(myObj != null && myObj.someProp == "Test")
{
//...
}

&& is short-circuiting so if myObj is indeed null then the second condition will never be evaluated.
This behaviour is the same for both C# and Java.

In your example the if condition expect a boolean value that is provided by the boolean operation myObj != null && myObj.someProp == "Test".
When using the && operator the left operand is checked first. If its value equals true then the right operand is checked as it's not possible to know its state in advance. But if its value equals false then no need to check the right operand as no matter the right condition state will be, the whole operation will result to false.
This is why it's safe.
But when using the & operator both operands are always checked. Your example would look as follows with the & operator:
if(myObj != null & myObj.someProp == "Test")
{
//...
}
Doing so, when myObj variable is equals to null then the code above will fail. In this case your code won't be safe.
I hope this helps;

Related

How is `return <boolean exp> || <Object exp>` a valid return statement for a method that returns an Object?

I was reading a book, and saw this code:
public Animal getWinner(List<Animal> animals) {
return animals == null || animals.size() == 0 ? null : animals.get(0);
}
The latter expression is fine as it returns an Animal or null. The former expression is puzzling though, as it's just a boolean expression.
I made a test class and called getWinner(null). It returned null. As far as I know, animals == null would be true, the expression would short-circuit, and I expect the method to return true instead of null.
How does this line compile, and even work as expected?
This has to do with operator precedence in Java and which operator - the boolean or the ternary, will be executed first.
The ternary has lower precedence, so the or will be evaluated first, meaning it would look like this with parenthesis:
return (animals == null || animals.size() == 0) ? null : animals.get(0);
So the result of the entire line is either to return null or return animals.get(0).

java - What's the difference between (obj != null) and !(obj == null) in an condition?

I have the following question, for Java programmers.
Does there be any difference between setting (obj != null) rather than !(obj == null)?
Quoting JLS Sec 15.21.3:
At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.
The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.
And JLS Sec 15.15.6, which describes the logical complement operator (!):
At run time, the operand is subject to unboxing conversion (ยง5.1.8) if necessary. The value of the unary logical complement expression is true if the (possibly converted) operand value is false, and false if the (possibly converted) operand value is true.
So the two are exactly the same from an evaluation point of view; but != is easier to read.
There are no difference here, the !(obj==null) is just the another way for writing (reverse), and it also hard to understand than the first one.
There is not any difference. (obj != null) is easier to read for most people.
NO difference.
Also, some prefer having null close to each other while making a conditional check.
if(obj1 == null || null == obj2) // looks better to read
...
if(obj1 == null && obj.method()) // have high chances to throw an exception
even if True && this will be checked
if(obj1 == null || obj.method()) // is preferred over the above one
if True || this will be NOT be checked
No, there is not any difference.
'Not equal to' (!=) is the sam as not be 'Equal to'.

Java: Can't check the boolean for null

if a HashMap is empty and I check for .containsKey()
I get a null answer.
My Problem is that If I want to check for null I get an error message
if(containsKey == null || !containsKey){
I receive the error message
Operator '==' cannot be applied to 'boolean', 'null'
Can someone tell me why this is happening. I thought that this should work
Check that the map isn't null (not that HashMap.containsKey(T) returned null, because it didn't - it can't. It returns a boolean primitive, which can only be true or false).
if (map != null && map.containsKey(someKey)) {
// ...
}
You can use the HashMap .isEmpty() method to check if your hashmap is empty or not.
containsKey can't be null as it is the method being called. Try checking if the map itself is null.
Booleans are primitives, and primitives will never be null.
Only Object classes can be null.
Following this argument, you can do this for object class Integer:
Integer myObject = 1;
if (myObject != null){
...
}
But you cannot do this for int, which is a primitive like booleans:
int myPrimitve = 1;
if (myPrimitve == null){
...
}
Your IDE will show the error Operator == cannot be applied to int, null

How to handle null string in java

I am .net programmer and completely new in java. I am facing problem in handling null string in java. I am assigning value from string array to string variable completeddate.
I tried all this but that didn't work.
String COMPLETEDATE;
COMPLETEDATE = country[23];
if(country[23] == null && country[23].length() == 0)
{
// ...
}
if (COMPLETEDATE.equals("null"))
{
// ...
}
if(COMPLETEDATE== null)
{
// ...
}
if(COMPLETEDATE == null || COMPLETEDATE.equals("null"))
{
// ...
}
For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:
if("constantString".equals(COMPLETEDDATE)) {
// logic
}
But in general, your approach isn't correct.
The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.
The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.
Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.
Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".
To check null string you can use Optional in Java 8 as below:
import Optional
import java.util.Optional;
import it as above
String str= null;
Optional<String> str2 = Optional.ofNullable(str);
then use isPresent() , it will return false if str2 contains NULL otherwise true
if(str2.isPresent())
{
//If No NULL
}
else
{
//If NULL
}
reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
It is not entirely clear what you are asking, but to check if a String variable is null, use the following statement.
if(myString==null)
This checks whether the object reference is null.
The following statement, which you have written is incorrect for two reasons.
if (COMPLETEDATE.equals("null"))
{
// ...
}
1. null is a keyword in Java, "null" is just a string of text.
2. .equals() checks to see if two objects are equal according to the given method's definition of equality. Null checks should always be made using the == comparison operator, as it checks reference equality.
If a variable is null, you cannot dereference it.
That means you can not invoke methods on it.
So... The following if statement will throw a NullPointerException every time the first clause is true:
if (a == null && a.length() == 0)
In other words: if a is null, you CANNOT invoke the length method on a.

Getting confused with == and = in "if" statement

I know that we cant use assignment operator in if statements in java as we use in any other few languages.
that is
int a;
if(a = 1) { }
will give a compilation error.
but the following code works fine, how?
boolean b;
if(b = true) { }
EDIT : Is this the exception to rule that assignment cant be used in if statement.
Because the "result" of an assignment is the value assigned... so it's still a boolean expression in the second case. if expressions require the condition to be a boolean expression, which is satisfied by the second but not the first. Effectively, your two snippets are:
int a;
a = 1;
if (a) { }
and
boolean b;
b = true;
if (b) { }
Is it clear from that expansion that the second version will compile but not the first?
This is one reason not to do comparisons with true and false directly. So I would always just write if (b) instead of if (b == true) and if (!b) instead of if (b == false). You still get into problems with if (b == c) when b and c are boolean variables, admittedly - a typo there can cause an issue. I can't say it's ever happened to me though.
EDIT: Responding to your edit - assignments of all kinds can be used in if statements - and while loops etc, so long as the overall condition expression is boolean. For example, you might have:
String line;
while ((line = reader.readLine()) != null)
{
// Do something with a line
}
While I usually avoid side-effects in conditions, this particular idiom is often useful for the example shown above, or using InputStream.read. Basically it's "while the value I read is useful, use it."
For if you need an expression that evaluates to boolean. b = true evalueates to boolean but a = 1 evaluates to int as assignments always evaluate to the assigned values.
The reason the second code works okay is because it is assigning 'b' the value of true, and then comparing to see if b is true or false. The reason you can do this is because you can do assignment operators inside an if statement, AND you can compare against a boolean by itself. It would be the same as doing if(true).
In java, you don't have implicit casting. So non-boolean values or not automatically transformed to booleans.
In the first case, the result of the statements is an int, which is non-boolean, which will not work. The last case, the result is boolean, which can be evaluated in an if-statement.
The rule is not that "assignment can't be used in an if statement", but that "the condition in an if statement must be of type boolean". An assignment expression produces a value of the type being assigned, so Java only permits assignment in an if statement if you're assigning a boolean value.
This is a good reason why the style if (foo == true) should be avoided, and instead simply write if (foo).

Categories