Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising instance variables as null, "" or 0

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.


2 Answers

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).
like image 174
Sergey Kalinichenko Avatar answered Nov 26 '25 16:11

Sergey Kalinichenko


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.

like image 36
Christian Tapia Avatar answered Nov 26 '25 16:11

Christian Tapia