为什么String是班级? [英] Why is String a class?

查看:72
本文介绍了为什么String是班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可以仅使用它启动

String s = "Hello";

那为什么要上课?参数在哪里?

then why is it a class? Where's the parameters?

推荐答案

鉴于 String 是一个如此有用且经常使用的类,它具有特殊的语法(通过字符串文字表示形式:文本在" 内)来创建其实例,但从语义上讲,这两个是等效的:

Given that String is such a useful and frequently used class, it has a special syntax (via a string literal representation: the text inside "") for creating its instances, but semantically these two are equivalent:

String s = "Hello"; // just syntactic sugar
String s = new String("Hello");

在引擎盖后面,两种形式都是不是 100%等效,因为使用" 的语法会尝试重用Java字符串池中的字符串,而使用的显式实例化> new String(")将始终创建一个新对象.

Behind the hood both forms are not 100% equivalent, as the syntax using "" tries to reuse strings from Java's string pool, whereas the explicit instantiation with new String("") will always create a new object.

但请不要误解,这两种语法都会产生对对象实例的引用,字符串在Java中不被视为原始类型,并且像其他任何类型一样,都是类的实例.

But make no mistake, either syntax will produce a reference to an object instance, strings are not considered primitive types in Java and are instances of a class, like any other.

这篇关于为什么String是班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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