CloudFlare suffered a massive security issue affecting all of its customers, including Rosetta Code. All passwords not changed since February 19th 2017 have been expired, and session cookie longevity will be reduced until late March.--Michael Mol (talk) 05:15, 25 February 2017 (UTC)

Null object

From Rosetta Code
Null object
You are encouraged to solve this task according to the task description, using any language you may know.

Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't.


Show how to access null in your language by checking to see if an object is equivalent to the null object.

This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.


null? if "item was null" . then


if (object == null)
trace("object is null");

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


with Ada.Text_Io;
if Object = null then
Ada.Text_Io.Put_line("object is null");
end if;

ALGOL 68[edit]

In ALGOL 68 the NIL yields a name that does not refer to any value. NIL can never be naturally coerced and can only appear where the context is strong.

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d
REF STRING no result = NIL;
STRING result := "";
IF no result :=: NIL THEN print(("no result :=: NIL", new line)) FI;
IF result :/=: NIL THEN print(("result :/=: NIL", new line)) FI;
IF no result IS NIL THEN print(("no result IS NIL", new line)) FI;
IF result ISNT NIL THEN print(("result ISNT NIL", new line)) FI;
COMMENT using the UNESCO/IFIP/WG2.1 ALGOL 68 character set
result := °;
IF REF STRING(result) :≠: ° THEN print(("result ≠ °", new line)) FI;
# Note the following gotcha: #
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


no result :=: NIL
result :/=: NIL
no result IS NIL
result ISNT NIL
The address of var ISNT NIL
The address of var IS REF STRING(NIL)

NIL basically is an untyped ref (pointer) that does not refer anywhere.

ALGOL 68 also has empty. This is a "constant" of size 0 and type void. c.f. Roots of a function for two different examples of usage.

  • empty as an undefined argument to a routine.
  • empty as a routine return if no result is found.

empty is typically used to refer to am empty leaf in a tree structure.


  • ALGOL 68's empty is python's None,
  • ALGOL 68's void is python's NoneType, and
  • ALGOL 68's nil is python's hash(None)

ALGOL W[edit]

 % declare a record type - will be accessed via references  %
record R( integer f1, f2, f3 );
 % declare a reference to a R instance  %
reference(R) refR;
 % assign null to the reference  %
refR := null;
 % test for a null reference - will write "refR is null"  %
if refR = null then write( "refR is null" ) else write( "not null" );


DEF x : PTR TO object
-> ...
IF object <> NIL
-> ...


Many applications will return missing value, but null is also available.

if x is missing value then
display dialog "x is missing value"
end if
if x is null then
display dialog "x is null"
end if


If (object == null)
MsgBox, object is null


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.

#!/usr/bin/awk -f
print "<"b,length(b)">"
print "<"u,length(u)">"
print "<"u+0,length(u+0)">";


<0 1>
< 0>
<0 1>


Null pointers can be checked by simply comparing the pointer with 0.

If P=0
Disp "NULL PTR",i


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.

{ nil { nil? } { "Whew!\n" } { "Something is terribly wrong!\n" } ifte << }


Applesoft BASIC[edit]


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.

TRUE = 1 : FALSE = 0


A null object has a pointer with a value of zero or one.

DEF PROCtestobjects
PRIVATE a(), b(), s{}, t{}
DIM a(123)
DIM s{a%, b#, c$}
IF !^a() <= 1 PRINT "a() is null" ELSE PRINT "a() is not null"
IF !^b() <= 1 PRINT "b() is null" ELSE PRINT "b() 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"


a() is not null
b() is null
s{} is not null
t{} is null


Bracmat has no null objects.

The operators for multiplication, addition and concatenation have neutral elements, which are 1, 0 and the empty string, respectively, but these are values like any other string.

a:?x*a*?z {assigns 1 to x and to z}
a:?x+a+?z {assigns 0 to x and to z}
a:?x a ?z {assigns "" (or (), which is equivalent) to x and to z}


C has the null pointer, written as "0", whose internal representation is often, though not always, the same as integer zero. It is (supposedly) garanteed to be pointing to nothing, so receiving one of those likely means you are not looking at an object--but, there are occasions where changing content of a null pointer actually does something (say, on DOS); and a function that's supposed to return a pointer on success doesn't always return a 0 otherwise (e.g. mmap returns -1 for failure).

There is a very common macro, NULL, which evaluates to (void*) 0 or an equivalent value. NULL is compatible with all pointer types, including both data pointers and function pointers.

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.

#include <stdio.h>
int main()
char *object = 0;
if (object == NULL) {
puts("object is null");
return 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.

#include <iostream>
#include <cstdlib>
if (object == 0) {
std::cout << "object is null";

boost::optional is available for cases where the programmer wishes to pass by value, but still support a null value.

#include <boost/optional.hpp>
#include <iostream>
boost::optional<int> maybeInt()
int main()
boost::optional<int> maybe = maybeInt();
std::cout << "object is null\n";


In C++11 there is nullptr of type nullptr_t which represents a pointer to an invalid place. You can use it like

int *p = nullptr;
if (p == nullptr){
// do some thing
//or just
if (p){
// do some thing


As with Java, any reference type may be null, and testing for nullity uses ordinary boolean operators.

if (foo == null)
Console.WriteLine("foo is null");

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# version 2.0+
int? x = 12;
x = 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# version 2.0+
Console.WriteLine(name ?? "Name not specified");
//Without the null coalescing operator, this would instead be written as:
//if(name == null){
// Console.WriteLine("Name not specified");
// Console.WriteLine(name);


Objects variables without an initializer expression will be initiallized to nil:

class C { };
var c:C; // is nil
writeln(if c == nil then "nil" else "something");


Clojure's nil is equivalent to Java's null.

(let [x nil]
(println "Object is" (if (nil? x) "nil" "not nil")))

Test wether symbol foo is defined:

(find (ns-interns *ns*) 'foo)

Undefining foo:

(ns-unmap *ns* 'foo)


Works with GnuCOBOL 2.0

       identification division.
program-id. null-objects.
remarks. test with cobc -x -j null-objects.cob
data division.
working-storage section.
01 thing-not-thing usage pointer.
*> call a subprogram
*> with one null pointer
*> an omitted parameter
*> and expect void return (callee returning omitted)
*> and do not touch default return-code (returning nothing)
procedure division.
call "test-null" using thing-not-thing omitted returning nothing
end program null-objects.
*> Test for pointer to null (still a real thing that takes space)
*> and an omitted parameter, (call frame has placeholder)
*> and finally, return void, (omitted)
identification division.
program-id. test-null.
data division.
linkage section.
01 thing-one usage pointer.
01 thing-two pic x.
procedure division using
optional thing-two
returning omitted.
if thing-one equal null then
display "thing-one pointer to null" upon syserr
if thing-two omitted then
display "no thing-two was passed" upon syserr
end program test-null.
prompt$ cobc -x -j null-objects.cob
thing-one pointer to null
no thing-two was passed

Common Lisp[edit]


Common Lisp has an object denoted by the symbol nil. When the symbol nil is evaluated as an expression, it evaluates to itself.

nil uniquely represents boolean false, and so code like
(if (condition) (do-this))
is actually testing whether (condition) returns the value nil. The object nil 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. (list (values)) produces (nil) (list containing one element, which is the empty list), because (values) produces no value, but the function call (list ...) needs to reduce the expression to a single argument value, and so nil is supplied.

Beginnings of Null Object[edit]

The idea of making functions accept nil without failing did not appear in early Lisps. For instance (car nil) was erroneous: it was incorrect to try to access the first element of a non-list.

The defaulting behavior (car nil) which Common Lisp programmers take for granted was introduced in InterLisp, and then copied into MacLisp. (InterLisp had other liberties that do not survive into Common Lisp: it was possible to call a function with insufficient arguments, and the missing ones defaulted to nil. Likewise, excess arguments were ignored. CL has a disciplined syntax and semantics for default and variable arguments.)

This (car nil) -> nil behavior shows nil in an kind of new role: the role of a null object which takes methods that apply to other objects and provides some default non-failing behavior. It is the beginnings of the [null object design pattern].

Object-Oriented Null Object[edit]

In Common Lisp, in fact, there is a class called null, of which the object nil is understood to be the only instance. Furthermore, the null class is at the bottom of the type spindle: it is a subclass of every class. This is in contrast with the type T which is a superclass of every class.

Since null is at the bottom of the class hierarchy, it is possible to write methods specialized to parameters of class null which will only be applicable if the argument is the object nil. No other object is a subtype of null.

Some traditional Lisp functions could be expressed using the object system like this. Suppose that the car function did not have a safe defaulting behavior for nil. We could use the methods of the object system to define a car* which does have the safe behavior:

(defmethod car* ((arg cons))
(car arg))
(defmethod car* ((arg null))

Now if we invoke car* on something which is neither a cons, nor nil, we get an error about no applicable method being found.

We can handle that ourselves by writing a method specialized to the master supertype t:

(defmethod car* ((arg t))  ;; can just be written (defmethod car* (arg) ...)
(error "CAR*: ~s is neither a cons nor nil" arg))

The classes t and null are widely exploited in Lisp OO programming.

Component Pascal[edit]

MODULE ObjectNil;
Object = POINTER TO ObjectDesc;
ObjectDesc = RECORD
x: Object; (* default initialization to NIL *)
StdLog.String("x is NIL");StdLog.Ln
END ObjectNil.


In D is is used to perform bitwise identity, like to compare an object reference against null.

import std.stdio;
class K {}
void main() {
K k;
if (k is null)
writeln("k is null");
k = new K;
if (k !is null)
writeln("Now k is not null");
k is null
Now k is not null


  // the following are equivalent
if lObject = nil then
if not Assigned(lObject) then

Déjà Vu[edit]

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:

if not obj:
pass #obj is seen as null
if = :nil obj:
pass #obj is seen as null


See Delphi


object == null


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.

(null? 3) → #f
(!null? 4) → #t
(null? null) → #t
;; careful - null is not false :
(if null 'OUI 'NON) → OUI
;; usual usage : recursion on lists until (null? list)
(define (f list)
(when (!null? list)
(write (first list)) (f (rest list))))
(f '( a b c)) → a b c


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.

feature {NONE} -- Initialization
s: detachable STRING
if i = Void then
print("i = Void")
if s = Void then
print("s = Void")
s = Void


nil is atom in fact:

iex(1)> nil == :nil
iex(2)> is_nil(nil)

nil is thought of as being false in the conditional expression.

If the condition given to if/2 returns false or nil, the body given between do/end is not executed and it simply returns nil.

iex(3)> if nil, do: "not execute"


Erlang does not have an null object.

As an alternative, many applications tend to pick a convention for returning an empty condition and use that.

Example alternatives:

  1. Something like
    {ok, 3} % normal case
    {err, no_more} % error case
    on error.
  2. Don't ever allow an undefined return value, and throw an exception instead.
  3. Return an atom:
    1. undefined*
    2. undef
    3. null
    4. nil
    5. none

undefined is often used by records as an initial value and the stdlib module.

Atoms are erlang's user-defined constants that always evaluates to is itself. It is also equal to no other value else but itself.


As a .Net languages F# inherits the null as a potential value for object variables. 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:

let sl : string list = [null; "abc"]
let f s =
match s with
| null -> "It is null!"
| _ -> "It's non-null: " + s
for s in sl do printfn "%s" (f s)


: is-f? ( obj -- ? ) f = ;


Test for equality with 'null', which is the null value.

fansh> x := null
fansh> x == null
fansh> x = 1
fansh> x == null

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

Int? y := null is valid, but

Int y := null is not.


Standard ANS Forth does not distinguish a particular invalid memory value like NULL. Instead, ALLOCATE returns an out-of-band success code to indicate a failed allocation. Dictionary words have the option of throwing an exception on a dictionary space overrun. Forth lacks a NULL symbol because it has such a wide variety of target platforms. On some embedded targets, the memory space may be as small as 64 direct-mapped addresses, where eliminating a valid zero address would have a high price.

In practice, all notable hosted implementations follow the C practice of being able to treat a zero address (i.e. FALSE) as a null address for the purpose of list termination.


'FB 1.05.0 Win64
' FreeBASIC does not have a NULL keyword but it's possible to create one using a macro
#Define NULL CPtr(Any Ptr, 0) '' Any Ptr is implicitly convertible to pointers of other types
Type Dog
name As String
age As Integer
End Type
Dim d As Dog Ptr = New Dog
d->Name = "Rover"
d->Age = 5
Print d->Name, d->Age
Delete d
d = NULL '' guard against 'd' being used accidentally in future
' in practice many FB developers would simply have written: d = 0 above
Rover          5


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 Go solution of task Undefined values.

package main
import "fmt"
var (
s []int // slice type
p *int // pointer type
f func() // function type
i interface{} // interface type
m map[int]int // map type
c chan int // channel type
func main() {
fmt.Println(s == nil)
fmt.Println(p == nil)
fmt.Println(f == nil)
fmt.Println(i == nil)
fmt.Println(m == nil)
fmt.Println(c == nil)

Output is "true" in each case.


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.

undefined      -- undefined value provided by the standard library
error "oops" -- another undefined value
head [] -- undefined, you can't take the head of an empty list

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:

 data Maybe a = Nothing | Just a

That is, a Maybe Integer is either Nothing or Just <some integer>.

There are many ways to work with Maybe, but here's a basic case expression:

case thing of
Nothing -> "It's Nothing. Or null, whatever."
Just v -> "It's not Nothing; it is " ++ show v ++ "."

Icon and Unicon[edit]

Icon/Unicon have a null value/datatype. It isn't possible to undefine a variable.

procedure main()
nulltest("a",a) # unassigned variables are null by default
nulltest("b",b := &null) # explicit assignment is possible
nulltest("c",c := "anything")
nulltest("c",c := &null) # varibables can't be undefined
procedure nulltest(name,var)
return write(name, if /var then " is" else " is not"," null.")


if(object == nil, "object is nil" println)


J doesn't have an untyped NULL. Instead, it has a concept of "fill". Numeric fill is 0, character fill is the space character, and boxed fill is the ace (a:) which is an empty box. Fill is what is used to pad an array structure when that is needed. (And some operations support using a user specified value in place of the default fill.)

To indicate "missing data", "normal" data is usually pressed into service (e.g. 0 or _1 in a numeric context, ' ' in a literal context, a: in a boxed context, etc). Frequently, missing data is represented by the empty vector '', or other arrays without any elements.

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:

isUndefined=: _1 = [email protected]

Example use:

   isUndefined 'foo'
isUndefined 'foo'

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

Finally, note: the concept of an empty array can be natural in J (and APL) for representing data which is not there -- it is the structural equivalent of the number zero. That said, its implications can sometimes be non-obvious for people coming from a languages which requires that arrays have content. As a result, you will sometimes encounter empty array jokes...

Marie Pennysworth, having spent a productive day shopping, stopped by Robert Cuttingham's butcher shop.
"How much for your t-bones?" she asked.
"Eleven dollars per pound," he responded.
"How about for your sirloin?" she continued.
"Sirloin is thirteen dollars per pound today," he answered.
"But Harkin's Grocery down the street is selling sirloin for nine dollars per pound!" she exclaimed.
"So, why don't you buy it from them?" he asked.
"Well, they're out," she sighed.
He smiled, "When I am out, I only charge seven dollars a pound."

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:

   1 1 0 1#3 4 _ 5           NB. use bitmask to select numbers
3 4 5
I.1 1 0 1 NB. get indices for bitmask
0 1 3
0 1 3 { 3 4 _ 5 NB. use indices to select numbers
3 4 5
1 1 0 1 #inv 3 4 5 NB. use bitmask to restore original positions
3 4 0 5
1 1 0 1 #!._ inv 3 4 5 NB. specify different fill element
3 4 _ 5
3 4 5 (0 1 3}) _ _ _ _ NB. use indices to restore original positions
3 4 _ 5


In Java, "null" is a value of every reference type.

// here "object" is a reference
if (object == null) {
System.out.println("object is null");


In Javascript null is the value that isn't anything. null is not an object, but because of a bug typeof null will return "object".

if (object === null) {
alert("object is null");
// The object is nothing
typeof null === "object"; // This stands since the beginning of JavaScript


jq has null as a value, but while on the subject of nothing, it may be worth mentioning that jq also has a filter, empty, for producing an empty sequence, a.k.a. nothing.

null is distinct from false. Here are some examples:

null|type      # => "null"
null == false # => false
null == null # => true
empty|type # => # i.e. nothing (as in, nada)
empty == empty # => # niente
empty == "black hole" # => # Ничего


K has well developed notions of data null :

The special numeric atoms 0I and 0N refer to integer infinity and “not-a-number” (or “null” in database parlance) concepts, and similarly 0i and 0n for floating-point.

eg : ( 1 2 3 0N 6 7 )

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:
(1;;2) ~ (1 ; _n ; 2) / ~ is ''identical to'' or ''match'' .
_n ~' ( 1 ; ; 2 ) / ''match each''
0 1 0
additional properties : [email protected] and _n?i are i; _n`v is _n

For more detail on K's concept of typed nulls, see


Kotlin distinguishes between non-nullable types and nullable types. The latter are distinguished from the former by a '?' suffix. Only nullable types have a 'null' value indicating that they don't currently refer to an object of their non-nullable equivalent.

In addition, Kotlin has a Nothing type which has no instances and is a sub-type of every other type. There is also a nullable Nothing? type whose only value is 'null' and so, technically, this is the type of 'null' itself.

Here are some examples:

// version 1.1.0
fun main(args: Array<String>) {
val i: Int = 3 // non-nullable Int type - can't be assigned null
val j: Int? = null // nullable Int type - can be assigned null
println(null is Nothing?) // test that null is indeed of type Nothing?


local(x = string, y = null)
// 0 (false)
// 1 (true)
#x == null
// false
#y == null
#x->type == 'null'
// false
#y->type == 'null'


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.

put _global.doesNotExist
-- <Void>
put voidP(_global.doesNotExist)
-- 1
x = VOID
put x
-- <Void>
put voidP(x)
-- 1


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

enum class Option[A] {
# Only variables of class Option can be assigned to None.
# Type: Option[integer]
var v = Some(10)
# Valid: v is an Option, and any Option can be assigned to None
v = None
# Invalid! v is an Option[integer], not just a plain integer.
v = 10
# Type: integer
var w = 10
# Invalid! Likewise, w is an integer, not an Option.
w = None


to test :thing
if empty? :thing [print [list or word is empty]]
print empty? []  ; true
print empty? "|| ; true


isnil = (object == nil)


In Maple, NULL and () represent the null object.

a := NULL;
a :=
is (NULL = ());
if a = NULL then
print (NULL);
end if;

A null object is different from an undefined value.

b := Array([1, 2, 3, Integer(undefined), 5]);
b := [ 1 2 3 undefined 5 ]
b := Array([1, 2, 3, Float(undefined), 5]);
b := [ 1 2 3 Float(undefined) 5 ]
b := Array([1, 2, 3, NULL, 5]);
b := [ 1 2 3 5 ]


Mathematica can assign a Null value to a symbol, two examples:

x =.
x = (1 + 2;)

Both set x to be Null. To specifically test is something is Null one can use the SameQ function (with infix operator: ===):


Or equivalent:


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:

x =.;
x = 3;



MATLAB / Octave[edit]

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.

a = []; b='';
if (a)
octave:4> a = []; b='';
octave:5> isempty(a)
ans =  1
octave:6> isempty(b)
ans =  1
octave:7> if (a) 1, else, 0, end;
ans = 0


There is no null object in Maxima. Usually, a function that returns nothing (as the builtin "disp") returns in fact the symbol 'done.


if obj == undefined then print "Obj is undefined"


In Modula-3, NIL is a value, and NULL is a type. The NULL type contains only one value, NIL. NULL is a subtype of all reference types, which allows all reference types to have the value NIL.

This can lead to errors, if for example you write:

VAR foo := NIL

This (most likely incorrectly) gives foo the type NULL, which can only have the value NIL, so trying to assign it anything else will not work. To overcome this problem, you must specify the reference type when declaring foo:

IO.Put("Object is nil.\n");


A variable can be declared implicitly by using it as on the left side in a SET, or by making a new version for the current scope with a NEW statement. A variable can have descendants without having a value set.

The $DATA (or $D) function will return a number:

$DATA returns: Variable is defined
Variable has children   No Yes
No 0 1
Yes 10 11

Or, by examples (in immediate mode):

CACHE>NEW VARI WRITE $DATA(VARI) ;Change to a new scope
<CACHE 1S1>QUIT ;Leave the scope


In NetRexx as in Java, "null" is a value of every reference type.

/* NetRexx */
options replace format comments java crossref symbols binary
robject = Rexx -- create an object for which the value is undefined
say String.valueOf(robject) -- will report the text "null"
if robject = null then say 'Really, it''s "null"!'


Really, it's "null"!


There is a nil value in Nim, which is the same as a 0. It can be explicitly forbidden as a value:

var s: string = nil
var ns: string not nil = nil # Compile time error


Works with: oo2c
Object = POINTER TO ObjectDesc;
ObjectDesc = RECORD
o: Object; (* default initialization to NIL *)
IF o = NIL THEN Out.String("o is NIL"); Out.Ln END
END Null.
o is NIL


The value nil is used to indicate that an object pointer (variable of type id) doesn't point to a valid object.

// here "object" is an object pointer
if (object == nil) {
NSLog("object is nil");

An interesting thing is that in Objective-C, it is possible to send a message to nil, and the program will not crash or raise an exception (nothing will be executed and nil will be returned in place of the usual return value).

[nil fooBar];

Note that nil is distinct from NULL, which is only used for regular C pointers.

For class pointers (values of type Class), they have a separate null pointer value called Nil.

Confusingly, there is also NSNull, a singleton class with one value, [NSNull null], used as a dummy object to represent the lack of a useful object. This is needed in collections like arrays and dictionaries, etc., because they do not allow nil elements, so if you want to represent some "empty" slots in the array you would use this.


In Objeck, "Nil" is a value of every reference type.

# here "object" is a reference
if(object = Nil) {
"object is null"->PrintLine();


Maybe the closest type of OCaml would be the type option, which is defined like this in the standard library:

type 'a option = None | Some of 'a
match v with
| None -> "unbound value"
| Some _ -> "bounded value"


null is an object, the only instance of Null class. When an object is created, all attributes are initiallized to null value. When a method or function is called, all local variables begin with null value.

null isNull
"abcd" isNull
: testNull { | a | a ifNull: [ "Variable value is null" println ] ;


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

if a[i] == .nil then say "Item" i "is missing"

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:

if a[i] == .nil then say "Item" i "of array A is missing"
if \var("INPUT") then say "Variable INPUT is not assigned"
if \var("var") then say "Variable" var "is not assigned"


Item 3 of array A is missing
Variable INPUT is not assigned
Variable VAR is not assigned


There is no explicit null in Oz.

Unbound variables[edit]

If an unbound variable is accessed, the current thread will be suspended:

{Show X+2} %% blocks

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' declarative concurrency.

Undefined values[edit]

Access to undefined values (like using an out-of-range array index or a non-existing record feature) will usually provoke an exception in Oz.

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.

X = {Value.failed dontTouchMe}
{Wait X} %% throws dontTouchMe

Sometimes algebraic data types like Haskell's Maybe are simulated using records.

X = just("Data")
case X of nothing then skip
[] just(Result) then {Show Result}


GP does not have good facilities for this, but this test suffices for most purposes:



See Delphi


In Perl, undef is a special scalar value, kind of like null in other languages. A scalar variable that has been declared but has not been assigned a value will be initialized to undef. (Array and hash variables are initialized to empty arrays or hashes.)

If strict mode is not on, you may start using a variable without declaring it; it will "spring" into existence, with value undef. In strict mode, you must declare a variable before using it. Indexing an array or hash with an index or key that does not exist, will return undef (however, this is not an indication that the index or key does not exist; rather, it could be that it does exist, and the value is undef itself). If warnings is on, most of the time, if you use the undef value in a calculation, it will produce a warning. undef is considered false in boolean contexts.

It is possible to use undef like most other scalar values: you can assign it to a variable (either by doing $var = undef; or undef($var);), return it from a function, assign it to an array element, assign it to a hash element, etc. When you do list assignment (i.e. assign a list to a list of variables on the left side), you can use undef to "skip" over some elements of the list that you don't want to keep.

You can check to see if a value is undef by using the defined operator:

print defined($x) ? 'Defined' : 'Undefined', ".\n";

From the above discussion, it should be clear that if defined returns false, it does not mean that the variable has not been set; rather, it could be that it was explicitly set to undef.

Starting in Perl 5.10, there is also a defined-or operator in Perl. For example:

say $number // "unknown";

prints $number if it is defined (even if it is false) or the string "unknown" otherwise.

Perl 6[edit]

Translation of: Haskell
(as it were...)

In Perl 6 you can name the concept of Nil, but it not considered an object, but rather the absence of an object, more of a "bottom" type. The closest analog in real objects is an empty list, but an empty list is considered defined, while Nil.defined always returns false. Nil is what you get if you try to read off the end of a list, and () is just very easy to read off the end of... :-)

If you try to put Nil into a container, you don't end up with a container that has Nil in it. Instead the container reverts to an uninitialized state that is consistent with the declared type. Hence, Perl 6 has the notion of typed undefined values, that are real objects in the sense of "being there", but are generic in the sense of representing type information without being instantiated as a real object. We call these type objects since they can stand in for real objects when one reasons about the types of objects. So type objects fit into the type hierarchy just as normal objects do. In physics terms, think of them as "type charge carriers" that are there for bookkeeping between the "real" particles.

All type objects derive from Mu, the most-undefined type object, and the object most like "null" in many languages. All other object types derive from Mu, so it is like Object in other languages as well, except Mu also encompasses various objects that are not discrete, such as junctions. So Perl 6 distinguishes Mu from Any, which is the type that functions the most like a discrete, mundane object.

Mostly the user doesn't have to think about it. All object containers behave like "Maybe" types in Haskell terms; they may either hold a valid value or a "nothing" of an appropriate type. Most containers default to an object of type Any so you don't accidentally send quantum superpositions (junctions) around in your program.

my $var;
say $var.WHAT; # Any()
$var = 42;
say $var.WHAT; # Int()
say $var.defined; # True
$var = Nil;
say $var.WHAT; # Any()
say $var.defined # False

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

my Mu $junction;
say $junction.WHAT; # Mu()
$junction = 1 | 2 | 3;
say $junction.WHAT; # Junction()

Or you can declare a more restricted type than Any

my Str $str;
say $str.WHAT; # Str()
$str = "I am a string.";
say $str.WHAT; # Str()
$str = 42; # (fails)

But in the Perl 6 view of reality, it's completely bogus to ask for a way "to see if an object is equivalent to the null object." The whole point of such a non-object object is that it doesn't exist, and can't participate in computations. If you think you mean the null object in Perl 6, you really mean some kind of generic object that is uninstantiated, and hence undefined. One of those is your "null object", except there are many of them, so you can't just check for equivalence. Use the defined predicate (or match on a subclass of your type that forces recognition of abstraction or definedness).

Perl 6 also has Failure objects that, in addition to being undefined carriers of type, are also carriers of the reason for the value's undefinedness. We tend view them as lazily thrown exceptions, at least until you try to use them as defined values, in which case they're thrown for real.


There is a builtin NULL, however it is equivalent to the integer 0 and will trigger a type check if assigned to a variable declared as string or sequence. In most programs the zero-length string/sequence (""/{}) suffices, 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:

type nullableString(object o)
return string(o) or o=NULL
end type
nullableString s
s = "hello"
s = NULL
--s = 1 -- error
--s = {1,2,3} -- error
type nullableSequence(object o)
return sequence(o) or o=NULL
end type
nullableSequence q
q = {1,2,3}
q = "string" -- fine (strings are a subset of sequences)
q = NULL
--q = 1 -- error

See also Undefined_values


if (obj == null) printf("obj is null!\n");


There is a special value NULL. You can test for it using is_null() or !isset()

$x = NULL;
if (is_null($x))
echo "\$x is null\n";


New internal symbols are initialized with the value NIL. NIL is also the value for "false", so there is never really an "undefined value". 'not' is the predicate to check for NIL, but many other (typically flow control) functions can be used.

(if (not MyNewVariable)
(handle value-is-NIL) )


(unless MyNewVariable
(handle value-is-NIL) )


In Pike all variables are initialized to , regardless of their type. thus functions as a Null value for all types except integer.

is also used to indicate the absence of a key or object member.

to tell the difference between a value and absence of a key, zero_type() is used:

> mapping bar;
> bar;
Result: 0
> bar = ([ "foo":0 ]);
> bar->foo;
Result 0;
> zero_type(bar->foo);
Result: 0
> bar->baz;
Result: 0
> zero_type(bar->baz);
Result: 1


declare x fixed decimal (10);
if ^valid(x) then signal error;
declare y picture 'A9XAAA9';
if ^valid(y) then signal error;

Comment:- In the picture specification, the content of variable y must consist of letters where the letter 'A' is given, digits or space where the digit '9' appears, and the letter X signfies that any character is acceptable.


In PowerShell the automatic variable $null represents a null value. Comparisons are not left/right symmetrical which means placing $null on the left side greatly assists when comparing to an array.

if ($null -eq $object) {


All variables that has not yet been given any other value will be initiated to #Null

If variable = #Null
Debug "Variable has no value"


x = None
if x is None:
print "x is None"
print "x is not None"
x is None


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.

is.null(NULL)       # TRUE
is.null(123) # FALSE
is.null(NA) # FALSE
123==NULL # Empty logical value, with a warning
foo <- function(){} # function that does nothing
foo() # returns NULL


"null", or its literal form "'()", is used to denote empty lists and sometimes it is used as a generic null value.

-> null
-> (null? null)
-> (null? 3)

But a value that is more used as a generic "nothing" value is "#f", false. Racket also has a void value, mostly the result of side-effect functions. (And an undefined value.)


This example is in need of improvement:
Add NULL handling with MySQL data.
NULL as $v
$v NULL = # TRUE
$v NULL != # FALSE
1.1 NULL = # FALSE
NULL as $v2
$v2 $v = # TRUE


x: none
print ["x" either none? x ["is"]["isn't"] "none."]


x is none.

REBOL also has the concept of unset values, testable with get/any

unset? get/any 'some-var
unset? get 'some-var
** Script Error: some-var has no value
** Near: unset? get 'some-var


REXX can have variables with a null value.
With the   symbol   built-in function, it can be determined if a variable is defined (or not).
The   length   built-in function can be used to see what the length of the value of a defined variable.
A variable with a   null   value has a length of   0   (zero).

The   drop   statement can be used to "undefine" a REXX variable.

/*REXX program demonstrates null strings, and also undefined values. */
if symbol('ABC')=="VAR" then say 'variable ABC is defined, value='abc"<<<"
else say "variable ABC isn't defined."
if symbol('XYZ')=="VAR" then say 'variable XYZ is defined, value='xyz"<<<"
else say "variable XYZ isn't defined."
drop xyz
if symbol('XYZ')=="VAR" then say 'variable XYZ is defined, value='xyz"<<<"
else say "variable XYZ isn't defined."
if symbol('CAT')=="VAR" then say 'variable CAT is defined, value='cat"<<<"
else say "variable CAT isn't defined."


variable ABC isn't defined.
variable XYZ is defined, value=47<<<
variable XYZ isn't defined.
variable CAT is defined, value=<<<


see isnull(5) + nl + # print 0
isnull("hello") + nl + # print 0
isnull([1,3,5]) + nl + # print 0
isnull("") + nl + # print 1
isnull("NULL") # print 1


The value when referring to the instance variable which isn't initialized is nil.

puts "@object is nil" if @object.nil?		# instance variable
puts "$object is nil" if $object.nil? # global variable, too
# It recognizes as the local variable even if it isn't executed.
object = 1 if false
puts "object is nil" if object.nil?
# nil itself is an object:
puts nil.class # => NilClass
@object is nil
$object is nil
object is nil


// If an option may return null - or nothing - in Rust, it's wrapped
// in an Optional which may return either the type of object specified
// in <> or None. We can check this using .is_some() and .is_none() on
// the Option.
fn check_number(num: &Option<u8>) {
if num.is_none() {
println!("Number is: None");
} else {
println!("Number is: {}", num.unwrap());
fn main() {
let mut possible_number: Option<u8> = None;
possible_number = Some(31);


S-Lang uses NULL; it is the only object of type Null_Type:

variable foo = NULL;
if (foo == NULL)


This blog post has a good explanations of the different types of null-like values.

scala> Nil
res0: scala.collection.immutable.Nil.type = List()
scala> Nil == List()
res1: Boolean = true
scala> Null
<console>:8: error: not found: value Null
scala> null
res3: Null = null
scala> None
res4: None.type = None
scala> Unit
res5: Unit.type = object scala.Unit
scala> val a = println()
a: Unit = ()


(null? object)

Note: "null?" here tests whether a value is the empty list.


The absence of a value is represented by nil

var undefined;         # initialized with an implicit nil
say undefined==nil; # true
say defined(nil) # false

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

var null_obj = null;        # initialize with a null value  
say null_obj.is_a(null); # true
say defined(null_obj); # true


Nil isNil = True.


object isNil ifTrue: [ "true block" ]
ifFalse: [ "false block" ].
nil isNil ifTrue: [ 'true!' displayNl ]. "output: true!"
foo isNil ifTrue: [ 'ouch' displayNl ].
x := (foo == nil).
x := foo isNil

notice that nil is the singleton instance of the UndefinedObject class; i.e. it is a first class object. Thus we can do:

foo := nil.
foo class. "-> UndefinedObject"
foo respondsTo: #'bar'. "asking if a message is implemented"
foo class compile:'fancyOperation ^ 123'.
foo fancyOperation "->123"

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

Standard ML[edit]

Maybe the closest type of Standard ML would be the type option, which is defined like this in the standard library:

datatype 'a option = NONE | SOME of 'a
case v of NONE => "unbound value"
| SOME _ => "bounded value"


The closest thing in Swift are optional types.

var opt : Int? = nil // use "nil" to represent no value
opt = 5 // or simply assign a value to the optional type

To deconstruct it, use if let:

if let v = opt {
println("There is some value: \(v)")
} else {
println("There is no value")


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:

if {$value eq ""} ...

A stricter approximation to NULL can be had with non-existing variables or elements of a dict or array:

if {![info exist nullvar]} ...
if {![info exists arr(nullval)]} ...
if {![dict exists $dic nullval]} ...

Note that lists do not support anything like nulls, since they are strictly sequences of values.


# the type at declaration doesn't matter
decl int x
set x null
if (= x null)
out "x is null" endl console
out "x is not null" endl console
end if


The null value nil is also the only false value.

(not nil)


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.

if(Void == n) ...