Summary:
In this article, you will learn about Literals in Java.
- Literals in Java
- Integral Literals
- Floating-Point Literals
- Char Literals
- String Literals
- Boolean Literals
- Null Literals
Read more to know each in detail.
Programming needs to be optimized for efficiency, faster outputs, and memory. Variables are key in programming that stores data at a particular memory location. While executing a Java program, it stores values in containers called variables, a basic storage unit. To enhance the program’s readability, one needs to follow particular conventions while naming variables and assigning values. A source code representing a fixed value is called ‘literal’.
Literals in Java are defined directly in the code without any kind of computation. Any primitive type variables are assigned using literals. Java has a generic, class-based, reflective, imperative, multi-paradigm, and is an object-oriented programming language.
There is no way of how the literals in java are represented. The literals in java are represented in various ways. They could be represented in boolean, string, character, or numeric data. The literals in java are a form of data type covering the fixed values temporarily assigned fixed values as well.
The literals in java are source code representing a fixed value. These literals could be assigned to any primitive variable type.
One of the popular programming languages has different data types, viz. primitive data types, and non-primitive data types. Primitive data types include int, byte, short, float, boolean, double, and char, whereas non-primitive data types include arrays, string, and classes.
The primitive literals in java int, byte, short, float, boolean, double, and char represent certain signed integer values. Such as byte data type is an 8-bit signed, the short data type is a 16-bit signed, the int data type is 32-bit signed, the long data type is a 64-bit type, the float is 32-bit signed, double is 64-bit, boolean has only two possible values i.e. either true or false and lastly, char is 16-bit unicode character.
This article is focused on the ‘Literal in Java’. It covers the concept and types of literals used in Java and their application in programming. After reading this article, readers will have a clear understanding of the literal, how and where to use specific literal while coding in Java.
Also, check out our free courses to get an edge over the competition.
Literals in Java
Literal in Java is a synthetic representation of boolean, numeric, character, or string data. It is a means of expressing particular values in the program, such as an integer variable named ‘’/count is assigned an integer value in the following statement.
int count = 0;
A literal ‘0’ represents the value zero.
Thus, a constant value assigned to the variable can be called literal. But before everything, one must know how to define literals in Java and get a brief idea of what is literal in Java programming.
The question of what are literals has been answered; now let’s understand the use of literals briefly and types of literals in Java. The literals are represented directly in the code without any need or use of computation. Also, they facilitate the process and can be assigned to any primitive variable type, allowing the task to run smoothly.
Literals In Java: Why Use Them?
Now that you know what is literal in Java, learn why Java programmers should use them in their codes.
The various types of literals in Java are particularly helpful for implementation in the code since it eliminates the need to add labels and declare constants on the same line.
Literals In Java: How To Use Them?
While learning what is literal in Java programming, you may have read that a literal is declared along with a data type, a variable name. A literal is preceded by a = sign, which gives the variable its literal value.
Types of Literals In Java
Check Out upGrad’s Java Bootcamp
To understand what is literal in Java, let’s take a look at their classification:
- Integral Literals
- Floating-point Literals
- Char Literals
- String Literals
- Boolean Literals
- Null Literals
Our learners also read: Free java course!
These literals are again specified in different sub-types, let us see them one by one in the article.
1. Integral Literals
In computer programming, integral literals are constant values that represent integers in various number systems, such as decimal, binary, octal, and hexadecimal. These literals assign fixed integer values directly to variables or expressions in code. The syntax for integral literals may vary depending on the programming language used. Integral literals are specified in four different ways, as follows:
Decimal: It has a base of ten, and digits from 0 to 9.
For example,
Int x = 108;
Octal: It has base eight and allows digits from 0 to 7. While assigning an octal literal in the Java code, a number must have a prefix 0.
For example,
int x = 0745;
Hexadecimal:
It has a base of 16. Hexadecimal allows digits from 0 to 9, and characters from A to F. Even though Java is case sensitive, it also provides an exception for using either uppercase or lowercase characters in the code for hexadecimal literals.
For example,
int x = 0X123Fadd;
Binary:
It can be specified in binary literals, that is 0 and 1 with a prefix 0b or 0B.
For example,
int x = 0b1011;
One thing to keep in knowledge is that the prefix is used before adding any integer literal. This prefix gives a direction by specifying the base. Also, the integer literal can also have a suffix namely U and L representing unsigned or long. And as mentioned above, the U and L could be either in uppercase or lowercase.
Integral Literals Coding Example
Here is a Java program example that will help you better understand the Integral Literals in Java:
public class Test { public static void main(String[] args) { // decimal-form literal int a = 101; // octal-form literal int b = 0100; // Hexa-decimal form literal int c = 0xFace; // Binary literal int d = 0b1111; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } }
Output:
101 64 64206 15
Note:
Java literals an int by default, but we may signal explicitly that we want a long literal by adding the suffix l or L. Byte and short literals cannot be explicitly specified but can be inferred. The compiler automatically interprets integral literals assigned to byte variables as byte literals if the value is within the range of byte.
Check Out upGrad’s Advanced Certification in DevOps
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
2. Floating-Point Literals
Floating-point literals are literal in programming that represent real numbers (numbers with a decimal point) using the floating-point notation. These literals are commonly used to represent numbers that can have fractional parts. In simple words, floating-point literals can be expressed using only decimal fractions or exponential notation.
For example,
decimal Number = 89d;
decimal Number = 3.14159e0;
decimal Number = 1.0e-6D;
Floating-point literals can indicate a positive or negative value, leading + or – sign respectively. If not specified, the value is always considered positive. It can be represented in the following formats:
-Integer digits (representing digits 0 through 9) followed by either a suffix or an exponent to distinguish it from an integral literal.
-Integer digit.
-integer digit. integer digit
– integer digit
An optional exponent of the form might be as below:
-an optional exponent sign + or –
-the exponent indicator e or E
–integer digit representing the integer exponent value
An optional floating-point suffix might be as below:
Single precision (4 bytes) floating-point number indicating either for F
Double precision (8 bytes) floating-point number indicating d or D
The floating-point literals facilitate providing values basis the instance requirement. For example, it provides the values that could be used either in the float or double instances. The integer and floating-point literals should not be confused, as the integer literals have fixed integer values whereas the floating literals do not have fixed integers but rather has either fraction or decimal values.
Floating-Point Literal Coding Example
Here is a Java program example to help you understand the application of floating-point literal in Java:
public class Test { public static void main(String[] args) { // decimal-form literal float a = 101.230f; // It also serves the purpose of a decimal literal float b = 0123.222f; // Hexa-decimal form (error) float c = 0x123.222; System.out.println(a); System.out.println(b); System.out.println(c); } }
Output:
101.230 123.222 Error: malformed floating point literal
Note:
Since every floating-point literal by default is of the double type, we are unable to assign directly to the float variable. However, by prefixing a floating-point literal with f or F, we can declare it as a float type. By prefixing with d or D, we can explicitly define a floating-point literal as being of the double type. This particular procedure isn’t necessary.
Explore our Popular Software Engineering Courses
3. Char Literals
Character (Char) literals have the type char and are an unsigned integer primitive type. They are constant value character expressions in the Java program. These are sixteen-bit Unicode characters that range from 0 to 65535. Char literals are expressed as a single quote, a single closing quote, and the character in Java.
Char literals are specified in four different ways, as given below:
Single quote: Java literal is specified to a char data type as a single character enclosed in a single quote.
For example,
char ch = ‘a’;
Char Literal: Java literal is specified as an integer literal representing the Unicode value of a char. This integer can be specified in octal, decimal, and hexadecimal, ranging from 0 to 65535.
For example,
char ch = 062;
Escape Sequence: Every escape char can be specified as char literal.
For example,
char ch = ‘\n’;
Unicode Representation: Java literal is specified in Unicode representation ‘\uzzz’, where zzzz are four hexadecimal numbers.
For example,
char ch = ‘\u0061’;
The char literals in Java contain characters arranged sequentially enclosed in single quotation marks i.e. ‘a’. The character is another type of literal representing the character’s value enclosed within the code.
Char Literals In Java Coding Example
public class Test { public static void main(String[] args) { // single character literal within a single quote char ch = 'a'; // It is an Integer literal with an octal form char b = 0789; // Unicode representation char c = '\u0061'; System.out.println(ch); System.out.println(b); System.out.println(c); // Escape character literal System.out.println("\" is a symbol"); } }
Output:
a error: Integer number too large a " is a symbol
4. String Literals
A sequence of (zero or more including Unicode characters) characters within double quotes is referred to as string literals.
For example,
String s = “Hello”;
String literals may not have unescaped line feed or newline characters, but the Java compiler always evaluates compile-time expressions. Unicode escape sequences or special characters can be used within the string and character literal as backlash characters to escape special characters, as shown in the table below:
Name | Character | ASCII | Hex |
Single quote | \’ | 39 | 0x27 |
Double quotes | \” | 34 | 0x22 |
Carriage control | \r | 13 | 0xd |
Backlash | \\ | 92 | 0x5c |
Newline | \n | 10 | 0x0a |
NUL character | \0 | 0 | 0x00 |
Backspace | \b | 8 | 0x08 |
TAB | \t | 9 | 0x09 |
These string literals in java is used to populate the string objects. These string literals are a sequence of characters from the source characters enclosed within double quotation marks eg: “a”. The string literals are easier to read and can be easily compilable giving a better chance to optimise the code.
5. Boolean Literals
Boolean literals allow only two values and thus are divided into two literals:
True: it represents a real boolean value
False: it represents a false boolean value
For example,
boolean b = true;
boolean d = false;
The boolean literals represent the logical value either true or false. These values are not case-sensitive they could be either in uppercase or lowercase and can be valid.
In-Demand Software Development Skills
6. Null Literals
Null literal is a particular literal in Java representing a null value. This value refers to no object. Java throws NullPointerException. Null often describe the uninitialized state in the program. It is an error to attempt to dereference the null value.
Literals in Java help build basics in programming. Every Java programmer must be aware of this fundamental and essential concept that assigns values to the program’s variables. As null literal is not much used, commonly only the first five literal types are applied. It is necessary to follow the rules and maintain the correct syntax while using any literal in Java.
Read: Why is Java Platform Independent?
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
It is important to keep in mind that null is case sensitive and it’s important to write it in lowercase. The null literal type cannot be cast to the primitive types such as float, integer, etc but can only be cast to the reference type. Also, contradictory to the general perspective the null is neither a type nor an object. It is only a literal special constant used to point out the absence of value.
Finishing up with certain added information- there are valid long literal in java, are represented by the character L at the end of the expression. The letter L could be either in lowercase or uppercase. This valid long literal represented by the letter L allows the literal to be recognised as a long literal in Java.
Benefits of Literals
Literals are constants in programming that represent fixed values directly in the code. They are used to initialize variables or provide values directly within expressions. Here are the benefits of using literals in programming:
1. Readability and Clarity
Literals clearly and concisely represent fixed values in code. This enhances the readability of the codebase, making it easier for other developers (and even yourself in the future) to understand the purpose and meaning of the values.
2. Ease of Maintenance
Since literals make the code more readable, maintaining and debugging the code becomes easier. When values are represented explicitly as literals, it’s simpler to identify errors or inconsistencies.
3. Reduced Dependency
Using literals reduces the need for creating and managing additional variables solely to hold constant values. This can lead to a cleaner and more streamlined codebase, as there are fewer variables to keep track of.
4. Compile-time Optimizations
Some compilers and interpreters can optimize when literals are used. For instance, they might replace constant expressions with their computed values during compilation, leading to potentially faster execution.
5. Performance Improvement
Using literals can improve performance in certain scenarios. When the compiler knows a value won’t change, it can optimize the code accordingly, avoiding unnecessary memory allocations or operations.
6. Immediate Initialization
Literals allow you to immediately initialize variables with a specific value at the point of declaration. This can lead to more concise and expressive code.
7. Consistency and Standardization
Using literals ensures consistent values are used throughout the codebase, reducing the likelihood of errors due to typos or inconsistencies in values.
8. Avoiding Unintended Changes
If a constant value needs to be used multiple times across the codebase, using literals instead of duplicating the value reduces the risk of introducing errors when making updates or modifications.
9. Enhanced Documentation
Code readability and maintainability are crucial in programming. Using descriptive literal values alongside well-thought-out variable names can help convey the purpose and meaning of a value directly within the code. This eliminates the need for excessive comments and improves the overall readability of the codebase.
10. Language Flexibility
Different programming languages may support different literals, such as numeric, string, boolean, and even more complex types like arrays and objects. This flexibility allows developers to choose the most appropriate literal for the data they need to represent.
This diverse range of literals enhances the programmer’s ability to model real-world concepts accurately. It promotes code efficiency by providing direct data representations, reducing the need for convoluted workarounds. Developers can leverage language-specific literal conventions to achieve concise and expressive code, fostering better communication of intent within the codebase and improving collaboration among team members. Using literals in programming provides benefits ranging from improved readability and maintainability to potential performance optimizations. It’s a best practice to leverage literals when representing fixed values in your code.
Rules to Use Underscore in Java Literals
- To divide groups of digits in numeric literals, use underscores.
- An underscore can be used only between numerals and not at the start or end of a literal.
- An underscore cannot be used next to a decimal point in a floating-point literal.
- The identifiers b and x in binary or hexadecimal format cannot be preceded or followed by underscores.
- Only in between numerals can an underscore be used repeatedly.
Read our Popular Articles related to Software Development
Why Learn to Code? How Learn to Code? | How to Install Specific Version of NPM Package? | Types of Inheritance in C++ What Should You Know? |
Conclusion
upGrad provides support to build your skills in Java that also including Literals. If you are looking for a platform to develop your skill-set in Java programming, then upGrad has the best learning platform, hands-on practice assignments, and guidance.
If you’re interested to learn more about Java, and full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.