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.
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.
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
nullliteral that can be used as a value for any reference type.nullmay be assigned to any variable, except variables of primitive types. There's little you can do with anullvalue beyond testing for its presence. Therefore,nullis 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 )andObjects.nonNull( myVar )null == myVarandnull != myVarmyVar == nullandmyVar != null
I prefer the first, as words are easier to read than mathematical-like symbols.
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.
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.
I was using IntelliJ and it said that a string needed to be initialized in order for the program to work. It suggests I initialize it this way
String example = null;
instead of
String example = "";
Do you agree with this? I've found conflicting information as to whether or not this is a good idea.
Why do you set variables to null? instead just blank?
String x;
VS.
String x = null;
You may also understand the difference between null and an empty string this way:

Original image by R. Sato (@raysato)
"" 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.
An alternative to is to use a static util method to do the compare. Apache commons-lang StringUtils.equals(String,String) is a possible with clearly defined behaviour for nulls.
// null safe compare
if (StringUtils.equals(variable,"hello")) {...}
// is "" or null
if (StringUtils.isEmpty(variable)) { ... }
// with static imports it's a bit nicer
if (isNotEmpty(var1) && isEmpty(var2)) { ... }
You have three options - If the item you are comparing too is known not to be null (e.g. a constant) then use that first.
if ("hello".equals(variable)) { ... }
Check for null first
if (variable != null && variable.equals("hello")) { ... }
Finally if null and the empty string can be considered the same down stream then set the string to the empty string. But if you wish to handle null differently then you can not do this.
Another alternative using Guava's emptyToNull:
text = Strings.emptyToNull(text);
I don't know the context in which you thought to mention streams relating to your question, but if you are open to the Apache StringUtils library, then one option would be to use the StringUtils#isEmpty() method:
if (StringUtils.isEmpty(text)) {
text = null;
}
You can use Objects.toString() (standard in Java 7):
Objects.toString(gearBox, "")
Objects.toString(id, "")
From the linked documentation:
public static String toString(Object o, String nullDefault)Returns the result of calling
toStringon the first argument if the first argument is not null and returns the second argument otherwise.Parameters:
o- an object
nullDefault- string to return if the first argument isnullReturns:
the result of callingtoStringon the first argument if it is notnulland the second argument otherwise.See Also:
toString(Object)
For java 8 you can use Optional approach:
Optional.ofNullable(gearBox).orElse("");
Optional.ofNullable(id).orElse("");
That way lies madness (usually). If you're running into a lot of null pointer problems, that's because you're trying to use them before actually populating them. Those null pointer problems are loud obnoxious warning sirens telling you where that use is, allowing you to then go in and fix the problem. If you just initially set them to empty, then you'll be risking using them instead of what you were actually expecting there.
Absolutely not. An empty string and a null string are entirely different things and you should not confuse them.
To explain further:
- "null" means "I haven't initialized this variable, or it has no value"
- "empty string" means "I know what the value is, it's empty".
As Yuliy already mentioned, if you're seeing a lot of null pointer exceptions, it's because you are expecting things to have values when they don't, or you're being sloppy about initializing things before you use them. In either case, you should take the time to program properly - make sure things that should have values have those values, and make sure that if you're accessing the values of things that might not have value, that you take that into account.
Since Strings are immutable, you should assign your String variable to the result of the replace method.
String str = "ADS||abc||null||null to become ADS||abc||||";
str = str.replace("null", "");
System.out.println(str);
Output:
ADS||abc|||| to become ADS||abc||||
Do you mean below code?
String[] names = new String("ADS||abc||null||null to become ADS||abc||||").split("\\|\\|");
List<String> list = new ArrayList<>();
for (String name : names) {
list.add(name.replace("null", ""));
}