What Is a Literal in Java? [Hands-On Tutorial]

Roger Winter

Updated:

Published:

During a program’s lifecycle, it’s often necessary to store values in a manner that allows access and manipulation. For example, you can store the value of an object’s length and width to calculate its perimeter or area, then save the outcome in memory.

person writing literals in java on a glass wall with a marker

In programming, variables provide a mechanism for storing data in memory by referencing them using a name and — for Java — the data type to store. In Java (and other programming languages) we call the values assigned to variables “literals.”

In this guide, we’ll explore the core Java literals in-depth. You can follow along with the examples in this guide just by reading. But, if you’d like to test them out for yourself, here’s what you’ll need to do to get started:

  • Download and install a Java IDE, such as IntelliJ or Eclipse.
  • Download a Java Development Kit (JDK), which provides the Java Runtime Environment (JRE) to execute your Java programs. You can find the latest JDK here.
  • Set up the JAVA_HOME environment variable so your system can access the installed JRE. This guide will help you set up JAVA_HOME.

Download Now: An Introduction to Java & JavaScript

A basic example of a literal in a program is an integer like 50. This value is fixed — you can’t assign another value to the integer 50. Another example would be a string like “hello world”, or a boolean value like TRUE. These literals can be assigned to a variable, but the literals themselves do not change.

How Literals Work in Java

Java literals are fixed values assigned to variables, represented directly in the program, without needing instantiation. You use literals to assign values to primitive variables, effectively initializing them to the value of the literal. For example:

int myNum = 12; boolean isTrue = true; char myChar = 'c';

Here, myNum, isTrue, and myChar, are primitive variables of the integer (int), Boolean (boolean), and character (char) types — assigned the literal values 12, true, and c, respectively.

There are five major literal types in Java: Boolean (boolean), integer (int), character (char), string (string), and floating-point (float and double) literals.

a graph showing the different types of java literals

Integer Literals

Integer literals are numerical values that don’t have fractional or exponential parts. Basic integers are of the integer (int) data type.

The int type (32-bit integer) holds whole numbers in the range of -2,147,483,648 to 2,147,483,647. It’s common for some values to exceed this range.

The long type holds values exceeding the int type range. If an integer ends with the letter l or L, then it’s of the long data type. Using L with long type integers is a standard practice because l is hard to distinguish from the value 1. The long type holds whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

You can further express integer literals using these four number systems:

  • Decimal: A base 10 integer type that contains values 0 through 9. This system is typical for everyday computations.
  • Octal: A base 8 integer type containing the values 0 through 7. All octal integers start with 0 — for example, 075, 083, and so on.
  • Hexadecimal: A base 16 number system represented by integers 0 through 9 (1 to 10) and letters A to F (10 to 15). This system commonly represents MAC addresses, IPV6 addresses, and color codes. Hexadecimal integers start with 0X or 0x — for example, 0x1f5, and 0xb12.
  • Binary: A base 2 number system containing the values 0 and 1. You use this system primarily for low-level machine language. Binary literals start with 0b — for example, 0b101, and 0b110.

The example below illustrates how these systems can be represented in a Java program using integer literals.

public class JavaIntegerLiterals { public static void main (String[]args){ //initialize variables with integer literals int decimalNum = 25; int hexaNum = 0xa5; int binaryNum = 0b1101; int octalNum = 0172; //print out the values of the literal System.out.println("Decimal Integer: " + decimalNum); System.out.println("Octal Integer: " + octalNum); System.out.println("Hexadecimal Integer: " + hexaNum); System.out.println("Binary Integer: " + binaryNum); } } // Output // Decimal Integer: 25 // Octal Integer: 122 // Hexadecimal Integer: 165 // Binary Integer: 13

Boolean Literals

Java Boolean literals may be the easiest to understand, they’re used in some of the most complex logic and computation the language handles. The Boolean type accepts two values: true or false. The binary equivalent of true is 1, while that of false is 0.

Below are the two literals isTrue and isFalse assigned the true and false Boolean values, respectively. The output shows the corresponding values of the literals.

public class JavaBooleanLiterals { public static void main(String[] args) { boolean isTrue = true; boolean isFalse =false; System.out.println("The boolean value of isTrue: " + isTrue); System.out.println("The boolean value of isFalse: " + isFalse); } } // Output // The boolean value of isTrue: true // The boolean value of isFalse: false

In programming, many comparisons between variables and values resolve to Boolean types, even though most of the output of such computations is not represented explicitly by the literal values, true or false.

Floating-Point Literals

Floating point literals are double data types (the default type) or float types. To represent the latter, append the letter F or f at the end of a number and add the letter D or d (optional) to denote the double type values. The difference between the two types is that the float type handles 32-bit floating-point literals, while the double type represents 64-bit double literals. Since double is the default type, the letters D and d do not follow floating-point values.

The example below shows three floating-point literal assignments with varying outputs. The first literal — piDoubleValue — has a 10-precision value (ten decimal places). Since it’s of the type double, its value is a double precision value.

The second literal — piFloatValue — is of the data type float and is denoted by the F appended at the end of the value. Since it’s a float, the value is rounded off to seven decimal places (7-precision float).

The third literal — piScientific — is represented using scientific notation. The e0 means that the number 3.1415926535 is raised to the power of zero (0 exponents). Since the value is a double type, it is not rounded off.

public class JavaFloatLiterals { public static void main(String[] args) { double piDoubleValue = 3.1415926535; float piFloatValue = 3.1415926535F; double piScientific = 3.1415926535e0; System.out.println("Pi to ten decimal places: " + piDoubleValue); System.out.println("A rounded value of Pi: " + piFloatValue); System.out.println("Pi from a scientific notation: " + piScientific); } } // Output // Pi to ten decimal places: 3.1415926535 // A rounded value of Pi: 3.1415927 // Pi from a scientific notation: 3.1415926535

If you’re building applications to perform high-precision scientific or similar computations, it’s ideal to use floating-point literals because they accommodate not only fractional components but also values represented as scientific notations.

Character Literals

Character literals are of the data type char and typically contain Unicode (UTF-16) characters. You can represent characters directly in code by enclosing them in single quotes, provided the editor supports them. You can also use Unicode escapes such as '\u002d', '\u002b','\u003a', and many others to generate character literals.

You can also use escape sequences as character literals. In Java and many other programming languages, escape sequences are a combination of characters that has a meaning other than the literal characters used in the sequence and is marked by one or more preceding (and possibly terminating) characters when placed inside either string or character literals.

You’ll typically use escape sequences to specify actions such as carriage returns and tab movements on terminals and printers. Some of the popular escape sequences include: \t (tab space), \n (new line), \b (backspace), \' (single quote), \" (double quotes), \r (carriage return), \f (form feed), and \\(backslash).

In the following example, the first three statements are direct character literal assignments of the char data type. The values are a, b, and c. The fourth statement, however, represents the char literal using Unicode characters — '\u002b' — which are the equivalent of the ‘+’ character (or symbol). The last output statement, which prints ‘a+b’ on the screen, illustrates this.    

public class JavaCharLiterals { public static void main(String[] args) { char myFirstChar = 'a'; char mySecondChar = 'b'; char myThirdChar = 'c'; char plusInUnicode = '\u002b'; System.out.println("First three letters of the alphabet: " + myFirstChar + mySecondChar + myThirdChar); //Escape sequence as character literals System.out.println("The same three characters on separate lines: " + "\n" + myFirstChar + "\n\t" + mySecondChar + "\n" +myThirdChar); //Unicode character literal System.out.println("Letter a added to letter b: " + myFirstChar + plusInUnicode + mySecondChar); } } // Output // First three letters of the alphabet: abc // The same three characters on separate lines: // a // b // c // Letter a added to letter b: a+b

String Literals

Enclosing a combination of character literals in double quotes creates a string literal of the string data type in Java. String literals don’t have to be text only. To create a string, you can combine different character types, including letters, numbers, special characters, and even spaces.

Since a string literal is a combination of characters, printing out myString displays “I am a string literal” on the screen. You can also apply the built-in function, length, to check the length of the string, as illustrated in the following example. There are also many other functions available for string operations and manipulation.

public class JavaStringLiterals { public static void main(String[] args) { String myString = "I am a string literal"; System.out.println("Who am I? \n" + myString); System.out.println("What is my length? "); //String method length() get length in characters System.out.println("I am " + myString.length() + " characters long"); } } // Output // Who am I? // I am a string literal // What is my length? // I am 21 characters long

The representation of strings as arrays of characters allows you to perform many operations on this literal type. Check out our full guide to Java strings for more advanced string literal concepts, including how to manipulate them using built-in Java methods.

Special Literals: Null and Class Literals

Java has special literals such as null and class. As the name suggests, the null literal is a value you can assign to any reference type. Except for primitive variable types, you can assign null to any variable. It helps indicate when an object does not have a reference value.

The class literal is another special literal you can create by appending .class after a variable type, such as string. For example, String.class refers to an object (of the class type) representing the string variable type.

Using Literals in Java Programming

Literals assign value to variables directly within a program. They are instrumental in reducing the declaration of constants and eliminating code verbosity by encouraging same-line variable declarations.

In Java, the five literals are the foundation of the most simple and complex programming logic. Without literals, creating meaningful programs becomes inherently tricky. It’s worth learning more about string literals as they support advanced operations provided by the String class.

java

Topics: Java

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about the differences between and uses of these popular programming languages.