String representation in Java

后端 未结 3 1678
执念已碎
执念已碎 2021-01-25 05:02

A String is represented as objects in Java. Accordingly, an object contains values stored in instance variables within the object. An object also contains bodies of cod

相关标签:
3条回答
  • 2021-01-25 05:23

    A string is a char[] containing a series of UTF-16 code units, an int offset into that array, and an int length.

    I think the source of your confusion is the idea that

    String s
    

    creates a string that is assigned into.

    It does not. It creates space for a string reference. Assigning copies references around but does not modify the objects to which those references refer.

    You should also be aware that

    new String(s)
    

    doesn't really do anything useful. It merely creates another instance backed by the same array, offset, and length as s. There is very rarely a reason to do this so it is considered bad practice by most Java programmers.

    Java double quoted strings like "my string" are really references to interned String instances so "foo" is a reference to the same String instance regardless of how many times it appears in your code.

    0 讨论(0)
  • 2021-01-25 05:26

    Strings are immutable in Java, so when you do a println, a new String is created by the toUpperCase (and later garbage collected).

    0 讨论(0)
  • 2021-01-25 05:27

    If I get what you want to know. The String object is represented by the double quotes ". This is called the String literal.

    0 讨论(0)
提交回复
热议问题