java - do <= and >= relational operators work with Integer objects -
this question has answer here:
- how compare 2 integers in java? 6 answers
i understand can't use == or != compare values of numeric objects , have use .equals() instead. after fair amount of searching haven't been able find statement whether or not can use other comparison operators, other suggestions use .compare() or .compareto() feel inefficient because require 2 comparisons: b, result of zero.
despite == , != comparing addresses of objects, other comparison operators appear compare numeric values. instance following code snippet:
integer = new integer(3000); integer b = new integer(3000); system.out.println("a < b " + (a < b)); system.out.println("a <= b " + (a <= b)); system.out.println("a == b " + (a == b)); system.out.println("a >= b " + (a >= b)); system.out.println("a > b " + (a > b));
produces
a < b false <= b true == b false >= b true > b false
which appears indicate operators == compare value, not address of object. accepted usage use <= class of operators, or unsupported feature of compiler or something?
yes, note integer
objects, not primitive int
. usage of >
, <
, >=
, <=
operators not meant objects, primitives, when using of these, integer
autoboxed int
. while when using ==
in objects comparing references. use equals
instead compare them.
still, note integer
class has cache store integer
references -128
127
. means if this:
integer i1 = 127; integer i2 = 127; system.out.println(i1 == i2);
will print true
.
Comments
Post a Comment