Assign null

When we write:

String s = "Hello World!";
s = null;

The String object still exists in memory because this does not delete it. However the garbage collector will clear the object from memory as there is no variable referencing it.
For all practical purposes s = null; deletes the String.

Answer from user18098820 on Stack Overflow
Top answer
1 of 3
1

Assign null

When we write:

String s = "Hello World!";
s = null;

The String object still exists in memory because this does not delete it. However the garbage collector will clear the object from memory as there is no variable referencing it.
For all practical purposes s = null; deletes the String.

2 of 3
0

tl;dr

set a String to null in Java?

myString = null ;

declare the variable without initializing it

Uninitialized deaults to null, no String object. Empty reference variable.

String myString ;  

You can explicitly assign null. Same effect as line above. No object, empty reference.

String name = null;

Declare and initialize to empty string:

String myString = "" ;  // A `String` object containing no characters. Not null.

Details

Before posting here on basic Java Questions, study the Java Tutorials provided by Oracle free of cost.

See the tutorial page on string literals. To quote:

There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.

So null is not a piece of text with four characters. The keyword null means “no object at all”, no String, nothing at all, an empty reference.

To test if an object reference variable is null (contains no reference), you have a few choices:

  • Objects.isNull( myVar ) and Objects.nonNull( myVar )
  • null == myVar and null != myVar
  • myVar == null and myVar != null

I prefer the first, as words are easier to read than mathematical-like symbols.

Top answer
1 of 3
11

First let's clarify something: You mention that after assigning null to the variable you could forget to initialize it, but by assigning null to it you are in effect initializing it.

public static void main (String args[]){
    String s;       
    System.out.println(s); // compiler error variable may not be initialized
}

vs

public static void main (String args[]){
    String s=null;      
    System.out.println(s); // no compiler error
    System.out.println(s.equals("helo")); // but this will generate an exception
}

So after you do String s=null; there's is no way that you could forget to initialize because you did initialize it.

That being clear, I would recommend you to use a "smart default". In your case perhaps the empty string "" would be a good default value if you want to avoid NullPointerException. In the other hand, sometimes it is desirable that the program produce an exception because it indicates something wrong happened under the hood that should not have happened.

2 of 3
8

In general you want to keep declaration and initialisation as close as possible to minimise exactly the type of problem you're talking about.

There is also the issue of redundant initialisation where the value null you're assigning is never used which is extra code that harms readability even if the redundant assignment is optimised away by the compiler.

Sometimes assigning some sort of default value is unavoidable, for example if you declare before a try catch, initialise inside and use it afterwards. For other types you can often find a more natural default value such as an empty list.

🌐
Coderanch
coderanch.com › t › 522022 › java › parse-null-string-null
How to parse null string to null. (Beginning Java forum at Coderanch)
You will want a validator to notice invalid value null for a last name, where "null" would be accepted as a valid last name... A third example is when you explicitly do not want your application to store the string "null" in a database's nullable (var)char field.
🌐
Coderanch
coderanch.com › t › 543588 › java › set-String-null
Cannot set a String to null? [Solved] (Java in General forum at Coderanch)
The thing is, it was fine if the code was run the first time, the output of the code will be something like, example: "301130K0" (A String object) When it goes through the loop the second time, I thought that my codes will "RESET" the old PIN and re-generate a new PIN for it, but instead, it gave me another kinds of result which I didn't want: "131L35011007300" The format of the PIN wasn't suppose to be like this. I thought the uspObj.setUsp(null) line will help to set the PIN to NULL and re-generate a new PIN once again but it didn't.
🌐
Quora
quora.com › What-is-the-difference-between-initializing-a-string-to-null-and-initializing-a-string-to-an-empty-string-for-the-Java-language
What is the difference between initializing a string to null and initializing a string to an empty string (for the Java language)? - Quora
Answer (1 of 12): Declaring a String in the following way [code]String s = null; [/code]will throw a NullPointerException if you try to access it before initializing it, or giving it some value, which means, the String s has not yet been allocated ...
🌐
Oracle
docs.oracle.com › javaee › 7 › tutorial › bean-validation002.htm
21.2 Validating Null and Empty Strings - Java Platform, Enterprise Edition: The Java EE Tutorial (Release 7)
if (testString==null) { doSomething(); } else { doAnotherThing(); } By default, the doAnotherThing method is called even when the user enters no data, because the testString element has been initialized with the value of an empty string. In order for the Bean Validation model to work as intended, you must set the context parameter javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true in the web deployment descriptor file, web.xml:
Find elsewhere
Top answer
1 of 16
408

You may also understand the difference between null and an empty string this way:

Original image by R. Sato (@raysato)

2 of 16
251

"" is an actual string, albeit an empty one.

null, however, means that the String variable points to nothing.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) returns false because "" does not equal null, obviously.

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

and so on.

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()


If the difference you are wondering about is == versus equals, it's this:

== compares references, like if I went

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

That would output false because I allocated two different objects, and a and b point to different objects.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

Be warned, though, that Java does have a special case for Strings.

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

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

🌐
Baeldung
baeldung.com › home › java › java string › difference between null and empty string in java
Difference Between null and Empty String in Java | Baeldung
April 19, 2024 - By default, Java initializes reference variables with null values and primitives with default values based on their type. As a result, we cannot assign null to primitives. If we assign null to a String object, it’s initialized but not instantiated and hence holds no value or reference.
🌐
Delft Stack
delftstack.com › home › howto › java › difference between null and empty strings in java
Null and Empty String in Java | Delft Stack
October 12, 2023 - The null string means no string at all. It does not have a length because it’s not a string at all. Applying any standard string operation to the null string will cause a NullPointerException runtime.
🌐
Quora
quora.com › How-can-I-empty-a-String-in-Java
How to empty a String in Java - Quora
Answer (1 of 11): You can't. Strings are immutable. You can just reference a new string object that has 0 characters. So if you have the string [code] String whoIsAwesome = "you"; [/code] you can assign a new String object to your variable like ...
🌐
YouTube
youtube.com › codelines
java set string to null - YouTube
Get Free GPT4o from https://codegive.com in java, you can set a `string` variable to `null` to indicate that it does not reference any object. this can be u...
Published   November 1, 2024
Views   0