""를 사용하여 문자열을 초기화하는 방법은 무엇입니까?
String이 다른 클래스와 같은 클래스라면 큰 따옴표를 사용하여 어떻게 초기화 할 수 있습니까?
Java 설계자는 언어의 성능을 향상시키기 위해 모든 것을 객체로 만드는 대신 객체 지향 언어로 기본 유형을 유지하기로 결정했습니다. 프리미티브는 호출 스택에 저장되며, 저장 공간이 적고 조작하기가 더 저렴합니다. 반면에 객체는 프로그램 힙에 저장되므로 복잡한 메모리 관리 및 더 많은 저장 공간이 필요합니다.
성능상의 이유로 Java의 문자열은 기본과 클래스 사이에 있도록 설계되었습니다.
예를 들어
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
참고 : 문자열 리터럴 은 공통 풀에 저장됩니다. 이것은 동일한 내용을 가진 문자열을위한 스토리지 공유를 용이하게하여 스토리지를 보존합니다. String
new 연산자를 통해 할당 된 객체는에 저장되며 heap
동일한 콘텐츠에 대한 스토리지 공유가 없습니다.
Java는 String을 특수 클래스로 취급하므로 두 가지 방법으로 초기화 할 수 있습니다
직접 리터럴 할당
String a = "adsasdf";
새 키워드를 사용하는 다른 개체로
String a = new String("adsasdf");
==
부호 와 비교하려면 특별한주의가 필요합니다 .
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
첫 번째 경우에는 객체 a와 b가 호출 된 것으로 유지되고 literal pool
둘 다 동일한 객체를 참조하므로 두 방식이 동일하기 때문입니다.
그러나 두 번째 경우 a와 b는 다른 객체를 초기화 할 때와 같이 다른 객체를 참조합니다. 따라서 ==
연산자 와 비교할 때 값이 같지 않지만 값이 같습니다.
문자열은 JLS에서 특별한 처리를 얻습니다. 리터럴이 존재하는 두 가지 비 기본 유형 중 하나입니다 (다른 하나는 Class
) * .
에서 JLS :
문자열 리터럴은`String [...] 클래스의 인스턴스에 대한 참조입니다.
* 음, "null literal "을 가진 "null type"도null
있지만 대부분의 사람들은 "null type"을 적절한 유형으로 생각하지 않습니다.
Java 언어의 기능입니다. 소스 코드의 문자열 리터럴에는 특별한 처리가 제공됩니다.
언어 사양은, 여기 , 단순히 문자열 리터럴의 것을 말한다 String
유형
큰 따옴표 안의 텍스트는 리터럴 String
객체를 만듭니다 .
String myString = "Some text";
위의 코드는 String
큰 따옴표를 사용하여 객체를 만듭니다 .
문자열은 프로그래밍 언어에서 매우 자주 사용됩니다. java는 객체 지향이므로 문자열은 객체입니다. 번거로운 새 String ( "someString"); 문자열 객체가 필요할 때마다 statement java를 사용하면 문자열 리터럴을 사용하여 문자열 객체를 만들 수 있습니다.
그러나 문자열 평등을 명심해야합니다. 여기에 내가 의미하는 바를 보여주는 짧은 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());
}
그냥 언급하면됩니다. 문자열 리터럴은 다음과 같은 코드를 작성할 수있는 String 클래스의 인스턴스에 대한 참조입니다.
"abc".getBytes (); "a : b : c".split ( ":"); "愛".codePointAt(0);
- String is a class in Java. You are right about it, so we can always initialize with the new
keyword.
- But when we do something like:
String s = "";
The above statement is marked by the compiler to be a special String object and then JVM during loading of the class (loading is done before initialization), sees this what is known as a string literal, which is stored in a string literal pool.
- 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.
Java does a two step process for us.
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.
String(Char[]) constructor
does
String(char[] value)
Adding references:-
- http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
- http://msdn.microsoft.com/en-us/library/system.string.aspx
Java.lang.String
is 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
컴파일러는 객체 버전과 기본 유형 사이에서 상자 / 상자를 풀지 않아도되는 것을 포함하여 많은 것을위한 구문 설탕을 가지고 있습니다. 부모는 Object, 기본 생성자를 의미하지 않습니다 ...
참고 URL : https://stackoverflow.com/questions/17489250/how-can-a-string-be-initialized-using
'IT' 카테고리의 다른 글
iOS에서 프로그래밍 방식으로 절전 모드를 비활성화 / 활성화하는 방법은 무엇입니까? (0) | 2020.06.08 |
---|---|
IncludeExceptionDetailInFaults를 켭니다 (ServiceBehaviorAttribute 또는 (0) | 2020.06.08 |
열망하는 로딩이란 무엇입니까? (0) | 2020.06.08 |
두 정수 값을 나누어 플로트 결과를 얻는 방법은 무엇입니까? (0) | 2020.06.08 |
Fragment와 함께 데이터 바인딩을 사용하는 방법 (0) | 2020.06.08 |