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)
source
share