Sobes.tech
Intern

What are literals in Java?

sobes.tech AI

Answer from AI

Literals in Java represent fixed values embedded directly into the program code. They are used to represent specific data without the need for computation.

Main types of literals:

  • Integer literals: Represent whole numbers. They can be in decimal, hexadecimal, or octal systems. Suffixes 'l' or 'L' are used to indicate the long type.
    int decimalLiteral = 10;
    int hexLiteral = 0xFF; // 255 in decimal
    int octalLiteral = 010; // 8 in decimal
    long longLiteral = 123456789012345L;
    
  • Floating-point literals: Represent numbers with a decimal part. By default, they are of type double. Suffixes 'f'/'F' for float, 'd'/'D' for double (not mandatory for double).
    double doubleLiteral = 3.14;
    float floatLiteral = 2.71f;
    double scientificLiteral = 1.2e3; // 1200.0
    
  • Character literals: Represent single characters enclosed in single quotes. They can be ASCII characters or escape sequences.
    char charLiteral = 'A';
    char newlineChar = '\n'; // Newline
    char unicodeChar = '\u03A3'; // Greek capital sigma
    
  • String literals: Represent a sequence of characters enclosed in double quotes. Type String.
    String stringLiteral = "Hello, World!";
    String emptyString = "";
    
  • Boolean literals: Represent boolean values: true and false.
    boolean trueLiteral = true;
    boolean falseLiteral = false;
    
  • null literal: Represents the absence of an object reference.
    Object obj = null;
    String str = null;
    

Table of main literal types:

Data type Example literals
int, long 10, 0xFF, 123L
float, double 3.14, 2.71f, 1.2e3
char 'A', '\n', '\u03A3'
String "Hello", ""
boolean true, false
Any object null
What are literals in Java? — Java - sobes.tech