development

널 (null)과 비어있는 ( "") Java 문자열의 차이점

big-blog 2020. 6. 22. 07:19
반응형

널 (null)과 비어있는 ( "") Java 문자열의 차이점


null""(빈 문자열) 의 차이점은 무엇입니까 ?

간단한 코드를 작성했습니다.

String a = "";
String b = null;

System.out.println(a == b); // false
System.out.println(a.equals(b)); // false

두 문장이 모두 리턴 false합니다. 나는 그들 사이의 실제 차이점이 무엇인지 알 수없는 것 같습니다.


""는 실제 문자열이지만 빈 문자열입니다.

그러나 null은 String 변수가 아무것도 가리 키지 않음을 의미합니다.

a==b ""및 null이 메모리에서 동일한 공간을 차지하지 않기 때문에 false를 반환합니다. 즉, 변수가 동일한 객체를 가리 키지 않습니다.

a.equals(b) ""는 null이 아니므로 false를 반환합니다.

차이점은 ""는 실제 문자열이므로 다음과 같이 메소드 또는 함수를 계속 호출 할 수 있습니다.

a.length()

a.substring(0, 1)

등등.

b와 같이 String이 null이면 Java는 NullPointerException호출을 시도하면 a를 던집니다 .

b.length()


궁금한 차이점이 == 대 같으면 다음과 같습니다.

== 내가 간 것처럼 참조를 비교

String a = new String("");
String b = new String("");
System.out.println(a==b);

두 개의 다른 객체를 할당하고 a와 b가 다른 객체를 가리 키기 때문에 false가 출력됩니다.

그러나이 a.equals(b)경우 String은 인수 String이 null이 아니고 동일한 문자 시퀀스를 나타내는 경우에만equals true를 리턴 하므로 true 를 리턴합니다 .

그러나 Java에는 특별한 문자열이 있습니다.

String a = "abc";
String b = "abc";
System.out.println(a==b);

false두 개의 다른 문자열을 할당해야하기 때문에 출력은이라고 생각할 것입니다 . 실제로 Java는 리터럴 문자열 (이 예제에서 a 및 b처럼 초기화 된 문자열) 인턴 합니다. 따라서 == 작동 방식에 대한 오탐 (false positive)이 발생할 수 있으므로주의하십시오.


이 방법으로 null과 빈 문자열의 차이점을 이해할 수도 있습니다.

null과 0 / 빈 문자열의 차이점


문자열은 객체이며 null 일 수 있습니다

null은 문자열 객체가 인스턴스화되지 않았 음을 의미합니다.

""는 "aaa"와 같은 인스턴스화 된 객체 문자열의 실제 값입니다.

다음은 그 점을 명확히 할 수있는 링크입니다. http://download.oracle.com/javase/tutorial/java/concepts/object.html


귀하의 진술에서 말하는 것은 ""는 null과 동일하지 않다는 것입니다. ""는 빈 문자열입니다. null은 값이 할당되지 않았 음을 의미합니다.

시도하는 것이 더 깨달을 수도 있습니다.

System.out.println(a.length()); // 0
System.out.println(b.length()); // error; b is not an object

""는 여전히 문자열이므로 메서드를 호출하고 의미있는 정보를 얻을 수 있습니다. null은 빈 변수입니다. 문자 그대로 아무것도 없습니다.


둘 사이에는 상당한 차이가 있습니다. 빈 문자열 ""은 "문자가없는 문자열"입니다. 길이가 잘 정의 된 실제 문자열입니다. 모든 표준 문자열 연산은 빈 문자열에서 잘 정의되어 있습니다. 소문자로 변환하고 일부 문자의 색인을 검색 할 수 있습니다. 널 문자열 null은 "문자열 없음"입니다. 문자열이 아니기 때문에 길이가 없습니다. 표준 문자열 작업을 null 문자열에 적용하려고하면 NullPointerException런타임에 가 발생 합니다.


에 여기 a is an Objectb(null)입니다 하지 개체가 널 참조입니다

System.out.println(a instanceof Object); // true

System.out.println(b instanceof Object); // false

여기 내 비슷한 대답입니다


null means the name isn't referencing any instantiated object. "" means an empty string.

Here a is referencing some object which happens to be an empty string. b isn't referencing any object as it's null.


In Java a reference type assigned null has no value at all. A string assigned "" has a value: an empty string, which is to say a string with no characters in it. When a variable is assigned null it means there is no underlying object of any kind, string or otherwise.


"" and null both are different . the first one means as part of string variable declaration the string constant has been created in the string pool and some memory has been assigned for the same.

But when we are declaring it with null then it has just been instantiated jvm , but no memory has been allocated for it. therefore if you are trying to access this object by checking it with "" - blank variable , it can't prevent nullpointerexception . Please find below one use-case.

public class StringCheck {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String s1 = "siddhartha";
    String s2 = "";
    String s3 = null;

    System.out.println("length s1 ="+s1.length());
    System.out.println("length s2 ="+s2.length());

    //this piece of code will still throw nullpointerexception . 
    if(s3 != ""){
        System.out.println("length s3 ="+s3.length());
    }
}

}


String s = "";
s.length();

String s = null;
s.length();

A reference to an empty string "" points to an object in the heap - so you can call methods on it.

But a reference pointing to null has no object to point in the heap and thus you'll get a NullPointerException.


The empty string is distinct from a null reference in that in an object-oriented programming language a null reference to a string type doesn't point to a string object and will cause an error were one to try to perform any operation on it. The empty string is still a string upon which string operations may be attempted.

From the wikipedia article on empty string.


String s=null;

String is not initialized for null. if any string operation tried it can throw null pointer exception

String t="null";

It is a string literal with value string "null" same like t = "xyz". It will not throw null pointer.

String u="";

It is as empty string , It will not throw null pointer.


A string can be empty or have a null value. If a string is null, it isn't referring to anything in memory. Try s.length()>0. This is because if a string is empty, it still returns a length of 0. So if you enter nothing for the same, then it will still continue looping since it doesn't register the string as null. Whereas if you check for length, then it will exit out of it's loop.


This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).

Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.

In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null string in java. The second example is akin to empty string.


When you write

String a = "";

It means there is a variable 'a' of type string which points to a object reference in string pool which has a value "". As variable a is holding a valid string object reference, all the methods of string can be applied here.

Whereas when you write

String b = null;

알 수없는 참조b 를 가리키는 string 유형 의 변수가 있음을 의미합니다 . 알 수없는 참조에 대한 작업은 .NullPointerException

이제 아래 식을 평가 해 봅시다.

System.out.println(a == b); // false. because a and b both points to different object reference

System.out.println(a.equals(b)); // false, because the values at object reference pointed by a and b do not match.

System.out.println(b.equals(a)); // NullPointerException, because b is pointing to unknown reference and no operation is allowed

간단히 말해서

  • ""는 빈 문자열입니다

  • null은 빈 문자열 변수 입니다.

참고 URL : https://stackoverflow.com/questions/4802015/difference-between-null-and-empty-java-string

반응형