Is it better to use a search in an array or in elseif statuses?

I was doing basic programming for the course that I am doing. One of the tasks was to compare the two ints and print something along the lines "5 less than 10".

Since this exercise was a review, I assume that the teacher was expecting if ... if.

I used the method of comparing a java integer with an array constant to output the result. I was wondering which approach is better (in terms of speed, memory, clarity, etc.)?

Code example

If the method:

int a = 5;
int b = 10;
String text;

if (a < b)
  text = "less than";
else if (a > b)
  text = "greater than";
else
  text = "equal to";

System.out.printf("%d is %s %d", a, text, b);

Array Method:

final String[] COMPS = {"less than", "equal to", "greater than"};

int a = 5;
int b = 10;
int cmp = Integer.compare(a, b) + 1;

System.out.printf("%d is %s %d", a, COMPS[cmp], b)
+4
source share
5 answers

For clarity, I will not select text into a variable at all.

if (a < b)
  System.out.printf("%d is less than %d%n", a, b);
else if (a > b)
  System.out.printf("%d is greater than %d%n", a, b);
else
  System.out.printf("%d is equal to %d%n", a, b);

, , .


int cmp = Integer.compare(a, b) + 1;

, (, , , ...)

Javadoc, Integer # compare " 0, x == y; 0, x < y, 0, x > y". , +1 -1.

+5

, , , , . , JVM. "" JIT. Java , . , , . , , if-statement .

+4

, String , , . , .

+1

IF . (?) :

int a = 10;
int b = 10;
String text = (a < b) ? "less than" :  (a > b) ? "greater than" : "equal to";
System.out.printf("%d is %s %d", a, text, b);
+1

, , , - . , , , 60-100 .

, . "".

, .

+1

All Articles