Java中的字符串表示 [英] String representation in Java

查看:151
本文介绍了Java中的字符串表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String在Java中表示为对象。因此,对象包含存储在对象内的实例变量中的值。对象还包含对对象进行操作的代码体。这些代码体称为方法

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 code that operate upon the object. These bodies of code are called methods.

包含相同类型值的对象相同的方法组合在一起。可以将类视为这些对象的类型定义。因此,Java中的String如何表示?让我们考虑Java中的以下代码片段。

Objects that contain the same types of values and the same methods are grouped together into classes. A class may be viewed as a type definition for those objects. Accordingly, how is a String in Java represented? Let's consider the following code snippet in Java.

 final public class Main
 {
    public static void main(String[] args)
    {
        String s="black lion";
        String s1=new String(s);

        System.out.println(s.toUpperCase());
        System.out.println("black lion".toUpperCase());
        System.out.println(s1.toUpperCase());
    }
}






上面的代码在将其转换为大写后显示String。在此语句中 String s =black lion; ,其中分配的字符串在哪里。它被分配到String类或某个地方的实例变量中吗?并在此声明中black lion.toUpperCase(); 。它是String类的对象吗?怎么样?


The above code displays the String after converting it into uppercase. In this statement String s="black lion"; , Where is the String being assigned. Is it being assigned into an instance variable within the String class or somewhere? and in this statement "black lion".toUpperCase();. Is it an object of the String class? How?

推荐答案

字符串是一个包含系列的 char [] UTF-16代码单元 int 偏移到该数组,并且 int 长度。

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.

您还应该知道

new String(s)

并不是真的什么有用的。它只是创建另一个由相同数组,偏移量和长度支持的实例 s 。很少有理由这样做,因此大多数Java程序员都认为这是不好的做法。

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双引号字符串,如my string 实际上是对实习的引用字符串实例所以foo是对同一个String实例的引用,无论它在代码中显示多少次。

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.

这篇关于Java中的字符串表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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