Java Literals

A Java literal is a sequence of characters that represents a fixed constant value directly in source code.


A literal is the source code representation of a fixed value.

Literals are directly used to assign values to variables or constants.

Java specifies 5 major types of literals:
  1. Integer Literals
  2. Floating-Point Literals
  3. Character Literals
  4. String Literals
  5. Boolean Literals

1. Integer Literals

An integer literal is of type long if it ends with L or l, otherwise it is of type int.

Can be written in decimal, octal, hexadecimal, or binary form:

int dec = 20;     // Decimal
int oct = 076;    // Octal
int hex = 0x13A;  // Hexadecimal
int bin = 0b101;  // Binary

2. Floating-Point Literals

Floating-point literals represent decimal values with a fractional part.

By default, they are of type double.

double d = 223.56;
float f = 223.56F; // must use F for float

3. Character Literals

A character literal is a single character enclosed in single quotes, or a Unicode escape sequence.

char a = 'a';
char c = '@';
char ch = '\u0041'; // Unicode for 'A'

4. String Literals

String literals are enclosed in double quotes and represent objects of type java.lang.String.

String s = "Java Prowess";

5. Boolean Literals

Boolean literals have only two possible values: true or false.

boolean flag = true;   // Legal
boolean test = false;
boolean error = 1;     // Compiler Error

Next: Java Escape Sequences



πŸš€ Quick Knowledge Check

Topic: Literals | Language: Java

Q1. Which of the following represents a valid character literal in Java?
Q2. What is the default type of a floating-point literal in Java?
Q3. What are the only possible values for a boolean literal in Java?
Q4. Which of the following is NOT a valid integer literal in Java?
Q5. Which of the following correctly defines a string literal in Java?