Undefined values: Difference between revisions
Content added Content deleted
(Added R code) |
No edit summary |
||
Line 115: | Line 115: | ||
nc;:'foo bar' |
nc;:'foo bar' |
||
_1 0</lang> |
_1 0</lang> |
||
=={{header|Java}}== |
|||
In Java there are two kinds of types: primitive types and reference types. The former are predefined in the language (eg. <code>boolean</code>, <code>int</code>, <code>long</code>, <code>double</code>, &c), while the latter are pointers to objects (class instances or arrays). |
|||
Java has a special null type, the type of the expression <code>null</code>, that can be cast to any reference type; in practice the null type can be ignored and <code>null</code> can be treated as a special literal that can be of any reference type. When a reference variable has the special value <code>null</code> it refers to no object, meaning that it is undefined. |
|||
<lang java>String string = null; // the variable string is undefined |
|||
System.out.println(string); // dereferencing null throws java.lang.NullPointerException</lang> |
|||
Variables of primitive types cannot be assigned the special value <code>null</code>, but there are wrapper classes corresponding to the primitive types (eg. <code>Boolean</code>, <code>Integer</code>, <code>Long</code>, <code>Double</code>, &c), that can be used instead of the corresponding primitive; since they can have the special value <code>null</code> it can be used to identify the variable as undefined. |
|||
<lang java>int i = null; // compilation error: incompatible types, required: int, found: <nulltype> |
|||
if (i == null) { // compilation error: incomparable types: int and <nulltype> |
|||
i = 1; |
|||
}</lang> |
|||
But this piece of code can be made valid by replacing <code>int</code> with <code>Integer</code>, and thanks to the automatic conversion between primitive types and their wrapper classes (called autoboxing) the only change required is in the declaration of the variable: |
|||
<lang java>Integer i = null; // variable i is undefined |
|||
if (i == null) { |
|||
i = 1; |
|||
}</java> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 426: | Line 445: | ||
Done |
Done |
||
</pre> |
</pre> |
||
{{omit from|Java|everything is null or defined}} |