Understanding Java Literals

06 May 2023 Balmiki Mandal 0 Core Java

Understanding Java Literals

Literals, in Java programming language, are a way of representing fixed values. In other words, literals are data that is explicitly provided in the source code, rather than calculated or assigned as a variable. Java language supports several types of literals including integer literals, floating-point literals, boolean literals, character literals and string literals.

Integer Literals

Integer literals are used to represent whole numbers such as 10, 2, and -7. Integer literals can be represented in decimal (base 10), hexadecimal (base 16) and octal (base 8) notation. Integer literals are composed of digits from 0 to 9. The prefix 0x represents a hexadecimal literal, while the prefix 0 represents an octal literal.

Floating-Point Literals

Floating-point literals represent real numbers with a fractional component such as 9.5, 6.02, and -3.14. Floating-point literals are composed of digits from 0 to 9 with at least one digit before and after the decimal point. Unlike integer literals, they must contain a decimal point (.), an exponent (e/E) or a fraction (f/F). The prefix 0x is not accepted for floating-point literals.

Boolean Literals

Boolean literals are used to represent the two logical states of true and false. For example, true, false. These literals are generally used in conditional statements such as IF and SWITCH.

Character Literals

Character literals are used to represent a single character. It is basically a single quoted character such as ‘a’, ‘b’, or ‘!’. Character literals can also be represented by their corresponding ASCII value using the prefix \u followed by 4 hex digits.

String Literals

String literals are used to represent a sequence of characters such as “Hello World” and “Welcome”. String literals are enclosed within double quotes. A string literal can also span multiple lines using the \ symbol.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.