Home > Articles > Programming > Java

This chapter is from the book

3.10 Literals

A literal is the source code representation of a value of a primitive type (§4.2), the String type (§4.3.3), or the null type (§4.1):

    
   Literal:
        
   IntegerLiteral
        
   FloatingPointLiteral
        
   BooleanLiteral
        
   CharacterLiteral
        
   StringLiteral
        
   NullLiteral

3.10.1 Integer Literals

See §4.2.1 for a general discussion of the integer types and values.

An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8):

    
   IntegerLiteral:
        
   DecimalIntegerLiteral
        
   HexIntegerLiteral
        
   OctalIntegerLiteral

    
   DecimalIntegerLiteral:
        
   DecimalNumeral IntegerTypeSuffixopt
   

    
   HexIntegerLiteral:
        
   HexNumeral IntegerTypeSuffixopt
   

    
   OctalIntegerLiteral:
        
   OctalNumeral IntegerTypeSuffixopt
   

    
   IntegerTypeSuffix: one of
        l L

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1). The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one).

A decimal numeral is either the single ASCII character 0, representing the integer zero, or consists of an ASCII digit from 1 to 9, optionally followed by one or more ASCII digits from 0 to 9, representing a positive integer:

    
   DecimalNumeral:
       0
       NonZeroDigit Digitsopt
   

    
   Digits:
       
   Digit
       
   Digits Digit

    
   Digit:
       0
       NonZeroDigit

    
   NonZeroDigit: one of
       1  2  3  4  5  6  7  8  9

A hexadecimal numeral consists of the leading ASCII characters 0x or 0X followed by one or more ASCII hexadecimal digits and can represent a positive, zero, or negative integer. Hexadecimal digits with values 10 through 15 are represented by the ASCII letters a through f or A through F, respectively; each letter used as a hexadecimal digit may be uppercase or lowercase.

    
   HexNumeral:
       0 x HexDigits
       0 X HexDigits

    
   HexDigits:
       
   HexDigit
       
   HexDigit HexDigits

The following production from §3.3 is repeated here for clarity:

    
   HexDigit: one of
       0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f  A  B  C  D  E  F

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 and can represent a positive, zero, or negative integer.

    
   OctalNumeral:
        0 OctalDigits

    
   OctalDigits:
        
   OctalDigit
        
   OctalDigit OctalDigits

    
   OctalDigit: one of
        0  1  2  3  4  5  6  7

Note that octal numerals always consist of two or more digits; 0 is always considered to be a decimal numeral—not that it matters much in practice, for the numerals 0, 00, and 0x0 all represent exactly the same integer value.

The largest decimal literal of type int is 2147483648 (231). All decimal literals from 0 to 2147483647 may appear anywhere an int literal may appear, but the literal 2147483648 may appear only as the operand of the unary negation operator -.

The largest positive hexadecimal and octal literals of type int are 0x7fffffff and 017777777777, respectively, which equal 2147483647 (231 – 1). The most negative hexadecimal and octal literals of type int are 0x80000000 and 020000000000, respectively, each of which represents the decimal value –2147483648 (–231). The hexadecimal and octal literals 0xffffffff and 037777777777, respectively, represent the decimal value -1.

A compile-time error occurs if a decimal literal of type int is larger than 2147483648 (231), or if the literal 2147483648 appears anywhere other than as the operand of the unary - operator, or if a hexadecimal or octal int literal does not fit in 32 bits.

Examples of int literals:

                 0  2  0372 0xDadaCafe 1996 0x00FF00FF

The largest decimal literal of type long is 9223372036854775808L (263). All decimal literals from 0L to 9223372036854775807L may appear anywhere a long literal may appear, but the literal 9223372036854775808L may appear only as the operand of the unary negation operator -.

The largest positive hexadecimal and octal literals of type long are 0x7fffffffffffffffL and 0777777777777777777777L, respectively, which equal 9223372036854775807L (263 –1). The literals 0x8000000000000000L and 01000000000000000000000L are the most negative long hexadecimal and octal literals, respectively. Each has the decimal value –9223372036854775808L (–263). The hexadecimal and octal literals 0xffffffffffffffffL and 01777777777777777777777L, respectively, represent the decimal value -1L.

A compile-time error occurs if a decimal literal of type long is larger than 9223372036854775808L (263), or if the literal 9223372036854775808L appears anywhere other than as the operand of the unary - operator, or if a hexadecimal or octal long literal does not fit in 64 bits.

Examples of long literals:

                 0l  0777L  0x100000000L  2147483648L  0xC0B0L

3.10.2 Floating-Point Literals

See §4.2.3 for a general discussion of the floating-point types and values.

A floating-point literal has the following parts: a whole-number part, a decimal or hexadecimal point (represented by an ASCII period character), a fractional part, an exponent, and a type suffix. A floating point number may be written either as a decimal value or as a hexadecimal value. For decimal literals, the exponent, if present, is indicated by the ASCII letter e or E followed by an optionally signed integer. For hexadecimal literals, the exponent is always required and is indicated by the ASCII letter p or P followed by an optionally signed integer.

For decimal floating-point literals, at least one digit, in either the whole number or the fraction part, and either a decimal point, an exponent, or a float type suffix are required. All other parts are optional. For hexadecimal floating-point literals, at least one digit is required in either the whole number or fraction part, the exponent is mandatory, and the float type suffix is optional.

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.

    
   FloatingPointLiteral:
        
   DecimalFloatingPointLiteral
        
   HexadecimalFloatingPointLiteral

    
   DecimalFloatingPointLiteral:
        
   Digits . Digitsopt ExponentPartopt FloatTypeSuffixopt
   
        . Digits ExponentPartopt FloatTypeSuffixopt
   
        
   Digits ExponentPart FloatTypeSuffixopt
   
        
   Digits ExponentPartopt FloatTypeSuffix

    
   ExponentPart:
        
   ExponentIndicator SignedInteger

    
   ExponentIndicator: one of
        e E

    SignedInteger:
        
   Signopt Digits

    
   Sign: one of
        + -

    FloatTypeSuffix: one of
        f F d D

    HexadecimalFloatingPointLiteral:
        
   HexSignificand BinaryExponent FloatTypeSuffixopt
   

    
   HexSignificand:
        
   HexNumeral
        
   HexNumeral .
        
   0x HexDigitsopt . HexDigits
        
   0X HexDigitsopt . HexDigits

    
   BinaryExponent:
        
   BinaryExponentIndicator SignedInteger

    
   BinaryExponentIndicator:one of
        p P

The elements of the types float and double are those values that can be represented using the IEEE 754 32-bit single-precision and 64-bit double-precision binary floating-point formats, respectively.

The details of proper input conversion from a Unicode string representation of a floating-point number to the internal IEEE 754 binary floating-point representation are described for the methods valueOf of class Float and class Double of the package java.lang.

The largest positive finite float literal is 3.4028235e38f. The smallest positive finite nonzero literal of type float is 1.40e-45f. The largest positive finite double literal is 1.7976931348623157e308. The smallest positive finite nonzero literal of type double is 4.9e-324.

A compile-time error occurs if a nonzero floating-point literal is too large, so that on rounded conversion to its internal representation it becomes an IEEE 754 infinity. A program can represent infinities without producing a compile-time error by using constant expressions such as 1f/0f or -1d/0d or by using the predefined constants POSITIVE_INFINITY and NEGATIVE_INFINITY of the classes Float and Double.

A compile-time error occurs if a nonzero floating-point literal is too small, so that, on rounded conversion to its internal representation, it becomes a zero. A compile-time error does not occur if a nonzero floating-point literal has a small value that, on rounded conversion to its internal representation, becomes a nonzero denormalized number.

Predefined constants representing Not-a-Number values are defined in the classes Float and Double as Float.NaN and Double.NaN.

Examples of float literals:

                 1e1f2.f.3f0f3.14f6.022137e+23f

Examples of double literals:

                 1e12..30.03.141e-9d1e137

Besides expressing floating-point values in decimal and hexadecimal, the method intBitsToFloat of class Float and method longBitsToDouble of class Double provide a way to express floating-point values in terms of hexadecimal or octal integer literals. For example, the value of:

    Double.longBitsToDouble(0x400921FB54442D18L)

is equal to the value of Math.PI.

3.10.3 Boolean Literals

The boolean type has two values, represented by the literals true and false, formed from ASCII letters.

A boolean literal is always of type boolean.

    
   BooleanLiteral: one of
        true false

3.10.4 Character Literals

A character literal is expressed as a character or an escape sequence, enclosed in ASCII single quotes. (The single-quote, or apostrophe, character is $$$$\u0027.) Character literals can only represent UTF-16 code units (§3.1), i.e., they are limited to values from \u0000 to \uffff. Supplementary characters must be represented either as a surrogate pair within a char sequence, or as an integer, depending on the API they are used with.

A character literal is always of type char.

    
   CharacterLiteral:
       ' SingleCharacter '
       ' EscapeSequence '

    SingleCharacter:
       
   InputCharacter 
   but not ' or 

The escape sequences are described in §3.10.6.

As specified in §3.4, the characters CR and LF are never an InputCharacter; they are recognized as constituting a LineTerminator.

It is a compile-time error for the character following the SingleCharacter or EscapeSequence to be other than a '.

It is a compile-time error for a line terminator to appear after the opening ' and before the closing '.

The following are examples of char literals:

    'a'
    '%'
    '\t'
    '\\'
    '\''
    '\u03a9'
    '\uFFFF'
    '\177'
    'W'
    'U2297.GIF'

Because Unicode escapes are processed very early, it is not correct to write '\u000a' for a character literal whose value is linefeed (LF); the Unicode escape \u000a is transformed into an actual linefeed in translation step 1 (§3.3) and the linefeed becomes a LineTerminator in step 2 (§3.4), and so the character literal is not valid in step 3. Instead, one should use the escape sequence '\n' (§3.10.6). Similarly, it is not correct to write '\u000d' for a character literal whose value is carriage return (CR). Instead, use '\r'.

In C and C++, a character literal may contain representations of more than one character, but the value of such a character literal is implementation-defined. In the Java programming language, a character literal always represents exactly one character.

3.10.5 String Literals

A string literal consists of zero or more characters enclosed in double quotes. Characters may be represented by escape sequences - one escape sequence for characters in the range U+0000 to U+FFFF, two escape sequences for the UTF-16 surrogate code units of characters in the range U+010000 to U+10FFFF.

A string literal is always of type String (§4.3.3). A string literal always refers to the same instance (§4.3.1) of class String.

    
   StringLiteral:
         " StringCharactersopt
    "

    StringCharacters:
         
   StringCharacter
         
   StringCharacters StringCharacter

    
   StringCharacter:
         
   InputCharacter 
   but not " or          EscapeSequence

The escape sequences are described in §3.10.6.

As specified in §3.4, neither of the characters CR and LF is ever considered to be an InputCharacter; each is recognized as constituting a LineTerminator.

It is a compile-time error for a line terminator to appear after the opening " and before the closing matching ". A long string literal can always be broken up into shorter pieces and written as a (possibly parenthesized) expression using the string concatenation operator + (§15.18.1).

The following are examples of string literals:

    ""                 // the empty string
    "\""               // a string containing " alone
    "This is a string" // a string containing 16 characters
    "This is a " +     // actually a string-valued constant expression,
       "two-line string"  //    formed from two string literals

Because Unicode escapes are processed very early, it is not correct to write "\u000a" for a string literal containing a single linefeed (LF); the Unicode escape \u000a is transformed into an actual linefeed in translation step 1 (§3.3) and the linefeed becomes a LineTerminator in step 2 (§3.4), and so the string literal is not valid in step 3. Instead, one should write "\n" (§3.10.6). Similarly, it is not correct to write "\u000d" for a string literal containing a single carriage return (CR). Instead use "\r".

Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals—or, more generally, strings that are the values of constant expressions (§15.28)—are "interned" so as to share unique instances, using the method String.intern.

Thus, the test program consisting of the compilation unit (§7.3):

    package testPackage;

    class Test {
       public static void main(String[] args) {
          String hello = "Hello", lo = "lo";
          System.out.print((hello == "Hello") + " ");
          System.out.print((Other.hello == hello) + " ");
          System.out.print((other.Other.hello == hello) + " ");
          System.out.print((hello == ("Hel"+"lo")) + " ");
          System.out.print((hello == ("Hel"+lo)) + " ");
          System.out.println(hello == ("Hel"+lo).intern());
       }
    }

    class Other { static String hello = "Hello"; }

and the compilation unit:

    package other;

    public class Other { static String hello = "Hello"; }

produces the output:

    true true true true false true

This example illustrates six points:

  • Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
  • Literal strings within different classes in the same package represent references to the same String object.
  • Literal strings within different classes in different packages likewise represent references to the same String object.
  • Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
  • Strings computed by concatenation at run time are newly created and therefore distinct.

The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

3.10.6 Escape Sequences for Character and String Literals

The character and string escape sequences allow for the representation of some nongraphic characters as well as the single quote, double quote, and backslash characters in character literals (§3.10.4) and string literals (§3.10.5).

    
   EscapeSequence:
       \ b                /* \u0008: backspace BS
    */
       \ t                /* \u0009: horizontal tab HT
    */
       \ n                /* \u000a: linefeed LF
    */
       \ f                /* \u000c: form feed FF
    */
       \ r                /* \u000d: carriage return CR
    */
       \ "                /* \u0022: double quote " */
       \ '                /* \u0027: single quote ' */
       \ \                /* \u005c: backslash \ */
       OctalEscape          /* \u0000 to \u00ff: from octal value */

    OctalEscape:
       \ OctalDigit
       \ OctalDigit OctalDigit
       \ ZeroToThree OctalDigit OctalDigit

    
   OctalDigit: one of
       0 1 2 3 4 5 6 7

    ZeroToThree: one of
       0 1 2 3

It is a compile-time error if the character following a backslash in an escape is not an ASCII b, t, n, f, r, ", ', \, 0, 1, 2, 3, 4, 5, 6, or 7. The Unicode escape \u is processed earlier (§3.3). (Octal escapes are provided for compatibility with C, but can express only Unicode values \u0000 through \u00FF, so Unicode escapes are usually preferred.)

3.10.7 The Null Literal

The null type has one value, the null reference, represented by the literal null, which is formed from ASCII characters. A null literal is always of the null type.

    
   NullLiteral:
        null

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020