🌐
Coderanch
coderanch.com › t › 397787 › java › Declare-initialize-empty-String
Declare and initialize empty String (Beginning Java forum at Coderanch)
It will need to be assigned a String object before it can be used. If you try to use before-hand, you'll get a null pointer exception. Which one is correct? Preference. ... Probably going to sound totally dumb here and embarras myself!! BUT if I don't say something I won't learn........... I thought the following: null means it is empty i.e. nothing there And " " means it is just initialised to something (Please, please be kind!)
🌐
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 ...
🌐
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)
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:
🌐
iO Flood
ioflood.com › blog › empty-string-java
Working with Java Empty String: A Detailed Guide
February 20, 2024 - It’s a fully-fledged string that you can manipulate and operate on, just like any other string. While the isEmpty() method is a straightforward way to check if a string is empty, Java offers other methods that can be used for the same purpose.
🌐
Reddit
reddit.com › r/programmerhumor › how to create an empty string
r/ProgrammerHumor on Reddit: How To Create an Empty String
October 26, 2019 - The same goes for all keyword aliases ... such as int, long, short, byte, etc. More replies More replies ... Though I suppose this could be Java where you use String and not string like C#. Would be a coincidence if you guys have a StringBuilder too. ... Was going to post the lovely string.Empty as ...
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.

🌐
Saylor Academy
learn.saylor.org › mod › book › view.php
Strings and Object References in Java: The Empty String | Saylor Academy | Saylor Academy
The reference variable c is initialized to a reference to this String object. This is most certainly a different value than null. A String object that contains no characters is still an object. Such an object is called an empty string. It is similar to having a blank sheet of paper (different ...
Find elsewhere
🌐
Delft Stack
delftstack.com › home › howto › java › empty string in java
How to Check Empty String in Java | Delft Stack
February 2, 2024 - If you are working with the apache commons library, you can use the StringUtils class with an Empty constant to create an empty string in Java. This class has a built-in empty constant so the programmer can directly use it in the code.
🌐
Coderanch
coderanch.com › t › 375744 › java › representing-empty-string
better way of representing an empty string... (Java in General forum at Coderanch)
programming forums Java Mobile ... ... ... Hi, Just wanted to know if there is any difference between the following usage of an empty string 1) String empty = ""; 2) String empty = SomeInterface.emptyString; Now, in SomeInterface interface......
🌐
W3Schools
w3schools.com › java › ref_string_isempty.asp
Java String isEmpty() Method
String myStr1 = "Hello"; String myStr2 = ""; System.out.println(myStr1.isEmpty()); System.out.println(myStr2.isEmpty()); ... The isEmpty() method checks whether a string is empty or not.
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 › string initialization in java
String Initialization in Java | Baeldung
January 8, 2024 - As we know by now, the emptyLiteral will be added to the String pool, while the other two go directly onto the heap.
🌐
Javatpoint
javatpoint.com › java-string-isempty
Java String isEmpty()
Java String isEmpty() method with method signature and examples of concat, compare, touppercase, tolowercase, trim, length, equals, split, string isempty in java etc.
🌐
Dot Net Perls
dotnetperls.com › isempty-java
Java - String isEmpty Method - Dot Net Perls
This program uses the isEmpty method. We declare a string called "value" and assign it to an empty string literal. Result The isEmpty method returns true. So the inner statements of the if-block are reached.
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.

🌐
Medium
medium.com › @rahul.tpointtech12 › exploring-the-possibilities-of-empty-string-in-java-f6f2b300ae70
Exploring the Possibilities of Empty String in Java | by Rahul | Medium
March 20, 2025 - However, frequent string concatenations, especially in loops, can be costly. Using StringBuilder or StringBuffer for such operations is recommended to improve efficiency. Empty Strings in Java are essential for handling text data efficiently and avoiding common pitfalls such as NullPointerException.