Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why instantiate variables with a null value

In many pieces of example code I see variables instatiated with null values and later assigned more meaningful values.

I was just wondering why people may do this. I'm guessing try-catch blocks may well come into this, but I also see variables instantiated will null values inside of a try block.

(I'm sure this is a fairly language agnostic question, but just for reference I program almost entirely in Java)

All insights appreciated!

like image 859
QuakerOat Avatar asked Nov 04 '10 17:11

QuakerOat


People also ask

Why would you set a variable to null?

You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value. In the above example, null is assigned to a variable myVar. It means we have defined a variable but have not assigned any value yet, so value is absence.

What does it mean if a variable has a null value?

You can think of NULL as an unknown or empty value. A variable is NULL until you assign a value or an object to it. This can be important because there are some commands that require a value and generate errors if the value is NULL.

What is the purpose of nulls?

A NULL value is a special marker used in SQL to indicate that a data value does not exist in the database. In other words, it is just a placeholder to denote values that are missing or that we do not know. NULL can be confusing and cumbersome at first.

What is the benefit of setting a variable to null when you no longer need it?

Explicitly assigning a null value to variables that are no longer needed helps the garbage collector to identify the parts of memory that can be safely reclaimed.


1 Answers

The Java compiler detects in certain cases if a variable has not been initialized in all possible control flows and prints an error. To avoid these error messages, it's necessary to explicitly initialize the variable.

For example in this case:

  public Integer foo() {
    Integer result;

    if (Math.random() < 0.5) {
      result = 1;
    }

    return result;
  }

The compiler would give this error message: "The local variable result may not have been initialized".

Here is what the Java Language Specification says:

Each local variable (§14.4) and every blank final (§4.5.4) field (§8.3.1.2) must have a definitely assigned value when any access of its value occurs. A Java compiler must carry out a specific conservative flow analysis to make sure that, for every access of a local variable or blank final field f, f is definitely assigned before the access; otherwise a compile-time error must occur.

Note that (in contrast to fields!) local variables are not automatically initialized to null.

like image 97
MForster Avatar answered Sep 19 '22 18:09

MForster