6. Operators

Velocity knows a number of relational and logical operators. They can be used everywhere an expression is evaluated, most prominently in #if and #set directives.

Each operator is available in two notations, a short version which is roughly equal to the Java notation and a text representation which can be used to avoid problems e.g. with XML templates and the <, > and && operators.

Example 6.1. Using operators

#set ($a = true)
#set ($b = false)

#if ($a || $b)
  short version 'or' was true
#end

#if ($a and $b)
  text version 'and' was true
#end


Table 6.1. Velocity Relational and logical operators

Type of operatorshort versiontext version
equal[1]==eq
not equal!=ne
greater than>gt
greater or equal than>=ge
less than<lt
less or equal than<=le
logical and&&and
logical or||or
logical not!not

[1] Note that the semantics of the equal operator are slightly different than Java where== can only be used to test object equality. In Velocity the equivalent operator can be used to directly compare numbers, strings, or objects. When the objects are of different classes, the string representations are obtained by calling toString() for each object and then compared.


[Caution]Caution

Unlike other languages, Velocity does not consider the number 0 (zero) or the empty String ('') to be equivalent to false. Only the boolean value false (primitive oder Boolean.FALSE) and null are evaluated to false. Everything else evaluates to true.[13]

Here is a simple example to illustrate how the equivalent operator is used.

#set ($foo = "deoxyribonucleic acid")
#set ($bar = "ribonucleic acid")

#if ($foo == $bar)
  In this case it's clear they aren't equivalent. So...
#else
  They are not equivalent and this will be the output.
#end

The text versions of all logical operators can be used to avoid problems with < and > in XML templates.

6.1 The AND Operator

## logical AND

#if( $foo && $bar )
  <strong>This AND that</strong>
#end

The #if() directive will only evaluate to true if both $foo and $bar are true. If $foo is false, the expression will evaluate to false; $bar will not be evaluated. If $foo is true, the Velocity Templating Engine will then check the value of $bar; if $bar is true, then the entire expression is true and This AND that becomes the output. If $bar is false, then there will be no output as the entire expression is false.



[13] This was a conscious decision by the Velocity designers and is not likely to change.