jvm对boolean类型的处理

   JVM对boolean类型的支持比较有意思,java虚拟机规范里这样说: 
  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.

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.

  实际测试了一下,代码:

  


  1. /**
  2. *
  3. *@authorZangXT
  4. */
  5. publicclassTest{

  6. publicstaticvoidmain(String[]args){
  7. booleanb=true;
  8. booleanb1=false;
  9. boolean[]bs={true,false,false,true};
  10. int[]array=newint[3];
  11. byte[]bytes=newbyte[3];
  12. System.out.println(bs.getClass());
  13. System.out.println(array.getClass());
  14. System.out.println(bytes.getClass());
  15. }
  16. }

输出是:

class [Z
class [I
class [B
对于boolean数组类型,内部表示为[Z,和byte[]的[B还是有差别的.

看实际字节码操作:

 

  1.  0:iconst_1  //true用1表示
  2. 1:istore_1   
  3. 2:iconst_0  //false用0表示
  4. 3:istore_2
  5. 4:iconst_4
  6. 5:newarrayboolean //boolean数组
  7. 7:dup
  8. 8:iconst_0
  9. 9:iconst_1
  10. 10:bastore
  11. 11:dup
  12. 12:iconst_1
  13. 13:iconst_0
  14. 14:bastore
  15. 15:dup
  16. 16:iconst_2
  17. 17:iconst_0
  18. 18:bastore
  19. 19:dup
  20. 20:iconst_3
  21. 21:iconst_1
  22. 22:bastore
  23. 23:astore_3
  24. 24:iconst_3
  25. 25:newarrayint
  26. 27:astore4
  27. 29:iconst_3
  28. 30:newarraybyte
  29. 32:astore5

从上面可以看出对boolean数组的操作使用的是bastore,也就是操作byte 数组的指令.  

ps:分析这个问题的时候,使用了两个反编译工具jad和jd-gui,发现它们对boolean,short,byte,char这些类型处理的时候都是存在问题的.

你可能感兴趣的:(java,jvm,虚拟机)