Why null is not equal to null? [duplicate] - java

This question already has answers here:
How to compare null value from the JsonObject in java
(7 answers)
Closed 3 years ago.
I dont understand what is happening in my application. I'm sending PUT request with updates from Angular project to java api. I have a method that validates query parameters from the put request, the method looks like this:
private JsonObject validateRequestBody(JsonElement requestBody) {
if (!(requestBody instanceof JsonObject)) {
throw new IllegalArgumentException("Request body cannot be case to JSON object");
}
JsonObject bodyObj = requestBody.getAsJsonObject();
System.out.println(bodyObj.get("entityIri").equals(null));
if (bodyObj.get("entityIri") == null) {
System.out.println("null");
throw new IllegalArgumentException("Request body must contain entity IRI");
}
return bodyObj;
}
As you can see, I'm just trying to check if the enityIri paramter is equal to null. To test it, Im sending null as entityIri from Angular project. I tried to compare them with equal method and with ==, but in both cases the output is always false. Could someone explain me why they are not equal? Is it because I'm passing it to JsonObject?
I attach a screenshot from debugging (I cut out irrelevant parts).

Try to use isJsonNull method:
provides check for verifying if this element represents a null value
or not.
if (bodyObj.get("entityIri").isJsonNull()) {
...
}
Of course, you need to check whether bodyObj.get("entityIri") is not null before. I did not add it statement to make statement clear.

Related

How can I rewrite null checks with optional in a better way [duplicate]

This question already has an answer here:
Java 8 avoiding null pointer checks using Optional
(1 answer)
Closed 1 year ago.
I am having a small snippet of code. I would like to write it in a better way with fewer nested checks. How can I achieve it?
Item item = itemResponse.getItem();
Optional<Item> optionalItem = Optional.ofNullable(item);
if (optionalItem.isPresent()) {
List<NameValue> listValues = item.getValues();
Optional<List<NameValue>> optionalListValues = Optional.ofNullable(listValues);
if (optionalListValues.isPresent()) {
System.out.println(listValues);
}
}
Is there any concise way I can rewrite the above piece of code using Java 8?
You can make itemResponse.getItem() class to return Optional<Item> and use the chained map method which will executed only if Optional has value, and if map method return non null value then only final ifPresent(Consumer consumer) is executed
Optional<Item> item = itemResponse.getItem()
item.map(item::getValues)
.ifPresent(System.out::println);

How to mock the function in a loop using Mockito in Java to return different value for each iteration [duplicate]

This question already has answers here:
How to tell a Mockito mock object to return something different the next time it is called?
(5 answers)
Closed 2 years ago.
I am new to using Mockito. In my logic I need to mock a function that is inside the loop and for every iteration, it should return different value.
Example :
for(value : values )
{
int i = getValue(value);
i=i+1;
}
if(i=somevalue)
{
some code
}
else
{
Some other code
}
So if I mock getValue() method to return a particular value. Everytime, it is returning the same value and only one part of if else is covered.
Can you please suggest me a way such that everytime in the loop getValue() is returned different value.
Thank you !
Since you have an input in getValue() you can use that.
when(mockFoo.getValue(value1).thenReturn(1);
when(mockFoo.getValue(value2).thenReturn(2);
when(mockFoo.getValue(value2).thenReturn(3);
But if you just don't care you can return different values in a sequence.
when(mockFoo.getValue(any()))
.thenReturn(0)
.thenReturn(1)
.thenReturn(-1); //any subsequent call will return -1
// Or a bit shorter with varargs:
when(mockFoo.getValue())
.thenReturn(0, 1, -1); //any subsequent call will return -1
Also please note, that if(i=somevalue) will always be true, you might want to use if (i == somevalue).

Handle Chained Method Calls avoiding NullPointerException - Which is the best way? [duplicate]

This question already has answers here:
Check chains of "get" calls for null
(11 answers)
Closed 3 years ago.
Handle Chained Method Calls avoiding NullPointerException - Which is the best way?
Let's imagine this kind of scenario:
3 class Meeting, Room, Projector
A Meeting might have set a Room and it might have a Projector inside them.
Now suppose that I want to know what is the model of the Projector.
The most natural thing is to do something like
Meeting meeting = someMethod();
return meeting.getRoom().getProjector().getModelName();
This code could return the model name of the Projector correctly,
unfortunately this code could also cause an Exeption: an java.lang.NullPointerException in case that one of the class contained into the root class Meeting (or even the Meeting class) is null.
In order to prevent this problem, and get a default value in the worst case we should check the returned value of each call.
Meeting meeting = someMethod();
if (meeting != null) {
Room room = meeting.getRoom();
if (room != null) {
Projector projector = room.getProjector();
if (projector != null) {
return projector.getModelName;
}
}
}
return "No Projector Exist";
The code now is pretty nasty.
What is the best way to deal with this kind of chained method calls avoiding the NullPointerException?
Use Optional:
return Optional.ofNullable(someMethod())
.map(Meeting::getRoom)
.map(Room::getProjector)
.map(Projector::getModelName)
.orElse("No Projector Exist");
As an aside, consider returning Optional or null from your method - having to compare your String to the special hardcoded value to detect the null case is going to get tiresome...
Checking all the null conditions in one if statement also can be done as follows.
So that the code will be much easier to read.
if (meeting != null && meeting.getRoom() != null && meeting.getRoom().getProjector() != null) {
return meeting.getRoom().getProjector().getModelName();
} else {
return "No Projector Exist";
}
The best way is to move the null checks to a private method. So when you give a meeting object, it do the required checks and return the model of the project as a string. So your code will be much simpler and with less complex.
You can catch() the NullPointerException or throw a NoRoomException and a NoProjectorException from your getRoom() and getProjector() methods and catch those.

Java Stream - NullPointExeption when filter list [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to filter from the list objects that field isActive have either set to N or null. Unfortunately, I get NullPointerException in method filter and I don't know what is wrong?
Code:
...
return dictionary.getAllPermissions().stream()
.filter(Objects::nonNull)
.filter(z->"N".equals(z.getIsActive().toString()) || z.getIsActive().equals(null)) //field isActive is Character
.collect(Collectors.toList());
You've got the ordering wrong, it should be:
.filter(z -> z.getIsActive() == null || "N".equals(z.getIsActive().toString()))
You should invert the checks here:
.filter(z->"N".equals(z.getIsActive().toString()) || z.getIsActive().equals(null))
to
.filter(z-> z.getIsActive() == null || "N".equals(z.getIsActive().toString()))
The idea is to first make sure that the value z.getIsActive() is not null before you can actually invoke the tostring() method to it.
z.getIsActive().toString() throws a NullPointExeption when isActive is null.
You said "field 'isActive' have either set to N or null", so if it's null all your z.getIsActive are null, so you need to check z.getIsActive==null

Searching through a collection of an array list pair [duplicate]

This question already has answers here:
How to compare two java objects [duplicate]
(5 answers)
Closed 9 years ago.
I am trying to search through a collection of an ArrayList if pairs. What I want to be able to do, is to go through the collection and find the first value in a pair and return the second value of that pair. The problem I am having is that the check I have to find the first value doesn't seem to be working, so every time I search, I end up returning null. I know that the problem exists with my if statement, but I cannot seem to sort out what it is I am doing wrong. Since this is a homework assignment, I can't show all the code to my pair class, or my pair list class, but I can show you the method I have for searching the first value:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
S tmp2 = null;
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (tmp1.getFirst() == firstCall) {
tmp2 = (S) tmp1.getSecond();
}
}
return tmp2;
}
If I throw in an else statement that just calls what I am attempting to do in my if check, like this:
else{
tmp2 = (S) tmp1.getSecond();
}
then whenever I test for the first value, I get the second value, so I know I am at least on the correct path, but I am assuming that I am doing something wrong with what I am checking for in my if statement. Does anyone know how I can correctly do this, (and please bear in mind that this is homework, so a guide to how to figure this out is far more valuable to me than just some random answer, I want to learn, not just be given an answer) Thanks in advance!
Don't use == to compare objects. Override and use equals().
I think
if (tmp1.getFirst() == firstCall)
should probably say
if (tmp1.getFirst().equals(firstValue))
The important difference is that == checks whether two expressions refer to the exact same object. You're more interested in knowing whether your two expressions actually refer to objects that are equal.
Try this:
if (tmp1.getFirst().equals(firstValue))
instead of
if (tmp1.getFirst() == firstCall)
Also you can override your own equals method.
You should never use == to compare objects.
Check How to compare two java objects
What Matt says, (don't use == ) but I think a bigger problem is that you don't return the 'first' encounter.... your if statement should look like:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (firstValue.equals(tmp1.getFirst())) {
return (S) tmp1.getSecond();
}
}
return null;
}

Categories