Null Pointer Exception in an If statement - java

Hoping you guys can figure out why im getting a null pointer exception with what I can provide, the program has several classes and method but this is the one that is breaking.
public void search(Node node, String sData, int iData)
{
if (sData.equals(node.getString()) && (iData == node.getInt()))
{
System.out.println("Nailed it");
}else if (sData.compareTo(node.stringData) < 0)
{
search(node.left, sData, iData);
}else if (sData.compareTo(node.stringData) > 0)
{
search(node.right, sData, iData);
}
}
the Node that is getting input at first is the root and then it goes left or right from there through recursion, but the line that says its erroring is the if statement up top. Cannot figure out what is wrong sData is just a standard string input when the method is called and iData is just an int thats input as well. Cannot figure it out =/ thanks for any help

You need to add the following at the top of your method:
if (node == null) return;
This would ensure that the method returns gracefully if you search for something that doesn't exist in the structure. Otherwise with your existing code, you'll encounter NullPointerExceptions when the method encounters leaf nodes.

Two possibilities: either sData or node are null; your recursive calls potentially pass null nodes, that's what I'd start with. I can't really tell more from your code, sorry.
Additionally, consider using a debugger to step through your code if you can't find the error. That usually helps with code like this.

Related

Why does Intellij idea warn about nullpointer in that if condition?

Here is my code
if (!multipartFile.isEmpty() && multipartFile.getOriginalFilename() != null && !multipartFile.getOriginalFilename().isBlank()) {
String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
dishCreationDto.setImageFileName(fileName);
dishService.saveWithFile(dishCreationDto, multipartFile);
} else {
dishService.save(dishCreationDto);
}
Here is how I see that code
As you can see, the last part of IF condition is underlined as Idea thinks that getOriginalFilename can return null, but I've checked this with that line of a code
multipartFile.getOriginalFilename() != null. What am I doing wrong?
Idea thinks that getOriginalFilename can return null
Because it can.
but I've checked this with that line of a code multipartFile.getOriginalFilename() != null
You checked that the previous invocation did not return null. The next one still can.
What am I doing wrong?
Calling a method twice in rapid succession, instead of storing its result in a variable and using that one for the check and the further processing. In fact you then call it for a 3rd time.
(this was just a copy of my comment from above)
While there may be ways to simplify the condition as the other answer shows, as you also need the result of getOriginalFilename() inside the if, I would assume the IDE will complain about that one next, and at the end you will probably have to bite the bullet and have a variable for it:
String originalFilename = multipartFile.getOriginalFilename();
if (!multipartFile.isEmpty() && originalFilename != null && !originalFilename.isBlank()) {
String fileName = StringUtils.cleanPath(originalFilename);
dishCreationDto.setImageFileName(fileName);
dishService.saveWithFile(dishCreationDto, multipartFile);
} else {
dishService.save(dishCreationDto);
}
You could simplify that expression by using the StringUtils:
!StringUtils.isNullOrEmpty(multipartFile.getOriginalFilename())
There are other functions in that utility class that might be helpful depending on what you're trying to do.
IntelliJ isn't always right but is always good to look a bit more in detail to our code to see what can be improved/simplified for better debugging/readability.

Recursion reverse a SingleLinkedList and print as a String

I was given the task to add a method reversed to a SingleLinkedList using recursion preferably.
public String reversed() {
StringBuilder b = new StringBuilder();
reversed(first, b);
return b.toString();
}
private void reversed(Node<E> n, StringBuilder b) {
if (n != null) {
reversed(n.next, b);
b.append(n.element);
b.append(ā€™\nā€™);
}
}
Seems to work very well when I test in eclipse.
However, I am not sure if I understand 100% why.
This is how I think. Let us imagine we have SingleLinkedList with 5 Nodes and we put in the first Node in the private method to reverse it.
Since n isnt null, its the first node. It will enter the if statement.
It will call on itself, but now with Node second, its not null since it will repeat....
Now it reaches Node 5, it calls itself, but then it will call on reversed (six,b) since Node six dosent exist and is null, it will not work. Therefore it moves to the row "b.append(n.element);" however. It now remembers where it started and appends "first.element"; after that it will append a new row.
What exaplins the logic that it will hereafter append second.element; Can someone explain how I should think to understand that it will now append the second element?
Thanks in advance, think I really need to understand this to under recursion fully in java
Each method call keeps its own state. Once you get to node 6, there will be 5 calls on the stack waiting for reversed(n.next, b) to finish. Each method can only continue after the call to reversed on the stack above it finishes.
In this example you have last in as the first to act, i.e. you have a non-tail recursive function (the recursive call is happening before you perform the action of that method).
Imagine if every time you got to reversed you replaced that method call with the code it would execute. Remember all the calls happens serially (there is only one thread, nothing can happen in parallel). You'd get something that looks like this:
if (n0 != null) {
Node<E> n1 = n0.next;
if (n1 != null) {
Node<E> n2 = n1.next;
if (n2 != null) {
Node<E> n3 = n2.next;
if (n3 != null) {
Node<E> n4 = n3.next;
if (n4 != null) {
Node<E> n5 = n4.next;
if (n5 != null) {
// would be null so nothing happens
}
b.append(n4.element);
b.append('\n');
}
b.append(n3.element);
b.append('\n');
}
b.append(n2.element);
b.append('\n');
}
b.append(n1.element);
b.append('\n');
}
b.append(n0.element);
b.append('\n');
}
You can see how this code gets pretty hard to read once the number of elements goes up. When we don't know exactly how long the list will be this approach breaks down... you wouldn't want to do this 10, 100, or possibly thousands of times!
This is exactly why recursion is so useful for applications like this. We are able to re-use the interesting logic without having to know the length of the list, and are able to reduce duplicated code significantly.
Just keep in mind that recursion comes at a memory cost. Each time you enter the recursive method you add state to the stack. Once you cap out the memory on your machine you'll have to begin looking at non recursive ways of performing this work.

"If" makes NullPointerException

I'm writing program, which do some operations with doublylinked lists(my implementation).
There is one thing which i do not understand and it confusing me a lot.
Ok. So. I have two doubly linked list. I need to create method where argument is a index of first doublylinked list, and on that index i need to put second list.
I wrote that method:
public void PutInPlace(int i){
DoublyLinkedList ldw3 = new DoublyLinkedList(); // New doublylinked list.
Node current = ldw1.tail; // ldw1 - First doublylinked list, created earlier.
Node current1 = ldw2.tail; //ldw2 - Second doublylinked list, created earlier.
int counter = 0;
while(true){
ldw3.AddHead(current.number);
current = current.prev;
counter++;
if(counter == i){ // THAT if makes NullPointerException
ldw3.AddHead(current1.liczba);
current1 = current1.prev;
if(current1 == null)
break;
}
}
I dont wanna put all code, because it is long and can be not-easy to read. So, why "if(counter == i)" makes NullPointerException? Without that "if" program works. Where is the problem?
Thank you for help, guys!
current1 may be null. But you are trying to get the value
if(current1 != null)
{
ldw3.AddHead(current1.liczba);
current1 = current1.prev;
}
instead of
current1 = current1.prev;
(or)
change the statement like this,
if(current1 == null)
break;
ldw3.AddHead(current1.liczba);
current1 = current1.prev;
instead of
ldw3.AddHead(current1.liczba);
current1 = current1.prev;
if(current1 == null)
break;
I think the current variable is the one being null. The i variable has a unique value, let's say 3.
While(true) is an infinite loop, and your condition (counter==i) will be executed only once (since you always increment counter and it will hit the value 3 only once). So unless current1 has no previous, the break will never be it and you will arrive to a point where current has no more previous (making it null and giving an exception when doing current.prev)
A good practice is always checking if an object is null before using one of its methods or attributes.
No, that "if" cannot make a NullPointerException.
First, make sure you recompile everything, and run a test. Then post the output from that test, including the stack trace from the exception.
Second, post the source code verbatim (so the line numbers are clear).
Third, post the javap output for the PutInPlace method.

I keep getting wrong output or null pointer exception in my towers program

I'm working on solving towers game by using stacks and linked lists and moving blocks from tower to tower by using recursion.
I encountered a problem in my problem which causes java.lang.NullPointerException. My guess why this was happening was that I try to pop value from a stack even when there are no entries. After I put bound control I still receive that error.
Th error points to the line with deleteFirst() method but I don't see why this would happens even after I check if lists are empty.
My task here was just to pass towers or LinkedStack objects then move the content of theirs in tower game fashion.
Errors:
Exception in thread "main" java.lang.NullPointerException
at LinkList.deleteFirst(towers.java:47) // code with: **first = first.next;**
at LinkedStack.pop(towers.java:82) // code with: return theList.deleteFirst();
at LinkListApp.doTowers(towers.java:146) // code with: A.pop();
at LinkListApp.doTowers(towers.java:140) // doTowers(a-1, A, C, B);
at LinkListApp.main(towers.java:121) // doTowers(nDisks, linkA, linkB, linkC);
What am I doing wrong here? I can't make this work. as it should.
Your doTowers call makes calls to A.pop() and C.pop(), neither of which is protected. Your LinkedStack directly calls theList.deleteFirst() without an empty check, and your deleteFirst method calls first = first.next without checking if first is null or not. It would be good to make your LinkedList smart enough that deleteFirst doesn't throw a NPE in this case, then you won't need special checks all over the place in the upper layers. To do that, change deleteFirst to something like
public long deleteFirst()
{
if ( first != null ) {
Link temp = first;
first = first.next;
return temp.dData;
}
else {
return whateverIndicatesTheListIsAlreadyEmptyWhichMayBeHardWithReturnTypelong;
}
}

Trying to implement level order traversal on a binary search tree in Java

Okay, so I'm trying to make a method that will return the level order of a basic binary search tree that carries int values in its nodes. I've figured out most of the other methods, such as insertion, post order and pre order, but I keep running into the same problem with the level order method
Here's the code:
private DoubleStackQueue<Node> queue = new DoubleStackQueue<Node>();
//this is a queue that uses two stacks, one for the front and one for the back.
//it works just like a queue.
public String levelOrder(){
s = ""; //The s is a private String that is implemented earlier
queue.add(this);
while (!queue.isEmpty())
{
Node node = (Node)queue.remove();
if (!(node.equals(null))) {s += ""+node.getVal();}
if (!(left.equals(null))) {queue.add(node.left);}
if (!(right.equals(null))) {queue.add(node.right);}
}
return s;
}
The main problem that I am having is that, when the program gets to a leaf node, it still adds its children to the queue, even though there are no children, just null, so I'll get a queue that has two nulls in front of the actual item in it. I originally had the if statements as (left != null) and such, but that didn't work either. I'm just trying to figure out how to make the program recognize when there aren't any children. What do I need to do?
Several comments:
The primary issue is that you're using left and right instead of node.left and node.right in your comparisons.
To compare against null use if (var != null). Do not use equals(). If a variable is null you cannot call methods on it as that will trigger NullPointerExceptions.
Once you have fixed your code you will never have null inserted into the queue. The first object you add is this which is guaranteed to be non-null, and subsequently you always check for null before inserting items onto the queue. That means your first if (node != null) check is unnecessary.
The cast in (Node) queue.remove() should be unnecessary. Your compiler ought to warn you about this.
Result:
queue.add(this);
while (!queue.isEmpty())
{
Node node = queue.remove();
s += "" + node.getVal();
if (node.left != null) { queue.add(node.left); }
if (node.right != null) { queue.add(node.right); }
}
Within your code I can find the lines
if (!(left.equals(null))) {queue.add(node.left);}
if (!(right.equals(null))) {queue.add(node.right);}
where in the condition it states left and right which are nowhere defined in the parts you show but on the right it reads node.left and node.right. Is this intentionally? I'd expect also node.left and node.right in the if conditions.
Look at this question: Level-order tree traversal
I believe this is the same thing you're trying to achieve, is it not? This is a pretty classic problem, so in my experience it's been discussed over-and-over before.

Categories