-5

Just a general Java question. Why does the null variable exist? I'm working with some introduction to CS students and one of the most common mistakes is semi-colons where they are not supposed to be. For example

if(isTired());{
    sleep(10);
}

The misplaced semi-colon before the open parenthesis keeps the if statement from working correctly, and I was wondering why the null line did in a Java program. In this example null seems to be a detriment and was wondering when someone would use it when coding.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Ashley
  • 21
  • 1
  • 6

1 Answers1

3

The null statement is useful because there are some places in Java where you want to do nothing. They are not frequent, but they exist. Often they are the 'compulsory' statements that you have to put in as part of a construct. For example, if you want to write a for loop that only terminates on a 'break', then you want there to be nothing in the 'conditional' part of the for:

for (int i=0;;i++) {
  int j = complexCalculation(i);
  if (j<0 && complexCondition(j)) {
    break;
   }
}

If the null statement wasn't allowed, that wouldn't compile. If it was allowed there, but not in other places, that would be inconsistent (and make life more difficult for compiler writers).

The reality is that, once you get to be fairly proficient with the language, errors caused by accidentally adding null statements are rare.

DJClayworth
  • 26,349
  • 9
  • 53
  • 79