Programming

문자열은 Java에서 객체이므로 'new'를 사용하여 생성하지 않는 이유는 무엇입니까?

procodes 2020. 8. 17. 10:48
반응형

문자열은 Java에서 객체이므로 'new'를 사용하여 생성하지 않는 이유는 무엇입니까?


일반적으로 new다음과 같은 키워드를 사용하여 객체를 만듭니다 .

Object obj = new Object();

문자열은 객체이지만이 new를 생성하는 데 사용하지 않습니다 .

String str = "Hello World";

왜 이런거야? 문자열을 만들 수 있습니까 new?


이미 말한 것 외에도 Java에서 문자열 리터럴 [즉, 유사 "abcd"하지만 유사 하지 않은 문자열 new String("abcd")]이 인턴됩니다. 이것은 "abcd"를 참조 할 때마다 String새 인스턴스가 아닌 단일 인스턴스에 대한 참조를 얻는다는 것을 의미합니다. 매번. 따라서 다음을 갖게됩니다.

String a = "abcd";
String b = "abcd";

a == b; //True

하지만 만약 당신이

String a = new String("abcd");
String b = new String("abcd");

그런 다음 가질 수 있습니다

a == b; // False

(그리고 누군가가 상기시킬 필요가있는 경우 항상 .equals()문자열을 비교 하는 사용하십시오 ==. 물리적 동등성 테스트).

Interning String 리터럴은 종종 두 번 이상 사용되기 때문에 좋습니다. 예를 들어 (기인 된) 코드를 고려하십시오.

for (int i = 0; i < 10; i++) {
  System.out.println("Next iteration");
}

문자열의 인턴이 없다면 "Next iteration"은 10 번 인스턴스화되어야하지만 지금은 한 번만 인스턴스화됩니다.


문자열은 Java에서 "특별한"개체입니다. 자바 설계자들은 문자열이 너무 자주 사용되어 캐싱 전략뿐만 아니라 자체 구문이 필요하다고 현명하게 결정했습니다. 다음과 같이 말하여 문자열을 선언 할 때 :

String myString = "something";

myString은 값이 "something"인 String 객체에 대한 참조입니다. 나중에 선언하는 경우 :

String myOtherString = "something";

Java는 myString과 myOtherString이 동일하고 동일한 객체로 전역 문자열 테이블에 저장된다는 것을 알아낼만큼 똑똑합니다. 이 작업을 수행하기 위해 문자열을 수정할 수 없다는 사실에 의존합니다. 이렇게하면 필요한 메모리 양이 줄어들고 더 빠르게 비교할 수 있습니다.

대신에

String myOtherString = new String("something");

Java는 myString 객체와는 다른 새로운 객체를 생성합니다.


String a = "abc"; // 1 Object: "abc" added to pool

String b = "abc"; // 0 Object: because it is already in the pool

String c = new String("abc"); // 1 Object

String d = new String("def"); // 1 Object + "def" is added to the Pool

String e = d.intern(); // (e==d) is "false" because e refers to the String in pool

String f = e.intern(); // (f==e) is "true" 

//Total Objects: 4 ("abc", c, d, "def").

이것이 몇 가지 의심을 없애기를 바랍니다. :)


지름길입니다. 원래는 그렇지 않았지만 Java가 변경했습니다.

FAQ 는 이에 대해 간략하게 설명합니다. Java 사양 가이드에서도 이에 대해 설명합니다. 하지만 온라인에서 찾을 수 없습니다.


문자열은 몇 가지 최적화를 거쳐야합니다 (더 나은 문구를 원하기 위해). String에는 다른 객체와 달리 연산자 오버로딩 (+ 연산자의 경우)도 있습니다. 그래서 그것은 매우 특별한 경우입니다.


We usually use String literals to avoid creating unnecessary objects. If we use new operator to create String object , then it will create new object everytime .

Example:

String s1=“Hello“;
String s2=“Hello“;
String s3= new String(“Hello“);
String s4= new String(“Hello“);

For the above code in memory :

enter image description here


In Java, Strings are a special case, with many rules that apply only to Strings. The double quotes causes the compiler to create a String object. Since String objects are immutable, this allows the compiler to intern multiple strings, and build a larger string pool. Two identical String constants will always have the same object reference. If you don't want this to be the case, then you can use new String(""), and that will create a String object at runtime. The intern() method used to be common, to cause dynamically created strings to be checked against the string lookup table. Once a string in interned, the object reference will point to the canonical String instance.

    String a = "foo";
    String b = "foo";
    System.out.println(a == b); // true
    String c = new String(a);
    System.out.println(a == c); // false
    c = c.intern();
    System.out.println(a == c); // true

When the classloader loads a class, all String constants are added to the String pool.


Syntactic sugar. The

String s = new String("ABC");

syntax is still available.


You can still use new String("string"), but it would be harder to create new strings without string literals ... you would have to use character arrays or bytes :-) String literals have one additional property: all same string literals from any class point to same string instance (they are interned).


There's almost no need to new a string as the literal (the characters in quotes) is already a String object created when the host class is loaded. It is perfectly legal to invoke methods on a literal and don, the main distinction is the convenience provided by literals. It would be a major pain and waste of tine if we had to create an array of chars and fill it char by char and them doing a new String(char array).


Feel free to create a new String with

String s = new String("I'm a new String");

The usual notation s = "new String"; is more or less a convenient shortcut - which should be used for performance reasons except for those pretty rare cases, where you really need Strings that qualify for the equation

(string1.equals(string2)) && !(string1 == string2)

EDIT

In response to the comment: this was not intended to be an advise but just an only a direct response to the questioners thesis, that we do not use the 'new' keyword for Strings, which simply isn't true. Hope this edit (including the above) clarifies this a bit. BTW - there's a couple of good and much better answers to the above question on SO.


The literal pool contains any Strings that were created without using the keyword new.

There is a difference : String without new reference is stored in String literal pool and String with new says that they are in heap memory.

String with new are elsewhere in memory just like any other object.


Because String is an immutable class in java.

Now why it is immutable? As String is immutable so it can be shared between multiple threads and we dont need to synchronize String operation externally. As String is also used in class loading mechanism. So if String was mutable then java.io.writer could have been changed to abc.xyz.mywriter


TString obj1 = new TString("Jan Peter");                
TString obj2 = new TString("Jan Peter");                    

if (obj1.Name == obj2.Name)                 
    System.out.println("True");
else                
    System.out.println("False");

Output:

True

I created two separate objects, both have a field(ref) 'Name'. So even in this case "Jan Peter" is shared, if I understand the way java deals..

참고URL : https://stackoverflow.com/questions/2009228/strings-are-objects-in-java-so-why-dont-we-use-new-to-create-them

반응형