Java – boxed Boolean equivalent

Quick question: are you sure this code is always true?

Boolean b1 = true;
Boolean b2 = true;
System.out.println(b1 == b2);

Boxing Boolean always seems to lead to the same Boolean object, but I can't find much information about boxed Boolean equality in JLS On the contrary, it even seems to imply that boxing should create new objects, which may even lead to oom exceptions

What do you think?

Solution

From Java language specification on Boxing conversion

It's relatively simple, like implemented

/**
 * The {@code Boolean} object corresponding to the primitive
 * value {@code true}.
 */
public static final Boolean TRUE = new Boolean(true);

/**
 * The {@code Boolean} object corresponding to the primitive
 * value {@code false}.
 */
public static final Boolean FALSE = new Boolean(false);

public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>