volume_mute

What is the difference between the following code from the original one in terms of performance?

publish date2020/10/30 03:42:00 GMT+11

volume_mute
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int input = in.nextInt();
if (input > 0){
System.out.println("Positive Number");
}
if (input < 0){
System.out.println("Negative Number");
}
if (input == 0) {
System.out.println("Zero");
}
}
}
No difference
The first one is faster
The second one is faster
It depends on the environment

Correct Answer

The first one is faster

Explanation

The original code is safer as it determines the output based on conditions.  The system does not have to test the rest of the conditions.  This behavior is controlled by the code.

In the second code, the controller of the one output behavior is solely determined by the input.  However, if the conditions are changed, then it is possible to evaluate TRUE for more than one condition.  For example, if first condition is changed to  >= instead of >, then values of 0 and above will be evaluated as TRUE and the last condition will evaluate 0 value as well and will print 0.

So, if a single result is required, then first code is preferred.  But if more than one result is required, then second code may be useful.  Moreover, for a single output, the first code is more optimum as it evaluates only the conditions needed for the output.  However, the second code evaluates all the conditions regardless.


Quizzes you can take where this question appears