Home > Articles

This chapter is from the book

Using Literals

Literals are used to create values that are assigned to variables, used in expressions, or passed to methods. You need to know the correct ways of creating integer, floating-point, character, string, and boolean literals.

Numeric Literals

Literal numbers can appear in Java programs in base ten, hexadecimal, and octal forms, as shown in the following sample code statements, which combine declaring a variable and initializing it to a value:

1. int n = 42 ; 
2. long j = 4096L ; // appending L or l makes it a long
3. long k = 0xFFFFFFL ; 
4. byte b2 = 010 ; // an octal literal
5.  double f2 = 1.023 ; // double is assumed
6.  float f2 = 1.023F ;  // F or f makes it a float

Notice that an unmodified integer value is assumed to be the 32-bit int primitive, but a value containing a decimal point is assumed to be the 64-bit double, unless you append an F or f to indicate the 32-bit float primitive.

In line 1, an unmodified literal integer is assumed to be in base ten format. In line 3, a number starting with a leading zero followed by an uppercase or lowercase X is interpreted as a hexadecimal number. In line 4, a number with a leading zero and no X is interpreted as an octal number. Appending an uppercase or lowercase L indicates a long integer.

Tricky Literal Assignment Facts

The compiler does a variety of automatic conversions of numeric types in expressions, but in assignment statements, it gets quite picky as a defense against common programmer errors. In the following code, lines 1 and 3 cause a compiler "possible loss of precision" error:

1. int n2 = 4096L ; // would require a specific (int) cast
2. short s1 = 32000 ; // ok 
3. short s2 = 33000 ; // out of range for short primitive 
4. int secPerDay = 24 * 60 * 60 ;

Although 4096 would fit in an int primitive, the compiler would object to line 1 because the literal is in the long format. It would require a special operator called a cast to allow the statement. A Java cast operator takes the form of a type enclosed in parentheses. It is an instruction to the compiler to allow conversion of one variable type to another. Casts are discussed in detail in Chapter 6, "Converting and Casting Primitives and Objects."

The compiler also pays attention to the known range of primitives, passing line 2 in the previous example but objecting to line 3. You could force the compiler to accept line 3 with a specific (short) cast, but the result would be a negative number due to the high bit being set.

In line 4, the compiler pre-computes the resulting value rather than writing code to perform the multiplication. This handy feature lets you write out the factors of a useful number such as secPerDay without any runtime penalty in memory used.

Numeric Wrapper Classes

Each of the primitive data types has a corresponding wrapper class in the Java standard library. Java uses these classes for several purposes. The static variables of a wrapper class hold various constants, and the static methods are used for convenient conversion routines, such as the toString method, which returns a String representing a primitive value. You can also create objects that contain a primitive value, using either literals or primitive variables, as in the following examples:

1. Integer cmd = new Integer( 42 ) ;
2. Boolean flag = new Boolean( false ) ;
3. Character pi = new Character( '\u03c0' ) ;
4. Long lx = new Long( x ) ; // where x is a long variable

The values contained in a wrapper object cannot be changed, so they are not used for computation. Wrapper objects are useful when you want to store primitive values using Java's utility classes, such as Vector, Stack, and Hashtable, that work only with objects. The names of the wrapper classes are Byte, Short, Character, Integer, Long, Float, Double, and Boolean. As you can see, the names reflect the primitive values they contain but start with a capital letter. These wrapper classes are discussed more extensively in Chapter 11, "Standard Library Utility Classes."


The most important point to remember about the wrapper class objects is that the contained value cannot be changed. These objects are said to be immutable.

Character Literals

Even though typical Java code looks as if it is made up of nothing but ASCII characters, you should never forget that Java characters are, in fact, 16-bit Unicode characters. The following code shows legal ways to declare and initialize char type primitive variables:

1. char c1 = '\u0057' ; // the letter W as Unicode
2. char c2 = 'W' ;
3. char c3 = (char) 87 ; // the letter W 
4. char cr = '\r' ; // carriage return

Line 1 illustrates the Unicode representation of a character indicated by the leading \u sequence. The numeric value is always a four-digit hexadecimal number in this format. Line 2 uses single quotation marks surrounding the literal character, and an integer is cast to the char primitive type in line 3. Line 4 shows a literal representing a nonprinting character with an escape sequence.

You can also mix in Unicode characters and special characters with ASCII strings using the \u escape sequence (as shown in the "String Literals" section later in this chapter). Table 3.1 summarizes Java escape sequences that can be used in strings or to initialize character primitives.

Table 3.1 Java Escape Sequences

Escape Sequence

Character Represented




Horizontal tab.


New line (line feed).


Form feed.


Carriage return.


Double quotation mark.


Single quotation mark.




A character in octal representation; xxx must range from 000 through 377.


A Unicode character, where xxxx is a hexadecimal-format number in the range 0000 through FFFF. Note that this is the only escape sequence that represents a 16-bit character.

Special Precautions to Take with Unicode

Java translates Unicode characters as it reads the text, so you can't insert the code for carriage return or line feed characters using Unicode in program source code. The compiler sees the carriage return or line feed as an end-of-line character and reports an error. That is why you must use the escape sequences shown in Table 3.1 to insert these characters in string literals.

String Literals

Because Java does not deal with strings as arrays of bytes, but as objects, the compiler has to do a lot of work behind the scenes. The following sample code shows the declaration and initialization of String variables with literal values enclosed in double quotation marks. Note that unlike some languages, Java does not allow single quotation marks as an alternative for delineating strings. Single quotes are only used for character literal values.

1. String name = "" ; // an empty string, but still an object
2. String type = ".TXT" ;
3. String longtxt = "A great long bunch of text \n" 
4.    + "to illustrate how you break long lines." ; 

At the end of line 3, notice the sequence \n; this is an example of an escape code sequence used to insert special characters—in this case, a line feed. Line 4 illustrates the special meaning of the + operator when used with strings; this is discussed in "String Objects and the + Operator" section later in this chapter. Here is an example of a String literal with the Unicode representation of a capital Greek letter delta inserted between two double quotation mark characters:

String tx = "Delta values are labeled \"\u0394\" on the chart.";


Remember that string literals create String objects, not byte arrays. Most of the things you are used to doing with strings in C will not work in Java.

Boolean Literals

Fortunately, boolean literals are simple. Only the Java reserved words true and false can be used. Note that these words are always all lowercase. If you write

boolean flag = True ;

the compiler goes looking for a boolean variable named True.


C programmers should remember that integer variables can never be interpreted as boolean values. You must leave behind all of your tricks that depend on zero being interpreted as false.

Pearson IT Certification Promotional Mailings & Special Offers

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


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Pearson IT Certification 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.


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.


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.


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


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


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.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. 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.pearsonitcertification.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.


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