在 Java 内部,原始布尔值被视为 -1? [英] Internally in Java primitive booleans are treated like -1?

查看:57
本文介绍了在 Java 内部,原始布尔值被视为 -1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天在一个论坛上,我讨论了原始布尔数据类型.一个人说,在 ALL 语言中,true 在内部(或本机)被视为 -1.真的是这样吗?

The other day in a forum I was having a discusion about primitive booleans data types. And one guy said that in ALL languages true internally (or natively) is treated like -1. Is this really the case?

PD:我们专门讨论了 Java

PD: We were specially talking about Java

推荐答案

这实际上是 JVM 规范的一部分,至少在某些方面 - 而它不是 -1.规范的 第 3.3.4 节 是这样说的:

This is actually part of the JVM specification, at least in certain terms - and it's not -1. Section 3.3.4 of the spec has this to say:

虽然Java虚拟机定义了boolean类型,但只提供了非常有限的支持.没有专用于布尔值运算的 Java 虚拟机指令.相反,Java 编程语言中对布尔值进行操作的表达式被编译为使用 Java 虚拟机 int 的值数据类型.

Although the Java virtual machine defines a boolean type, it only provides very limited support for it. There are no Java virtual machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java virtual machine int data type.

Java 虚拟机确实直接支持布尔数组.它的 newarray 指令可以创建布尔数组.使用字节数组指令 baload 和 bastore.2

The Java virtual machine does directly support boolean arrays. Its newarray instruction enables creation of boolean arrays. Arrays of type boolean are accessed and modified using the byte array instructions baload and bastore.2

Java 虚拟机对布尔数组组件进行编码,使用 1 表示真,0 表示假.在 Java 编程语言布尔值由编译器映射到 Java 虚拟机类型 int 的值的情况下,编译器必须使用相同的编码.

The Java virtual machine encodes boolean array components using 1 to represent true and 0 to represent false. Where Java programming language boolean values are mapped by compilers to values of Java virtual machine type int, the compilers must use the same encoding.

举个例子:

public static boolean returnFalse() {
    return false;
}

public static boolean returnTrue() {
    return true;
}

编译为:

public static boolean returnFalse();
  Code:
     0: iconst_0
     1: ireturn

public static boolean returnTrue();
  Code:
     0: iconst_1
     1: ireturn

这篇关于在 Java 内部,原始布尔值被视为 -1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆