java 如何使用“”初始化字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17489250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:09:35  来源:igfitidea点击:

How can a string be initialized using " "?

javastring

提问by splitgames

If String is a class just like any other, how can it be initialized using double quotes?

如果 String 和其他类一样是一个类,那么如何使用双引号对其进行初始化?

回答by Suresh Atta

Java String is Special

Java 字符串是特殊的

The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.

For performance reason, Java's String is designed to be in between a primitive and a class.

Java 的设计者决定在面向对象的语言中保留原始类型,而不是将一切都变成对象,以提高语言的性能。原语存储在调用堆栈中,需要更少的存储空间并且操作成本更低。另一方面,对象存储在程序堆中,需要复杂的内存管理和更多的存储空间。

出于性能原因,Java 的 String 被设计为介于原始类型和类之间。

For example

例如

String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // same reference
String s4 = new String("Hello");  // String object
String s5 = new String("Hello");  // String object

enter image description here

在此处输入图片说明

Note :String literalsare stored in a common pool. This facilitates sharing of storage for strings with the same contents to conserve storage. Stringobjects allocated via new operator are stored in the heap, and there is no sharing of storage for the same contents.

注意:字符串文字存储在公共池中。这有助于共享具有相同内容的字符串的存储空间以节省存储空间。String通过 new 操作符分配的对象存储在 中heap,对于相同的内容没有共享存储。

回答by chetan

Java treats String as a special class, you can initialize in both ways

Java把String当成一个特殊的类,两种方式都可以初始化

  1. Directly assigning literal

    String a = "adsasdf";
    
  2. As other Objects using new keyword

    String a = new String("adsasdf");
    
  1. 直接赋值文字

    String a = "adsasdf";
    
  2. 作为其他使用 new 关键字的对象

    String a = new String("adsasdf");
    

You need to take special care when you wants to compare with ==sign:

==符号比较时需要特别注意:

String a = "asdf";
String b = "asdf";
System.out.println(a == b);  // True
System.out.println(a.equals(b)); // True

String a = new String("asdf");
String b = new String("asdf");
System.out.println(a == b);  // False
System.out.println(a.equals(b)); // True

That is because in first case the objects a and b are kept in something called literal pooland they both are referencing same object so they are equal in both ways.

那是因为在第一种情况下,对象 a 和 b 被保存在一个被调用的东西中,literal pool并且它们都引用同一个对象,因此它们在两种方式中都是相等的。

But in second case a and b references different objects like when we initialize any other objects. so they are unequal when compared with ==operator whereas they are equal in values.

但在第二种情况下, a 和 b 引用不同的对象,就像我们初始化任何其他对象时一样。所以它们与==运算符相比是不相等的,而它们的值是相等的。

回答by Joachim Sauer

String gets special treatment in the JLS: it's one of the two non-primitive types for which literals exist (the other is Class) *.

String 在 JLS 中得到特殊处理:它是存在文字的两种非原始类型之一(另一种是Class*

From the JLS:

JLS

A string literal is a reference to an instance of class `String [...].

字符串文字是对类`String [...] 的实例的引用。

* well, there's also the "null type"with it's "null literal" null, but most people don't think of the "null type" as a proper type.

* 好吧,还有“空类型”和“空文字” null,但大多数人不认为“空类型”是正确的类型。

回答by nos

It's a feature of the Java language. String literals in the source code is given special treatment.

这是 Java 语言的一个特性。源代码中的字符串文字被给予特殊处理。

The language spec, here, simply says that a string literal is of Stringtype

此处的语言规范只是说字符串文字的String类型为

回答by tristan2468

Text inside double quotes creates a literal Stringobject.

双引号内的文本创建一个文字String对象。

String myString = "Some text";

The code above creates a Stringobject, using double quotes.

上面的代码String使用双引号创建了一个对象。

回答by René Link

Strings are very often used in a programming language. Since java is object oriented a string is an object. To avoid the cumbersome new String("someString"); statement everytime you need a string object java allows you to just create a string object by using the string literal.

字符串在编程语言中非常常用。由于 java 是面向对象的,因此字符串是一个对象。避免繁琐的new String("someString"); 每次需要字符串对象时的语句 java 允许您使用字符串文字创建字符串对象。

But you should keep in mind the string equality. Here a short JUnit test to demonstrate what I mean.

但是你应该记住字符串相等。这里有一个简短的 JUnit 测试来演示我的意思。

    @Test
    public void stringTest() {
       // a string literal and a string object created 
       // with the same literal are equal
       assertEquals("string", new String("string"));

       // two string literals are the same string object
       assertSame("string", "string"); 

       // a string literal is not the same object instance 
       // as a string object created with the same string literal
       assertFalse("string" == new String("string"));

       // java's String.intern() method gives you the same
       // string object reference for all strings that are equal.
       assertSame("string", new String("string").intern());
    }

回答by mkdev

Just to mention. A a string literal is a reference to an instance of class String you can write code like this:

顺便提一下。字符串文字是对 String 类实例的引用,您可以编写如下代码:

 "abc".getBytes();

 "a:b:c".split(":");

 "愛".codePointAt(0);

回答by user1769790

Java does a two step process for us.

Java 为我们做了一个两步过程。

String str = "hello";

is equivalent to

相当于

char data[] = {'h', 'e', 'l' , 'l', 'o'};
String str = new String(data);

Like [.NET][1] got a similar thing.

就像 [.NET][1] 得到了类似的东西。

String(Char[]) constructor

does

String(char[] value)

Adding references:-

添加参考:-

回答by Kumar Vivek Mitra

-String is a class in Java. You are right about it, so we can always initialize with the newkeyword.

-String 是Java 中的一个类。你是对的,所以我们总是可以用new关键字初始化。

-But when we do something like:

-但是当我们做类似的事情时:

String s = "";

String s = "";

The above statement is marked by the compilerto be a special String objectand then JVM during loadingof the class (loading is done before initialization), sees this what is known as a string literal, which is stored in a string literal pool.

上面的语句被编译器标记为一个特殊的 String 对象,然后JVM 在类的加载过程中(加载在初始化之前完成),看到这就是所谓的字符串文字,它存储在字符串文字池中

-So a String can be created using new()and by the ""method, but the latter provides a string literal which stays in the heap even when there is no reference to that string object, because it has a reference from the string literal pool.

-因此,可以使用new()""方法创建字符串,但后者提供了一个字符串文字,即使没有对该字符串对象的引用,该字符串文字也会保留在堆中,因为它具有来自字符串文字池的引用。

回答by Sylwester

Java.lang.Stringis not just a class. It's an integral part of the core language. The compiler has syntactic sugar for it. For example, ""is like an abbreviation for new String(""). When written ""the compiler optimizes identical strings to the same instance to save space. "a" + 5 == "a5" ==> true

Java.lang.String不仅仅是一个类。它是核心语言的一个组成部分。编译器有它的语法糖。例如,""就像是 的缩写new String("")。编写时"",编译器将相同的字符串优化为相同的实例以节省空间。"a" + 5 == "a5" ==> true

The compiler has syntactic sugar for a lot of stuff, including not having to box/unbox between object versions and their native types, no parent means Object, default constructor, ...

编译器有很多东西的语法糖,包括不必在对象版本和它们的本机类型之间装箱/拆箱,没有父级意味着对象,默认构造函数,......