Literals

Common types of literals are string, Boolean, and numeric.

String literals

String literals can be enclosed in either single quotation marks or double quotation marks. You can use either form to make quotations in strings easier:

Examples:

"Hello World!"

"He said ’Hello World!’"

’He said "Hello World!"’

You can use the \uxxxx Unicode escape where xxxx is a four digit hexadecimal Unicode code point value. To represent the backslash character \, you must represent it as two backslashes \\.

Strings enclosed in double quotation marks, but not single quotation marks, can also use other backslash encoded values:

\" means the double quote character itself

\r means carriage return

\n means a newline character

\t means a tab character

\b means a backspace character

Boolean literals

The following literals represent the Boolean values of TRUE and FALSE respectively:

TRUE

FALSE

These literals are not case-sensitive. For example, the literals TRUE, true, True, and TrUe mean the same thing.

Numeric literals

Numeric literals support Integer, Long, BigInteger, BigDecimal, Float, and Double types.

Integral numeric literals, without a decimal point, that start with a 0 are treated as octal numbers. Integral numeric literals that start with either 0x or 0X are treated as hexadecimal numbers. Those that start with non-zero digits are treated as decimal numbers. Decimal, octal, and hexadecimal integral literals can have an integral suffix (G,L,I). Integral numeric literals without a suffix are the smallest type into which the value fits (Integer, Long, or BigInteger).

Numeric literals with decimal points are treated as java.math.BigDecimal types rather than binary floating point types (Float, Double). To specify Float and Double types, use a suffix of F and D respectively. Exponential notation is supported for decimal types (BigDecimal, Double Float) with or without a signed exponent.

Table 1.
Literal Type Value (decimal)
123 Integer 123
077 Integer 127
0xFF Integer 255
2147483648 Long 2147483648
123L Long 123
9999999999 BigDecimal 9999999999
1.200065D Double 1.200065
1.234F Float 1.234
1.23E23D Double 1.23E23

This description is intended to be a summary only. Numeric literals are described in more detail at http://groovy.codehaus.org/Groovy+Math.


Feedback