I have the following code:
String a= null
Element element = ...
if(element == null) {
System.out.println("...");
}
a = element.getText();
I got a null pointer exception on this code.
I thought that it would be better to use an if else statement in order to avoid this error.
String a= null
Element element = ...
if(element == null) {
System.out.println("...");
} else {
a = element.getText();
}
Is it a good solution to use the above code to solve the problem or it would be better to manage it another way?
I got a null pointer exception on this code
Yes, because you don't not execute element.getText() if element == null.
Element element = ...
if(element == null) { // This check is irrelevant to...
System.out.println("...");
}
a = element.getText(); // ...whether this statement is executed.
Is it a good solution
It's a solution, because the else isn't executed when element == null.
You might consider inverting the condition, so the "happy" case (the one you want to execute when things are working normally) comes first. But this is not an important difference, functionally.
if(element != null) {
a = element.getText();
} else {
System.out.println("...");
}
You approach is ok since it works and you dont get the NPE anymore.
You could invert the if condition and simplify things like:
String a= null
Element element = ...
if(element != null) {
a = element.getText();
}
This way you do your things in a protected code block and you don't need else part unless you really wanted to print "..."
Yes it is a solution for the reasons already mentioned by the other answers. I want to provide another solution:
String a;
try {
Element element = ...;
a = element.getText();
} catch (NullPointerException e) {
System.out.println("...");
a = null; // Or some other value that can be tested but cannot produce a NPE
}
This would have the same error handling as your if statement, but it has the advantage, that ´element´ cannot be referenced later and produce a NPE somewhere else. This is of course only useful if the String cannot produce a NPE either way and if the Element could actually used later (in other words if the method doesn't end directly afterwards).
Related
Which way of returning from condition is better , Like the process1 and process 2 both does the same. But I want to know better way returning.
In both cases I don't want to enter inside of loop, I just want to return. I would like to know that, Is there any performance difference If I put return before control passes to end. I don't want Java Virtual Machine to check end of loop and returning from there. I thought If I put return Immediately when the condition not satisfied, then I could see minor performance difference and also code readability. Please suggest me the best way.
Let us consider the below scenarios.
Process1:
public Method()
{ //Method
Company company = new Company(); //Object
if (null != Address && null = Address.location()) //Condition
{
return company; //I want to return
}
for (Location location: Address.location())
{
//forloop
}
return company; //return
}
Process2:
public Method()
{
Company company = new Company();
if (null != Address && null != Address.location())
{
//enters loop
}
return company; // return
}
There will be some performance impact. Iterating complete objects from the for loop to verify the condition.
For example:
We can write like this.
if(condition is false){
return ;
else{
for(DataType ref: collection){
if(true){
return;// return from here, so that it will not iterate remaining elements.
}
}
}
ex 2:
if there is a logic after the if and that should not be executed, if the object is null.
if(object is null){
return ;
}
//Remaining logic here will not be executed, if the object is null. it's a good way of writing.
ex 3:
if there is no logic after the if and else, then directly return from the end of method.
if(object is null){
return
}else{
//process logic and return.
}
you can write something like this.
if(object is not null){
// return either from here.
}
return here is also fine...
I am implementing the Shannon/Fano algorithm using Java and I am doing this by calculating the frequencies of symbols in a text file, and after that I put all these values in a tree. The problem is that when I am searching for a certain symbol in a tree I also have to update the code of the respective symbol (e.g If I go to left append 0, otherwise 1) and doing this recursively I am getting a stackoverflow error. Below is my code :
private String getNodeValue(Node node, String symbol) {
if (node.getLeftChild() != null) {
if (node.getLeftChild().getData().equalsIgnoreCase(symbol)) {
node.updateCode(0);
return node.getData() + "";
}
} else if (node.getRightChild() != null) {
if (node.getRightChild().getData().equalsIgnoreCase(symbol)) {
node.updateCode(1);
return node.getData() + "";
}
}
Node nextLeftNode = node.getLeftChild().getLeftChild();
if (nextLeftNode != null) {
getNodeValue(nextLeftNode, symbol);
}
Node nextRightNode = node.getRightChild().getRightChild();
if (nextRightNode != null) {
getNodeValue(nextRightNode, symbol);
}
// if symbol is not found return null
return null;
}
and the stackoverflow error is triggered at the very first line of the method when the call to node.getData() takes place. This is my stack trace:
Exception in thread "main" java.lang.StackOverflowError
at ro.uvt.it.datastractures.Node.getData(Node.java:47)
at ro.uvt.it.datastractures.Node.getData(Node.java:47)
at ro.uvt.it.datastractures.Node.getData(Node.java:47)
And this is my getData() method:
public String getData() {
return this.getData();
}
Any help or hint would be appreciated,
Thank you.
There are many mistakes in your code.
As you showed in your stacktrace, the infinite recursion is in the getData method and not in the getNodeValue method, so you need to post the source code of the getData method.
But the getNodeValue method has many bugs as well.
Your first two if statements have exactly the same condition:
if (node.getData().equalsIgnoreCase(symbol)) {
and
else if (((String) node.getData()).equalsIgnoreCase(symbol)) {
the returns inside these if statements append an empty string to the result of getData(), which already returns String. Replace each of them with:
return node.getData();
are just a different way of writing the same, since getData() already returns a String so casting to String again doesn't make a difference.
Your next to if statements recursively call getNodeValue on leftChild and rightChild, but they never return anything, so you always end up returning null in your code once you're past the first two identical if statements in your method.
You code should probably read:
if (node.getLeftChild() != null) {
String found = getNodeValue(node.getLeftChild(), symbol);
if (found != null) {
return found;
}
}
if (node.getRightChild() != null) {
String found = getNodeValue(node.getRightChild(), symbol);
if (found != null) {
return found;
}
}
Almost certainly unbounded recursion. At a guess I'd say it was a mistake in the implementation of getLeftChild or getRightChild. I would suggest you step through in the debugger, and I'll bet you will quickly see where this goes.
However, if you have a very deep tree, you may discover that the stack overflow exception is legitimate, in which case you will need to revisit the algorithm. And the traditional technique of tail recursion appears to be hard to achieve in Java.
I have this recursive method:
public Hund getMor(int id) {
Hund barn = getHund(id);
int idMor = barn.getId_mor();
Hund mor = getHund(idMor);
return mor;
}
public String getMorTre(int id) {
if (id == 0) {
return null;
}
if (!existHund(id)) {
return "Hunden du søkte etter finnes ikke";
} else {
if (id == 0) {
return null;
} else {
Hund mor = getMor(id);
MinRamme.jta.append(mor.toString() + "\n");
int morId = mor.getId();
return getMorTre(morId);
}
}
}
I have tried to remove the nullpointer by returning null if the id is 0 but this does not work. Does anyone have a solution?
NPE:
Exception in thread "AWT-EventQueue -0" java.lang.nullpointerexception
at Arkiv.getMorTre(Arkiv.java:209)
at Arkiv.getMorTre(Arkiv.java:211)
at Arkiv.getMorTre(Arkiv.java:211)
at MinRamme$4.actionPerformed(MinRamme.java:89) <37 internal calls>
Where does the NullPointerException occur? That would help... That being said:
Inside your else clause, your
if (id==0) {
is useless, since you're testing that at the beginning and the id isn't changed.
I think you need to check if
getMother(id)
returns null, that is probably where you're getting the NullPointer... but you could confirm that now, couldn't you?
It is likely (but difficult to confirm until you let us know what line is throwing the NPE) that the line that generates the NPE is
MyFrame.jta.append(mother.toString() + "\n");
because mother is null. You could change your code into this:
Dog mother = getMother(id);
if (mother == null) {
//do something
}
There really isn't enough information here. What line are you getting the null pointer on?
if, as I suspect, it's here:
MyFrame.jta.append(mother.toString() + "\n");
Then you need to determine, through debugging, that it's definitely mother that is null. If you have done that, then you can be absolutely positive that your getMother(id); returns null, for the id that you are passing in.
If I were you I would create a unit test for the getMother(id) method and pass in the id that is causing the failure.
If you don't know what id value is causing the problem, then at the very least stick in some System.out.print() statement to find out what is going on. Although, you'd be better using some logging framework, such as log4j.
Hope this helps.
Its because your exception is at mother.toString() method..
try this
try
{
MyFrame.jta.append(mother.toString() + "\n");
}catch(NullPointerException ignore){}
Here's the code
public void findDNode(String name)
{
DNode u = header;
while(u != null)
{
if(name == u.getElement())
{
System.out.println(u.getElement());
break;
}
else if (u == null)
{
System.out.println("Error: not found");
break;
}
u = u.nextNode();
}
}
For some reason when the node that I am looking for doesn't exist it's doesn't print the error: not found message.
edit: nevermind just realised when u== null the while loop won't happen
You should use equals() to compare Java strings:
if (name.equals(u.getElement()))
{
...
Comparing strings using the == operator compares the references, which in most cases isn't the right thing to do.
Also, the "not found" logic is misplaced. It should probably be placed outside the loop (with an appropriate if condition).
u never becomes null inside the loop! Perform the check after the loop.
public void findDNode(String name)
{
DNode u = header;
while(u != null)
{
if(name == u.getElement())
{
System.out.println(u.getElement());
break;
}
u = u.nextNode();
}
if (u==null)
System.out.println("Error: not found");
}
Edit: and yes, you should use equals()
Other than using equals() instead of == to compare String there is another issue.
How can you have if (u == null) inside a while(u != null) loop. That if (u == null) block will never execute since while loop will end when u == null. That is the reason Error: not found is never printed.
Note: This is homework/assignment feel not to answer if you don't want to.
Ok after some search and reading these:
How to check if array element is null to avoid NullPointerException in Java
Gracefully avoiding NullPointerException in Java
http://c2.com/cgi/wiki?NullPointerException
Am still not making any progress on how to deal with NullPointerException error on my code, snippet for questionable code:
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem != -1 ) {
setElements[numberOfElements] = newValue;
numberOfElements++;
} else { System.out.println("Element " + newValue + "already exist"); }
}
It compile but adding new element to a set throws a NullPointerException error.
D:\javaprojects>java SetDemo
Enter string element to be added
A
You entered A
Exception in thread "main" java.lang.NullPointerException
at Set.findElement(Set.java:31)
at Set.add(Set.java:44)
at SetDemo.main(Set.java:145)
I added another check, though honestly don't have clue if this right to line 31.
if ( setElements != null && setElements[i].equals(element) ) but still no joy.
A documentation/tips or explanation is greatly appreciated.
learning,
lupin
Did you initialize setElements anywhere? Meaning:
String[] setElements = new String[100];
If you simply declare an array variable:
String[] setElements;
as a data member of your class it is initialized to null. You have to make it point to something. You can either do this inline:
public class MyClass {
private String[] setElements = new String[100];
...
}
or in a constructor:
public class MyClass {
private String[] setElements;
public MyClass() {
setElements = new String[100];
}
...
}
The for-loop in findElement doesn't make sense.
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
You should iterate through all values before returning -1, only then do you know that there is no element in the set that matches element.
Post the entire class - this snippet is useless.
You're making two serious mistakes: failing to believe the compiler, and assuming that your code is correct.
If the JVM tells you that line 31 is the problem, believe it.
My guess is that setElements[i] is null.
It should be setElements[i] != null && setElements[i].equals(element). If a collection contains null elements you will try to dereference a null reference when you call equals method on that element.
As for NullPointerException - you should never catch it. For things that shouldn't be null, they must be initialized properly. For those things that cannot be null - they must be checked for null before dereferencing them (i.e. calling methods on them).
The only use case for catching NullPointerException is when you are using a third-party library that you don't have the source for and has a bug that causes NullPointerException to be thrown. These cases are rare and since you only beginning to learn Java, forget that I mentioned this and concentrate on more important things.
Try testing the element itself for null, not the array:
setElements[i] != null && setElements[i].equals(element)
You should not attempt to catch a null pointer exception. Instead, the best way to avoid null pointers is:
In any function that takes parameters where you assume that the parameter is non-null, always check that the parameter is non-null and throw an IllegalArgumentException if it is null.
Whenever you invoke a function that does not allow null parameters, ensure that you do not pass a null pointer to that function; if you already know that the object is non-null (because you already checked it and would have thrown an IllegalArgumentException), then you do not need to recheck; otherwise, you should double-check that the object is non-null before passing it along.
Since you do not check the parameters to your findElement and add functions, it is quite possible that the parameters are the culprits. Add the appropriate check and throw IllegalArgumentException if they are null. If, after you do that, you get an IllegalArgumentException, then you've solved your problem. If not, then you at least know that the problem is not the parameter and is elsewhere in the code.
Its working now, thanks to Lars,Igor and the rest who took time to critic the code, there's a logic error that wasn't check,anyway here's the corrected working code, lastly I'm bother am I doing cheating? :(
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) { //loop first to the array and only return -1 once we can't find it.
//setElements[i] != null is the NullPointerException killer :)
if ( setElements[i] != null && setElements[i].equals(element) ) {
return retval = i;
}
retval = -1;
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem == -1 ) { # == instead of != as I only need to add if elements is non-existing
setElements[numberOfElements] = newValue;
numberOfElements++;
}
}
with thanks,
lupin