Null object: Difference between revisions

19,982 bytes added ,  2 months ago
mNo edit summary
(20 intermediate revisions by 11 users not shown)
Line 15:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F f([Int]? &a)
I a != N
a.append(1)
Line 22:
[Int] arr
f(&arr)
print(arr)</langsyntaxhighlight>
 
{{out}}
Line 28:
[1]
</pre>
 
=={{header|6502 Assembly}}==
{{trans|Z80 Assembly}}
 
Technically there is no such thing as a null pointer; all pointers point to ''something.'' It's a matter of what you're willing to give up. Often the null pointer is thought of as memory address 0, and on many CPUs this is the case - however this is most assuredly '''not''' the case on the 6502. Reason being, zero page RAM is limited and quite valuable, given that there are only 256 bytes of it and it is much more efficient to access than regular memory. As such, declaring <code>$0000</code> to be the null pointer would be a very poor choice. Ideally, the null pointer on a 6502 should:
* Be somewhere that isn't zero page RAM
* Be somewhere that we cannot change at runtime (e.g. read-only memory) or doing so would cause major problems (the vector table)
* Point to something that has no value to the programmer.
 
 
We can choose quite a few places, the easiest one I can think of is <code>$FFFF</code>. Although it sort of breaks our first rule, as when dereferenced as a 16-bit value, you get the value stored at <code>$0000</code> as the high byte, we still can access <code>$0000</code> normally anyway. Since it points to the high byte of the interrupt request vector, it's something we don't want to (or most likely can't) modify at runtime, and is of no use to us (if we really wanted the IRQ handler's address we'd dereference <code>$FFFE</code> instead.)
 
How a null pointer is implemented is very simple. You decide beforehand what your null pointer will be, and before you dereference a pointer variable, compare it to the null pointer, and if they're equal, don't dereference it. That's all there is to it.
 
<syntaxhighlight lang="6502asm">lda pointer ;a zero-page address that holds the low byte of a pointer variable.
CMP #$FF
BNE .continue
lda pointer+1
CMP #$FF
BNE .continue
RTS ;return without doing anything
.continue</syntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
null? if "item was null" . then
</syntaxhighlight>
</lang>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program nullobj64.s */
Line 83 ⟶ 105:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">TYPE Object=[
BYTE byteData
INT intData
Line 104 ⟶ 126:
IsNull(ptr1)
IsNull(ptr2)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Null_object.png Screenshot from Atari 8-bit computer]
Line 113 ⟶ 135:
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">if (object == null)
trace("object is null");</langsyntaxhighlight>
 
ActionScript also has an '''undefined''' value: see [[Undefined values#ActionScript]].
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io;
 
if Object = null then
Ada.Text_Io.Put_line("object is null");
end if;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 132 ⟶ 154:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">REF STRING no result = NIL;
STRING result := "";
Line 150 ⟶ 172:
REF STRING var := NIL;
IF var ISNT NIL THEN print(("The address of var ISNT NIL",new line)) FI;
IF var IS REF STRING(NIL) THEN print(("The address of var IS REF STRING(NIL)",new line)) FI</langsyntaxhighlight>
Output:
<pre>
Line 175 ⟶ 197:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% declare a record type - will be accessed via references %
record R( integer f1, f2, f3 );
Line 184 ⟶ 206:
% test for a null reference - will write "refR is null" %
if refR = null then write( "refR is null" ) else write( "not null" );
end.</langsyntaxhighlight>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">DEF x : PTR TO object
-> ...
IF object <> NIL
-> ...
ENDIF</langsyntaxhighlight>
 
=={{header|APL}}==
APL is a vector/array-based language, so rather than a 'null pointer' or 'null value' there is the 'null vector'.
<syntaxhighlight lang="apl">
<lang APL>
⍝⍝ GNU APL
]help ⍬
Line 204 ⟶ 226:
⍬≡⍳0
1
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
Many applications will return <code>missing value</code>, but <code>null</code> is also available.
<langsyntaxhighlight AppleScriptlang="applescript">if x is missing value then
display dialog "x is missing value"
end if
Line 214 ⟶ 236:
if x is null then
display dialog "x is null"
end if</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 281 ⟶ 303:
bx lr @ return
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">v: null
if v=null -> print "got NULL!"</langsyntaxhighlight>
 
{{out}}
Line 293 ⟶ 315:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">If (object == null)
MsgBox, object is null</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">Local $object = Null
If $object = Null Then MsgBox(0, "NULL", "Object is null")</langsyntaxhighlight>
 
=={{header|AWK}}==
Undefined elements correspond to an empty string; when converted to a numerical value, it evaluates to 0. In order to distinguish a undefined value from a value of 0, length(var) need to be used.
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
BEGIN {
b=0;
Line 308 ⟶ 330:
print "<"u,length(u)">"
print "<"u+0,length(u+0)">";
}</langsyntaxhighlight>
Output
<pre><0 1>
Line 316 ⟶ 338:
=={{header|Axe}}==
Null pointers can be checked by simply comparing the pointer with 0.
<langsyntaxhighlight lang="axe">If P=0
Disp "NULL PTR",i
End</langsyntaxhighlight>
 
=={{header|Babel}}==
In this example, we place nil on the stack, then perform an if-then-else (ifte) based on the value returned by the 'nil?' operator which returns true if top-of-stack (TOS) is nil. If TOS is nil, then we can be relieved, otherwise, the interpreter has gone absolutely haywire. The '<<' operator prints the selected string to STDOUT.
<langsyntaxhighlight lang="babel">{ nil { nil? } { "Whew!\n" } { "Something is terribly wrong!\n" } ifte << }</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 331 ⟶ 353:
 
Applesoft has no built-in object system. The closest values to NULL or nil for each of the types are 0 for integers and floating point numbers, and "" for strings. There is also the NUL character: CHR$(0). One could create an object system using global variables and include a special value for NULL, but this is probably a mistake.
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">TRUE = 1 : FALSE = 0
NULL = TRUE
IF NULL THEN PRINT "NULL"
NULL = FALSE
IF NOT NULL THEN PRINT "NOT NULL"</langsyntaxhighlight>'''Output:'''<pre>NULL
NOT NULL</pre>
 
Line 341 ⟶ 363:
{{works with|BBC BASIC for Windows}}
A null object has a pointer with a value of zero or one.
<langsyntaxhighlight lang="bbcbasic"> PROCtestobjects
END
Line 353 ⟶ 375:
IF !^s{} <= 1 PRINT "s{} is null" ELSE PRINT "s{} is not null"
IF !^t{} <= 1 PRINT "t{} is null" ELSE PRINT "t{} is not null"
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 365 ⟶ 387:
These dialects of BASIC have no built-in object system. One STRING variable can have a default empty ("") value and a numeric one a default zero (0) value. A STRING variable can be assigned with the NULL (Chr$(0)) value if needed and can be assesed with the instruction.
 
<syntaxhighlight lang="basic">
<lang BASIC>
IF VAR$ = CHR$(0) THEN PRINT "Variable has a null value."
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
Line 374 ⟶ 396:
The operators for multiplication, addition and concatenation have neutral elements, which are <code>1</code>, <code>0</code> and the empty string, respectively, but these are values like any other string.
 
<langsyntaxhighlight lang="bracmat">
a:?x*a*?z {assigns 1 to x and to z}
a:?x+a+?z {assigns 0 to x and to z}
a:?x a ?z {assigns "" (or (), which is equivalent) to x and to z}
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Line 387 ⟶ 409:
The standard library defines NULL in locale.h, stddef.h, stdio.h, stdlib.h, string.h, time.h and wchar.h. [[POSIX]] systems also define NULL in dirent.h and unistd.h. Many C files include at least one of these headers, so NULL is almost always available.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main()
Line 397 ⟶ 419:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
As with Java, any reference type may be null, and testing for nullity uses ordinary boolean operators.
<langsyntaxhighlight lang="csharp">if (foo == null)
Console.WriteLine("foo is null");</langsyntaxhighlight>
 
C# 2.0 introduced nullable types for situations in which even primitive value types may have undefined or unknown values (for example, when reading from a database). Prior to the introduction of nullable types, these situations would require writing wrapper classes or casting to a reference type (e.g., object), incurring the penalties of boxing and reduced type safety. A variable with nullable type can be declared simply by adding the '?' operator after the type.
 
{{works with|C sharp|C#|2.0+}}
<langsyntaxhighlight lang="csharp">int? x = 12;
x = null;</langsyntaxhighlight>
 
Also new in C# 2.0 was the null coalescing operator, '??', which is simply syntactic sugar allowing a default value to replace an operand if the operand is null:
 
{{works with|C sharp|C#|2.0+}}
<langsyntaxhighlight lang="csharp">Console.WriteLine(name ?? "Name not specified");
 
//Without the null coalescing operator, this would instead be written as:
Line 420 ⟶ 442:
//}else{
// Console.WriteLine(name);
//}</langsyntaxhighlight>
 
=={{header|C++}}==
In C++ non-pointer types do not support null. (C++ provides value semantics rather than reference semantics). When using pointers C++ permits checking for null by comparing the pointer to a literal of 0, or (as in C) by way of a macro (NULL) which simply expands to 0.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cstdlib>
if (object == 0) {
std::cout << "object is null";
}</langsyntaxhighlight>
 
std::optional is available since C++17 (or Boost's boost::optional via boost/optional.hpp for earlier standards) for cases where the programmer wishes to pass by value, but still support a null value.
 
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <optional>
Line 445 ⟶ 467:
std::cout << "object is null\n";
}
</syntaxhighlight>
</lang>
 
===C++11===
 
In C++11 there is <code>nullptr</code> of type <code>nullptr_t</code> which represents a pointer to an invalid place. You can use it like
<langsyntaxhighlight lang="cpp">
int *p = nullptr;
...
Line 460 ⟶ 482:
// do some thing
}
</syntaxhighlight>
</lang>
 
=={{header|Chapel}}==
 
Objects variables without an initializer expression will be initiallized to nil:
<langsyntaxhighlight lang="chapel">class C { };
var c:C; // is nil
writeln(if c == nil then "nil" else "something");</langsyntaxhighlight>
 
=={{header|Clojure}}==
Clojure's <code>nil</code> is equivalent to Java's <code>null</code>.
 
<langsyntaxhighlight lang="lisp">(let [x nil]
(println "Object is" (if (nil? x) "nil" "not nil")))</langsyntaxhighlight>
 
Test wether symbol <code>foo</code> is defined:
 
<langsyntaxhighlight lang="lisp">(find (ns-interns *ns*) 'foo)</langsyntaxhighlight>
 
Undefining <code>foo</code>:
 
<langsyntaxhighlight lang="lisp">(ns-unmap *ns* 'foo)</langsyntaxhighlight>
 
=={{header|COBOL}}==
Works with GnuCOBOL 2.0
 
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. null-objects.
remarks. test with cobc -x -j null-objects.cob
Line 528 ⟶ 550:
end-if
goback.
end program test-null.</langsyntaxhighlight>
 
{{out}}
Line 543 ⟶ 565:
Common Lisp has an object denoted by the symbol <code>nil</code>. When the symbol <code>nil</code> is evaluated as an expression, it evaluates to itself.
 
<code>nil</code> uniquely represents boolean false, and so code like <langsyntaxhighlight lang="lisp">(if (condition) (do-this))</langsyntaxhighlight> is actually testing whether <code>(condition)</code> returns the value <code>nil</code>. The object <code>nil</code> is also used to denote the empty list which also terminates other lists. The value is also used as a default when some function returns fewer values than expected. <code>(list (values))</code> produces <code>(nil)</code> (list containing one element, which is the empty list), because <code>(values)</code> produces no value, but the function call <code>(list ...)</code> needs to reduce the expression to a single argument value, and so <code>nil</code> is supplied.
 
====Beginnings of Null Object====
Line 562 ⟶ 584:
Suppose that the <code>car</code> function did not have a safe defaulting behavior for <code>nil</code>. We could use the methods of the object system to define a <code>car*</code> which does have the safe behavior:
 
<langsyntaxhighlight lang="lisp">(defmethod car* ((arg cons))
(car arg))
 
(defmethod car* ((arg null))
nil)</langsyntaxhighlight>
 
Now if we invoke <code>car*</code> on something which is neither a cons, nor <code>nil</code>, we get an error about no applicable method being found.
Line 572 ⟶ 594:
We can handle that ourselves by writing a method specialized to the master supertype <code>t</code>:
 
<langsyntaxhighlight lang="lisp">(defmethod car* ((arg t)) ;; can just be written (defmethod car* (arg) ...)
(error "CAR*: ~s is neither a cons nor nil" arg))</langsyntaxhighlight>
 
The classes <code>t</code> and <code>null</code> are widely exploited in Lisp OO programming.
 
=={{header|Component Pascal}}==
<syntaxhighlight lang="oberon2">
<lang Oberon2>
MODULE ObjectNil;
IMPORT StdLog;
Line 596 ⟶ 618:
 
END ObjectNil.
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
In Crystal, nil is represented by an instance of the Nil type, accessed by the identifier <code>nil</code>. A variable can only become nil if Nil is one of its possible types. All objects inheriting from the base Object class implement the method <code>.nil?</code> which returns true if the object is nil and false if it isn't. The equality and case equality operators can also be used to check for nil. The compiler returns an error if an object may be nil but is not treated as such. This can be suppressed with the <code>.not_nil!</code> method, which throws an exception at runtime if the object is in fact nil.
<langsyntaxhighlight lang="crystal">foo : Int32 | Nil = 5 # this variable's type can be Int32 or Nil
bar : Int32? = nil # equivalent type to above, but shorter syntax
baz : Int32 = 5 # this variable can never be nil
Line 613 ⟶ 635:
puts "Is bar equivalent to nil? #{bar === nil}"
 
bar.not_nil! # bar is nil, so an exception is thrown</langsyntaxhighlight>
{{out}}
<pre>Is foo nil? false
Line 625 ⟶ 647:
=={{header|D}}==
In D ''is'' is used to perform bitwise identity, like to compare an object reference against null.
<langsyntaxhighlight lang="d">import std.stdio;
 
class K {}
Line 636 ⟶ 658:
if (k !is null)
writeln("Now k is not null");
}</langsyntaxhighlight>
{{out}}
<pre>k is null
Line 642 ⟶ 664:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi"> // the following are equivalent
if lObject = nil then
...
if not Assigned(lObject) then
...</langsyntaxhighlight>
 
=={{header|DWScript}}==
Line 656 ⟶ 678:
Dyalect has a notion of <code>nil</code> - a special sigleton value which can be used in the cases when no other meaningful value can be provided.
 
<langsyntaxhighlight lang="dyalect">var x = nil
if x == nil {
//Do something
}</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
There isn't an actual null object, so generally falsy objects are used to indicate a missing value, or when that's impractical a specific ident:
<langsyntaxhighlight lang="dejavu">if not obj:
pass #obj is seen as null
 
if = :nil obj:
pass #obj is seen as null</langsyntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">object == null</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
The null object - '''null''' - is the same as the empty list (). It may be tested with the '''null?''' or '''!null?''' predicates. NB : null is not the same as the boolean #f (false). null evaluates to #t (true) in logical operations.
 
<langsyntaxhighlight lang="lisp">
null → null
() → null
Line 692 ⟶ 714:
 
(f '( a b c)) → a b c
</syntaxhighlight>
</lang>
 
=={{header|Ecstasy}}==
In Ecstasy, everything is an object, including the <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span> value. <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span> is the only value in the [https://github.com/xtclang/xvm/blob/dd32c2eba0930c4a59f4ba7507c6af37818d255c/lib_ecstasy/src/main/x/ecstasy.x#L21 <span style="background-color: #e5e4e2"><tt>&nbsp;Nullable&nbsp;</tt></span> enumeration defined in the "<tt>ecstasy</tt>" core module]. As a regular old object, the <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span> value has a regular old class, a regular old type, and it implements regular old methods such as <span style="background-color: #e5e4e2"><tt>&nbsp;toString()&nbsp;</tt></span>. There are, however, a few specific ways in the language (both the compiler and runtime) that <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span> is treated specially:
 
<ul><li>Syntax support: A type union with <span style="background-color: #e5e4e2"><tt>&nbsp;Nullable&nbsp;</tt></span> can be indicated with the postfix "?"; for example, the long-hand type union syntax <span style="background-color: #e5e4e2"><tt>&nbsp;Nullable|String s&nbsp;</tt></span> can be replaced using the short-hand notation <span style="background-color: #e5e4e2"><tt>&nbsp;String? s&nbsp;</tt></span>.
</li><li>Syntax support: The postfix "?" operator is a short-circuiting null value test, allowing a cascading sequence of null tests to replace a series of nested if statements; for example, <span style="background-color: #e5e4e2"><tt>&nbsp;Int x = a?.b()?.c?[i?].d? : e;&nbsp;</tt></span> will result in the value of <span style="background-color: #e5e4e2"><tt>&nbsp;e&nbsp;</tt></span> if any of the expressions <span style="background-color: #e5e4e2"><tt>&nbsp;a&nbsp;</tt></span>, <span style="background-color: #e5e4e2"><tt>&nbsp;a.b()&nbsp;</tt></span>, <span style="background-color: #e5e4e2"><tt>&nbsp;a.b().c&nbsp;</tt></span>, <span style="background-color: #e5e4e2"><tt>&nbsp;i&nbsp;</tt></span>, or <span style="background-color: #e5e4e2"><tt>&nbsp;a.b().c[i].d&nbsp;</tt></span> are <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span>.
</li><li>Syntax support: The expression <span style="background-color: #e5e4e2"><tt>&nbsp;x ?: y&nbsp;</tt></span> will use the value <span style="background-color: #e5e4e2"><tt>&nbsp;y&nbsp;</tt></span> iff <span style="background-color: #e5e4e2"><tt>&nbsp;x&nbsp;</tt></span> is <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span>, and the corresponding assignment statement <span style="background-color: #e5e4e2"><tt>&nbsp;x ?:= y&nbsp;</tt></span> will assign <span style="background-color: #e5e4e2"><tt>&nbsp;y&nbsp;</tt></span> to <span style="background-color: #e5e4e2"><tt>&nbsp;x&nbsp;</tt></span> iff <span style="background-color: #e5e4e2"><tt>&nbsp;x&nbsp;</tt></span> is <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span>.
</li><li>Syntax support: The assignment statement <span style="background-color: #e5e4e2"><tt>&nbsp;x ?= y&nbsp;</tt></span> will assign <span style="background-color: #e5e4e2"><tt>&nbsp;y&nbsp;</tt></span> to <span style="background-color: #e5e4e2"><tt>&nbsp;x&nbsp;</tt></span> iff <span style="background-color: #e5e4e2"><tt>&nbsp;y&nbsp;</tt></span> is <b>not</b> <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span>.
</li><li>The assignment operator <span style="background-color: #e5e4e2"><tt>&nbsp;?=&nbsp;</tt></span> also yields a <span style="background-color: #e5e4e2"><tt>&nbsp;Boolean&nbsp;</tt></span> value indicating the <b>non-</b>null-ness the right hand side value, which can be used in an <span style="background-color: #e5e4e2"><tt>&nbsp;if&nbsp;</tt></span> condition, <span style="background-color: #e5e4e2"><tt>&nbsp;while&nbsp;</tt></span> condition, etc.; for example, <span style="background-color: #e5e4e2"><tt>&nbsp;if (x ?= y) ...&nbsp;</tt></span> will take the "then" branch if <span style="background-color: #e5e4e2"><tt>&nbsp;y&nbsp;</tt></span> is non-null and therefore <span style="background-color: #e5e4e2"><tt>&nbsp;x&nbsp;</tt></span> is definitely assigned, otherwise it will take the "else" branch and <span style="background-color: #e5e4e2"><tt>&nbsp;x&nbsp;</tt></span> will not be definitely assigned.
</li><li><span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span> values are treated specially by equality comparisons: Normally, the compiler prevents two references of different compile-time types from being compared (such as <span style="background-color: #e5e4e2"><tt>&nbsp;Int&nbsp;</tt></span> and <span style="background-color: #e5e4e2"><tt>&nbsp;String&nbsp;</tt></span>), but an explicit exception is made that allows a nullable type to be compared with a non-nullable type (such as <span style="background-color: #e5e4e2"><tt>&nbsp;String?&nbsp;</tt></span> and <span style="background-color: #e5e4e2"><tt>&nbsp;String&nbsp;</tt></span>).
</li></ul>
Other than these specific compiler and runtime features, <span style="background-color: #e5e4e2"><tt>&nbsp;Null&nbsp;</tt></span> is treated exactly like every other object.
 
 
<syntaxhighlight lang="java">
module NullObject {
void run() {
@Inject Console console;
console.print($"Null value={Null}, Null.toString()={Null.toString()}");
 
// String s = Null; // <-- compiler error: cannot assign Null to a String type
String? s = Null; // "String?" is shorthand for the union "Nullable|String"
String s2 = "test";
console.print($"{s=}, {s2=}, {s==s2=}");
 
// Int len = s.size; // <-- compiler error: String? does not have a "size" property
Int len = s?.size : 0;
console.print($"{len=}");
 
if (String test ?= s) {
// "s" is still Null in this test, we never get here
} else {
s = "a non-null value";
}
 
// if (String test ?= s){} // <-- compiler error: The expression type is not nullable
s2 = s; // at this point, s is known to be a non-null String
console.print($"{s=}, {s2=}, {s==s2=}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
Null value=Null, Null.toString()=Null
s=Null, s2=test, s==s2=False
len=0
s=a non-null value, s2=a non-null value, s==s2=True
</pre>
 
=={{header|Eiffel}}==
Any reference type variable can be Void. In the following example, STRING is a reference type, while INTEGER is an expanded type. The keyword "detachable" (as opposed to "attached") is used to indicate that the variable "s" may be Void. The default interpretation when neither of these two keywords is used depends on a compiler option. The first if statement will cause a compiler warning because an expanded type variable such as i will never be Void.
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 718 ⟶ 789:
end
end
end</langsyntaxhighlight>
{{out}}<pre>s = Void</pre>
 
=={{header|Elixir}}==
<code>nil</code> is atom in fact:
<langsyntaxhighlight lang="elixir">iex(1)> nil == :nil
true
iex(2)> is_nil(nil)
true</langsyntaxhighlight>
<code>nil</code> is thought of as being <code>false</code> in the conditional expression.
 
If the condition given to <code>if/2</code> returns <code>false</code> or <code>nil</code>, the body given between <code>do</code>/<code>end</code> is not executed and it simply returns <code>nil</code>.
<langsyntaxhighlight lang="elixir">iex(3)> if nil, do: "not execute"
nil</langsyntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|
| EMal has the Variable type (and its keyword var) that is the nullable universal supertype.
| EMal has the Void type (and its keyword void) that holds only one value: null.
| EMal has not nullable types (logic, int, real, text, blob), but null equality is always allowed.
|^
var a # defaults to null
int b # defaults to 0
void c # only one allowed value: null
writeLine("nullable var equals to not nullable int: " + (a == b)) # allowed, false
^| if the data type of a is void we are sure that a is null |^
writeLine("type of a equals to Void data type: " + (generic!a == void)) # true
writeLine("integer value " + b + " equals to null: " + (b == null)) # allowed, always false
writeLine("a void value equals to null: " + (c == null)) # always true</syntaxhighlight>
{{out}}
<pre>
nullable var equals to not nullable int: ⊥
type of a equals to Void data type: ⊤
integer value 0 equals to null: ⊥
a void value equals to null: ⊤
</pre>
 
=={{header|Erlang}}==
Line 757 ⟶ 851:
Other than in interfacing assemblies written in other .Net languages, null rarely serves a purpose in F# code.
Contrived code, to show using null, as per task description:
<langsyntaxhighlight lang="fsharp">let sl : string list = [null; "abc"]
 
let f s =
Line 764 ⟶ 858:
| _ -> "It's non-null: " + s
 
for s in sl do printfn "%s" (f s)</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: is-f? ( obj -- ? ) f = ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 773 ⟶ 867:
Test for equality with 'null', which is the null value.
 
<langsyntaxhighlight lang="fantom">
fansh> x := null
fansh> x == null
Line 781 ⟶ 875:
fansh> x == null
false
</syntaxhighlight>
</lang>
 
Note, nullable objects have a type ending in a question mark, for example:
Line 795 ⟶ 889:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">'FB 1.05.0 Win64
 
' FreeBASIC does not have a NULL keyword but it's possible to create one using a macro
Line 814 ⟶ 908:
 
' in practice many FB developers would simply have written: d = 0 above
Sleep</langsyntaxhighlight>
 
{{out}}
<pre>
Rover 5
</pre>
 
 
 
=={{header|FutureBasic}}==
While objects such as strings can be NULL in FB, arrays, dictionaries and other collections cannot contain NULL objects.
<syntaxhighlight lang="futurebasic">
// Object dimensioned, but not assigned
CFStringRef object
 
if ( object == NULL )
print "object is NULL"
end if
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
object is NULL
</pre>
 
=={{header|GDScript}}==
Godot has a null value. Here is an example of dealing with null.
<syntaxhighlight lang="gdscript">
extends Node2D
 
func _ready() -> void:
var empty : Object
var not_empty = Object.new()
# Compare with null.
if empty == null:
print("empty is null")
else:
print("empty is not null")
# C-like comparation.
if not_empty:
print("not_empty is not null")
else:
print("not_empty is null")
return
</syntaxhighlight>
{{out}}
<pre>
empty is null
not_empty is not null
</pre>
 
=={{header|Go}}==
Nil is a predefined identifier, defined for six types in Go. In each case, it represents the zero value for the type, that is, the memory representation of all zero bytes. This is the value of a newly created object. In the cases of these six types, an object must be subsequently initialized in some way before it has much use. Examples of initialization are given in the [[Undefined values#Go|Go solution]] of task [[Undefined values]].
<syntaxhighlight lang="go">
<lang go>
package main
 
Line 845 ⟶ 986:
fmt.Println(c == nil)
}
</syntaxhighlight>
</lang>
Output is "true" in each case.
 
Line 852 ⟶ 993:
Haskell does not have a universal null value. There is a 'value of every type', the undefined value (sometimes written ⊥, 'bottom'), but it is essentially a sort of exception — any attempt to use it is an error.
 
<langsyntaxhighlight lang="haskell">undefined -- undefined value provided by the standard library
error "oops" -- another undefined value
head [] -- undefined, you can't take the head of an empty list</langsyntaxhighlight>
 
When one would use "null" as a marker for "there is no normal value here" (e.g. a field which is either an integer or null), one uses the Maybe type instead. The definition of Maybe is:
 
<langsyntaxhighlight lang="haskell"> data Maybe a = Nothing | Just a</langsyntaxhighlight>
 
That is, a <tt>Maybe Integer</tt> is either <tt>Nothing</tt> or <tt>Just </tt>&lt;some integer&gt;.
Line 864 ⟶ 1,005:
There are many ways to work with Maybe, but here's a basic case expression:
 
<langsyntaxhighlight lang="haskell">case thing of
Nothing -> "It's Nothing. Or null, whatever."
Just v -> "It's not Nothing; it is " ++ show v ++ "."</langsyntaxhighlight>
 
It is easy to work with Maybe type using do-notation (since Maybe is a monad):
<langsyntaxhighlight lang="haskell">add_two_maybe_numbers x y do
a <- x
b <- y
return (a+b)</langsyntaxhighlight>
Then
<langsyntaxhighlight lang="haskell">*Main> add_two_maybe_numbers (Just 2) (Just 3)
Just 5
*Main> add_two_maybe_numbers (Just 2) Nothing
Nothing</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon/Unicon have a [[Icon%2BUnicon/Intro#null|null value/datatype]]. It isn't possible to undefine a variable.
 
<langsyntaxhighlight Iconlang="icon">procedure main()
nulltest("a",a) # unassigned variables are null by default
nulltest("b",b := &null) # explicit assignment is possible
Line 891 ⟶ 1,032:
procedure nulltest(name,var)
return write(name, if /var then " is" else " is not"," null.")
end</langsyntaxhighlight>
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">if(object == nil, "object is nil" println)</langsyntaxhighlight>
 
=={{header|J}}==
Line 903 ⟶ 1,044:
That said, undefined names in J are not associated with any data of any type. Furthermore, any attempt to use the value of an undefined is treated as an error (this is distinct from the concept of an empty array, which contains no data but which is not an error to use). However, it is possible to check if a name is defined before attempting to use it:
 
<langsyntaxhighlight Jlang="j">isUndefined=: _1 = nc@boxxopen</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> isUndefined 'foo'
1
foo=:9
isUndefined 'foo'
0</langsyntaxhighlight>
 
Note, of course, that this "name is not defined" state is not a first class value in J -- you can not create a list of "undefineds".
Line 929 ⟶ 1,070:
That said, note that a typical way to indicate missing or invalid data, in J, is to have a parallel array which is a bit mask (which selects the desired or valid values and, by implication, does not select the invalid values). Or, as a logical equivalent: a list of indices which select the desired and/or valid values. Alternatively, you can have an array without the invalid values and a bit mask which demonstrates how the data would be populated on a larger array -- in other words instead of 3,4,null,5 you could have (3 4 5) and (1 1 0 1). And you can transform between some of these representations:
 
<langsyntaxhighlight lang="j"> 1 1 0 1#3 4 _ 5 NB. use bitmask to select numbers
3 4 5
I.1 1 0 1 NB. get indices for bitmask
Line 940 ⟶ 1,081:
3 4 _ 5
3 4 5 (0 1 3}) _ _ _ _ NB. use indices to restore original positions
3 4 _ 5</langsyntaxhighlight>
 
=={{header|Java}}==
In Java, "null" is a value of every reference type.
<langsyntaxhighlight lang="java">// here "object" is a reference
if (object == null) {
System.out.println("object is null");
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
In Javascript <tt>null</tt> is the value that isn't anything. <tt>null</tt> is not an object, but because of a bug <tt>typeof null</tt> will return "object".
<langsyntaxhighlight lang="javascript">if (object === null) {
alert("object is null");
// The object is nothing
}
 
typeof null === "object"; // This stands since the beginning of JavaScript</langsyntaxhighlight>
 
=={{header|jq}}==
Line 963 ⟶ 1,104:
<tt>null</tt> is distinct from <tt>false</tt>.
Here are some examples:
<langsyntaxhighlight lang="jq">null|type # => "null"
 
null == false # => false
Line 973 ⟶ 1,114:
empty == empty # => # niente
 
empty == "black hole" # => # Ничего</langsyntaxhighlight>
 
=={{header|Jsish}}==
Line 980 ⟶ 1,121:
Jsish, with parameter typed functions, also allows '''void''' as a type spec, to indicate the parameter (of whatever type) may be omitted by a caller.
 
<langsyntaxhighlight lang="javascript">/* null non value */
 
if (thing == null) { puts("thing tests as null"); }
Line 986 ⟶ 1,127:
puts(typeof thing);
puts(typeof null);
puts(typeof undefined);</langsyntaxhighlight>
 
{{out}}
Line 1,007 ⟶ 1,148:
and and missing value ''nil'' :
: Empty expressions in both list expressions and function expressions actually represent a special atomic value called ''nil''. ... A list may contain one or more empty items (i.e. the nil value _n), which are typically indicated by omission:
<syntaxhighlight lang="k">
<lang k>
(1;;2) ~ (1 ; _n ; 2) / ~ is ''identical to'' or ''match'' .
1
Line 1,014 ⟶ 1,155:
 
additional properties : _n@i and _n?i are i; _n`v is _n
</syntaxhighlight>
</lang>
 
For more detail on K's concept of typed nulls, see http://code.kx.com/wiki/Reference/Datatypes#Primitive_Types
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">%t nan !t
$t nan == ?</langsyntaxhighlight>
{{out}}
<pre>1</pre>
Line 1,030 ⟶ 1,171:
 
Here are some examples:
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun main(args: Array<String>) {
Line 1,038 ⟶ 1,179:
println(j)
println(null is Nothing?) // test that null is indeed of type Nothing?
}</langsyntaxhighlight>
 
{{out}}
Line 1,048 ⟶ 1,189:
 
=={{header|langur}}==
Null can be compared for directly, using equality operators, or can be checked with the isNull() function. Operators ending with a ? mark propagate null. A null in an expression test is a non-truthy result.
 
{{works with|langur|0.10}}
Prior to 0.10, multi-variable declaration/assignment would use parentheses around variable names and values.
 
<langsyntaxhighlight lang="langur">val .x, .y = true, null
 
writeln .x == null
Line 1,061 ⟶ 1,199:
 
# null not a "truthy" result
writeln if(null: 0; 1)</langsyntaxhighlight>
 
{{out}}
Line 1,071 ⟶ 1,209:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(x = string, y = null)
#x->isA(::null)
// 0 (false)
Line 1,088 ⟶ 1,226:
 
#y->type == 'null'
//true</langsyntaxhighlight>
 
=={{header|Latitude}}==
 
Nil is an object in Latitude, like any other.
<langsyntaxhighlight lang="latitude">foo := Nil.
if { foo nil?. } then {
putln: "Foo is nil".
} else {
putln: "Foo is not nil".
}.</langsyntaxhighlight>
 
In particular, Nil satisfies the Collection mixin, so it can be treated as an (immutable) collection.
<langsyntaxhighlight lang="latitude">Nil to (Array). ;; []</langsyntaxhighlight>
 
Nil is the default value returned if a method body is empty.
<langsyntaxhighlight lang="latitude">func := {}.
func. ;; Nil</langsyntaxhighlight>
 
=={{header|Lily}}==
Lily doesn't provide a built-in nothing type, but allows one to be created using enum class:
 
<langsyntaxhighlight Lilylang="lily">enum class Option[A] {
Some(A)
None
Line 1,130 ⟶ 1,268:
 
# Invalid! Likewise, w is an integer, not an Option.
w = None</langsyntaxhighlight>
 
=={{header|Lingo}}==
Null/nil is called "<Void>" in Lingo. Lingo doesn't distinguish undefined variables from <Void> objects, and by using the constant VOID you can even assign <Void> to variables. Functions that don't return anything, return <Void>. Checking for <Void> (e.g. by using built-in function voidP) can be used to implement optional function arguments: if voidP() returns TRUE (1) for some argument, a default value can be assigned in the function body.
<langsyntaxhighlight lang="lingo">put _global.doesNotExist
-- <Void>
 
Line 1,145 ⟶ 1,283:
 
put voidP(x)
-- 1</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to test :thing
if empty? :thing [print [list or word is empty]]
end
 
print empty? [] ; true
print empty? "|| ; true</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
isnil = (object == nil)
print(isnil)
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
===For Com Objects===
There is a Nothing to assign to a COM object to released (but time to actually released depends from system). A com pointer can't get another value (only the first value, and the Nothing at the end).
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckWord {
Declare Alfa "WORD.APPLICATION"
Line 1,177 ⟶ 1,315:
}
CheckWord
</syntaxhighlight>
</lang>
===For Containers===
Container's pointers (for arrays, inventories, stack) we have to assign an empty container, there is not a null one.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckContainers {
\\ Arrays (A() and B() are value types)
Line 1,236 ⟶ 1,374:
}
CheckContainers
</syntaxhighlight>
</lang>
===For Groups===
Groups are value types, but we can make reference to them,or pointer to them
Line 1,249 ⟶ 1,387:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
class something {
}
Line 1,279 ⟶ 1,417:
a=pointer() ' same as a->0&
Print a is type null = true
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
In Maple, NULL and () represent the null object.
<langsyntaxhighlight lang="maple">a := NULL;
a :=
is (NULL = ());
Line 1,290 ⟶ 1,428:
print (NULL);
end if;
</syntaxhighlight>
</lang>
A null object is different from an undefined value.
<langsyntaxhighlight lang="maple">b := Array([1, 2, 3, Integer(undefined), 5]);
b := [ 1 2 3 undefined 5 ]
numelems(b);
Line 1,304 ⟶ 1,442:
numelems(b);
4
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica can assign a Null value to a symbol, two examples:
<langsyntaxhighlight Mathematicalang="mathematica">x=Null;</langsyntaxhighlight>
<syntaxhighlight lang="mathematica">x =.
<lang Mathematica>x =.
x = (1 + 2;)
FullForm[x]</langsyntaxhighlight>
Both set x to be Null. To specifically test is something is Null one can use the SameQ function (with infix operator: ===):
<syntaxhighlight lang Mathematica="mathematica">SameQ[x,Null]</langsyntaxhighlight>
Or equivalent:
<langsyntaxhighlight Mathematicalang="mathematica">x===Null</langsyntaxhighlight>
will give back True if and only if x is assigned to be Null. If x is empty (nothing assigned) this will return False.
To test if an object has something assigned (number, list, graphics, null, infinity, symbol, equation, pattern, whatever) one uses ValueQ:
<syntaxhighlight lang="mathematica">x =.;
<lang Mathematica>x =.;
ValueQ[x]
x = 3;
ValueQ[x]</langsyntaxhighlight>
gives:
<syntaxhighlight lang="mathematica">False
<lang Mathematica>False
True</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
The closest think to a NULL element in Matlab/Octave is an empty field or empty string; empty fields in a conditional expression evaluate to false.
<langsyntaxhighlight MATLABlang="matlab">a = []; b='';
isempty(a)
isempty(b)
Line 1,335 ⟶ 1,473:
else,
0
end;</langsyntaxhighlight>
 
<pre>octave:4> a = []; b='';
Line 1,349 ⟶ 1,487:
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">if obj == undefined then print "Obj is undefined"</langsyntaxhighlight>
 
=={{header|min}}==
<syntaxhighlight lang="min">null null? puts!</syntaxhighlight>
{{out}}
<pre>true</pre>
 
=={{header|Modula-3}}==
Line 1,355 ⟶ 1,498:
 
This can lead to errors, if for example you write:
<langsyntaxhighlight lang="modula3">VAR foo := NIL</langsyntaxhighlight>
This (most likely incorrectly) gives foo the type <code>NULL</code>, which can only have the value <code>NIL</code>, so trying to assign it anything else will not work. To overcome this problem, you must specify the reference type when declaring foo:
<langsyntaxhighlight lang="modula3">VAR foo: REF INTEGER := NIL;</langsyntaxhighlight>
<langsyntaxhighlight lang="modula3">IF foo = NIL THEN
IO.Put("Object is nil.\n");
END;</langsyntaxhighlight>
 
=={{header|MUMPS}}==
Line 1,388 ⟶ 1,531:
</table>
<p>Or, by examples (in immediate mode):</p>
<syntaxhighlight lang="mumps">
<lang MUMPS>
CACHE>WRITE $DATA(VARI)
0
Line 1,407 ⟶ 1,550:
<CACHE>W $DATA(VARI)," ",VARI
1 HELLO
</syntaxhighlight>
</lang>
 
=={{header|Nanoquery}}==
{{trans|Ursa}}
<langsyntaxhighlight Nanoquerylang="nanoquery">$x = $null
 
if ($x = $null)
Line 1,417 ⟶ 1,560:
else
println "x is not null"
end if</langsyntaxhighlight>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
<doc>
<p>Neko uses <i>null</i> for undefined variables,
Line 1,431 ⟶ 1,574:
var n = null
if n == null $print("n is null\n")
if $not($istrue(n)) $print("and tests as boolean false\n")</langsyntaxhighlight>
 
=={{header|NetRexx}}==
In NetRexx as in Java, "null" is a value of every reference type.
 
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,442 ⟶ 1,585:
say String.valueOf(robject) -- will report the text "null"
if robject = null then say 'Really, it''s "null"!'
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,450 ⟶ 1,593:
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="newlisp">
#! /usr/local/bin/newlisp
(setq myobject nil)
(println (nil? myobject))
(exit)
</syntaxhighlight>
</lang>
<pre>
true
Line 1,462 ⟶ 1,605:
=={{header|Nim}}==
There is a <code>nil</code> value in Nim, which is the same as a 0. It can be explicitly forbidden as a value:
<langsyntaxhighlight lang="nim">let s: pointer = nil
 
{.experimental: "notnil".}
let ns: pointer not nil = nil # Compile time error</langsyntaxhighlight>
 
The value "nil" can be used for pointers, references (i.e. pointers managed by the garbage collector) and procedures. It was also used for strings and sequences, but this is no longer the case (option <code>--nilseqs:on</code> allows to retrieve the old behavior).
Line 1,471 ⟶ 1,614:
Testing if a pointer “p” is <code>nil</code> can be done either by using <code>==</code> or using the procedure <code>isNil</code>.
 
<langsyntaxhighlight Nimlang="nim">var p: ptr int
if p == nil: echo "it is nil"
if p != nil: echo "it is not nil"
if p.isNil: echo "it is nil"</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{works with|oo2c}}
<langsyntaxhighlight lang="oberon2">
MODULE Null;
IMPORT
Line 1,493 ⟶ 1,636:
IF o = NIL THEN Out.String("o is NIL"); Out.Ln END
END Null.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,501 ⟶ 1,644:
=={{header|Objeck}}==
In Objeck, "Nil" is a value of every reference type.
<syntaxhighlight lang="objeck">
<lang Objeck>
# here "object" is a reference
if(object = Nil) {
"object is null"->PrintLine();
};
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
The value <code>nil</code> is used to indicate that an object pointer (variable of type <code>id</code>) doesn't point to a valid object.
<langsyntaxhighlight lang="objc">// here "object" is an object pointer
if (object == nil) {
NSLog("object is nil");
}</langsyntaxhighlight>
An interesting thing is that in Objective-C, it is possible to send a message to <code>nil</code>, and the program will not crash or raise an exception (nothing will be executed and <code>nil</code> will be returned in place of the usual return value).
<syntaxhighlight lang ="objc">[nil fooBar];</langsyntaxhighlight>
 
Note that <code>nil</code> is distinct from <code>NULL</code>, which is only used for regular C pointers.
Line 1,525 ⟶ 1,668:
=={{header|OCaml}}==
Maybe the closest type of OCaml would be the type option, which is defined like this in the standard library:
<langsyntaxhighlight lang="ocaml">type 'a option = None | Some of 'a</langsyntaxhighlight>
<langsyntaxhighlight lang="ocaml">match v with
| None -> "unbound value"
| Some _ -> "bounded value"</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,536 ⟶ 1,679:
When a method or function is called, all local variables begin with null value.
 
<langsyntaxhighlight Oforthlang="oforth">null isNull
"abcd" isNull
: testNull { | a | a ifNull: [ "Variable value is null" println ] ;</langsyntaxhighlight>
 
=={{header|Ol}}==
Line 1,547 ⟶ 1,690:
=={{header|ooRexx}}==
ooRexx has a special singleton object called .nil that is used to indicate the absence of values in some situations (such as the default values returned from collection objects).
<syntaxhighlight lang="oorexx">
<lang ooRexx>
if a[i] == .nil then say "Item" i "is missing"
</syntaxhighlight>
</lang>
Uninitialized ooRexx variables do not evaluate to .nil, but rather the character string name of the variable (all uppercase). The var() built-in function allows variable validity to be tested:
<langsyntaxhighlight ooRexxlang="oorexx">a=.array~of('A','B')
i=3
if a[i] == .nil then say "Item" i "of array A is missing"
if \var("INPUT") then say "Variable INPUT is not assigned"
if \var("var") then say "Variable" var "is not assigned"</langsyntaxhighlight>
Output:
<pre>Item 3 of array A is missing
Line 1,565 ⟶ 1,708:
===Unbound variables===
If an unbound variable is accessed, the current thread will be suspended:
<langsyntaxhighlight lang="oz">declare
X
in
{Show X+2} %% blocks</langsyntaxhighlight>
If you later assign a value to X in another thread, the original thread will resume and print the result of the addition. This is the basic building block of Oz' [http://c2.com/cgi/wiki?DeclarativeConcurrency declarative concurrency].
===Undefined values===
Line 1,574 ⟶ 1,717:
 
It is also possible to assign a unique "failed" value to a variable. Such a failed value encapsulates an exception. This can be useful in concurrent programming to propagate exceptions across thread boundaries.
<langsyntaxhighlight lang="oz">declare
X = {Value.failed dontTouchMe}
in
{Wait X} %% throws dontTouchMe</langsyntaxhighlight>
 
Sometimes algebraic data types like Haskell's Maybe are simulated using records.
<langsyntaxhighlight lang="oz">declare
X = just("Data")
in
case X of nothing then skip
[] just(Result) then {Show Result}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
GP does not have good facilities for this, but this test suffices for most purposes:
<langsyntaxhighlight lang="parigp">foo!='foo</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,602 ⟶ 1,745:
 
You can check to see if a value is <code>undef</code> by using the <code>defined</code> operator:
<langsyntaxhighlight lang="perl">print defined($x) ? 'Defined' : 'Undefined', ".\n";</langsyntaxhighlight>
From the above discussion, it should be clear that if <code>defined</code> returns false, it does not mean that the variable has not been set; rather, it could be that it was explicitly set to <code>undef</code>.
 
Starting in Perl 5.10, there is also a [http://perldoc.perl.org/perlop.html#C-style-Logical-Defined-Or defined-or] operator in Perl. For example:
<langsyntaxhighlight lang="perl">say $number // "unknown";</langsyntaxhighlight>
prints $number if it is defined (even if it is false) or the string "unknown" otherwise.
 
Line 1,613 ⟶ 1,756:
but if you want a variable that can be a string/sequence or NULL, but not other arbitrary integer/float values, use something like the following user-defined types:
 
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">type</span> <span style="color: #000000;">nullableString</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">o</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004080;">string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">or</span> <span style="color: #000000;">o</span><span style="color: #0000FF;">=</span><span style="color: #004600;">NULL</span>
Line 1,631 ⟶ 1,774:
<span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">NULL</span>
<span style="color: #000080;font-style:italic;">--q = 1 -- error</span>
<!--</langsyntaxhighlight>-->
 
See also [[Undefined_values#Phix|Undefined_values]]
Line 1,637 ⟶ 1,780:
=={{header|PHL}}==
 
<langsyntaxhighlight lang="phl">if (obj == null) printf("obj is null!\n");</langsyntaxhighlight>
 
=={{header|PHP}}==
There is a special value <tt>NULL</tt>. You can test for it using <tt>is_null()</tt> or <tt>!isset()</tt>
<langsyntaxhighlight lang="php">$x = NULL;
if (is_null($x))
echo "\$x is null\n";</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Line 1,650 ⟶ 1,793:
'[http://software-lab.de/doc/refN.html#not not]' is the predicate to check for
NIL, but many other (typically flow control) functions can be used.
<langsyntaxhighlight PicoLisplang="picolisp">(if (not MyNewVariable)
(handle value-is-NIL) )</langsyntaxhighlight>
or
<langsyntaxhighlight PicoLisplang="picolisp">(unless MyNewVariable
(handle value-is-NIL) )</langsyntaxhighlight>
 
=={{header|Pike}}==
Line 1,662 ⟶ 1,805:
 
to tell the difference between a value <math>0</math> and absence of a key, <code>zero_type()</code> is used:
<langsyntaxhighlight Pikelang="pike">> mapping bar;
> bar;
Result: 0
Line 1,673 ⟶ 1,816:
Result: 0
> zero_type(bar->baz);
Result: 1</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare x fixed decimal (10);
...
Line 1,684 ⟶ 1,827:
...
if ^valid(y) then signal error;
</syntaxhighlight>
</lang>
Comment:-
In the picture specification, the content of variable y
Line 1,693 ⟶ 1,836:
=={{header|PowerShell}}==
In PowerShell the automatic variable <code>$null</code> represents a null value. Comparisons are not left/right symmetrical which means placing <code>$null</code> on the left side greatly assists when comparing to an array.
<langsyntaxhighlight lang="powershell">if ($null -eq $object) {
...
}</langsyntaxhighlight>
 
=={{header|PureBasic}}==
All variables that has not yet been given any other value will be initiated to #Null
<langsyntaxhighlight PureBasiclang="purebasic">If variable = #Null
Debug "Variable has no value"
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">x = None
if x is None:
print "x is None"
else:
print "x is not None"</langsyntaxhighlight>
Output:<pre>
x is None
Line 1,715 ⟶ 1,858:
=={{header|R}}==
R has the special value NULL to represent a null object. You can test for it using the function is.null. Note that R also has a special value NA to represent missing or unknown values.
<langsyntaxhighlight Rlang="r">is.null(NULL) # TRUE
is.null(123) # FALSE
is.null(NA) # FALSE
123==NULL # Empty logical value, with a warning
foo <- function(){} # function that does nothing
foo() # returns NULL</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,727 ⟶ 1,870:
sometimes it is used as a generic null value.
 
<syntaxhighlight lang="racket">
<lang Racket>
-> null
'()
Line 1,734 ⟶ 1,877:
-> (null? 3)
#f
</syntaxhighlight>
</lang>
 
But a value that is more used as a generic "nothing" value is "#f",
Line 1,755 ⟶ 1,898:
Most containers default to an object of type <tt>Any</tt> so you don't accidentally send quantum superpositions (junctions) around in your program.
 
<syntaxhighlight lang="raku" perl6line>my $var;
say $var.WHAT; # Any()
$var = 42;
Line 1,762 ⟶ 1,905:
$var = Nil;
say $var.WHAT; # Any()
say $var.defined # False</langsyntaxhighlight>
 
You can declare a variable of type <tt>Mu</tt> if you wish to propagate superpositional types:
 
<syntaxhighlight lang="raku" perl6line>my Mu $junction;
say $junction.WHAT; # Mu()
$junction = 1 | 2 | 3;
say $junction.WHAT; # Junction()</langsyntaxhighlight>
 
Or you can declare a more restricted type than <tt>Any</tt>
 
<syntaxhighlight lang="raku" perl6line>my Str $str;
say $str.WHAT; # Str()
$str = "I am a string.";
say $str.WHAT; # Str()
$str = 42; # (fails)</langsyntaxhighlight>
 
But in the Raku view of reality, it's completely bogus to ask
Line 1,795 ⟶ 1,938:
=={{header|Raven}}==
{{improve|Raven|Add NULL handling with MySQL data.}}
<langsyntaxhighlight Ravenlang="raven">NULL as $v
$v NULL = # TRUE
$v NULL != # FALSE
Line 1,803 ⟶ 1,946:
 
NULL as $v2
$v2 $v = # TRUE</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">x: none
 
print ["x" either none? x ["is"]["isn't"] "none."]</langsyntaxhighlight>
 
Output:
Line 1,816 ⟶ 1,959:
REBOL also has the concept of <code>unset</code> values, testable with <code>get/any</code>
 
<langsyntaxhighlight REBOLlang="rebol">unset? get/any 'some-var
unset? get 'some-var</langsyntaxhighlight>
 
{{out}}
Line 1,830 ⟶ 1,973:
<br>A variable with a &nbsp; '''null''' &nbsp; value has a length of &nbsp; '''0''' &nbsp; (zero).
<br><br>The &nbsp; '''drop''' &nbsp; statement can be used to "undefine" a REXX variable.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates null strings, and also undefined values. */
 
if symbol('ABC')=="VAR" then say 'variable ABC is defined, value='abc"<<<"
Line 1,842 ⟶ 1,985:
cat=''
if symbol('CAT')=="VAR" then say 'variable CAT is defined, value='cat"<<<"
else say "variable CAT isn't defined."</langsyntaxhighlight>
'''output'''
<pre style=overflow:scroll">
Line 1,852 ⟶ 1,995:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see isnull(5) + nl + # print 0
isnull("hello") + nl + # print 0
Line 1,858 ⟶ 2,001:
isnull("") + nl + # print 1
isnull("NULL") # print 1
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
The value when referring to the instance variable which isn't initialized is nil.
<langsyntaxhighlight lang="ruby">puts "@object is nil" if @object.nil? # instance variable
 
puts "$object is nil" if $object.nil? # global variable, too
Line 1,871 ⟶ 2,014:
 
# nil itself is an object:
puts nil.class # => NilClass</langsyntaxhighlight>
{{out}}
<pre>
Line 1,882 ⟶ 2,025:
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">// If an option may return null - or nothing - in Rust, it's wrapped
// in an Optional which may return either the type of object specified
// in <> or None. We can check this using .is_some() and .is_none() on
Line 1,901 ⟶ 2,044:
possible_number = Some(31);
check_number(&possible_number);
}</langsyntaxhighlight>
 
=={{header|S-lang}}==
S-Lang uses NULL; it is the only object of type Null_Type:
<langsyntaxhighlight Slang="s-lang">variable foo = NULL;
print(foo);
if (foo == NULL)
print(typeof(foo));
</syntaxhighlight>
</lang>
{{out}}
<pre>NULL
Line 1,918 ⟶ 2,061:
[http://blog.sanaulla.info/2009/07/12/nothingness/ This blog post] has a good explanations of the different types of null-like values.
 
<langsyntaxhighlight lang="scala">
scala> Nil
res0: scala.collection.immutable.Nil.type = List()
Line 1,941 ⟶ 2,084:
scala> val a = println()
a: Unit = ()
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
<syntaxhighlight lang ="scheme">(null? object)</langsyntaxhighlight>
Note: "null?" here tests whether a value is the empty list.
 
=={{header|Sidef}}==
The absence of a value is represented by ''nil''
<langsyntaxhighlight lang="ruby">var undefined; # initialized with an implicit nil
say undefined==nil; # true
say defined(nil) # false</langsyntaxhighlight>
 
However, ''nil'' is not an object, so we can't call methods on it. Alternatively, Sidef provides the ''null'' object:
 
<langsyntaxhighlight lang="ruby">var null_obj = null; # initialize with a null value
say null_obj.is_a(null); # true
say defined(null_obj); # true</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">Nil isNil = True.</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
<langsyntaxhighlight lang="smalltalk">object isNil ifTrue: [ "true block" ]
ifFalse: [ "false block" ].
nil isNil ifTrue: [ 'true!' displayNl ]. "output: true!"
foo isNil ifTrue: [ 'ouch' displayNl ].
x := (foo == nil).
x := foo isNil</langsyntaxhighlight>
 
notice that nil is the singleton instance of the UndefinedObject class; i.e. it is a first class object. Thus we can do:
<langsyntaxhighlight lang="smalltalk">foo := nil.
foo class. "-> UndefinedObject"
foo respondsTo: #'bar'. "asking if a message is implemented"
 
foo class compile:'fancyOperation ^ 123'.
foo fancyOperation "->123"</langsyntaxhighlight>
 
the last example being for demonstration only - it is not considered well behaved to add arbitrary code that way, except for framework support, such as encoding, decoding marshalling etc.)
Line 1,984 ⟶ 2,127:
=={{header|Standard ML}}==
Maybe the closest type of Standard ML would be the type option, which is defined like this in the standard library:
<langsyntaxhighlight lang="sml">datatype 'a option = NONE | SOME of 'a</langsyntaxhighlight>
<langsyntaxhighlight lang="sml">case v of NONE => "unbound value"
| SOME _ => "bounded value"</langsyntaxhighlight>
 
=={{header|Swift}}==
Swift has <code>Optional<T></code> type, where <code>nil</code> means a lack of value.
<code>T?</code> is syntactic sugar for <code>Optional<T></code>.
<langsyntaxhighlight lang="swift">let maybeInt: Int? = nil</langsyntaxhighlight>
To just check if variable is nil, you can use <code>==</code> operator.
<langsyntaxhighlight lang="swift">if maybeInt == nil {
print("variable is nil")
} else {
print("variable has some value")
}</langsyntaxhighlight>
 
Usually you want to access the value after checking if it's nil. To do that you use <code>if let</code>
<langsyntaxhighlight lang="swift">if let certainlyInt = maybeInt {
print("variable has value \(certainlyInt)")
} else {
print("variable is nil")
}</langsyntaxhighlight>
 
=={{header|Tailspin}}==
Tailspin does not have a null value, but a transform is allowed to produce nothing at all, in which case that chain of computation simply stops. A templates transform can explicitly label cases as producing nothing by !VOID but also input values for which there is no matching branch will produce nothing. If you need computation to continue even in the event of nothing being produced, you can wrap the transform in an array/list to get an empty list.
<langsyntaxhighlight lang="tailspin">
templates mightBeNothing
when <=0> do !VOID
Line 2,034 ⟶ 2,177:
otherwise 'Produced $(1);. ' !
\) -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>Produced something. Produced something. Produced nothing. Produced nothing. </pre>
 
It is an error to try to assign nothing to a symbol or field.
<langsyntaxhighlight lang="tailspin">
// throws an error
def nothing: 0 -> mightBeNothing;
Line 2,048 ⟶ 2,191:
// OK, simply results in the empty structure without a field called 'nothing'
{ 0 -> mightBeNothing -> (nothing: $) }
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
In Tcl, where every value is a string, there is no out-of band value corresponding to NULL. In many cases, using the empty string is sufficient:
<langsyntaxhighlight Tcllang="tcl">if {$value eq ""} ...</langsyntaxhighlight>
A stricter approximation to NULL can be had with non-existing variables or elements of a dict or array:
<langsyntaxhighlight Tcllang="tcl">if {![info exist nullvar]} ...
if {![info exists arr(nullval)]} ...
if {![dict exists $dic nullval]} ...</langsyntaxhighlight>
Note that lists do not support anything like nulls, since they are strictly sequences of values.
 
=={{header|TXR}}==
=={{trans|Common Lisp}}==
TXR Lisp has a <code>nil</code> symbol which serves as the empty list and Boolean false, like Common Lisp and similar dialects. It is a very important symbol which plays a central role.
 
Variable definitions, global and local, without initial value expressions take on the value <code>nil</code>. Elements of newly created vectors and structure slots are <code>nil</code> by default. Optional function parameters that don't receive arguments are given <code>nil</code> arguments by default. Many functions which search for something use <code>nil</code> for indicating not found.
 
Object-oriented programming in TXR Lisp is done with structures, which do not provide a CLOS-like object system. The <code>nil</code> object isn't a structure, and so it cannot take slot references, or method invocation. Only structures have methods, which means that it's not possible to define a null object method <code>m</code> such that <code>obj.(m)</code> can be invoked if <code>obj</code> is an expression evaluating to <code>nil</code>.
 
The Gang-of-Five Null Object Pattern can be employed: defining struct types that behave like null. This null object doesn't have to be related by inheritance to the structs in conjunction with which it is used.
 
<syntaxhighlight lang="txrlisp">
(defstruct null-widget ()
(:method popularity (me) 0))
 
(defvarl null-widget (new null-widget))
 
(defstruct real-widget ()
pop
(:method popularity (me) me.pop))</syntaxhighlight>
 
In situations when a null object would be used simply to provide safe treatment of null without the verbosity of checks for its presence, and a default value of <code>nil</code> is acceptable, TXR Lisp has null-safe slot and method access: <code>obj.?slot</code>, <code>obj.?(method arg)</code>.
 
The expression <code>w.?(popularity)</code> will evaluate to <code>nil</code> if <code>w</code> is <code>nil</code>, being equivalent to <code>(if w w.(popularity))</code>, except that <code>w</code> is evaluated only once.
 
Like in Common Lisp, <code>nil</code> an instance of the type <code>null</code>, which is a unit type having only that instance. And <code>nil</code> is also the name of the bottom type of the type system: the <code>nil</code> type is the subtype of every type, including itself.
 
Like in Common Lisp, the expression <code>(or a b c ...)</code> evaluates the arguments from left to right, returning the value of the leftmost one which does not evaluate to <code>nil</code>.
 
<syntaxhighlight lang="txrlisp">;; Find widget in one of three places in order
(defun find-widget (name)
(or [%widget-hash% name]
(lookup-local-widget name)
(lookup-global-widget name)))</syntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa"># the type at declaration doesn't matter
decl int x
 
Line 2,068 ⟶ 2,245:
else
out "x is not null" endl console
end if</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Public Sub Main()
Dim c As VBA.Collection
Line 2,084 ⟶ 2,261:
Set c = Nothing
Debug.Print c Is Nothing
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
{{works with|VB6}}
Null by the definition of this task is called "Nothing" in VB6:
<syntaxhighlight lang="vb">
<lang vb>
Public Sub Main()
Dim c As VBA.Collection
Line 2,105 ⟶ 2,282:
 
End Sub
</syntaxhighlight>
</lang>
The Null keyword has a different meaning in VB6: it's one of the states that a Variant type variable can be in. Null means that a Variant doesn't hold valid (i.e.: defined) data.
<syntaxhighlight lang="vb">
<lang vb>
Public Sub Main()
Dim v As Variant
Line 2,125 ⟶ 2,302:
 
End Sub
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
V (Vlang) does not have nor normally allow null or nil (also called "the billion dollar mistake"):
 
1) All primitive types/variables have default values.
 
2) For arrays and structs, default values are automatically assigned.
 
3) Usage of voidptr or nil, only done in unsafe, and is usually only for the purposes of interoperability with other languages.
<syntaxhighlight lang="v (vlang)">
// Null or nil not used, default values for various primitive types/variables instead:
 
a_string :=''
a_bool := false
an_int := 0
[3]string{} // ['', '', '']
[3]bool{} // [false, false, false]
[3]int{} // [0, 0, 0]
</syntaxhighlight>
 
=={{header|Wart}}==
The null value <code>nil</code> is also the only false value.
<langsyntaxhighlight lang="wart">(not nil)
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
Line 2,142 ⟶ 2,338:
 
It is always easy to test for nullness either by querying a variable's type or checking the value of a boolean expression involving a potentially null variable.
<langsyntaxhighlight ecmascriptlang="wren">// Declare a variable without giving it an explicit value.
var s
 
Line 2,159 ⟶ 2,355:
var g = f.call()
// We find that the return value is null.
System.print(g)</langsyntaxhighlight>
 
{{out}}
Line 2,173 ⟶ 2,369:
=={{header|zkl}}==
In zkl, there isn't a C like 0/NULL, a value that, if referenced, causes bad things to happen. There is an Object, Void, that is used as generic NULL like thing but it is just another object.
<langsyntaxhighlight lang="zkl">if(Void == n) ...
return(Void)</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{trans|ARM Assembly}}
Even though this doesn't really apply to assembly, as there is no "null pointer" per se (that is, all data is a number), it would be interesting to demystify what <code>NULL</code> really is. At the lowest level, the null pointer is just a pointer to a memory location that is of no use to the programmer. The Z80 does not segfault, so any memory address we read is fair game. So without the hardware enforcing <code>NULL</code>, we need to pick an address we don't mind losing. Typically, using <code>&0000</code> to equal [[C]]'s <code>NULL</code> is acceptable, as address <code>&0000</code> on any randomly chosen Z80-based hardware is typically a jump to the kernel's entry point (or the main program's entry point, depending on the implementation.)
 
<syntaxhighlight lang="z80">ld a,(&0000) ;dereference the null pointer as a uint8
ld hl,(&0000) ;dereference the null pointer as a uint16</syntaxhighlight>
 
Typically, you would get 0xC3 when dereferencing as an 8-bit value and 0xC3nn when dereferencing as a 16-bit value, where nn is the low byte of the address of the aforementioned entry point. Neither of these are particularly useful, so having <code>&0000</code> as the null pointer is perfectly fine. Although there are technically other options, most CPUs can compare with zero more efficiently than most other numbers, and the Z80 is no exception. Of course, the Z80 will not check if a pointer is NULL for you, so you have to do it yourself:
<syntaxhighlight lang="z80">LD HL,myPointers
;there is no LD BC,(HL) so we have to do this:
LD c,(hl)
inc hl
LD b,(hl)
;and compare to null
LD a,b
or c ;compare BC to zero
JR z,isNull</syntaxhighlight>
 
{{omit from|GUISS}}
885

edits