This question already has answers here:
Difference between null and empty ("") Java String
(22 answers)
Closed 4 years ago.
I got different simulation results when I programmed in these two ways:
if (S == null) {
return new LinkedList<>();
}
and
int len = S.length();
if(len == 0) return new LinkedList<>();
The first code gave me [""], which passed the testing. While the second one gave me [], got failed.
And I also noticed that there is another way: S.isEmpty()
Would anyone please explain? Many thanks!
String == null checks if the object is null (nothing, not even an empty string) and String#length() == 0 (actually, you should use String#isEmpty() instead) checks if the string object has 0 chars. Also, you can't access any methods if the object is null, it will throw a NullPointerException (or NPE for short).
difference between (string == null) and (string.length() == 0)?
Very different.
When you check (string == null), it checks whether the string reference is pointing to any existing object. If it is not referencing to any object, it will return true.
string.length() == 0 just checks your existing String object's content and see if its length is 0. If no object exist in the current variable when you invoke .length(), you get a NullPointerException.
S is a reference variable (you should write it in lower case).
S (or rather s) references an object that provides the method length().
You can only access the object referenced by s, if s is a really a reference to an object. If s is null (s==null), s does not reference an object and therefore, you can not call the method length(). If you try, you will get a NullPointerException.
When s references an object, you can call the length method on that object. In this case, it is a string object. A string object may exist without any characters (empty string, or "").
String s; // just a reference, initial value is null
s = ""; // s now references an empty string and is no longer null
new String(""); // create a new object with an empty string
In Java, you never really work with objects. You only work with references to objects, though in most cases, it appears as if you work with the object directly.
Keep in mind that the reference variable and the object are really to different things.
If the string you are passing into the second one is null, an exception should occur, since .length() will throw an exception when called on a null string.
if a String instance is null, myInstance.length() == 0 would throw a NullPointerException, because you call an instance member of a not instantiated instance and crash your application.
So, if you're not sure your String instance is instantiated, always do a null-check, or better yet, with Java 8 or later, use Optional to avoid null's.
S == null mean that there if you try to print something for instance, nothing wiil happen (or maybe a nullPointerEcxeption) because null mean that there is nothing inside this variable.
String.lenght(S) == 0 mean that your string equals to ''
for instance :
String S1 = '';
String S2 = null;
try{
System.out.println(S1.length() == 0) {
System.out.println('S1 is not null');
}catch(nullPointerExeption e){
System.out.println('S1 is null');
}
try{
System.out.println(S2.length())//it will throw you a java.nullpointerexcption
System.out.println('S2 is not null');
}catch(nullPointerExeption e){
System.out.println('S2 is null');
}
The system will write
0
S1 is not null
S2 is null
//case1
String s;
if(s==null)System.out.println("I am null");
System.out.println(s.length());
//error: variable s might not have been initialized
//case2
String s=null;
if(s==null)System.out.println("I am null");
System.out.println(s.length());
/* output
I am null
error: Null pointer exception
*/
//case 3
String s=new String();
if(s==null)System.out.println("I am null");
System.out.println("length is "+s.length());
/* output
length is 0
*/
String s="";
if(s==null)System.out.println("I am null");
System.out.println("length is "+s.length());
/* output
length is 0
*/
Related
This question already has answers here:
What is null in Java?
(14 answers)
Closed 3 years ago.
I have a class with the two string variable i.e:
String str = null;
String str1="null";
One is a "string value null" and other in other case null object is assigned to a string variable.
So what is the difference in both the two assignments and how to check if one is different from other ??
String str = null; means str is a reference of String which points to null.
And String str1="null"; means str1 object which points to String Object which is "null".
First check if object is null or not ? then compare by using equals method.
like
if(str==null && str1==null){
//Both are null and equal
}
if(str != null && str.equals(str1)){
//return true;
}
else
{
//return false;
}
The String "null" is a string of length 4 with the characters n, u, l and l. It can be worked on as any other string.
The null reference isn't a string. Any attempt to use it like a string will result in a NullPointerException.
1) String str = null;
Here str has no instance is created because it is assigned to null, so no new memory is consumed in heap
2) String str1="null";
Here str1 string instance is created and "null" is stored as value
This is an extremely basic question but why is the following code returning a null pointer exception?
String a = null;
String b = null;
System.out.println(a.equals(b));
According to the docs here:
http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals(java.lang.Object,%20java.lang.Object)
the .equals() function is first checking for null before comparing values. Shouldn't it return true since they are both null?
The method you linked to takes in two objects and is a static method. You need to call it like Objects.equals(a, b). Instead you are calling .equals() on a null object which throws NPE
Shouldn't it return true since they are both null?
nop. since a is a null-referenced object, invoking ANY instance method on that object will throw a NPE
so what you can do:
if you are still on java 6 do
System.out.println(a == null ? b == null : a.equals(b));
and since java 7
System.out.println(Objects.equals(a, b));
I usually write following method,
private boolean equalsWithNull(String first, String second){
return ((first!=null&&second!=null && first.equals(second)) || (first==null && second==null));
}
Objects::equals is the best option, but you can use
Optional.ofNullable(a).equals(Optional.ofNullable(b))
as well. However I don't really see any cases when you will choose Optional approach instead of Objects
you can check both values instead of reference,
String a = null;
String b = null;
System.out.println(a == b ? "true":"false");
it returns true.
I know that in Java a variable can be null or not null. So I want to ask that is there any other possibility?
String abc = null; //or a value or anything or any other thing I don't know like undefined vs
if (abc == null) {
System.out.println("IF");
} else if (abc != null) {
System.out.println("ELSE IF");
}
In that code is there any need to insert an else branch? Like this:
String abc = null; //or a value or anything
if (abc == null) {
System.out.println("IF");
} else if (abc != null) {
System.out.println("ELSE IF");
} else {
//any possibility to come here ???
}
I know that in java a variable can be null or not null.
In fact that is not correct:
int test = null; // Compilation error
if (test == null) // Compilation error
Variables whose type is a primitive type cannot be null and cannot be compared with null.
Only variables whose type is a reference type (i.e. a class type or an array type) can have null as a value.
So ı want to ask that is there any other possibility
Assuming you are talking about reference types, then No.
But that is a logical tautology. If any variable can have null as a value, then its value either is null ... or it isn't null.
And in general1, for any type T, t is a variable of type T and v is an value of type T then
(t != V) <=> !(t == v)
In English: either t has the value v ... or it doesn't.
1 - There is one exception to this. If T is float or double, and you are comparing against the NaN value, then == always gives false, even if you are testing NaN == NaN !
Java have primitives and objects.
Primitives like int can not be null (they have big brothers though like Integer wrappers which actually can).
Talking about "nullness" of objects we're speaking abount reference variables or links to them. A link can be not null if it references some object or null if it does not. That's it, period, no other case.
You don't need a IF .. ELSE IF .. ELSE construct here since there is only two possibility NULL or NOT NULL. Simple IF .. ELSE construct would suffice. Better would be to use Ternary Operator like
string str = (abc == null) ? "IF" : "ELSE IF";
System.out.println(str);
(OR)
System.out.println((abc == null) ? "IF" : "ELSE IF");
Use if..else instead of if...else if...else. You have only two possibilities.
String abc=null;
if(abc==null){
System.out.println("IF");
}else{
System.out.println("ELSE");
}
I am .net programmer and completely new in java. I am facing problem in handling null string in java. I am assigning value from string array to string variable completeddate.
I tried all this but that didn't work.
String COMPLETEDATE;
COMPLETEDATE = country[23];
if(country[23] == null && country[23].length() == 0)
{
// ...
}
if (COMPLETEDATE.equals("null"))
{
// ...
}
if(COMPLETEDATE== null)
{
// ...
}
if(COMPLETEDATE == null || COMPLETEDATE.equals("null"))
{
// ...
}
For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:
if("constantString".equals(COMPLETEDDATE)) {
// logic
}
But in general, your approach isn't correct.
The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.
The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.
Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.
Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".
To check null string you can use Optional in Java 8 as below:
import Optional
import java.util.Optional;
import it as above
String str= null;
Optional<String> str2 = Optional.ofNullable(str);
then use isPresent() , it will return false if str2 contains NULL otherwise true
if(str2.isPresent())
{
//If No NULL
}
else
{
//If NULL
}
reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
It is not entirely clear what you are asking, but to check if a String variable is null, use the following statement.
if(myString==null)
This checks whether the object reference is null.
The following statement, which you have written is incorrect for two reasons.
if (COMPLETEDATE.equals("null"))
{
// ...
}
1. null is a keyword in Java, "null" is just a string of text.
2. .equals() checks to see if two objects are equal according to the given method's definition of equality. Null checks should always be made using the == comparison operator, as it checks reference equality.
If a variable is null, you cannot dereference it.
That means you can not invoke methods on it.
So... The following if statement will throw a NullPointerException every time the first clause is true:
if (a == null && a.length() == 0)
In other words: if a is null, you CANNOT invoke the length method on a.
In Java I am told that when doing a null check one should use == instead of .equals(). What are the reasons for this?
They're two completely different things. == compares the object reference, if any, contained by a variable. .equals() checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals is a method, if you try to invoke it on a null reference, you'll get a NullPointerException.
For instance:
class Foo {
private int data;
Foo(int d) {
this.data = d;
}
#Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
return ((Foo)other).data == this.data;
}
/* In a real class, you'd override `hashCode` here as well */
}
Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances
System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition
Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it
System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything
System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null
if you invoke .equals() on null you will get NullPointerException
So it is always advisble to check nullity before invoking method where ever it applies
if(str!=null && str.equals("hi")){
//str contains hi
}
Also See
difference-between-equals-and == in Java
In addition to the accepted answer (https://stackoverflow.com/a/4501084/6276704):
Since Java 1.7, if you want to compare two Objects which might be null, I recommend this function:
Objects.equals(onePossibleNull, twoPossibleNull)
java.util.Objects
This class consists of static utility methods for operating on
objects. These utilities include null-safe or null-tolerant methods
for computing the hash code of an object, returning a string for an
object, and comparing two objects.
Since:
1.7
In Java 0 or null are simple types and not objects.
The method equals() is not built for simple types. Simple types can be matched with ==.
Object.equals is null safe, however be aware that if two objects are null, object.equals will return true so be sure to check that the objects you are comparing aren't null (or hold null values) before using object.equals for comparison.
String firstname = null;
String lastname = null;
if(Objects.equals(firstname, lastname)){
System.out.println("equal!");
} else {
System.out.println("not equal!");
}
Example snippet above will return equal!
foo.equals(null)
What happens if foo is null?
You get a NullPointerException.
If an Object variable is null, one cannot call an equals() method upon it, thus an object reference check of null is proper.
If you try calling equals on a null object reference, then you'll get a null pointer exception thrown.
According to sources it doesn't matter what to use for default method implementation:
public boolean equals(Object object) {
return this == object;
}
But you can't be sure about equals in custom class.
If we use=> .equals method
if(obj.equals(null))
// Which mean null.equals(null) when obj will be null.
When your obj will be null it will throw Null Point Exception.
so we should use ==
if(obj == null)
it will compare the references.
here is an example where str != null but str.equals(null) when using org.json
JSONObject jsonObj = new JSONObject("{field :null}");
Object field = jsonObj.get("field");
System.out.println(field != null); // => true
System.out.println( field.equals(null)); //=> true
System.out.println( field.getClass()); // => org.json.JSONObject$Null
EDIT:
here is the org.json.JSONObject$Null class:
/**
* JSONObject.NULL is equivalent to the value that JavaScript calls null,
* whilst Java's null is equivalent to the value that JavaScript calls
* undefined.
*/
private static final class Null {
/**
* A Null object is equal to the null value and to itself.
*
* #param object
* An object to test for nullness.
* #return true if the object parameter is the JSONObject.NULL object or
* null.
*/
#Override
public boolean equals(Object object) {
return object == null || object == this;
}
}
Because equal is a function derived from Object class, this function compares items of the class. if you use it with null it will return false cause cause class content is not null. In addition == compares reference to an object.
So I never get confused and avoid problems with this solution:
if(str.trim().length() <=0 ) {
// is null !
}
I have encountered this case last night.
I determine that simply that:
Don't exist equals() method for null
So, you can not invoke an inexistent method if you don't have
-->>> That is reason for why we use == to check null
You code breaks Demeter's law. That's why it's better to refactor the design itself. As a workaround, you can use Optional
obj = Optional.ofNullable(object1)
.map(o -> o.getIdObject11())
.map(o -> o.getIdObject111())
.map(o -> o.getDescription())
.orElse("")
above is to check to hierarchy of a object so simply use
Optional.ofNullable(object1)
if you have only one object to check
Hope this helps !!!!
You could always do
if (str == null || str.equals(null))
This will first check the object reference and then check the object itself providing the reference isnt null.