📘

Data Types and Literals in Java

Jul 16, 2024

Data Types and Literals in Java

Introduction to Literals

  • Literals: Direct values like 9, 8.
  • Types of literals: Integer, Binary, Hexadecimal, Float, Double, Boolean, Char, String.

Integer Literals

  • Decimal (Base 10): Standard integers like 9.
  • Binary (Base 2): Prefix with 0b, e.g., 0b101 (outputs 5). Example:
int num1 = 0b101; System.out.println(num1); // prints 5
  • Hexadecimal (Base 16): Prefix with 0x, e.g., 0x7E, use X or x. Example:
int num2 = 0x7E; System.out.println(num2); // prints 126

Underscores in Numeric Literals

  • Used for readability with large numbers, e.g., 1_000_000. Example:
int bigNum = 1_000_000; System.out.println(bigNum); // prints 1000000

Floating Point Literals

  • Double: Automatically converts integers, e.g., 56. Example:
double num3 = 56;
  • Scientific Notation: Use e, e.g., 1.2e3 for 1.2 * 10^3.*

Boolean Literals

  • Only true or false. Example:
boolean flag = true;

Avoid using 1 or 0 (will cause compilation error).

Character Literals

  • Single characters in single quotes, e.g., 'a'. Example:
char letter = 'a';
  • Operations on Characters: Can be treated as integers, incrementing is possible, e.g., 'a' + 1 results in 'b'. Example:
char letter = 'a'; letter++; System.out.println(letter); // prints 'b'

String Literals

  • Enclosed in double quotes, e.g., "Hello World". Example:
String greeting = "Hello World";

Summary

  • Literals are direct values used in the code.
  • Different types of literals for different data types.
  • Special features like binary, hexadecimal, and scientific notation are supported.
  • Use underscores in large numeric literals for better readability.