What is the difference between null
and the \"\"
(empty string)?
I have written some simple code:
String a = \"\";
String b
"" and null both are different . the first one means as part of string variable declaration the string constant has been created in the string pool and some memory has been assigned for the same.
But when we are declaring it with null then it has just been instantiated jvm , but no memory has been allocated for it. therefore if you are trying to access this object by checking it with "" - blank variable , it can't prevent nullpointerexception . Please find below one use-case.
public class StringCheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "siddhartha";
String s2 = "";
String s3 = null;
System.out.println("length s1 ="+s1.length());
System.out.println("length s2 ="+s2.length());
//this piece of code will still throw nullpointerexception .
if(s3 != ""){
System.out.println("length s3 ="+s3.length());
}
}
}