Skip to content

Java Basic Datatypes

Variables are fundamental to programming. Think of them as named containers in your computer’s memory where you can store information (values). When you declare a variable, you tell Java the variable’s name and the type of data it will hold. This reserves memory space.

The data type determines how much memory is allocated and what kind of data (like whole numbers, decimal numbers, or characters) can be stored. Java has two main categories of data types:

  • Primitive Data Types: The basic building blocks for data.
  • Reference Data Types: Used to refer to objects (instances of classes).

Java provides eight primitive data types. These are built directly into the language and are identified by keywords. They store the actual value directly in the variable’s allocated memory.

  • Size: 8-bit signed two’s complement integer.
  • Range: -128 to 127.
  • Default Value: 0.
  • Use Case: Saves memory in large arrays when the values are within the byte range. Useful for stream/file data.
  • Example: byte smallNumber = 100; byte negativeByte = -50;
  • Size: 16-bit signed two’s complement integer.
  • Range: -32,768 to 32,767.
  • Default Value: 0.
  • Use Case: Memory saving like byte, but for a wider range. Less common than int.
  • Example: short mediumNumber = 10000; short negativeShort = -20000;
  • Size: 32-bit signed two’s complement integer.
  • Range: -2,147,483,648 to 2,147,483,647 (approximately +/- 2 billion).
  • Default Value: 0.
  • Use Case: The most commonly used integer type. Generally the default choice for whole numbers unless memory is a critical concern or a larger range is needed.
  • Example: int standardNumber = 100000; int negativeInt = -200000;
  • Size: 64-bit signed two’s complement integer.
  • Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (approximately +/- 9 quintillion).
  • Default Value: 0L.
  • Use Case: When you need a range wider than int, for example, timestamps in milliseconds or large counters.
  • Note: Append an ‘L’ or ‘l’ to the number to indicate it’s a long literal.
  • Example: long largeNumber = 100000L; long veryLargeNumber = -9000000000L;
  • Size: Single-precision 32-bit IEEE 754 floating point.
  • Default Value: 0.0f.
  • Use Case: Saves memory in large arrays of floating-point numbers compared to double. Not suitable for precise values like currency due to potential rounding errors.
  • Note: Append an ‘f’ or ‘F’ to the number to indicate it’s a float literal.
  • Example: float percentage = 98.5f; float temperature = -10.2F;
  • Size: Double-precision 64-bit IEEE 754 floating point.
  • Default Value: 0.0d.
  • Use Case: The default choice for decimal values. Offers a larger range and more precision than float. Still not suitable for exact financial calculations.
  • Note: Decimal literals are treated as double by default (a ‘d’ or ‘D’ suffix is optional).
  • Example: double price = 199.99; double piApproximation = 3.1415926535;

Important Note on Precision:

For calculations requiring high precision, especially financial ones, avoid float and double. Use the java.math.BigDecimal class instead. It provides exact representation of decimal numbers.

  • Represents one bit of information.
  • Possible Values: Only true or false.
  • Default Value: false.
  • Use Case: Used for flags or conditions that track true/false states (e.g., in if statements, loops).
  • Example: boolean isLoggedIn = true; boolean isComplete = false;
  • Size: Single 16-bit Unicode character.
  • Range: ‘\u0000’ (0) to ‘\uffff’ (65,535).
  • Default Value: ‘\u0000’.
  • Use Case: Stores single characters. Can also store special characters using escape sequences.
  • Note: Character literals are enclosed in single quotes.
  • Example: char grade = 'A'; char initial = 'J'; char newlineChar = '\n';

Unlike primitive types that store values directly, reference variables store the memory address where an object (an instance of a class) is located. Think of it like having a remote control (reference variable) that points to the actual TV (object) in memory.

  • Created using class constructors (new ClassName(...)).
  • Used to access the object’s fields (state) and methods (behavior).
  • Can be assigned to variables of the declared type or a compatible supertype.
  • Includes class objects (like String, Scanner, or custom classes like Employee, Dog), arrays, interfaces, and enums.
  • Default Value: null (meaning the variable doesn’t currently point to any object).
  • Example: String greeting = "Hello"; // String object
  • Dog myDog = new Dog("Buddy"); // Custom Dog object
  • int[] numbers = new int[10]; // Array object

A literal is a fixed value represented directly in the source code, without requiring computation. Literals can be assigned to variables.

Examples:

int age = 30; // Integer literal
double weight = 65.5; // Floating-point literal
boolean active = true; // Boolean literal
char firstInitial = 'C';// Character literal
String name = "Alice"; // String literal

Integer literals (byte, short, int, long) can be expressed in different number systems:

  • Decimal (Base 10): Standard numbers (e.g., 100).
  • Hexadecimal (Base 16): Prefix 0x or 0X (e.g., 0x64 is 100).
  • Octal (Base 8): Prefix 0 (e.g., 0144 is 100). Use with caution as it’s easy to mistake for decimal.
  • Binary (Base 2, Java 7+): Prefix 0b or 0B (e.g., 0b1100100 is 100).
int decimalValue = 100;
int hexValue = 0x64;
int octalValue = 0144; // Be careful with leading zeros!
int binaryValue = 0b1100100;
long socialSecurity = 123_45_6789L; // Underscores (Java 7+) improve readability

String literals are sequences of characters enclosed in double quotes ("").

"Hello, World!"
"Line one\nLine two" // \n is a newline escape sequence
"He said, \"Java is fun!\"" // \" escapes the double quote

String and char literals support Unicode characters and escape sequences:

char copyrightSymbol = '\u00A9'; // © using Unicode escape
String greeting = "\u0048\u0065\u006C\u006C\u006F"; // "Hello"
NotationCharacter Represented
\nNewline
\rCarriage return
\fForm feed
\bBackspace
\tTab
\"Double quote
\'Single quote
\\Backslash
\uXXXXUnicode character (hexadecimal XXXX)

Since Java 10, you can use the var keyword for declaring local variables (variables inside methods). The compiler infers the type based on the assigned value. This can make code more concise, but use it judiciously.

var message = "Hello from var!"; // Compiler infers type String
var count = 10; // Compiler infers type int
var list = new java.util.ArrayList<String>(); // Infers ArrayList<String>

Note: var is not a keyword but a reserved type name. It cannot be used for fields, method parameters, or return types. For beginners, explicitly declaring types is often clearer.

Now that you understand the basic data types, the next chapter delves into different types of variables (local, instance, static) and their scope, explaining where and how they are used within Java classes and methods.