Home Rocket Daily

Design Your Perfect Home Using Technology

What are the Different Types of Literals in Java?

Untitled design - 2023-01-08t084536.127

Literals are used to specify the values of the different datatypes in Java. In this article, we’ll explore the various types of literals in Java and discuss the different ways to use them in your program. We’ll also discuss how to format literals correctly and what information they can provide. This article will provide an in-depth understanding of literals in Java to help you better utilize them in your code.

What is a literal in java

A literal is a compile-time constant value that is represented in the source code of a program and can be used by the program at runtime. In Java, there are several types of literals available, including boolean literals, integer literals, character literals and string literals.

  • Boolean Literals: A boolean literal represents a true or false value. It must always be written with either “true” or “false” in lowercase letters, without quotes.
  • Integer Literals: Integer literals are whole numbers without a fractional part or exponent part. They may have an optional sign (+/-). Examples include 42, -4242.
  • Character Literals: Character literals represent an integer value of a character (a character from the Unicode character set). A character literal is written between single quotes as follows – ‘a’, ‘c’, ‘7’, ‘+’. Note that escape sequences may also be used as characters within single quotes. Examples include ‘n’ for newline, ‘r’ for carriage return and ‘t’ for tab.
  • String Literals: String literals are represented in double-quotes and they can hold multiple characters including numbers, letters and special characters such as n (new line), b (backspace) etc. Example – “Hello World”.

Numeric Literals

Numeric literals in Java refer to the elements used to represent numeric values in a program. These values can range from integers and floating-point numbers to characters and boolean values. Java delimits numeric literals with special characters and allows for the use of underscores to improve readability.

In this section, we’ll take a look at the different types of numeric literals in Java:

Integer Literals

An integer literal is a type of literal which denotes a whole number value, that is, a number without a fractional component. Integer literals are used to denote values in the primitive integer data types byte, short, int, and long. These literals can be expressed in three different ways:

  1. Decimal (base 10): Numbers beginning with 0 are decimal numbers by default. So the number 25 is interpreted as an integer containing the value 25.
  2. Octal (base 8): To specify an octal number, add an extra leading zero to the number. For example, 017 represents an integer containing the value 15.
  3. Hexadecimal (base 16): To specify a hexadecimal number, add 0x or 0X before the digits. For example 0x11 is interpreted as an integer containing the value 17.

Untitled design - 2023-01-08t084629.797

Floating Point Literals

Floating point literals refer to numbers that use the standard form of scientific notation and are assigned the data type double or float. A valid floating point literal must have at least one digit before and after the decimal point. Optionally, if desired, it may have a plus or minus sign in front of it.

When a number includes a decimal point and/or an exponent part (in scientific notation), it is known as a floating-point literal:

Examples of valid floating point literals include:

  • -9.876543
  • +678.087
  • -0.001234e+6
  • +456.09e-10
  • 6e23

The float data type can also be used to designate a single precision floating point literal by adding f or F as follows:

  • 9.876543f – single precision with f/F
  • 678.087F – single precision with f/F

Hexadecimal Literals

Hexadecimal Literals are typically used to represent numbers in the hexadecimal numerical system, that is numbers between 0 and 15 represented with base 16 symbols. Hexadecimal literals always start with a 0x or 0X which distinguishes them from other types of numeric literals.

This type of literal can represent any integer or floating-point value and may contain underscores to improve readability. A few examples are as follows:

  • 0xFFFF is a hexadecimal literal representing the integer 65,535
  • 0x1FFF_FF is a hexadecimal literal representing the integer 131,071
  • 0xFE7F_B_C020_7A4FL is a hexadecimal literal representing the floating‐point number 398,752,842,271,676.25

Untitled design - 2023-01-08t084645.179

Octal Literals

Octal Literals are a type of numeric literal used in Java. They are used to represent numbers written in the base-8 number system, and are represented by a series of octal digits that begin with a 0 (zero). Octal numbers have 8 possible values for each digit (0 – 7). Octal literals must be written using three or more octal digits, otherwise they will be interpreted as decimal literals.

Octal literals can range in size from 0 to 377 (0777). For example, the octal literal 045 represents the decimal value 35. This is because each digit of an octal number is multiplied by an increasing power of 8, starting with 80. So 0*80 + 4*81 + 5*82 = 0 + 32 + 160 = 192 + 35 = 227. Therefore, 045 is equal to decimal value 35.

Octal literals are commonly used for setting file permissions on UNIX-based architectures such as Linux and macOS. The file permissions indicated by an octal number specify which operations can be performed on a file or folder by different users such as the owner, group members and all other users (i.e., everyone else). For example, chmod 777 testfile gives everyone read/write/execute access to testfile.

Binary Literals

In Java, a binary literal is a number that is represented in the binary numeral system. Binary literals are designated by a sequence of ‘0’s and ‘1’s preceded by the letter “b“. For example, “0b1001” is a binary literal representing the number 9.

Binary literals are useful when performing arithmetic operations, especially those involving bitwise operators such as AND and XOR, as it helps to shorten code by using fewer lines of code for a given task. Additionally, binary literals can also improve readability as it provides visual clarity regarding which bit(s) are being manipulated in code. Furthermore, since all characters used in binary literals have pre-determined values – ‘0‘ equals 0 and ‘1‘ equals 1 – there is no issue with the ambiguity associated with octal and hexadecimal formats.

For instance, to denote the hexadecimal number 6F in Java Syntax you would need two characters – 63 (6) and 46 (F). However, with binary literal syntax it requires only seven characters – 01101111 (6F), which makes it much shorter than its hexadecimal counterpart.

Character Literals

Character literals are enclosed in single quotes and represent single characters. They can also be used to represent characters in ASCII or special characters, such as a new line. For example, ‘n’.

Single Character Literals

A single character literal is a character that is surrounded by single quotation marks and is used to represent the ASCII value of a single character. It can be either any single letter (for example ‘a’, ‘A’, ‘F’), any special symbol (for example, ‘+’, ‘%’, ‘$’), or any whitespace character (for example, space, tab, new line). The maximum value of this type of literal is uFFFF which represents the highest Unicode value. All other characters that are higher than this value are represented by Unicode escaped sequences. For example, u03D5 is a Greek letter Phi and it can be written simply as ‘u03D5’ in Java code.

Multiple Character Literals

Multiple character literals are sequences of characters that are enclosed in double quotes and assigned to char variables or constants. They define a value similar to a string object but do not allow any method execution like a string object. Multiple character literals can have up to 65535 characters and they must consist of an even number of hexadecimal digits.

These character sequences can also be expressed in escape sequences such as n (newline), t (tab), b (backspace) etc., which represent specific control character or Unicode values.

String Literals

String Literals are a type of literal in Java programming language which are used to represent fixed values. String literals are written in a pair of single or double quotes and can be used to store a combination of characters, numbers and special characters. They are commonly used to store messages, file paths, or URLs.

String literals are immutable, which means that once you assign a value to them, they cannot be changed.

Single Line String Literals

Single Line String Literals are a type of literal that can be used in the Java programming language to define a single line containing any text or whitespace characters. A single line string literal starts with the three double quotation marks (“) and terminates with the same sequence. Any text within those quotation marks is considered a single line string literal.

Single line string literals can be useful when you want to enter an entire sentence as a program value instead of listing words as individual values in an array or list. For example, you could use a single line string to print out an entire address on one line instead of having to break it up into multiple strings. Single line string literals also allow you to add escape sequences, such as “t” for tab characters and “r” for carriage returns.

The following is an example of how to define and use a single line string literal in Java:

  • String myAddress = “My address is 123 Main Street, Anytown USA”;
  • System.out.println(myAddress); // Prints “My address is 123 Main Street, Anytown USA

Multiple Line String Literals

Java supports the use of multiple line string literals to create strings with multiple lines and preserve formatting. Multiple line literals must be enclosed within triple length opening and closing quotation marks, with each new line preceded by a backslash ().

Multiple line string literals are commonly used when defining a long String that would otherwise require you to break up statements and type out each sentence without proper formatting, as newlines would not be respected.

Below is an example of using multiple-line literal strings:

String poem = “The road not takennTwo roads diverged in a yellow wood.nAnd sorry I could not travel both nand be one traveler, long I stoodnand looked down one as far as I could”;  

System.out.println(poem);  

// Output:         The road not taken

//                Two roads diverged in a yellow wood.

//                And sorry I could not travel both

//                and be one traveler, long I stood

//                and looked down one as far as I could

Boolean Literals

In Java, literals are used to represent values of fixed, literal values including strings, integers, characters, and other types of objects. Boolean literals are one type of literal used in Java for boolean values. Boolean literals are a type of literal that can only have one of two possible values: true or false. These values are used to create boolean expressions and to determine the flow of execution in code. This section will discuss the details of boolean literals.

True Literals

In Java, boolean literals are classified as primitive data types and have two possible values: true or false. Boolean literals are used to evaluate a logical expression and indicate the result of the evaluation. When used in program code, they represent an assignment of either true or false to a Boolean type object.

Java supports several types of booleans such as the explicit boolean true and false literals, the Integer 0 (false) and 1 (true) literals, null pointer handling (a null indication is considered false value), and any non-zero values which are taken into account as true. In addition, certain comparisons such as equal (==), not equal (!=), less than (<) and greater than/equal to (>=) also evaluate as either true or false when used for comparison operators.

Finally, booleans can be assigned using other boolean values. For example:

  • boolean x = true; – Assigns a value of ‘true’ to x
  • boolean y = x; – Assigns the same value of ‘x’ to y

False Literals

False literals are an important and useful concept to understand when dealing with Java programming. A false literal is a literal that evaluates and returns the boolean value of “false” (also known as a Boolean expression). False literals include the literal “false”, 0 (zero) in any type, any object that evaluates to null, and empty strings.

False Literal Examples:

  • The boolean literal “false”
  • 0 (zero) in any type
  • Any object that evaluates to null such as an uninitialized array or an empty array list
  • The empty string or “”
  • The Boolean expression: !(expression)

Null Literals

Null literals in Java are used to represent the null value, or that which does not exist. A null literal is also used to initialize a reference variable once it has been declared. Java has a single type of null literal, simply written as “null“.

Null literals can be used to:

  • Declare reference variables
  • Initialize reference variables
  • Test whether an expression or statement is equal to the null value.

For example:

String str = null; // Initializes String reference str with ‘null’ constant.

if (str == null) { // compares the content of str with ‘null’ constant.

System.out.println(“str holds no value.”); // Prints ‘str holds no value’.

In all cases, mapping ‘null’ values to references refer to nothing at all and the referent does not typically have any meaning. Therefore, it is important to carry out proper checks for ‘null’ values when dealing with instances of objects in Java applications as these may eventually cause runtime errors if not handled correctly.

Conclusion

In conclusion, literals are any data that is given a constant value. In the Java programming language, constants come in various forms, including:

  • Integer literals,
  • Character literals,
  • String literals,
  • Floating-point literals, and
  • Boolean literals.

Integer and character literals can be expressed in various numerical systems such as decimal (base 10), hexadecimal (base 16), octal (base 8), and binary (base 2). Integer and character literals may contain underscores to make them more readable. String literals consist of an arbitrary sequence of characters surrounded by double quotes (“”). Floating-point numerals consist of a whole number, a decimal point (or exponent), and another digit group that represents fractional or exponential parts. Lastly, boolean literals are simply assigned values of true or false.

By being aware of the specific forms of each type of literal in the Java programming language you can write more accurate code quickly and with fewer errors.