Comparison Operators and AutoBoxingUnboxing

######## Key points extracted from below ####################

1. Consider the following snippet of code:

Integer aa = new Integer(100);
Integer bb = new Integer(100);
Integer cc = new Integer(505);
System.out.println(aa == bb); // will print false
System.out.println(aa == cc); // will print false

In this snippet of code, no autoboxing/unboxing takes place. Here, aa == bb and aa == cc compare the references of aa, bb and cc, not their values. Every object created with the new operator has a unique reference.

2. For Integer.valueof() method, for all values between –128 and 127, the Integer class caches Integer object references

#####################################

Comparison Operators and AutoBoxing/Unboxing

I will discuss comparison operations ==, >, >=, <, <=. Only == (logical equality operator) can be used with both reference type and primitive types. The other operators must be used only with primitive types.

Let’s discuss the easy ones (>, >=, < and <=) first. If a numeric wrapper object is used with these comparison operators, it must be unboxed and the corresponding primitive type used in the comparison. Consider the following snippet of code:

Integer a = 100;
Integer b = 100;
System.out.println("a : " + a);
System.out.println("b : " + 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));

a : 100
b : 100
a > b: false
a >= b: true
a < b: false
a <= b: true

There is no surprise in the above output. If you mix the two types, reference and primitive, with these comparison operators, you still get the same results. First, the reference type is unboxed and a comparison with the two primitive types takes place. For example,

if (101 > new Integer(100)) {
// Do something
}

is converted to

if(101 <= (new Integer(100)).intValue()) {
// Do something
}

Now, let’s discuss the == operator and the autoboxing rules. If both operands are primitive types, they are compared as primitive types using a value comparison. If both operands are reference types, their references are compared. In these two cases, no autoboxing/unboxing takes place. When one operand is a reference type and another is a primitive type, the reference type is unboxed to a primitive type and a value comparison takes place. Let’s see examples of each type.

Consider the following snippet of code. It is an example of using both primitive type operands for the == operator.

int a = 100;
int b = 100;
int c = 505;
System.out.println(a == b); // will print true
System.out.println(a == c); // will print false

Consider the following snippet of code:

Integer aa = new Integer(100);
Integer bb = new Integer(100);
Integer cc = new Integer(505);
System.out.println(aa == bb); // will print false
System.out.println(aa == cc); // will print false

In this snippet of code, no autoboxing/unboxing takes place. Here, aa == bb and aa == cc compare the references of aa, bb and cc, not their values. Every object created with the new operator has a unique reference.

Now, here’s a surprise: consider the following snippet of code. This time you are relying on autoboxing.

Integer aaa = 100; // Boxing – Integer.valueOf(100)
Integer bbb = 100; // Boxing – Integer.valueOf(100)
Integer ccc = 505; // Boxing – Integer.valueOf(505)
Integer ddd = 505; // Boxing – Integer.valueOf(505)
System.out.println(aaa == bbb); // will print true
System.out.println(aaa == ccc); // will print false
System.out.println(ccc == ddd); // will print false

You used aaa, bbb, ccc, and ddd as reference types. How is aaa == bbb true whereas ccc == ddd false? All right. This time, there is no surprise coming from the autoboxing feature. Rather, it is coming from the Integer.valueOf() method. For all values between –128 and 127, the Integer class caches Integer object references. The cache is used when you call its valueOf() method. For example, if you call Integer.valueOf(100) twice, you get the reference of the same Integer object from the cache that represents the int value of 100. However, if you call Integer.valueOf(n), where n is outside the range –128 to 127, a new object is created for every call. This is the reason that aaa and bbb have the same reference from the cache, whereas ccc and ddd have different references. Byte, Short, Character and Long classes also cache object references for values in the range –128 to 127.

时间: 2024-10-12 07:36:12

Comparison Operators and AutoBoxingUnboxing的相关文章

【你吐吧c#每日学习】10.29 C#字符串类型&amp;Common operators

backslash \反斜杠 escape sequence 转义字符 double quote 双引号 new line 新行字符 Bell アラート Console.WriteLine("\a");そうです.コンピューターの声を聞く. verbatim [v?:r'beitim] literal 逐字字符串 @忽略转义字符 much readable. Assignment operator = Arithmetic operators + - * / % Comparison o

寒城攻略:Listo 教你 25 天学会 Swift 语言 - 04 Basic Operators

import Foundation //*********************************************************************************************** //1.Basic Operators(基本操作符) //_______________________________________________________________________________________________ //简介 //操作

pig 的chararry类型不能用比较运算符comparison operator

pig 的chararry类型可能是按字段,逐个字段进行比较. element_id 是chararray类型, 语句: no_app_category_mapping = filter no_element_id by element_id == '' or element_id is null or element_id == '0' or element_id >='14'; 其中,element_id >='14'是错误的用法. comparison operator不能操作chara

Common operators to overload-c++运算符重载的标准语法(全)

Common operators to overload Most of the work in overloading operators is boiler-plate code. That is little wonder, since operators are merely syntactic sugar, their actual work could be done by (and often is forwarded to) plain functions. But it is

[Database]Operators

Arithmetic Operators +,-,×,÷ Comparison Operators =,<>,!=,>,<,>=,<= LIKE,BETWEEN,IN,IS NULL Logical Operators AND,OR,NOT[IN | LIKE| BETWEEN | NULL] String Operators LIKE,|| Operators precendence parentheses > comparison > AND >

Mysql Hash索引和B-Tree索引区别(Comparison of B-Tree and Hash Indexes)

上篇文章中说道,Mysql中的Btree索引和Hash索引的区别,没做展开描述,今天有空,上Mysql官方文档找到了相关答案,看完之后,针对两者的区别做如下总结: 引用维基百科上的描述,来解释一下这两种数据结构,这些知识在<数据结构与算法>这门课程中也有讲述: 在计算机科学中,B树(英语:B-tree)是一种自平衡的树,能够保持数据有序.这种数据结构能够让查找数据.顺序访问.插入数据及删除的动作,都在对数时间内完成.B树,概括来说是一个一般化的二叉查找树(binary search tree)

#定位系统性能瓶颈# sysdig

安装方法: curl -s https://s3.amazonaws.com/download.draios.com/stable/install-sysdig | sudo bash [[email protected] ~]# curl -s https://s3.amazonaws.com/download.draios.com/stable/install-sysdig | sudo bash * Detecting operating system * Installing EPEL

位运算操作

来源:https://discuss.leetcode.com/topic/50315/a-summary-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently/2 WIKI Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer p

Wireshark

PYTHON黑帽编程1.5 使用WIRESHARK练习网络协议分析 Python黑帽编程1.5  使用Wireshark练习网络协议分析 1.5.0.1  本系列教程说明 本系列教程,采用的大纲母本为<Understanding Network Hacks Attack and Defense with Python>一书,为了解决很多同学对英文书的恐惧,解决看书之后实战过程中遇到的问题而作.由于原书很多地方过于简略,笔者根据实际测试情况和最新的技术发展对内容做了大量的变更,当然最重要的是个人