Types of Literals

Basically, a literal is the source code representation of a fixed value. In order to be able to choose the right answer for some exam questions, you must be able to infer the data type of literals that appear in the sample code of those questions:

Literal type Description Data type of the literal
Integer
  • Decimal values with no decimal point
  • Decimal values ended in: l, L
  • Hexadecimal values (0x prefix)
  • Binary values (0b prefix)
  • long if it ends with L or l: 123L
  • int otherwise: 123, 0x1A, 0b110
Floating-point
  • Decimal values with a decimal point or using scientific notation
  • Decimal values ended in: f, F, d, D

 

  • float if it ends with F or f: 1.3f, 2e3f
  • double if it ends with D or d: 1.3d, 2e3d
  • double otherwise: 1.3, 2e3
Character
  • Values between single quotes (may contain Unicode characters)
  • char: 'A', '\u0041'
String
  • Values between double quotes (may contain Unicode characters)
  • String: "ABC", "\u0041BC"
Class
  • Any type name + .class
  • It refers to the object that represents the type itself
  • The object’s class, e.g.: String.class

Undescores in Numeric Literals

From Java version 7 on, it’s possible to use underscores in numeric literals to improve legibility. They can appear anywhere between the digits of the literal:

 


Leave a Reply