When initialising variables with default values:
What is the difference between:
private static String thing = null;
and
private static String thing = "";
I'm not understanding which is better and why nor what is the best way to deal with other data types.
private static int number = 0;
private static double number = 0;
private static char thing = 0;
Sorry I struggle learning new languages.
Except for initializing String
to an empty string
private static String thing = "";
the other assignments are unnecessary: Java will set all member variables of primitive types to their default values, and all reference types (including java.String
) to null
.
The decision to initialize a String
to a null
or to an empty string is up to you: there is a difference between "nothing" and "empty string" *, so you have to decide which one you want.
* The differences between "nothing" and "empty string" stem from the observation that no operations are possible on a
null
string - for example, its length is undefined, and you cannot iterate over its characters. In contrast, the length of an empty string is well-defined (zero), and you can iterate over its characters (it's an empty iteration).
When you make:
private static String ptNo = "";
you are creating a variable ptNo
and making it to refer an object String ""
.
When you make:
private static String ptNo = null;
you are creating a variable, but it doesn't refer to anything.
null
is the reserved constant used in Java to represent a void reference i.e a pointer to nothing.
In Java null and an empty are not the same thing.
From suns java tutorial
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it
is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
"" is an actual string with empty value.
null means that the String variable points to nothing.
As an example,
String a="";
String b=null;
a.equals(b) returns false because "" and null do not occupy the same space in memory.