Null object: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 15: Line 15:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F f([Int]? &a)
<syntaxhighlight lang="11l">F f([Int]? &a)
I a != N
I a != N
a.append(1)
a.append(1)
Line 22: Line 22:
[Int] arr
[Int] arr
f(&arr)
f(&arr)
print(arr)</lang>
print(arr)</syntaxhighlight>


{{out}}
{{out}}
Line 42: Line 42:
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.
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.


<lang 6502asm>lda pointer ;a zero-page address that holds the low byte of a pointer variable.
<syntaxhighlight lang="6502asm">lda pointer ;a zero-page address that holds the low byte of a pointer variable.
CMP #$FF
CMP #$FF
BNE .continue
BNE .continue
Line 49: Line 49:
BNE .continue
BNE .continue
RTS ;return without doing anything
RTS ;return without doing anything
.continue</lang>
.continue</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<syntaxhighlight lang="forth">
null? if "item was null" . then
null? if "item was null" . then
</syntaxhighlight>
</lang>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program nullobj64.s */
/* program nullobj64.s */
Line 105: Line 105:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>TYPE Object=[
<syntaxhighlight lang="action!">TYPE Object=[
BYTE byteData
BYTE byteData
INT intData
INT intData
Line 126: Line 126:
IsNull(ptr1)
IsNull(ptr1)
IsNull(ptr2)
IsNull(ptr2)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Null_object.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Null_object.png Screenshot from Atari 8-bit computer]
Line 135: Line 135:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>if (object == null)
<syntaxhighlight lang="actionscript">if (object == null)
trace("object is null");</lang>
trace("object is null");</syntaxhighlight>


ActionScript also has an '''undefined''' value: see [[Undefined values#ActionScript]].
ActionScript also has an '''undefined''' value: see [[Undefined values#ActionScript]].


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io;


if Object = null then
if Object = null then
Ada.Text_Io.Put_line("object is null");
Ada.Text_Io.Put_line("object is null");
end if;</lang>
end if;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 154: Line 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|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]}}
{{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]}}
<lang algol68>REF STRING no result = NIL;
<syntaxhighlight lang="algol68">REF STRING no result = NIL;
STRING result := "";
STRING result := "";
Line 172: Line 172:
REF STRING var := NIL;
REF STRING var := NIL;
IF var ISNT NIL THEN print(("The address of var ISNT NIL",new line)) FI;
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</lang>
IF var IS REF STRING(NIL) THEN print(("The address of var IS REF STRING(NIL)",new line)) FI</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 197: Line 197:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% declare a record type - will be accessed via references %
% declare a record type - will be accessed via references %
record R( integer f1, f2, f3 );
record R( integer f1, f2, f3 );
Line 206: Line 206:
% test for a null reference - will write "refR is null" %
% test for a null reference - will write "refR is null" %
if refR = null then write( "refR is null" ) else write( "not null" );
if refR = null then write( "refR is null" ) else write( "not null" );
end.</lang>
end.</syntaxhighlight>


=={{header|AmigaE}}==
=={{header|AmigaE}}==
<lang amigae>DEF x : PTR TO object
<syntaxhighlight lang="amigae">DEF x : PTR TO object
-> ...
-> ...
IF object <> NIL
IF object <> NIL
-> ...
-> ...
ENDIF</lang>
ENDIF</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
APL is a vector/array-based language, so rather than a 'null pointer' or 'null value' there is the 'null vector'.
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
⍝⍝ GNU APL
]help ⍬
]help ⍬
Line 226: Line 226:
⍬≡⍳0
⍬≡⍳0
1
1
</syntaxhighlight>
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Many applications will return <code>missing value</code>, but <code>null</code> is also available.
Many applications will return <code>missing value</code>, but <code>null</code> is also available.
<lang AppleScript>if x is missing value then
<syntaxhighlight lang="applescript">if x is missing value then
display dialog "x is missing value"
display dialog "x is missing value"
end if
end if
Line 236: Line 236:
if x is null then
if x is null then
display dialog "x is null"
display dialog "x is null"
end if</lang>
end if</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 303: Line 303:
bx lr @ return
bx lr @ return


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>v: null
<syntaxhighlight lang="rebol">v: null
if v=null -> print "got NULL!"</lang>
if v=null -> print "got NULL!"</syntaxhighlight>


{{out}}
{{out}}
Line 315: Line 315:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>If (object == null)
<syntaxhighlight lang="autohotkey">If (object == null)
MsgBox, object is null</lang>
MsgBox, object is null</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>Local $object = Null
<syntaxhighlight lang="autoit">Local $object = Null
If $object = Null Then MsgBox(0, "NULL", "Object is null")</lang>
If $object = Null Then MsgBox(0, "NULL", "Object is null")</syntaxhighlight>


=={{header|AWK}}==
=={{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.
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.
<lang AWK>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
BEGIN {
b=0;
b=0;
Line 330: Line 330:
print "<"u,length(u)">"
print "<"u,length(u)">"
print "<"u+0,length(u+0)">";
print "<"u+0,length(u+0)">";
}</lang>
}</syntaxhighlight>
Output
Output
<pre><0 1>
<pre><0 1>
Line 338: Line 338:
=={{header|Axe}}==
=={{header|Axe}}==
Null pointers can be checked by simply comparing the pointer with 0.
Null pointers can be checked by simply comparing the pointer with 0.
<lang axe>If P=0
<syntaxhighlight lang="axe">If P=0
Disp "NULL PTR",i
Disp "NULL PTR",i
End</lang>
End</syntaxhighlight>


=={{header|Babel}}==
=={{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.
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.
<lang babel>{ nil { nil? } { "Whew!\n" } { "Something is terribly wrong!\n" } ifte << }</lang>
<syntaxhighlight lang="babel">{ nil { nil? } { "Whew!\n" } { "Something is terribly wrong!\n" } ifte << }</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 353: Line 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.
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.
<lang ApplesoftBasic>TRUE = 1 : FALSE = 0
<syntaxhighlight lang="applesoftbasic">TRUE = 1 : FALSE = 0
NULL = TRUE
NULL = TRUE
IF NULL THEN PRINT "NULL"
IF NULL THEN PRINT "NULL"
NULL = FALSE
NULL = FALSE
IF NOT NULL THEN PRINT "NOT NULL"</lang>'''Output:'''<pre>NULL
IF NOT NULL THEN PRINT "NOT NULL"</syntaxhighlight>'''Output:'''<pre>NULL
NOT NULL</pre>
NOT NULL</pre>


Line 363: Line 363:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
A null object has a pointer with a value of zero or one.
A null object has a pointer with a value of zero or one.
<lang bbcbasic> PROCtestobjects
<syntaxhighlight lang="bbcbasic"> PROCtestobjects
END
END
Line 375: Line 375:
IF !^s{} <= 1 PRINT "s{} is null" ELSE PRINT "s{} is not null"
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"
IF !^t{} <= 1 PRINT "t{} is null" ELSE PRINT "t{} is not null"
ENDPROC</lang>
ENDPROC</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 387: Line 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.
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."
IF VAR$ = CHR$(0) THEN PRINT "Variable has a null value."
</syntaxhighlight>
</lang>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Line 396: Line 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.
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.


<lang bracmat>
<syntaxhighlight lang="bracmat">
a:?x*a*?z {assigns 1 to x and to z}
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 0 to x and to z}
a:?x a ?z {assigns "" (or (), which is equivalent) to x and to z}
a:?x a ?z {assigns "" (or (), which is equivalent) to x and to z}
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 409: Line 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.
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.


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


int main()
int main()
Line 419: Line 419:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
As with Java, any reference type may be null, and testing for nullity uses ordinary boolean operators.
As with Java, any reference type may be null, and testing for nullity uses ordinary boolean operators.
<lang csharp>if (foo == null)
<syntaxhighlight lang="csharp">if (foo == null)
Console.WriteLine("foo is null");</lang>
Console.WriteLine("foo is null");</syntaxhighlight>


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.
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+}}
{{works with|C sharp|C#|2.0+}}
<lang csharp>int? x = 12;
<syntaxhighlight lang="csharp">int? x = 12;
x = null;</lang>
x = null;</syntaxhighlight>


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:
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+}}
{{works with|C sharp|C#|2.0+}}
<lang csharp>Console.WriteLine(name ?? "Name not specified");
<syntaxhighlight lang="csharp">Console.WriteLine(name ?? "Name not specified");


//Without the null coalescing operator, this would instead be written as:
//Without the null coalescing operator, this would instead be written as:
Line 442: Line 442:
//}else{
//}else{
// Console.WriteLine(name);
// Console.WriteLine(name);
//}</lang>
//}</syntaxhighlight>


=={{header|C++}}==
=={{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.
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.
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <cstdlib>
#include <cstdlib>
if (object == 0) {
if (object == 0) {
std::cout << "object is null";
std::cout << "object is null";
}</lang>
}</syntaxhighlight>


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.
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.


<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <optional>
#include <optional>
Line 467: Line 467:
std::cout << "object is null\n";
std::cout << "object is null\n";
}
}
</syntaxhighlight>
</lang>


===C++11===
===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
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
<lang cpp>
<syntaxhighlight lang="cpp">
int *p = nullptr;
int *p = nullptr;
...
...
Line 482: Line 482:
// do some thing
// do some thing
}
}
</syntaxhighlight>
</lang>


=={{header|Chapel}}==
=={{header|Chapel}}==


Objects variables without an initializer expression will be initiallized to nil:
Objects variables without an initializer expression will be initiallized to nil:
<lang chapel>class C { };
<syntaxhighlight lang="chapel">class C { };
var c:C; // is nil
var c:C; // is nil
writeln(if c == nil then "nil" else "something");</lang>
writeln(if c == nil then "nil" else "something");</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
Clojure's <code>nil</code> is equivalent to Java's <code>null</code>.
Clojure's <code>nil</code> is equivalent to Java's <code>null</code>.


<lang lisp>(let [x nil]
<syntaxhighlight lang="lisp">(let [x nil]
(println "Object is" (if (nil? x) "nil" "not nil")))</lang>
(println "Object is" (if (nil? x) "nil" "not nil")))</syntaxhighlight>


Test wether symbol <code>foo</code> is defined:
Test wether symbol <code>foo</code> is defined:


<lang lisp>(find (ns-interns *ns*) 'foo)</lang>
<syntaxhighlight lang="lisp">(find (ns-interns *ns*) 'foo)</syntaxhighlight>


Undefining <code>foo</code>:
Undefining <code>foo</code>:


<lang lisp>(ns-unmap *ns* 'foo)</lang>
<syntaxhighlight lang="lisp">(ns-unmap *ns* 'foo)</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Works with GnuCOBOL 2.0
Works with GnuCOBOL 2.0


<lang COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. null-objects.
program-id. null-objects.
remarks. test with cobc -x -j null-objects.cob
remarks. test with cobc -x -j null-objects.cob
Line 550: Line 550:
end-if
end-if
goback.
goback.
end program test-null.</lang>
end program test-null.</syntaxhighlight>


{{out}}
{{out}}
Line 565: Line 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.
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 <lang lisp>(if (condition) (do-this))</lang> 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.
<code>nil</code> uniquely represents boolean false, and so code like <syntaxhighlight lang="lisp">(if (condition) (do-this))</syntaxhighlight> 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====
====Beginnings of Null Object====
Line 584: Line 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:
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:


<lang lisp>(defmethod car* ((arg cons))
<syntaxhighlight lang="lisp">(defmethod car* ((arg cons))
(car arg))
(car arg))


(defmethod car* ((arg null))
(defmethod car* ((arg null))
nil)</lang>
nil)</syntaxhighlight>


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.
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 594: Line 594:
We can handle that ourselves by writing a method specialized to the master supertype <code>t</code>:
We can handle that ourselves by writing a method specialized to the master supertype <code>t</code>:


<lang lisp>(defmethod car* ((arg t)) ;; can just be written (defmethod car* (arg) ...)
<syntaxhighlight lang="lisp">(defmethod car* ((arg t)) ;; can just be written (defmethod car* (arg) ...)
(error "CAR*: ~s is neither a cons nor nil" arg))</lang>
(error "CAR*: ~s is neither a cons nor nil" arg))</syntaxhighlight>


The classes <code>t</code> and <code>null</code> are widely exploited in Lisp OO programming.
The classes <code>t</code> and <code>null</code> are widely exploited in Lisp OO programming.


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
<syntaxhighlight lang="oberon2">
<lang Oberon2>
MODULE ObjectNil;
MODULE ObjectNil;
IMPORT StdLog;
IMPORT StdLog;
Line 618: Line 618:


END ObjectNil.
END ObjectNil.
</syntaxhighlight>
</lang>


=={{header|Crystal}}==
=={{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.
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.
<lang crystal>foo : Int32 | Nil = 5 # this variable's type can be Int32 or Nil
<syntaxhighlight 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
bar : Int32? = nil # equivalent type to above, but shorter syntax
baz : Int32 = 5 # this variable can never be nil
baz : Int32 = 5 # this variable can never be nil
Line 635: Line 635:
puts "Is bar equivalent to nil? #{bar === nil}"
puts "Is bar equivalent to nil? #{bar === nil}"


bar.not_nil! # bar is nil, so an exception is thrown</lang>
bar.not_nil! # bar is nil, so an exception is thrown</syntaxhighlight>
{{out}}
{{out}}
<pre>Is foo nil? false
<pre>Is foo nil? false
Line 647: Line 647:
=={{header|D}}==
=={{header|D}}==
In D ''is'' is used to perform bitwise identity, like to compare an object reference against null.
In D ''is'' is used to perform bitwise identity, like to compare an object reference against null.
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


class K {}
class K {}
Line 658: Line 658:
if (k !is null)
if (k !is null)
writeln("Now k is not null");
writeln("Now k is not null");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>k is null
<pre>k is null
Line 664: Line 664:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi> // the following are equivalent
<syntaxhighlight lang="delphi"> // the following are equivalent
if lObject = nil then
if lObject = nil then
...
...
if not Assigned(lObject) then
if not Assigned(lObject) then
...</lang>
...</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==
Line 678: Line 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.
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.


<lang dyalect>var x = nil
<syntaxhighlight lang="dyalect">var x = nil
if x == nil {
if x == nil {
//Do something
//Do something
}</lang>
}</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{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:
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:
<lang dejavu>if not obj:
<syntaxhighlight lang="dejavu">if not obj:
pass #obj is seen as null
pass #obj is seen as null


if = :nil obj:
if = :nil obj:
pass #obj is seen as null</lang>
pass #obj is seen as null</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==


<lang e>object == null</lang>
<syntaxhighlight lang="e">object == null</syntaxhighlight>


=={{header|EchoLisp}}==
=={{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.
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.


<lang lisp>
<syntaxhighlight lang="lisp">
null → null
null → null
() → null
() → null
Line 714: Line 714:


(f '( a b c)) → a b c
(f '( a b c)) → a b c
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{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.
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
class
APPLICATION
APPLICATION
Line 740: Line 740:
end
end
end
end
end</lang>
end</syntaxhighlight>
{{out}}<pre>s = Void</pre>
{{out}}<pre>s = Void</pre>


=={{header|Elixir}}==
=={{header|Elixir}}==
<code>nil</code> is atom in fact:
<code>nil</code> is atom in fact:
<lang elixir>iex(1)> nil == :nil
<syntaxhighlight lang="elixir">iex(1)> nil == :nil
true
true
iex(2)> is_nil(nil)
iex(2)> is_nil(nil)
true</lang>
true</syntaxhighlight>
<code>nil</code> is thought of as being <code>false</code> in the conditional expression.
<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>.
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>.
<lang elixir>iex(3)> if nil, do: "not execute"
<syntaxhighlight lang="elixir">iex(3)> if nil, do: "not execute"
nil</lang>
nil</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 779: Line 779:
Other than in interfacing assemblies written in other .Net languages, null rarely serves a purpose in F# code.
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:
Contrived code, to show using null, as per task description:
<lang fsharp>let sl : string list = [null; "abc"]
<syntaxhighlight lang="fsharp">let sl : string list = [null; "abc"]


let f s =
let f s =
Line 786: Line 786:
| _ -> "It's non-null: " + s
| _ -> "It's non-null: " + s


for s in sl do printfn "%s" (f s)</lang>
for s in sl do printfn "%s" (f s)</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>: is-f? ( obj -- ? ) f = ;</lang>
<syntaxhighlight lang="factor">: is-f? ( obj -- ? ) f = ;</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 795: Line 795:
Test for equality with 'null', which is the null value.
Test for equality with 'null', which is the null value.


<lang fantom>
<syntaxhighlight lang="fantom">
fansh> x := null
fansh> x := null
fansh> x == null
fansh> x == null
Line 803: Line 803:
fansh> x == null
fansh> x == null
false
false
</syntaxhighlight>
</lang>


Note, nullable objects have a type ending in a question mark, for example:
Note, nullable objects have a type ending in a question mark, for example:
Line 817: Line 817:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>'FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">'FB 1.05.0 Win64


' FreeBASIC does not have a NULL keyword but it's possible to create one using a macro
' FreeBASIC does not have a NULL keyword but it's possible to create one using a macro
Line 836: Line 836:


' in practice many FB developers would simply have written: d = 0 above
' in practice many FB developers would simply have written: d = 0 above
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 845: Line 845:
=={{header|Go}}==
=={{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]].
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
package main


Line 867: Line 867:
fmt.Println(c == nil)
fmt.Println(c == nil)
}
}
</syntaxhighlight>
</lang>
Output is "true" in each case.
Output is "true" in each case.


Line 874: Line 874:
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.
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.


<lang haskell>undefined -- undefined value provided by the standard library
<syntaxhighlight lang="haskell">undefined -- undefined value provided by the standard library
error "oops" -- another undefined value
error "oops" -- another undefined value
head [] -- undefined, you can't take the head of an empty list</lang>
head [] -- undefined, you can't take the head of an empty list</syntaxhighlight>


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:
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:


<lang haskell> data Maybe a = Nothing | Just a</lang>
<syntaxhighlight lang="haskell"> data Maybe a = Nothing | Just a</syntaxhighlight>


That is, a <tt>Maybe Integer</tt> is either <tt>Nothing</tt> or <tt>Just </tt>&lt;some integer&gt;.
That is, a <tt>Maybe Integer</tt> is either <tt>Nothing</tt> or <tt>Just </tt>&lt;some integer&gt;.
Line 886: Line 886:
There are many ways to work with Maybe, but here's a basic case expression:
There are many ways to work with Maybe, but here's a basic case expression:


<lang haskell>case thing of
<syntaxhighlight lang="haskell">case thing of
Nothing -> "It's Nothing. Or null, whatever."
Nothing -> "It's Nothing. Or null, whatever."
Just v -> "It's not Nothing; it is " ++ show v ++ "."</lang>
Just v -> "It's not Nothing; it is " ++ show v ++ "."</syntaxhighlight>


It is easy to work with Maybe type using do-notation (since Maybe is a monad):
It is easy to work with Maybe type using do-notation (since Maybe is a monad):
<lang haskell>add_two_maybe_numbers x y do
<syntaxhighlight lang="haskell">add_two_maybe_numbers x y do
a <- x
a <- x
b <- y
b <- y
return (a+b)</lang>
return (a+b)</syntaxhighlight>
Then
Then
<lang haskell>*Main> add_two_maybe_numbers (Just 2) (Just 3)
<syntaxhighlight lang="haskell">*Main> add_two_maybe_numbers (Just 2) (Just 3)
Just 5
Just 5
*Main> add_two_maybe_numbers (Just 2) Nothing
*Main> add_two_maybe_numbers (Just 2) Nothing
Nothing</lang>
Nothing</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon/Unicon have a [[Icon%2BUnicon/Intro#null|null value/datatype]]. It isn't possible to undefine a variable.
Icon/Unicon have a [[Icon%2BUnicon/Intro#null|null value/datatype]]. It isn't possible to undefine a variable.


<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
nulltest("a",a) # unassigned variables are null by default
nulltest("a",a) # unassigned variables are null by default
nulltest("b",b := &null) # explicit assignment is possible
nulltest("b",b := &null) # explicit assignment is possible
Line 913: Line 913:
procedure nulltest(name,var)
procedure nulltest(name,var)
return write(name, if /var then " is" else " is not"," null.")
return write(name, if /var then " is" else " is not"," null.")
end</lang>
end</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<lang io>if(object == nil, "object is nil" println)</lang>
<syntaxhighlight lang="io">if(object == nil, "object is nil" println)</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 925: Line 925:
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:
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:


<lang J>isUndefined=: _1 = nc@boxxopen</lang>
<syntaxhighlight lang="j">isUndefined=: _1 = nc@boxxopen</syntaxhighlight>


Example use:
Example use:


<lang J> isUndefined 'foo'
<syntaxhighlight lang="j"> isUndefined 'foo'
1
1
foo=:9
foo=:9
isUndefined 'foo'
isUndefined 'foo'
0</lang>
0</syntaxhighlight>


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".
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 951: Line 951:
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:
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:


<lang j> 1 1 0 1#3 4 _ 5 NB. use bitmask to select numbers
<syntaxhighlight lang="j"> 1 1 0 1#3 4 _ 5 NB. use bitmask to select numbers
3 4 5
3 4 5
I.1 1 0 1 NB. get indices for bitmask
I.1 1 0 1 NB. get indices for bitmask
Line 962: Line 962:
3 4 _ 5
3 4 _ 5
3 4 5 (0 1 3}) _ _ _ _ NB. use indices to restore original positions
3 4 5 (0 1 3}) _ _ _ _ NB. use indices to restore original positions
3 4 _ 5</lang>
3 4 _ 5</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
In Java, "null" is a value of every reference type.
In Java, "null" is a value of every reference type.
<lang java>// here "object" is a reference
<syntaxhighlight lang="java">// here "object" is a reference
if (object == null) {
if (object == null) {
System.out.println("object is null");
System.out.println("object is null");
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{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".
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".
<lang javascript>if (object === null) {
<syntaxhighlight lang="javascript">if (object === null) {
alert("object is null");
alert("object is null");
// The object is nothing
// The object is nothing
}
}


typeof null === "object"; // This stands since the beginning of JavaScript</lang>
typeof null === "object"; // This stands since the beginning of JavaScript</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 985: Line 985:
<tt>null</tt> is distinct from <tt>false</tt>.
<tt>null</tt> is distinct from <tt>false</tt>.
Here are some examples:
Here are some examples:
<lang jq>null|type # => "null"
<syntaxhighlight lang="jq">null|type # => "null"


null == false # => false
null == false # => false
Line 995: Line 995:
empty == empty # => # niente
empty == empty # => # niente


empty == "black hole" # => # Ничего</lang>
empty == "black hole" # => # Ничего</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
Line 1,002: Line 1,002:
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.
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.


<lang javascript>/* null non value */
<syntaxhighlight lang="javascript">/* null non value */


if (thing == null) { puts("thing tests as null"); }
if (thing == null) { puts("thing tests as null"); }
Line 1,008: Line 1,008:
puts(typeof thing);
puts(typeof thing);
puts(typeof null);
puts(typeof null);
puts(typeof undefined);</lang>
puts(typeof undefined);</syntaxhighlight>


{{out}}
{{out}}
Line 1,029: Line 1,029:
and and missing value ''nil'' :
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:
: 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;;2) ~ (1 ; _n ; 2) / ~ is ''identical to'' or ''match'' .
1
1
Line 1,036: Line 1,036:


additional properties : _n@i and _n?i are i; _n`v is _n
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
For more detail on K's concept of typed nulls, see http://code.kx.com/wiki/Reference/Datatypes#Primitive_Types


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>%t nan !t
<syntaxhighlight lang="klingphix">%t nan !t
$t nan == ?</lang>
$t nan == ?</syntaxhighlight>
{{out}}
{{out}}
<pre>1</pre>
<pre>1</pre>
Line 1,052: Line 1,052:


Here are some examples:
Here are some examples:
<lang scala>// version 1.1.0
<syntaxhighlight lang="scala">// version 1.1.0


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,060: Line 1,060:
println(j)
println(j)
println(null is Nothing?) // test that null is indeed of type Nothing?
println(null is Nothing?) // test that null is indeed of type Nothing?
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,075: Line 1,075:
Prior to 0.10, multi-variable declaration/assignment would use parentheses around variable names and values.
Prior to 0.10, multi-variable declaration/assignment would use parentheses around variable names and values.


<lang langur>val .x, .y = true, null
<syntaxhighlight lang="langur">val .x, .y = true, null


writeln .x == null
writeln .x == null
Line 1,083: Line 1,083:


# null not a "truthy" result
# null not a "truthy" result
writeln if(null: 0; 1)</lang>
writeln if(null: 0; 1)</syntaxhighlight>


{{out}}
{{out}}
Line 1,093: Line 1,093:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(x = string, y = null)
<syntaxhighlight lang="lasso">local(x = string, y = null)
#x->isA(::null)
#x->isA(::null)
// 0 (false)
// 0 (false)
Line 1,110: Line 1,110:


#y->type == 'null'
#y->type == 'null'
//true</lang>
//true</syntaxhighlight>


=={{header|Latitude}}==
=={{header|Latitude}}==


Nil is an object in Latitude, like any other.
Nil is an object in Latitude, like any other.
<lang latitude>foo := Nil.
<syntaxhighlight lang="latitude">foo := Nil.
if { foo nil?. } then {
if { foo nil?. } then {
putln: "Foo is nil".
putln: "Foo is nil".
} else {
} else {
putln: "Foo is not nil".
putln: "Foo is not nil".
}.</lang>
}.</syntaxhighlight>


In particular, Nil satisfies the Collection mixin, so it can be treated as an (immutable) collection.
In particular, Nil satisfies the Collection mixin, so it can be treated as an (immutable) collection.
<lang latitude>Nil to (Array). ;; []</lang>
<syntaxhighlight lang="latitude">Nil to (Array). ;; []</syntaxhighlight>


Nil is the default value returned if a method body is empty.
Nil is the default value returned if a method body is empty.
<lang latitude>func := {}.
<syntaxhighlight lang="latitude">func := {}.
func. ;; Nil</lang>
func. ;; Nil</syntaxhighlight>


=={{header|Lily}}==
=={{header|Lily}}==
Lily doesn't provide a built-in nothing type, but allows one to be created using enum class:
Lily doesn't provide a built-in nothing type, but allows one to be created using enum class:


<lang Lily>enum class Option[A] {
<syntaxhighlight lang="lily">enum class Option[A] {
Some(A)
Some(A)
None
None
Line 1,152: Line 1,152:


# Invalid! Likewise, w is an integer, not an Option.
# Invalid! Likewise, w is an integer, not an Option.
w = None</lang>
w = None</syntaxhighlight>


=={{header|Lingo}}==
=={{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.
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.
<lang lingo>put _global.doesNotExist
<syntaxhighlight lang="lingo">put _global.doesNotExist
-- <Void>
-- <Void>


Line 1,167: Line 1,167:


put voidP(x)
put voidP(x)
-- 1</lang>
-- 1</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to test :thing
<syntaxhighlight lang="logo">to test :thing
if empty? :thing [print [list or word is empty]]
if empty? :thing [print [list or word is empty]]
end
end


print empty? [] ; true
print empty? [] ; true
print empty? "|| ; true</lang>
print empty? "|| ; true</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang="lua">
isnil = (object == nil)
isnil = (object == nil)
print(isnil)
print(isnil)
</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
===For Com Objects===
===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).
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 {
Module CheckWord {
Declare Alfa "WORD.APPLICATION"
Declare Alfa "WORD.APPLICATION"
Line 1,199: Line 1,199:
}
}
CheckWord
CheckWord
</syntaxhighlight>
</lang>
===For Containers===
===For Containers===
Container's pointers (for arrays, inventories, stack) we have to assign an empty container, there is not a null one.
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 {
Module CheckContainers {
\\ Arrays (A() and B() are value types)
\\ Arrays (A() and B() are value types)
Line 1,258: Line 1,258:
}
}
CheckContainers
CheckContainers
</syntaxhighlight>
</lang>
===For Groups===
===For Groups===
Groups are value types, but we can make reference to them,or pointer to them
Groups are value types, but we can make reference to them,or pointer to them
Line 1,271: Line 1,271:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
class something {
class something {
}
}
Line 1,301: Line 1,301:
a=pointer() ' same as a->0&
a=pointer() ' same as a->0&
Print a is type null = true
Print a is type null = true
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
In Maple, NULL and () represent the null object.
In Maple, NULL and () represent the null object.
<lang maple>a := NULL;
<syntaxhighlight lang="maple">a := NULL;
a :=
a :=
is (NULL = ());
is (NULL = ());
Line 1,312: Line 1,312:
print (NULL);
print (NULL);
end if;
end if;
</syntaxhighlight>
</lang>
A null object is different from an undefined value.
A null object is different from an undefined value.
<lang maple>b := Array([1, 2, 3, Integer(undefined), 5]);
<syntaxhighlight lang="maple">b := Array([1, 2, 3, Integer(undefined), 5]);
b := [ 1 2 3 undefined 5 ]
b := [ 1 2 3 undefined 5 ]
numelems(b);
numelems(b);
Line 1,326: Line 1,326:
numelems(b);
numelems(b);
4
4
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica can assign a Null value to a symbol, two examples:
Mathematica can assign a Null value to a symbol, two examples:
<lang Mathematica>x=Null;</lang>
<syntaxhighlight lang="mathematica">x=Null;</syntaxhighlight>
<syntaxhighlight lang="mathematica">x =.
<lang Mathematica>x =.
x = (1 + 2;)
x = (1 + 2;)
FullForm[x]</lang>
FullForm[x]</syntaxhighlight>
Both set x to be Null. To specifically test is something is Null one can use the SameQ function (with infix operator: ===):
Both set x to be Null. To specifically test is something is Null one can use the SameQ function (with infix operator: ===):
<lang Mathematica>SameQ[x,Null]</lang>
<syntaxhighlight lang="mathematica">SameQ[x,Null]</syntaxhighlight>
Or equivalent:
Or equivalent:
<lang Mathematica>x===Null</lang>
<syntaxhighlight lang="mathematica">x===Null</syntaxhighlight>
will give back True if and only if x is assigned to be Null. If x is empty (nothing assigned) this will return False.
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:
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]
ValueQ[x]
x = 3;
x = 3;
ValueQ[x]</lang>
ValueQ[x]</syntaxhighlight>
gives:
gives:
<syntaxhighlight lang="mathematica">False
<lang Mathematica>False
True</lang>
True</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{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.
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.
<lang MATLAB>a = []; b='';
<syntaxhighlight lang="matlab">a = []; b='';
isempty(a)
isempty(a)
isempty(b)
isempty(b)
Line 1,357: Line 1,357:
else,
else,
0
0
end;</lang>
end;</syntaxhighlight>


<pre>octave:4> a = []; b='';
<pre>octave:4> a = []; b='';
Line 1,371: Line 1,371:


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>if obj == undefined then print "Obj is undefined"</lang>
<syntaxhighlight lang="maxscript">if obj == undefined then print "Obj is undefined"</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Line 1,377: Line 1,377:


This can lead to errors, if for example you write:
This can lead to errors, if for example you write:
<lang modula3>VAR foo := NIL</lang>
<syntaxhighlight lang="modula3">VAR foo := NIL</syntaxhighlight>
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:
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:
<lang modula3>VAR foo: REF INTEGER := NIL;</lang>
<syntaxhighlight lang="modula3">VAR foo: REF INTEGER := NIL;</syntaxhighlight>
<lang modula3>IF foo = NIL THEN
<syntaxhighlight lang="modula3">IF foo = NIL THEN
IO.Put("Object is nil.\n");
IO.Put("Object is nil.\n");
END;</lang>
END;</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
Line 1,410: Line 1,410:
</table>
</table>
<p>Or, by examples (in immediate mode):</p>
<p>Or, by examples (in immediate mode):</p>
<syntaxhighlight lang="mumps">
<lang MUMPS>
CACHE>WRITE $DATA(VARI)
CACHE>WRITE $DATA(VARI)
0
0
Line 1,429: Line 1,429:
<CACHE>W $DATA(VARI)," ",VARI
<CACHE>W $DATA(VARI)," ",VARI
1 HELLO
1 HELLO
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Ursa}}
{{trans|Ursa}}
<lang Nanoquery>$x = $null
<syntaxhighlight lang="nanoquery">$x = $null


if ($x = $null)
if ($x = $null)
Line 1,439: Line 1,439:
else
else
println "x is not null"
println "x is not null"
end if</lang>
end if</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
<doc>
<doc>
<p>Neko uses <i>null</i> for undefined variables,
<p>Neko uses <i>null</i> for undefined variables,
Line 1,453: Line 1,453:
var n = null
var n = null
if n == null $print("n is null\n")
if n == null $print("n is null\n")
if $not($istrue(n)) $print("and tests as boolean false\n")</lang>
if $not($istrue(n)) $print("and tests as boolean false\n")</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
In NetRexx as in Java, "null" is a value of every reference type.
In NetRexx as in Java, "null" is a value of every reference type.


<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
options replace format comments java crossref symbols binary


Line 1,464: Line 1,464:
say String.valueOf(robject) -- will report the text "null"
say String.valueOf(robject) -- will report the text "null"
if robject = null then say 'Really, it''s "null"!'
if robject = null then say 'Really, it''s "null"!'
</syntaxhighlight>
</lang>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 1,472: Line 1,472:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang newlisp>
<syntaxhighlight lang="newlisp">
#! /usr/local/bin/newlisp
#! /usr/local/bin/newlisp
(setq myobject nil)
(setq myobject nil)
(println (nil? myobject))
(println (nil? myobject))
(exit)
(exit)
</syntaxhighlight>
</lang>
<pre>
<pre>
true
true
Line 1,484: Line 1,484:
=={{header|Nim}}==
=={{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:
There is a <code>nil</code> value in Nim, which is the same as a 0. It can be explicitly forbidden as a value:
<lang nim>let s: pointer = nil
<syntaxhighlight lang="nim">let s: pointer = nil


{.experimental: "notnil".}
{.experimental: "notnil".}
let ns: pointer not nil = nil # Compile time error</lang>
let ns: pointer not nil = nil # Compile time error</syntaxhighlight>


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).
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,493: Line 1,493:
Testing if a pointer “p” is <code>nil</code> can be done either by using <code>==</code> or using the procedure <code>isNil</code>.
Testing if a pointer “p” is <code>nil</code> can be done either by using <code>==</code> or using the procedure <code>isNil</code>.


<lang Nim>var p: ptr int
<syntaxhighlight lang="nim">var p: ptr int
if p == nil: echo "it is nil"
if p == nil: echo "it is nil"
if p != nil: echo "it is not nil"
if p != nil: echo "it is not nil"
if p.isNil: echo "it is nil"</lang>
if p.isNil: echo "it is nil"</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{works with|oo2c}}
{{works with|oo2c}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE Null;
MODULE Null;
IMPORT
IMPORT
Line 1,515: Line 1,515:
IF o = NIL THEN Out.String("o is NIL"); Out.Ln END
IF o = NIL THEN Out.String("o is NIL"); Out.Ln END
END Null.
END Null.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,523: Line 1,523:
=={{header|Objeck}}==
=={{header|Objeck}}==
In Objeck, "Nil" is a value of every reference type.
In Objeck, "Nil" is a value of every reference type.
<syntaxhighlight lang="objeck">
<lang Objeck>
# here "object" is a reference
# here "object" is a reference
if(object = Nil) {
if(object = Nil) {
"object is null"->PrintLine();
"object is null"->PrintLine();
};
};
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{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.
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.
<lang objc>// here "object" is an object pointer
<syntaxhighlight lang="objc">// here "object" is an object pointer
if (object == nil) {
if (object == nil) {
NSLog("object is nil");
NSLog("object is nil");
}</lang>
}</syntaxhighlight>
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).
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).
<lang objc>[nil fooBar];</lang>
<syntaxhighlight lang="objc">[nil fooBar];</syntaxhighlight>


Note that <code>nil</code> is distinct from <code>NULL</code>, which is only used for regular C pointers.
Note that <code>nil</code> is distinct from <code>NULL</code>, which is only used for regular C pointers.
Line 1,547: Line 1,547:
=={{header|OCaml}}==
=={{header|OCaml}}==
Maybe the closest type of OCaml would be the type option, which is defined like this in the standard library:
Maybe the closest type of OCaml would be the type option, which is defined like this in the standard library:
<lang ocaml>type 'a option = None | Some of 'a</lang>
<syntaxhighlight lang="ocaml">type 'a option = None | Some of 'a</syntaxhighlight>
<lang ocaml>match v with
<syntaxhighlight lang="ocaml">match v with
| None -> "unbound value"
| None -> "unbound value"
| Some _ -> "bounded value"</lang>
| Some _ -> "bounded value"</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 1,558: Line 1,558:
When a method or function is called, all local variables begin with null value.
When a method or function is called, all local variables begin with null value.


<lang Oforth>null isNull
<syntaxhighlight lang="oforth">null isNull
"abcd" isNull
"abcd" isNull
: testNull { | a | a ifNull: [ "Variable value is null" println ] ;</lang>
: testNull { | a | a ifNull: [ "Variable value is null" println ] ;</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
Line 1,569: Line 1,569:
=={{header|ooRexx}}==
=={{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).
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"
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:
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:
<lang ooRexx>a=.array~of('A','B')
<syntaxhighlight lang="oorexx">a=.array~of('A','B')
i=3
i=3
if a[i] == .nil then say "Item" i "of array A is missing"
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("INPUT") then say "Variable INPUT is not assigned"
if \var("var") then say "Variable" var "is not assigned"</lang>
if \var("var") then say "Variable" var "is not assigned"</syntaxhighlight>
Output:
Output:
<pre>Item 3 of array A is missing
<pre>Item 3 of array A is missing
Line 1,587: Line 1,587:
===Unbound variables===
===Unbound variables===
If an unbound variable is accessed, the current thread will be suspended:
If an unbound variable is accessed, the current thread will be suspended:
<lang oz>declare
<syntaxhighlight lang="oz">declare
X
X
in
in
{Show X+2} %% blocks</lang>
{Show X+2} %% blocks</syntaxhighlight>
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].
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===
===Undefined values===
Line 1,596: Line 1,596:


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.
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.
<lang oz>declare
<syntaxhighlight lang="oz">declare
X = {Value.failed dontTouchMe}
X = {Value.failed dontTouchMe}
in
in
{Wait X} %% throws dontTouchMe</lang>
{Wait X} %% throws dontTouchMe</syntaxhighlight>


Sometimes algebraic data types like Haskell's Maybe are simulated using records.
Sometimes algebraic data types like Haskell's Maybe are simulated using records.
<lang oz>declare
<syntaxhighlight lang="oz">declare
X = just("Data")
X = just("Data")
in
in
case X of nothing then skip
case X of nothing then skip
[] just(Result) then {Show Result}
[] just(Result) then {Show Result}
end</lang>
end</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
GP does not have good facilities for this, but this test suffices for most purposes:
GP does not have good facilities for this, but this test suffices for most purposes:
<lang parigp>foo!='foo</lang>
<syntaxhighlight lang="parigp">foo!='foo</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,624: Line 1,624:


You can check to see if a value is <code>undef</code> by using the <code>defined</code> operator:
You can check to see if a value is <code>undef</code> by using the <code>defined</code> operator:
<lang perl>print defined($x) ? 'Defined' : 'Undefined', ".\n";</lang>
<syntaxhighlight lang="perl">print defined($x) ? 'Defined' : 'Undefined', ".\n";</syntaxhighlight>
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>.
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:
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:
<lang perl>say $number // "unknown";</lang>
<syntaxhighlight lang="perl">say $number // "unknown";</syntaxhighlight>
prints $number if it is defined (even if it is false) or the string "unknown" otherwise.
prints $number if it is defined (even if it is false) or the string "unknown" otherwise.


Line 1,635: Line 1,635:
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:
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:


<!--<lang Phix>-->
<!--<syntaxhighlight lang="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;">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>
<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,653: Line 1,653:
<span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">NULL</span>
<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>
<span style="color: #000080;font-style:italic;">--q = 1 -- error</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


See also [[Undefined_values#Phix|Undefined_values]]
See also [[Undefined_values#Phix|Undefined_values]]
Line 1,659: Line 1,659:
=={{header|PHL}}==
=={{header|PHL}}==


<lang phl>if (obj == null) printf("obj is null!\n");</lang>
<syntaxhighlight lang="phl">if (obj == null) printf("obj is null!\n");</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
There is a special value <tt>NULL</tt>. You can test for it using <tt>is_null()</tt> or <tt>!isset()</tt>
There is a special value <tt>NULL</tt>. You can test for it using <tt>is_null()</tt> or <tt>!isset()</tt>
<lang php>$x = NULL;
<syntaxhighlight lang="php">$x = NULL;
if (is_null($x))
if (is_null($x))
echo "\$x is null\n";</lang>
echo "\$x is null\n";</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Line 1,672: Line 1,672:
'[http://software-lab.de/doc/refN.html#not not]' is the predicate to check for
'[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.
NIL, but many other (typically flow control) functions can be used.
<lang PicoLisp>(if (not MyNewVariable)
<syntaxhighlight lang="picolisp">(if (not MyNewVariable)
(handle value-is-NIL) )</lang>
(handle value-is-NIL) )</syntaxhighlight>
or
or
<lang PicoLisp>(unless MyNewVariable
<syntaxhighlight lang="picolisp">(unless MyNewVariable
(handle value-is-NIL) )</lang>
(handle value-is-NIL) )</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
Line 1,684: Line 1,684:


to tell the difference between a value <math>0</math> and absence of a key, <code>zero_type()</code> is used:
to tell the difference between a value <math>0</math> and absence of a key, <code>zero_type()</code> is used:
<lang Pike>> mapping bar;
<syntaxhighlight lang="pike">> mapping bar;
> bar;
> bar;
Result: 0
Result: 0
Line 1,695: Line 1,695:
Result: 0
Result: 0
> zero_type(bar->baz);
> zero_type(bar->baz);
Result: 1</lang>
Result: 1</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare x fixed decimal (10);
declare x fixed decimal (10);
...
...
Line 1,706: Line 1,706:
...
...
if ^valid(y) then signal error;
if ^valid(y) then signal error;
</syntaxhighlight>
</lang>
Comment:-
Comment:-
In the picture specification, the content of variable y
In the picture specification, the content of variable y
Line 1,715: Line 1,715:
=={{header|PowerShell}}==
=={{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.
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.
<lang powershell>if ($null -eq $object) {
<syntaxhighlight lang="powershell">if ($null -eq $object) {
...
...
}</lang>
}</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
All variables that has not yet been given any other value will be initiated to #Null
All variables that has not yet been given any other value will be initiated to #Null
<lang PureBasic>If variable = #Null
<syntaxhighlight lang="purebasic">If variable = #Null
Debug "Variable has no value"
Debug "Variable has no value"
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>x = None
<syntaxhighlight lang="python">x = None
if x is None:
if x is None:
print "x is None"
print "x is None"
else:
else:
print "x is not None"</lang>
print "x is not None"</syntaxhighlight>
Output:<pre>
Output:<pre>
x is None
x is None
Line 1,737: Line 1,737:
=={{header|R}}==
=={{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.
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.
<lang R>is.null(NULL) # TRUE
<syntaxhighlight lang="r">is.null(NULL) # TRUE
is.null(123) # FALSE
is.null(123) # FALSE
is.null(NA) # FALSE
is.null(NA) # FALSE
123==NULL # Empty logical value, with a warning
123==NULL # Empty logical value, with a warning
foo <- function(){} # function that does nothing
foo <- function(){} # function that does nothing
foo() # returns NULL</lang>
foo() # returns NULL</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,749: Line 1,749:
sometimes it is used as a generic null value.
sometimes it is used as a generic null value.


<syntaxhighlight lang="racket">
<lang Racket>
-> null
-> null
'()
'()
Line 1,756: Line 1,756:
-> (null? 3)
-> (null? 3)
#f
#f
</syntaxhighlight>
</lang>


But a value that is more used as a generic "nothing" value is "#f",
But a value that is more used as a generic "nothing" value is "#f",
Line 1,777: Line 1,777:
Most containers default to an object of type <tt>Any</tt> so you don't accidentally send quantum superpositions (junctions) around in your program.
Most containers default to an object of type <tt>Any</tt> so you don't accidentally send quantum superpositions (junctions) around in your program.


<lang perl6>my $var;
<syntaxhighlight lang="raku" line>my $var;
say $var.WHAT; # Any()
say $var.WHAT; # Any()
$var = 42;
$var = 42;
Line 1,784: Line 1,784:
$var = Nil;
$var = Nil;
say $var.WHAT; # Any()
say $var.WHAT; # Any()
say $var.defined # False</lang>
say $var.defined # False</syntaxhighlight>


You can declare a variable of type <tt>Mu</tt> if you wish to propagate superpositional types:
You can declare a variable of type <tt>Mu</tt> if you wish to propagate superpositional types:


<lang perl6>my Mu $junction;
<syntaxhighlight lang="raku" line>my Mu $junction;
say $junction.WHAT; # Mu()
say $junction.WHAT; # Mu()
$junction = 1 | 2 | 3;
$junction = 1 | 2 | 3;
say $junction.WHAT; # Junction()</lang>
say $junction.WHAT; # Junction()</syntaxhighlight>


Or you can declare a more restricted type than <tt>Any</tt>
Or you can declare a more restricted type than <tt>Any</tt>


<lang perl6>my Str $str;
<syntaxhighlight lang="raku" line>my Str $str;
say $str.WHAT; # Str()
say $str.WHAT; # Str()
$str = "I am a string.";
$str = "I am a string.";
say $str.WHAT; # Str()
say $str.WHAT; # Str()
$str = 42; # (fails)</lang>
$str = 42; # (fails)</syntaxhighlight>


But in the Raku view of reality, it's completely bogus to ask
But in the Raku view of reality, it's completely bogus to ask
Line 1,817: Line 1,817:
=={{header|Raven}}==
=={{header|Raven}}==
{{improve|Raven|Add NULL handling with MySQL data.}}
{{improve|Raven|Add NULL handling with MySQL data.}}
<lang Raven>NULL as $v
<syntaxhighlight lang="raven">NULL as $v
$v NULL = # TRUE
$v NULL = # TRUE
$v NULL != # FALSE
$v NULL != # FALSE
Line 1,825: Line 1,825:


NULL as $v2
NULL as $v2
$v2 $v = # TRUE</lang>
$v2 $v = # TRUE</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>x: none
<syntaxhighlight lang="rebol">x: none


print ["x" either none? x ["is"]["isn't"] "none."]</lang>
print ["x" either none? x ["is"]["isn't"] "none."]</syntaxhighlight>


Output:
Output:
Line 1,838: Line 1,838:
REBOL also has the concept of <code>unset</code> values, testable with <code>get/any</code>
REBOL also has the concept of <code>unset</code> values, testable with <code>get/any</code>


<lang REBOL>unset? get/any 'some-var
<syntaxhighlight lang="rebol">unset? get/any 'some-var
unset? get 'some-var</lang>
unset? get 'some-var</syntaxhighlight>


{{out}}
{{out}}
Line 1,852: Line 1,852:
<br>A variable with a &nbsp; '''null''' &nbsp; value has a length of &nbsp; '''0''' &nbsp; (zero).
<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.
<br><br>The &nbsp; '''drop''' &nbsp; statement can be used to "undefine" a REXX variable.
<lang rexx>/*REXX program demonstrates null strings, and also undefined values. */
<syntaxhighlight lang="rexx">/*REXX program demonstrates null strings, and also undefined values. */


if symbol('ABC')=="VAR" then say 'variable ABC is defined, value='abc"<<<"
if symbol('ABC')=="VAR" then say 'variable ABC is defined, value='abc"<<<"
Line 1,864: Line 1,864:
cat=''
cat=''
if symbol('CAT')=="VAR" then say 'variable CAT is defined, value='cat"<<<"
if symbol('CAT')=="VAR" then say 'variable CAT is defined, value='cat"<<<"
else say "variable CAT isn't defined."</lang>
else say "variable CAT isn't defined."</syntaxhighlight>
'''output'''
'''output'''
<pre style=overflow:scroll">
<pre style=overflow:scroll">
Line 1,874: Line 1,874:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
see isnull(5) + nl + # print 0
see isnull(5) + nl + # print 0
isnull("hello") + nl + # print 0
isnull("hello") + nl + # print 0
Line 1,880: Line 1,880:
isnull("") + nl + # print 1
isnull("") + nl + # print 1
isnull("NULL") # print 1
isnull("NULL") # print 1
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
The value when referring to the instance variable which isn't initialized is nil.
The value when referring to the instance variable which isn't initialized is nil.
<lang ruby>puts "@object is nil" if @object.nil? # instance variable
<syntaxhighlight lang="ruby">puts "@object is nil" if @object.nil? # instance variable


puts "$object is nil" if $object.nil? # global variable, too
puts "$object is nil" if $object.nil? # global variable, too
Line 1,893: Line 1,893:


# nil itself is an object:
# nil itself is an object:
puts nil.class # => NilClass</lang>
puts nil.class # => NilClass</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,904: Line 1,904:
=={{header|Rust}}==
=={{header|Rust}}==


<lang rust>// If an option may return null - or nothing - in Rust, it's wrapped
<syntaxhighlight 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 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
// in <> or None. We can check this using .is_some() and .is_none() on
Line 1,923: Line 1,923:
possible_number = Some(31);
possible_number = Some(31);
check_number(&possible_number);
check_number(&possible_number);
}</lang>
}</syntaxhighlight>


=={{header|S-lang}}==
=={{header|S-lang}}==
S-Lang uses NULL; it is the only object of type Null_Type:
S-Lang uses NULL; it is the only object of type Null_Type:
<lang S-lang>variable foo = NULL;
<syntaxhighlight lang="s-lang">variable foo = NULL;
print(foo);
print(foo);
if (foo == NULL)
if (foo == NULL)
print(typeof(foo));
print(typeof(foo));
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>NULL
<pre>NULL
Line 1,940: Line 1,940:
[http://blog.sanaulla.info/2009/07/12/nothingness/ This blog post] has a good explanations of the different types of null-like values.
[http://blog.sanaulla.info/2009/07/12/nothingness/ This blog post] has a good explanations of the different types of null-like values.


<lang scala>
<syntaxhighlight lang="scala">
scala> Nil
scala> Nil
res0: scala.collection.immutable.Nil.type = List()
res0: scala.collection.immutable.Nil.type = List()
Line 1,963: Line 1,963:
scala> val a = println()
scala> val a = println()
a: Unit = ()
a: Unit = ()
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(null? object)</lang>
<syntaxhighlight lang="scheme">(null? object)</syntaxhighlight>
Note: "null?" here tests whether a value is the empty list.
Note: "null?" here tests whether a value is the empty list.


=={{header|Sidef}}==
=={{header|Sidef}}==
The absence of a value is represented by ''nil''
The absence of a value is represented by ''nil''
<lang ruby>var undefined; # initialized with an implicit nil
<syntaxhighlight lang="ruby">var undefined; # initialized with an implicit nil
say undefined==nil; # true
say undefined==nil; # true
say defined(nil) # false</lang>
say defined(nil) # false</syntaxhighlight>


However, ''nil'' is not an object, so we can't call methods on it. Alternatively, Sidef provides the ''null'' object:
However, ''nil'' is not an object, so we can't call methods on it. Alternatively, Sidef provides the ''null'' object:


<lang ruby>var null_obj = null; # initialize with a null value
<syntaxhighlight lang="ruby">var null_obj = null; # initialize with a null value
say null_obj.is_a(null); # true
say null_obj.is_a(null); # true
say defined(null_obj); # true</lang>
say defined(null_obj); # true</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>Nil isNil = True.</lang>
<syntaxhighlight lang="slate">Nil isNil = True.</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


<lang smalltalk>object isNil ifTrue: [ "true block" ]
<syntaxhighlight lang="smalltalk">object isNil ifTrue: [ "true block" ]
ifFalse: [ "false block" ].
ifFalse: [ "false block" ].
nil isNil ifTrue: [ 'true!' displayNl ]. "output: true!"
nil isNil ifTrue: [ 'true!' displayNl ]. "output: true!"
foo isNil ifTrue: [ 'ouch' displayNl ].
foo isNil ifTrue: [ 'ouch' displayNl ].
x := (foo == nil).
x := (foo == nil).
x := foo isNil</lang>
x := foo isNil</syntaxhighlight>


notice that nil is the singleton instance of the UndefinedObject class; i.e. it is a first class object. Thus we can do:
notice that nil is the singleton instance of the UndefinedObject class; i.e. it is a first class object. Thus we can do:
<lang smalltalk>foo := nil.
<syntaxhighlight lang="smalltalk">foo := nil.
foo class. "-> UndefinedObject"
foo class. "-> UndefinedObject"
foo respondsTo: #'bar'. "asking if a message is implemented"
foo respondsTo: #'bar'. "asking if a message is implemented"


foo class compile:'fancyOperation ^ 123'.
foo class compile:'fancyOperation ^ 123'.
foo fancyOperation "->123"</lang>
foo fancyOperation "->123"</syntaxhighlight>


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.)
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 2,006: Line 2,006:
=={{header|Standard ML}}==
=={{header|Standard ML}}==
Maybe the closest type of Standard ML would be the type option, which is defined like this in the standard library:
Maybe the closest type of Standard ML would be the type option, which is defined like this in the standard library:
<lang sml>datatype 'a option = NONE | SOME of 'a</lang>
<syntaxhighlight lang="sml">datatype 'a option = NONE | SOME of 'a</syntaxhighlight>
<lang sml>case v of NONE => "unbound value"
<syntaxhighlight lang="sml">case v of NONE => "unbound value"
| SOME _ => "bounded value"</lang>
| SOME _ => "bounded value"</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Swift has <code>Optional<T></code> type, where <code>nil</code> means a lack of value.
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>.
<code>T?</code> is syntactic sugar for <code>Optional<T></code>.
<lang swift>let maybeInt: Int? = nil</lang>
<syntaxhighlight lang="swift">let maybeInt: Int? = nil</syntaxhighlight>
To just check if variable is nil, you can use <code>==</code> operator.
To just check if variable is nil, you can use <code>==</code> operator.
<lang swift>if maybeInt == nil {
<syntaxhighlight lang="swift">if maybeInt == nil {
print("variable is nil")
print("variable is nil")
} else {
} else {
print("variable has some value")
print("variable has some value")
}</lang>
}</syntaxhighlight>


Usually you want to access the value after checking if it's nil. To do that you use <code>if let</code>
Usually you want to access the value after checking if it's nil. To do that you use <code>if let</code>
<lang swift>if let certainlyInt = maybeInt {
<syntaxhighlight lang="swift">if let certainlyInt = maybeInt {
print("variable has value \(certainlyInt)")
print("variable has value \(certainlyInt)")
} else {
} else {
print("variable is nil")
print("variable is nil")
}</lang>
}</syntaxhighlight>


=={{header|Tailspin}}==
=={{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.
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.
<lang tailspin>
<syntaxhighlight lang="tailspin">
templates mightBeNothing
templates mightBeNothing
when <=0> do !VOID
when <=0> do !VOID
Line 2,056: Line 2,056:
otherwise 'Produced $(1);. ' !
otherwise 'Produced $(1);. ' !
\) -> !OUT::write
\) -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Produced something. Produced something. Produced nothing. Produced nothing. </pre>
<pre>Produced something. Produced something. Produced nothing. Produced nothing. </pre>


It is an error to try to assign nothing to a symbol or field.
It is an error to try to assign nothing to a symbol or field.
<lang tailspin>
<syntaxhighlight lang="tailspin">
// throws an error
// throws an error
def nothing: 0 -> mightBeNothing;
def nothing: 0 -> mightBeNothing;
Line 2,070: Line 2,070:
// OK, simply results in the empty structure without a field called 'nothing'
// OK, simply results in the empty structure without a field called 'nothing'
{ 0 -> mightBeNothing -> (nothing: $) }
{ 0 -> mightBeNothing -> (nothing: $) }
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{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:
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:
<lang Tcl>if {$value eq ""} ...</lang>
<syntaxhighlight lang="tcl">if {$value eq ""} ...</syntaxhighlight>
A stricter approximation to NULL can be had with non-existing variables or elements of a dict or array:
A stricter approximation to NULL can be had with non-existing variables or elements of a dict or array:
<lang Tcl>if {![info exist nullvar]} ...
<syntaxhighlight lang="tcl">if {![info exist nullvar]} ...
if {![info exists arr(nullval)]} ...
if {![info exists arr(nullval)]} ...
if {![dict exists $dic nullval]} ...</lang>
if {![dict exists $dic nullval]} ...</syntaxhighlight>
Note that lists do not support anything like nulls, since they are strictly sequences of values.
Note that lists do not support anything like nulls, since they are strictly sequences of values.


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa># the type at declaration doesn't matter
<syntaxhighlight lang="ursa"># the type at declaration doesn't matter
decl int x
decl int x


Line 2,090: Line 2,090:
else
else
out "x is not null" endl console
out "x is not null" endl console
end if</lang>
end if</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public Sub Main()
<syntaxhighlight lang="vb">Public Sub Main()
Dim c As VBA.Collection
Dim c As VBA.Collection
Line 2,106: Line 2,106:
Set c = Nothing
Set c = Nothing
Debug.Print c Is Nothing
Debug.Print c Is Nothing
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
{{works with|VB6}}
{{works with|VB6}}
Null by the definition of this task is called "Nothing" in VB6:
Null by the definition of this task is called "Nothing" in VB6:
<syntaxhighlight lang="vb">
<lang vb>
Public Sub Main()
Public Sub Main()
Dim c As VBA.Collection
Dim c As VBA.Collection
Line 2,127: Line 2,127:


End Sub
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.
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()
Public Sub Main()
Dim v As Variant
Dim v As Variant
Line 2,147: Line 2,147:


End Sub
End Sub
</syntaxhighlight>
</lang>


=={{header|Wart}}==
=={{header|Wart}}==
The null value <code>nil</code> is also the only false value.
The null value <code>nil</code> is also the only false value.
<lang wart>(not nil)
<syntaxhighlight lang="wart">(not nil)
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
Line 2,164: Line 2,164:


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.
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.
<lang ecmascript>// Declare a variable without giving it an explicit value.
<syntaxhighlight lang="ecmascript">// Declare a variable without giving it an explicit value.
var s
var s


Line 2,181: Line 2,181:
var g = f.call()
var g = f.call()
// We find that the return value is null.
// We find that the return value is null.
System.print(g)</lang>
System.print(g)</syntaxhighlight>


{{out}}
{{out}}
Line 2,195: Line 2,195:
=={{header|zkl}}==
=={{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.
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.
<lang zkl>if(Void == n) ...
<syntaxhighlight lang="zkl">if(Void == n) ...
return(Void)</lang>
return(Void)</syntaxhighlight>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
Line 2,202: Line 2,202:
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.)
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.)


<lang z80>ld a,(&0000) ;dereference the null pointer as a uint8
<syntaxhighlight lang="z80">ld a,(&0000) ;dereference the null pointer as a uint8
ld hl,(&0000) ;dereference the null pointer as a uint16</lang>
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:
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:
<lang z80>LD HL,myPointers
<syntaxhighlight lang="z80">LD HL,myPointers
;there is no LD BC,(HL) so we have to do this:
;there is no LD BC,(HL) so we have to do this:
LD c,(hl)
LD c,(hl)
Line 2,214: Line 2,214:
LD a,b
LD a,b
or c ;compare BC to zero
or c ;compare BC to zero
JR z,isNull</lang>
JR z,isNull</syntaxhighlight>


{{omit from|GUISS}}
{{omit from|GUISS}}