HOME HTML EDITOR C JAVA PHP

Java Data Types: Memory & Precision

Data types specify the different sizes and values that can be stored in the variable. In Java, data types are divided into two main categories: Primitive and Non-Primitive.

Pro Concept: Java is a "Strongly Typed" language. This means every piece of data has a strict type, which helps the compiler catch errors before the program even runs.

1. Primitive vs. Non-Primitive

Before diving into details, it's important to understand the high-level classification:

2. The 8 Primitive Data Types

Java has 8 primitive data types, each with a fixed size in memory. This ensures portability across different hardware.

Data Type Size Description Range / Value
byte 1 byte Very small whole numbers -128 to 127
short 2 bytes Small whole numbers -32,768 to 32,767
int 4 bytes Standard whole numbers -2.1B to 2.1B
long 8 bytes Huge whole numbers -9 quintillion to 9 quintillion
float 4 bytes Decimal numbers 6-7 decimal digits precision
double 8 bytes High precision decimals 15 decimal digits precision
boolean 1 bit Logical state true or false
char 2 bytes Single character/Unicode 'A', 'B', '\u0041'

3. Integer Types: byte, short, int, long

Even though they all store whole numbers, you should choose based on the size of the data to save memory.

byte age = 25; int salary = 45000; long worldPopulation = 8000000000L; // Note the 'L' at the end

4. Floating Point Types: float vs. double

Use float or double when you need numbers with a fractional part (decimals). By default, every decimal in Java is a double.

Scientific Numbers

You can also use 'e' to indicate the power of 10:

float f1 = 35e3f; // 35000.0
float price = 19.99f; // 'f' is mandatory double pi = 3.1415926535;

5. Characters and Unicode

Unlike C/C++, Java uses 2 bytes for char because it supports Unicode. This allows Java to represent characters from almost all global languages.

char myGrade = 'A'; char myVar = 65; // This will also print 'A' (ASCII)

6. Non-Primitive (Reference) Types

Non-primitive types refer to objects. They are called reference types because they store the memory address of the data, not the value itself.

Feature Primitive Non-Primitive
Definition Predefined in Java Created by programmer
Value Always has a value Can be null
Size Depends on type All have same address size

Ready for Transformation?

Understanding data types is the key to writing memory-efficient code. But what happens if you want to store a double value into an int variable? That process is called Type Casting, and that is exactly what we will cover in the next chapter!

Next: Java Type Casting →