Hello,
does anybody know what is the difference between thies two codes?

1- With this code I get "NullPointerException at process1.getCurrentNode();"
public void signal(ProcessEntity process) {

ProcessEntity process1 = getEntityManager().find(ProcessEntity.class,
process.getId());

if (process1 == null) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
signal(process);
}
NodeEntity currentNode = process1.getCurrentNode();

if (currentNode == null) {
} else {
currentNode.run(this, process1);
}
}

2- "else" here solves this Problem!

public void signal(ProcessEntity process) {

ProcessEntity process1 = getEntityManager().find(ProcessEntity.class,
process.getId());

if (process1 == null) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
signal(process);
} else {
NodeEntity currentNode = process1.getCurrentNode();

if (currentNode == null) {
} else {
currentNode.run(this, process1);
}
}
}

Please help me!!!
Best regards,
Amjad, Germany

Recommended Answers

All 3 Replies

The else provides a fallback condition. Just a single if is there for one condition only.

for example, if you put just an if in the code, it goes through one condition then continues with the code.

with if-else, it checks the one condition, if that condition is not true it executes the condition in the "else" block then continues with code.

You get the error because process1 is null. At the if you check if it is null or not, but regardless the result you call this process1.getCurrentNode(); anyway. The idea is to call it only when it is not null.
So if this is true

if (process1==null) {

then what is inside the '} else { ... }' will not executed.
If it is false meaning that process1 is not null then the else will be executed.
Since you have process1.getCurrentNode() inside the else, it will executed only when process1 is not null.

With the first case, you check if proccess1 is null, but then you go and use it anyway.

if (process1 == null) {
....
}
//this will execute no matter 'if' is true or false.
NodeEntity currentNode = process1.getCurrentNode();


if (process1 == null) {
....
} else {
//this will execute only when if is false (proccess1 is not null)
NodeEntity currentNode = process1.getCurrentNode();
}

Thank you so much!
With best regards,
Amjad

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.