Uninitialized Object vs Object Initialized to NULL
Correct, both static and instance members of reference type not explicitly initialized are set to null
by Java. The same rule applies to array members.
From the Java Language Specification, section 4.12.5:
Initial Values of Variables
Every variable in a program must have a value before its value is used:
Each class variable, instance variable, or array component is initialized with a
default value when it is created[...] For all reference types, the default value is
null
.
Note that the above rule excludes local variables: they must be initialized explicitly, otherwise the program will not compile.
Initializing Objects to null or new?
I personally believe it depends on scope. Is object_DTO
used outside that if
statement? In this code example, it might be useful to use null
.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Note that unless except in certain cases (IoC)
// this scenario is quite easy to avoid
Object_DTO object_DTO = null;
if(request.getParameter("parameter").equals("hello")) {
object_DTO = new Object_DTO();
object_DTO.setAttr("attr");
...
} else if (request.getParameter("parameter").equals("goodbye")) {
object_DTO = new Object_DTO();
}
if (object_DTO == null) {
// Bad response
}
}
Otherwise, always try to use the most limited scope for a variable, but performance-wise this is minor.
On a seperate performance note, however, I would stop calling getParameter()
repeatedly. Assign it to a String and refer to that instead:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String parameter = request.getParameter("parameter");
if (parameter.equals("hello")) {
Object_DTO = new Object_DTO();
...
}
}
Uninitialized object is not null AND return in constructor
Answer to your first question:
Since this 'a' is a local variable they are in undefined states if not explicitly defined.Only instance variables are assigned null as the default value. This is why you get the above mentioned compilation error.
Please refer to oracle documentation here for more information.
The compiler will assign a reasonable default value for fields of the above types;
for local variables, a default value is never assigned
Answer to the second question:
In constructor you can only write return to stop execution. You can't write return with some value. It basically implies that the function will finish processing the current routine and will return to the calling routine.
What happens to a declared, uninitialized variable in Java?
How exactly a JVM does this is entirely up to the JVM and shouldn't matter for a programmer, since the compiler ensures that you do not read uninitialized local variables.
Fields however are different. They need not be assigned before reading them (unless they are final
) and the value of a field that has not been assigned is null
for reference types or the 0
value of the appropriate primitive type, if the field has a primitive type.
Using s.isEmpty()
for a field String s;
that has not been assigned results in a NullPointerException
.
So as I see now, it makes a big difference if the variable is declared
locally
or in theClass
, though I seem to be unable to understand why when declaring in the class it gives no error, but when declaring in the main it produces the"Not Initialized"
error.
In general it's undesirable to work with values that do not have a value. For this reason the language designers had 2 choices:
a) define a default value for variables not yet initialized
b) prevent the programmers from accessing the variable before writing to them.
b) is hard to achieve for fields and therefore option a) was chosen for fields. (There could be multiple methods reading/writing that could be valid or invalid depending on the order of calls, which could only be determined at runtime).
For local variables option b) is viable, since all possible paths of the execution of the method can be checked for assignment statements. This option was chosen during the language design for local variables, since it can help to find many easy mistakes.
What's the difference between non-initialisation and initialising to null?
- fields (member-variables) are initialized to
null
(or to a default primitive value, if they are primitives) - local variables are not initialized and you are responsible for setting the initial value.
Do I need to initialize a java object reference to null like I do in c++
Local variables must be initialized before the compiler will allow you to use them (therefore, as Marko Topolnik commented, it is impossible to dereference an unitialized reference). Member variables (instance fields or static fields), on the other hand, are automatically initialized to null
(references), 0 (primitive number types) or false
(boolean
) if you don't explicitly initialize them.
Why is null an object and what's the difference between null and undefined?
(name is undefined)
You: What is name
? (*)
JavaScript: name
? What's a name
? I don't know what you're talking about. You haven't ever mentioned any name
before. Are you seeing some other scripting language on the (client-)side?
name = null;
You: What is name
?
JavaScript: I don't know.
In short; undefined
is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null
is where the thing is known to exist, but it's not known what the value is.
One thing to remember is that null
is not, conceptually, the same as false
or ""
or such, even if they equate after type casting, i.e.
name = false;
You: What is name
?
JavaScript: Boolean false.
name = '';
You: What is name
?
JavaScript: Empty string
*: name
in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.
Objective-C uninitialized pointers vs null pointers
Instance variables of objects are initialized to nil
in alloc
(the whole object is bzeroed).
Edit:
Also, global and static storage variables are initialized to zero (6.7.8 10 of the C99 Standard, thanks Derek for pointing that out).
Local stack variables are not initialized automatically. This did not change in known history.
Related Topics
Preparedstatement Syntax Error
How to Get a Random Line of a Text File in Java
Advantage of Set and Get Methods VS Public Variable
How to Pass an Integer Class Correctly by Reference
Converting to Upper and Lower Case in Java
Constantly Update UI in Java Fx Worker Thread
How to Change Background Color of Jtabbedpane
Service Layer and Controller: Who Takes Care of What
Java 8 Streams - Collect VS Reduce
Automated Tests for Java Swing Guis
What Is the Point of Getters and Setters
Java: Get Month Integer from Date
How to Retrieve the Autoincrement Id from a Prepared Statement
Java Serialization - Java.Io.Invalidclassexception Local Class Incompatible
Java.Lang.Noclassdeffounderror: Org.Slf4J.Loggerfactory
In Java, How to Call a Base Class's Method from the Overriding Method in a Derived Class