null pointer exception from my code from the while loop - java

I decleared free block like
private DoublyLinkedList freeblock = new DoublyLinkedList();
and I initialize the freeblock in the constructor.
freeblock.add(new DoublyLinkedList.Node(null, null, 0, initBlockSize));
inside of one of method of my class, (below is part of my method.)
I get null pointer exception. I think the while loop has a problem. Can anyone help me to solve this problem?
symptom: java.lang.NullPointerException
at LinearMemPool.enlarge(LinearMemPool.java:220)
private void enlarge(int addSize) {
DoublyLinkedList.Node node = freeblock.head;
while (node.next != null) {
node = node.next;
}
}

Evidently freeblock.head is null. Look what add does.

Your enlarge method seems a bit dangerous. Try changing the null check to:
private void enlarge(int addSize) {
DoublyLinkedList.Node node = freeblock.head;
while (node != null) {
node = node.next;
}
}
As for the reason why your head is null, I'd debug the freeblock.add(...) method.

First check to see freeblock.head is null because most likely it is:
if(node!=null){
while(node.next!=null){
....
}
else{
System.out.println("Freeblock is null but why.....");
}
You probably should do this normally if the freeblock.head can ever be null. And just for cleaning up purposes:
void newMethod(Node node, int size){
if(node!=null)
enlarge(size);
else{
System.out.println("Freeblock is null");
}
}

Related

How can I iterate throughout on list of nested java objects?

I have an object class which is contains a list of itself... Something like this:
public class SearchItemType implements Serializable {
protected List<SearchItemType> childItem;
}
The childItem also can conatain list of child items. My question is, can I iterate over childItems in all levels?
Right now my code looks like this:
public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId, Boolean found) {
SearchItemType element = new SearchItemType();
if (gridResult.getId().equals(selectedRowId)) {
element = gridResult;
found = true;
}
for (SearchItemType child : gridResult.getChildItem()) {
if (child.getId().equals(selectedRowId)) {
element = child;
found = true;
break;
}
}
if (!found) {
for (SearchItemType child : gridResult.getChildItem()) {
element = getElementByOpenedRowID(child, selectedRowId, found);
checkChildID(child, selectedRowId);
if (element != null) break;
}
}
return element;
}
Many thanks.
There is one error: at the start of the method, you set SearchItemType element = new SearchItemType(); but then check for null when you recurse. element will never be null. You can fix this by setting it to null at the start, but I have some suggestions about your code:
Instead of assigning the found value to an element and setting a found flag, just return the object as soon as you find it. At the end of the method return null. This will be much clearer.
Iterating over the children and checking them will currently be executed even if the parent was the one that was searched for. In fact, you can remove this loop entirely, as it is handled by the recursive step below.
Why are you passing found as a parameter? If you pass it true, then there is no point in having it, so if you really need it, just instantiate it in the method.
Make sure to check that gridResult is not null. You could remedy this by making getElementByOpenedRowID a method on SearchItemType, meaning that gridResult does not need to be passed.
Applying these changes will result in:
public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId) {
// stop at null
if (gridResult == null) {
return null;
}
if (gridResult.getId().equals(selectedRowId)) {
return gridResult; // return once found
}
// check all of the children
for (SearchItemType child : gridResult.getChildItem()) {
// do the search again for every child
SearchItemType result = getElementByOpenedRowID(child, selectedRowId);
if (result != null) {
// return once found and sent it all the way to the top
return result;
}
}
return null;
}
You can do this with recursion:
public void iterate(SearchItemType type) {
// Do something with type
for (SearchItemType child in type.childItem) {
iterate(child);
}
}
Yes you can iterate on childItem object at any level as long as childItem is not null and object inside it has non-null values.
In Data structure implementation of LinkedList every node in the LinkedList has Data fields link to other nodes (In case of Java it's reference to other nodes).
It's also called as self referencing objects that means object pointing to object of similar type.
As long as you have non-null values in the list you can iterate at any level.
Data structures in Java are implemented in similar manner.
Have look at Node class in this code snippet:
Linked List implementation using self referencing pointers
You want to iterate through the children recursively as so:
public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId) {
SearchItemType element = null;
if (gridResult == null) return null;
else if (gridResult.getId().equals(selectedRowId)) return gridResult;
else {
for (SearchItemType child : gridResult.getChildItem()) {
element = getElementByOpenedRowID(child, selectedRowId);
if (element != null) break;
}
}
return element;
}

Java: What's incorrect with my general tree traversal implementation?

I've been tasked with finding and returning a particular node from a general tree given by the string targetName. Take a look at my implementation below:
public GeneralTreeNode findNode(String targetName) {
if (this.name.equals(targetName)) {
return this;
} else {
for (GeneralTreeNode child : this.children) {
return child.findNode(targetName);
}
}
// no node containing the string could be found
return null;
}
The only problem is that this too often seems to incorrectly return null when in fact a node does exist. It's as if the last line, return null, is too greedy.
Chucking a few breakpoints on this and watching it shows it only seems to go down to the lowest depth until a node has no children, in which case it simply returns null.
Can anyone offer suggestions on how to improve this?
Change your code to this:
public GeneralTreeNode findNode(String targetName) {
if (this.name.equals(targetName)) {
return this;
} else {
for (GeneralTreeNode child : this.children) {
GeneralTreeNode childResult = child.findNode(targetName);
if (childResult != null) {
return childResult; // only return if you really found something
}
}
}
// no node containing the string could be found
return null;
}
You only want to return the result from the child search if it really found something.
The readability of the code disappears if you implement in this way. Tree-traversal would be better implemented in an helper class and you pass the ROOT element with the target_name together.
If you return null in this way, it is something like node is null actually it is not. On the other hand, when you use "doer" or "processor" method/function, it can return true saying "I cannot find anything".
Still, your code seems ok. I just rewrite it.
static Node search(Node node, String nodeName) {
if (node.getName().equals(nodeName)) return node;
List<Node> children = node.getChildren();
foreach(Node child : children) {
Node resultChild = search(child, nodeName);
if (resutlChild != null) return resultChild;
}
return null;
}

Try-Catch block termination

I'm using a try-catch block to catch any exceptions that might be thrown when I run certain methods on a stack. My code for the pop method looks like this:
public T pop()
{
T temp = null;
try
{
temp = first.data;
}
catch(Exception e)
{
System.out.println("Invalid operation on an empty stack");
}
first = first.next;
return temp;
}
When I run the program the exception is caught... my terminal produces this:
(menu choice 'd' is the pop method)
Please enter a menu choice: d
Invalid operation on an empty stack
Exception in thread "main" java.lang.NullPointerException
at MyStack.pop(MyStack.java:58)
at StackTest.main(StackTest.java:52)
so I think my exception is being caught since it prints "Invalid operation...", but my program also terminates when the exception is thrown. Any help?
We have learned a very valuable lesson today: don't catch Exception without good reason.
The problem here is that first is coming back null, so we're going to throw that exception once we try to dereference it.
Let's look at it from a different angle. If first is null, we know we can't pop anything, so we should be throwing the exception instead.
public T pop() {
if(first == null) {
throw new EmptyStackException("Invalid operation on empty stack");
}
T value = first.data;
first = first.next;
return value;
}
Seems like there's another exception being thrown, after your catch block. It is very likely that first is null. That causes the catch block to be executed (because first.data is a null pointer exception), but it also causes another null pointer exception at
first = first.next;
Thus you have an uncaught exception. How you tackle this is up to you; it's more of a design decision than a correctness one.
The simplest and probably correct option is to do all of your modification inside the try block, so if something goes wrong you don't resume operations that probably won't work.
public T pop(){
T temp = null;
try{
temp = first.data;
first = first.next;
}
catch(Exception e){
System.out.println("Invalid operation on an empty stack");
}
return temp;
}
Of course, the try..catch construction isn't really appropriate here. A much more succinct way to write the same method would be:
public T pop(){
if(first == null) return null;
//By virtue of reaching this point, first is necessarily non-null.
T temp = first.data;
first = first.next;
return temp;
}
But if the goal was to experiment with try..catch use my top answer.
first is clearly null based on your output. Now, you're catching the NullPointerException that arises from temp = first.data, but not the one that arises from first = first.next (since that assignment is not enclosed with a try block):
public T pop()
{
T temp = null;
try
{
temp = first.data; // <-- you catch the exception thrown here
}
catch(Exception e)
{
System.out.println("Invalid operation on an empty stack");
}
first = first.next; // <-- but you don't catch the one thrown here
return temp;
}
In general it's a very bad idea to catch a NullPointerException; explicitly check for null beforehand.
It's highly likely that your first is null.
Try this code instead
public T pop()
{
T temp = null;
try
{
if (first != null)
{
temp = first.data;
first = first.next;
}
}
catch(Exception e)
{
System.out.println("Invalid operation on an empty stack");
}
return temp;
}

Java Dead Code, can someone explain?

This is part of a binary tree class, here is the find function, given the key to find the node in the tree, if not found return null, however this part have been recognized as dead code, when I move the if(current==null) statement to the bottom of inside while loop, it works, why? is it the same?
public class Tree {
public Node root;
public Node find(int key) {
Node current = root;
while (current.key != key) {
if (current == null) { //dead code here, why?
return null;
}
if (key < current.key) {
current = current.leftChild;
} else if (key > current.key) {
current = current.rightChild;
}
}
return current;
}
}
public class Node {
public char label;
public boolean visited = false;
public int key;
public float data;
public Node leftChild;
public Node rightChild;
}
If current is null it will never reach to the null check as you are accessing current.key beforehand it will throw a nullPointerException
If you move the if(current==null) to bottom as you are assigning new value before it won't be a dead code. (as the current.leftChild and current.rightChild might be null)
Because
while (current.key != key) // <-- current.key would throw NPE if current was null.
On the statement before, you're dereferencing current.key. If current == null, you will have an NPE. If it is not null, then the if check is meaningless since it will never be reached.
What you probably intended to do was move the if check to before the loop instead:
public Node find(int key) {
if (root == null) {
return null;
}
Node current = root;
while (current.key != key) {
if (key < current.key) {
current = current.leftChild;
} else if (key > current.key) {
current = current.rightChild;
}
}
return current;
}
This would give you the intended behavior that you want.
while (current.key != key) {
if (current == null) { //dead code here, why?
return null;
}
in your while condition you are already making sure that current is not null (by using current.key!=key) , so there's no point in rechecking it in if(current==null). if current=null, then you will get a NullPointerException in your while() and you will not even reach the if condition.
If current.key has not already thrown a NullPointerException through the attempt to access the key member, current cannot possibly be null at the beginning of the while loop. When the test is moved to the bottom of the loop, current has been assigned a new value which the compiler recognizes as potentially null.

Catching nullpointerexception in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I tried using try-catch block to catch NullPointerException but still the following program is giving errors. Am I doing something wrong or is there any other way to catch NullPointerException in the following program. Any help is highly appreciated.
public class Circular_or_not
{
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try
{
LinkedListNode[] nodes = new LinkedListNode[10];
for (int i = 0; i < 10; i++)
{
nodes[i] = new LinkedListNode(i, null, i > 0 ? nodes[i - 1] : null);
}
// Create loop;
// nodes[9].next = nodes[3];
Boolean abc= Check_Circular(nodes[0]);
System.out.print(abc);
}
catch(NullPointerException e)
{
System.out.print("NullPointerException caught");
}
}
public static boolean Check_Circular(LinkedListNode head)
{
LinkedListNode n1 = head;
LinkedListNode n2 = head;
// Find meeting point
while (n2.next != null)
{
n1 = n1.next;
n2 = n2.next.next;
if (n1 == n2)
{
return true;
}
}
return false;
}
}
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:
if(someVariable != null) someVariable.doSomething();
else
{
// do something else
}
As stated already within another answer it is not recommended to catch a NullPointerException. However you definitely could catch it, like the following example shows.
public class Testclass{
public static void main(String[] args) {
try {
doSomething();
} catch (NullPointerException e) {
System.out.print("Caught the NullPointerException");
}
}
public static void doSomething() {
String nullString = null;
nullString.endsWith("test");
}
}
Although a NPE can be caught you definitely shouldn't do that but fix the initial issue, which is the Check_Circular method.
The problem with your code is in your loop in Check_Circular. You are advancing through the list using n1 by going one node at a time. By reassigning n2 to n2.next.next you are advancing through it two at a time.
When you do that, n2.next.next may be null, so n2 will be null after the assignment. When the loop repeats and it checks if n2.next is not null, it throws the NPE because it can't get to next since n2 is already null.
You want to do something like what Alex posted instead.
I think your problem is inside CheckCircular, in the while condition:
Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException
You should be catching NullPointerException with the code above, but that doesn't change the fact that your Check_Circular is wrong. If you fix Check_Circular, your code won't throw NullPointerException in the first place, and work as intended.
Try:
public static boolean Check_Circular(LinkedListNode head)
{
LinkedListNode curNode = head;
do
{
curNode = curNode.next;
if(curNode == head)
return true;
}
while(curNode != null);
return false;
}

Categories

Resources