The classical answer: it depends. Nulls and empty strings may present different meanings if viewed from the business logic perspective. That being said, a nullable value at the boundary of a method/module/library/etc should be presented as an Optional. Answer from pragmos on reddit.com
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 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.

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.

🌐
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 space in memory.
🌐
Coderanch
coderanch.com › t › 397787 › java › Declare-initialize-empty-String
Declare and initialize empty String (Beginning Java forum at Coderanch)
1. String = ""; 2. String = null; Thanks a lot, ... First, you need a variable name in there for it to be legal. Question: does line 2 initialize 'b' to an empty string? Line 1 create a String object and assigns it the reference 'a'. Line 2 only creates a reference( 'b' ) to a String object.
Find elsewhere
🌐
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:
🌐
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.
🌐
Programiz
programiz.com › java-programming › examples › string-empty-null
Java Program to Check if a String is Empty or Null
... class Main { public static void main(String[] args) { // create null, empty, and regular strings String str1 = null; String str2 = ""; String str3 = " "; // check if str1 is null or empty System.out.println("str1 is " + isNullEmpty(str1)); // check if str2 is null or empty System.out.p...
🌐
EXLskills
exlskills.com › courses › java string › java string
Null Value | Java String - EXLskills
August 8, 2018 - package exlcode; public class NullValueExample { // exampleVariableOne is only declared and not initialised public static String exampleVariableOne; public static void main(String[] args) { System.out.println(exampleVariableOne); } } In Java, variables created from the String class are like containers, they hold a reference to an object.
🌐
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 - Applying any standard string operation to the null string will cause a NullPointerException runtime. In this example, we created an empty and a null String, and then we checked their working with the length() method.
🌐
Baeldung
baeldung.com › home › java › java string › string initialization in java
String Initialization in Java | Baeldung
January 8, 2024 - See, member variables are initialized with a default value when the class is constructed, null in String‘s case.
Top answer
1 of 5
210

Why must it work?

The JLS 5, Section 15.18.1.1 JLS 8 § 15.18.1 "String Concatenation Operator +", leading to JLS 8, § 5.1.11 "String Conversion", requires this operation to succeed without failure:

...Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

How does it work?

Let's look at the bytecode! The compiler takes your code:

String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"

and compiles it into bytecode as if you had instead written this:

String s = null;
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
System.out.println(s); // prints "nullhello"

(You can do so yourself by using javap -c)

The append methods of StringBuilder all handle null just fine. In this case because null is the first argument, String.valueOf() is invoked instead since StringBuilder does not have a constructor that takes any arbitrary reference type.

If you were to have done s = "hello" + s instead, the equivalent code would be:

s = new StringBuilder("hello").append(s).toString();

where in this case the append method takes the null and then delegates it to String.valueOf().

Note: String concatenation is actually one of the rare places where the compiler gets to decide which optimization(s) to perform. As such, the "exact equivalent" code may differ from compiler to compiler. This optimization is allowed by JLS, Section 15.18.1.2:

To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

The compiler I used to determine the "equivalent code" above was Eclipse's compiler, ecj.

2 of 5
28

See section 5.4 and 15.18 of the Java Language specification:

String conversion applies only to the operands of the binary + operator when one of the arguments is a String. In this single special case, the other argument to the + is converted to a String, and a new String which is the concatenation of the two strings is the result of the +. String conversion is specified in detail within the description of the string concatenation + operator.

and

If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28))that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string. If an operand of type String is null, then the string "null" is used instead of that operand.

Top answer
1 of 4
12

Normally, when you call a constructor or method for which multiple overridden versions might apply, Java will choose the most specific constructor or method. Section 15.12.2 of the Java Language Specification explains this in detail.

Suppose you have two overloaded methods, like this:

public void method(Object o) {
    // ...
}

public void method(String s) {
    // ...
}

When you call method(null), both these methods apply. Java chooses the most specific one, which is in this case the second method, that takes a String - because String is a more specific type than Object.

However, sometimes the most specific constructor or method cannot be determined. If we look at the constructors of class String that take one argument:

String(byte[] bytes)
String(char[] value)
String(String original)
String(StringBuffer buffer)
String(StringBuilder builder)

Note that there is no hierarchy between the types byte[], char[], String, StringBuffer and StringBuilder, so it's not possible to say that one of these constructors is more specific than the others. So, the Java compiler doesn't know which constructor to choose and will give you an error.

2 of 4
11

Because, compiler couldn't figure out which constructor to call. See here that how many one-argument-constructor it has.

[Edited] You said, if there is another reason. So why not try out yourself. Do something like this,

byte[] b = null;
String s = new String(b); // complier should be fine with this

char[] c = null;
String s = new String(c); // complier should be fine with this

.... // you can try other constructors using similar approach.
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
Learn about the `null` keyword in Java, its usage, syntax, and best practices to avoid `NullPointerException` with practical examples.
🌐
Baeldung
baeldung.com › home › java › java string › concatenating null strings in java
Concatenating Null Strings in Java | Baeldung
January 8, 2024 - If the input object is null, it returns an empty (“”) String, otherwise, it returns the same String: ... However, as we know, String objects are immutable in Java. That means, every time we concatenate String objects using the + operator, it creates a new String in memory.
🌐
BeginnersBook
beginnersbook.com › 2014 › 08 › stringbuilder-append-null-values-as-null-string
Java – StringBuilder append() null values as “null” String
class AppendNullDemo{ public static void main(String args[]){ // String array with few null elements String str[] = {" Mango ", null, " Orange ", " Banana ", null}; // Create StringBuilder object StringBuilder sb = new StringBuilder(); for (String temp: str){ sb.append(temp); } // Displaying the output System.out.println(sb); } }