本文介绍了原始的布尔到字符串连接/转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是如何工作的呢?我似乎无法找到答案。

how does this work? I can't seem to find an answer.

boolean bool=true;
System.out.println("the value of bool is : " + true);
//or
System.out.println("the value of bool is : " + bool);


  • 有哪些东西会在幕后?

  • 如何布尔被铸造为String作为一个布尔值不能隐
    键入铸造?

  • 自动装箱/拆箱的参与?

  • 仿若的toString方法()将String.valueOf()参与以某种方式?

    • What are the things that are going on behind the scene?
    • how does the boolean gets casted to the String as a boolean cannot be implicitlytype casted?
    • Is Autoboxing/Unboxing involved?
    • Are methods like toString() or String.valueOf() are involved in some way?
    • 推荐答案

      的确切规则在Java语言规范中都有明确规定,的

      The exact rules are spelled out in the Java Language Specification, §5.1.11. String Conversion

      根据这些规则,STR+布尔等价于:

      According to those rules, "str" + bool is equivalent to:

      "str" + new Boolean(bool).toString()
      

      这表示,允许编译器在整体前pression是如何准确地评估相当大的自主权。从JLS :

      That said, the compiler is permitted considerable leeway in how exactly the overall expression is evaluated. From JLS §15.18.1. String Concatenation Operator +:

      这是实现可以选择一步执行转换和级联,以避免创建,然后丢弃中间String对象。为了提高重复字符串连接的性能,Java编译器可以使用的StringBuffer 类或类似的技术,减少了中间字符串的数量由一个前pression评价创建的对象。

      有关基本类型,一个实现也可以通过直接从原始类型转换成字符串优化掉的包装对象的创建。

      For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

      例如,用我的编译如下:

      For example, with my compiler the following:

      boolean bool = true;
      System.out.println("the value of bool is : " + bool);
      

      是完全等价于:

      boolean bool = true;
      System.out.println(new StringBuilder("the value of bool is : ").append(bool).toString());
      

      他们导致相同的字节codeS:

      They result in identical bytecodes:

      Code:
         0: iconst_1
         1: istore_1
         2: getstatic     #59                 // Field java/lang/System.out:Ljava/io/PrintStream;
         5: new           #166                // class java/lang/StringBuilder
         8: dup
         9: ldc           #168                // String the value of bool is :
        11: invokespecial #170                // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
        14: iload_1
        15: invokevirtual #172                // Method java/lang/StringBuilder.append:(Z)Ljava/lang/StringBuilder;
        18: invokevirtual #176                // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
        21: invokevirtual #69                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        24: return
      

      这篇关于原始的布尔到字符串连接/转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 04:54