JAVA Syllabus
QUESTIONS & ANSWERS

What do you mean by Literals? Explain different types of Literals.

In Java, a literal refers to a value that is expressed in source code exactly as it is meant to be interpreted by the compiler. In other words, a literal is a fixed value that is directly used in the code, rather than being stored in a variable or calculated at runtime.

There are several types of literals in Java:

  1. Integer Literals:
    Integer literals represent whole numbers without a fractional part. They can be specified in decimal, hexadecimal, or octal notation. For decimal notation, the digits 0-9 are used. For hexadecimal notation, the prefix 0x or 0X is used followed by the digits 0-9 and letters A-F or a-f. For octal notation, the prefix 0 is used followed by the digits 0-7.

Example:

int a = 10;       // decimal literal
int b = 0x1F;     // hexadecimal literal
int c = 012;      // octal literal
  1. Floating-Point Literals:
    Floating-point literals represent numbers with a fractional part. They can be specified in either decimal or scientific notation. For decimal notation, the digits 0-9 are used, along with a decimal point. For scientific notation, the letter e or E is used to indicate the exponent.

Example:

float a = 3.14f;   // decimal literal
double b = 1.23e-4; // scientific notation
  1. Character Literals:
    Character literals represent a single character enclosed in single quotes.

Example:

char a = 'A';      // character literal
  1. String Literals:
    String literals represent a sequence of characters enclosed in double quotes.

Example:

String a = "Hello, world!";  // string literal
  1. Boolean Literals:
    Boolean literals represent true or false values.

Example:

boolean a = true;   // boolean literal
  1. Null Literal:
    The null literal represents a reference that does not refer to any object.

Example:

String a = null;    // null literal
03/03/2023, 1:13 pm Read : 174 times