Data Types in Java
Learn Java data types in detail, including primitive data types, reference data types, integer types, floating-point types, characters, booleans, memory size, ranges, default values, literals, type selection, and best practices.
Introduction
In the previous lessons, you learned how variables store data and how constants prevent values from being reassigned. However, every variable in Java must also have a data type.
A data type tells Java what kind of value a variable can store, what operations can be performed on that value, and how the value should be handled by the program.
int age = 25;
double price = 999.99;
char grade = 'A';
boolean isActive = true;
String name = "Alex";VARIABLE
│
▼
┌──────────────────────┐
│ DATA TYPE │
├──────────────────────┤
│ What value can fit? │
│ What operations work?│
│ How is it handled? │
└──────────────────────┘- What a data type is.
- Why Java needs data types.
- The two major categories of Java data types.
- What primitive data types are.
- What reference data types are.
- The difference between primitive and reference types.
- The eight primitive data types.
- How byte works.
- How short works.
- How int works.
- How long works.
- How float works.
- How double works.
- How char works.
- How boolean works.
- The size and range of primitive types.
- How integer literals work.
- How binary, octal, and hexadecimal literals work.
- How underscores improve numeric readability.
- What integer overflow and underflow are.
- How floating-point precision works.
- Why floating-point values require care in financial calculations.
- How Unicode characters work.
- How escape sequences work.
- How boolean expressions work.
- What default values Java provides.
- Why local variables do not receive automatic default values.
- How String and arrays work as reference types.
- How classes, interfaces, and enums create reference types.
- What null means.
- How primitive assignment differs from reference assignment.
- How to choose the correct data type.
- What wrapper classes are.
- What autoboxing and unboxing are.
- How the var keyword works.
- Common data type errors.
- Best practices for selecting Java data types.
What is a Data Type?
A data type defines the kind of data that a variable can store and determines the operations that can be performed on that data.
int age = 25;
double salary = 45000.50;
char grade = 'A';
boolean passed = true;int age = 25;
│ │ │
│ │ └── Value
│ │
│ └──────── Variable Name
│
└──────────── Data TypeThe type int tells Java that age stores an integer. The type double tells Java that salary stores a floating-point number.
Why Data Types are Needed
Define Storage
A data type defines what kind of value a variable can hold.
Type Safety
Java prevents many incompatible values from being assigned to variables.
Define Operations
The type determines which operations are valid for a value.
Improve Understanding
Types make the purpose of variables easier to understand.
Support Compilation
The compiler uses type information to validate code.
Control Representation
Different primitive types represent different ranges and kinds of values.
int age = 25;
// age = "Twenty Five"; // Compilation errorReal-World Analogy
Different containers are designed for different kinds of things. A water bottle stores liquid, a wallet stores money, and a document folder stores papers. Similarly, Java data types define what kind of value a variable is designed to hold.
int
┌──────────────┐
│ 100 │
└──────────────┘
Whole Numbers
double
┌──────────────┐
│ 99.99 │
└──────────────┘
Decimal Numbers
char
┌──────────────┐
│ 'A' │
└──────────────┘
Single Character
boolean
┌──────────────┐
│ true │
└──────────────┘
Logical ValueJava Data Type Categories
Java data types are broadly divided into two major categories: primitive data types and reference data types.
JAVA DATA TYPES
├── Primitive Types
│ │
│ ├── byte
│ ├── short
│ ├── int
│ ├── long
│ ├── float
│ ├── double
│ ├── char
│ └── boolean
│
└── Reference Types
│
├── String
├── Arrays
├── Classes
├── Interfaces
├── Enums
└── Other ObjectsPrimitive Data Types
Primitive types are the fundamental built-in data types provided directly by the Java language.
byte smallNumber = 10;
short distance = 2000;
int population = 100000;
long worldPopulation = 8000000000L;
float temperature = 36.5f;
double price = 999.99;
char grade = 'A';
boolean active = true;- Java has exactly eight primitive types.
- Primitive types are built into the language.
- They represent simple values.
- They are not objects.
- They cannot store null.
- Each primitive type has defined behavior and representation rules.
Reference Data Types
Reference variables store references to objects rather than directly representing primitive values.
String name = "Alex";
int[] numbers = {10, 20, 30};
Student student = new Student();student
┌──────────────┐
│ REFERENCE │
└──────────────┘
│
▼
┌──────────────────────┐
│ Student Object │
└──────────────────────┘Primitive vs Reference Types
PRIMITIVE TYPE
int age = 25;
Variable represents:
25
REFERENCE TYPE
Student student = new Student();
Variable stores:
Reference to an object- Primitive variables represent primitive values.
- Reference variables refer to objects.
- Primitive types are predefined by Java.
- Reference types include standard library types and user-defined types.
- Primitive variables cannot contain null.
- Reference variables can contain null.
The 8 Primitive Data Types
8 PRIMITIVE TYPES
INTEGER TYPES
├── byte
├── short
├── int
└── long
FLOATING-POINT TYPES
├── float
└── double
CHARACTER TYPE
└── char
LOGICAL TYPE
└── booleanInteger Data Types
Java provides four primitive integer types for storing whole numbers: byte, short, int, and long.
byte level = 10;
short year = 2026;
int population = 1000000;
long distance = 9876543210L;byte 8 bits
short 16 bits
int 32 bits
long 64 bitsbyte Data Type
The byte type is an 8-bit signed integer type. It stores whole numbers from -128 to 127.
byte age = 25;
byte temperature = -10;
byte maximum = 127;
byte minimum = -128;-128 ─────────────────────── 127
byte- When the value is guaranteed to remain between -128 and 127.
- When working with raw binary data.
- When APIs specifically require byte values.
- When compact numeric representation is important in large data structures.
short Data Type
The short type is a 16-bit signed integer type. It stores whole numbers from -32,768 to 32,767.
short year = 2026;
short temperature = -500;
short maximum = 32767;
short minimum = -32768;- When values fit within the short range.
- When a specific file format or API requires a 16-bit signed value.
- When memory representation matters across very large collections of values.
- For ordinary application integers, int is usually more common.
int Data Type
The int type is a 32-bit signed integer and is the most commonly used type for ordinary whole-number values.
int age = 25;
int score = 100;
int population = 1500000;
int temperature = -20;-2,147,483,648
to
2,147,483,647- Use int for most ordinary whole-number values.
- Integer literals are int by default when they fit in the int range.
- Use long when the required range exceeds int.
long Data Type
The long type is a 64-bit signed integer used for whole numbers that may exceed the range of int.
long worldPopulation = 8000000000L;
long distance = 9876543210L;
long timestamp = 1700000000000L;Large integer literals that exceed the int range require the L or l suffix. Uppercase L is preferred because lowercase l can look like the digit 1.
long value = 8000000000L;Integer Type Comparison
TYPE SIZE MINIMUM MAXIMUM
byte 8-bit -128 127
short 16-bit -32,768 32,767
int 32-bit -2,147,483,648 2,147,483,647
long 64-bit -9,223,372,036,854,775,808
to
9,223,372,036,854,775,807Choosing an Integer Type
NEED A WHOLE NUMBER?
│
▼
Ordinary application value?
│
├── YES ──► int
│
└── NO
│
▼
Value may exceed int range?
│
├── YES ──► long
│
└── NO
│
▼
Specific compact format required?
├── 8-bit ──► byte
└── 16-bit ──► shortInteger Literals
An integer literal is a whole-number value written directly in source code.
int decimal = 100;
int negative = -50;
long large = 8000000000L;Java supports decimal, binary, octal, and hexadecimal forms for integer literals.
Binary Literals
A binary integer literal begins with 0b or 0B and uses only the digits 0 and 1.
int value = 0b1010;
System.out.println(value);10Octal Literals
An octal integer literal begins with 0 and uses digits from 0 to 7.
int value = 012;
System.out.println(value);10- A leading zero can make an integer literal octal.
- Avoid unnecessary leading zeros in ordinary decimal values.
- The digit 8 or 9 is invalid in an octal literal.
Hexadecimal Literals
A hexadecimal integer literal begins with 0x or 0X and uses digits 0 to 9 and letters A to F.
int value = 0xA;
System.out.println(value);10Underscores in Numeric Literals
Java allows underscores inside numeric literals to improve readability.
int population = 1_000_000;
long distance = 9_876_543_210L;
double price = 1_999.99;1_000_000
is the same numeric value as
1000000Integer Overflow
Integer overflow occurs when an integer calculation exceeds the maximum value that its type can represent.
int value = Integer.MAX_VALUE;
System.out.println(value);
value = value + 1;
System.out.println(value);MAXIMUM int VALUE
2,147,483,647
│ + 1
▼
OVERFLOW
│
▼
-2,147,483,648- Ordinary integer arithmetic can overflow silently.
- The value can wrap around.
- Choose an appropriate type for the required range.
- Use checked arithmetic methods when overflow must be detected.
Integer Underflow
Integer underflow occurs when a calculation goes below the minimum value representable by the integer type.
int value = Integer.MIN_VALUE;
value = value - 1;
System.out.println(value);MINIMUM int VALUE
-2,147,483,648
│ - 1
▼
UNDERFLOW
│
▼
2,147,483,647Floating-Point Data Types
Java provides float and double for representing floating-point numbers.
float temperature = 36.5f;
double price = 999.99;FLOATING-POINT TYPES
├── float → 32-bit
│
└── double → 64-bitfloat Data Type
The float type is a 32-bit IEEE 754 floating-point type. A float literal normally requires the f or F suffix.
float temperature = 36.5f;
float percentage = 95.5F;
float weight = 72.8f;// float value = 10.5; // Compilation error
float value = 10.5f;double Data Type
The double type is a 64-bit IEEE 754 floating-point type and is the default choice for most decimal calculations.
double price = 999.99;
double distance = 12345.6789;
double percentage = 98.75;- Floating-point literals are double by default.
- double provides more precision than float.
- Use double for most general decimal calculations.
float vs double
float
Size:
32 bits
Approximate precision:
6 to 7 decimal digits
Literal:
10.5f
double
Size:
64 bits
Approximate precision:
15 to 16 decimal digits
Literal:
10.5- Use double for most decimal calculations.
- Use float when an API or data format specifically requires 32-bit floating-point values.
- Neither float nor double should be assumed to represent every decimal value exactly.
Floating-Point Literals
double first = 10.5;
double second = 99.99;
float third = 5.5f;
double fourth = 10.0d;The d or D suffix can explicitly mark a double literal, although it is usually unnecessary because floating-point literals are double by default.
Scientific Notation
double large = 1.5e6;
double small = 2.5e-3;
System.out.println(large);
System.out.println(small);1.5e6
1.5 × 10⁶
=
1,500,000
2.5e-3
2.5 × 10⁻³
=
0.0025Floating-Point Precision
Binary floating-point numbers cannot exactly represent every decimal fraction.
double result = 0.1 + 0.2;
System.out.println(result);0.30000000000000004- Many decimal fractions cannot be represented exactly in binary.
- Small rounding differences can appear.
- Avoid direct equality comparisons when approximate calculations are involved.
- Use an appropriate decimal representation when exact decimal arithmetic is required.
Money and Floating Point
Financial calculations often require exact decimal behavior. float and double can introduce binary floating-point rounding effects.
import java.math.BigDecimal;
BigDecimal price =
new BigDecimal("19.99");
BigDecimal tax =
new BigDecimal("0.18");
BigDecimal result =
price.multiply(tax);
System.out.println(result);- Do not assume double is exact for money.
- BigDecimal is commonly used when exact decimal arithmetic is required.
- Create BigDecimal from String values when exact decimal input matters.
- Financial rounding rules should be defined explicitly.
char Data Type
The char type is a 16-bit unsigned integral type that represents a UTF-16 code unit.
char grade = 'A';
char symbol = '$';
char digit = '7';
char letter = 'Z';- A char literal uses single quotes.
- char represents one UTF-16 code unit.
- Its numeric range is 0 to 65,535.
- Not every Unicode character fits in one char because some require a surrogate pair.
Character Literals
char letter = 'A';
char digit = '5';
char symbol = '#';char letter = 'A';
String text = "A";'A'
char literal
"A"
String literalUnicode and char
char letter = '\u0041';
System.out.println(letter);AThe Unicode value U+0041 represents the character A. Java source code also supports Unicode escapes.
Escape Sequences
\n New line
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\' Single quote
\" Double quote
\\ BackslashSystem.out.println("Java\nProgramming");
System.out.println("Name:\tAlex");Java
Programming
Name: Alexchar as a Numeric Type
char is an integral primitive type and can participate in numeric operations.
char letter = 'A';
int value = letter;
System.out.println(value);65char letter = 'A';
char next =
(char) (letter + 1);
System.out.println(next);Bboolean Data Type
The boolean type represents logical values and can contain only true or false.
boolean isLoggedIn = true;
boolean hasPermission = false;
boolean completed = true;boolean active = true;
boolean disabled = false;- Java does not treat 0 as false.
- Java does not treat 1 as true.
- A boolean value must be true or false.
- Numeric values cannot be assigned directly to boolean variables.
Boolean Expressions
int age = 20;
boolean eligible = age >= 18;
System.out.println(eligible);trueage >= 18
20 >= 18
│
▼
true
│
▼
eligible = truePrimitive Type Summary
TYPE CATEGORY SIZE
byte Integer 8 bits
short Integer 16 bits
int Integer 32 bits
long Integer 64 bits
float Floating Point 32 bits
double Floating Point 64 bits
char Character 16 bits
boolean Logical JVM-dependent representationSize and Range
byte
Size: 8 bits
Range: -128 to 127
short
Size: 16 bits
Range: -32,768 to 32,767
int
Size: 32 bits
Range:
-2,147,483,648
to
2,147,483,647
long
Size: 64 bits
Range:
-9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
float
Size: 32 bits
IEEE 754 floating point
double
Size: 64 bits
IEEE 754 floating point
char
Size: 16 bits
Range: 0 to 65,535
boolean
Values:
true or falseDefault Values
Fields receive default values automatically when an object or class is initialized.
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Reference nullpublic class Example {
int number;
boolean active;
String text;
public static void main(String[] args) {
Example example = new Example();
System.out.println(example.number);
System.out.println(example.active);
System.out.println(example.text);
}
}0
false
nullLocal Variables and Default Values
Local variables do not receive automatic default values. They must be definitely assigned before they are read.
public static void main(String[] args) {
int number;
// System.out.println(number); // Error
}public static void main(String[] args) {
int number = 0;
System.out.println(number);
}- Fields receive default values.
- Array elements receive default values.
- Local variables do not receive automatic default values.
- Local variables must be assigned before use.
Reference Types
Reference types represent objects and arrays. A reference variable can refer to an object or contain null.
String name = "Alex";
int[] numbers = new int[5];
Student student = new Student();REFERENCE TYPES
├── Classes
├── Arrays
├── Interfaces
├── Enums
├── Records
├── Strings
└── Other Object TypesString Type
String is a reference type used to represent sequences of characters.
String name = "Alex";
String language = "Java";
String message = "Hello, World!";- String is a class.
- String variables are reference variables.
- String literals receive special language support.
- String objects are immutable.
Arrays
An array is a reference type that stores a fixed-length sequence of values of one component type.
int[] numbers = {10, 20, 30};
String[] names = {
"Alex",
"Priya",
"John"
};numbers
┌──────────────┐
│ REFERENCE │
└──────────────┘
│
▼
┌────┬────┬────┐
│ 10 │ 20 │ 30 │
└────┴────┴────┘Classes and Objects
class Student {
String name;
int age;
}Student student =
new Student();
student.name = "Alex";
student.age = 20;Student is a user-defined reference type, and student is a reference variable.
Interfaces as Reference Types
interface Printable {
void print();
}
class Document implements Printable {
public void print() {
System.out.println("Printing");
}
}Printable item =
new Document();
item.print();An interface type can be used as the declared type of a reference when the referenced object implements that interface.
Enums as Reference Types
enum Status {
ACTIVE,
INACTIVE
}Status currentStatus =
Status.ACTIVE;Enums define a fixed set of named instances and are reference types.
The null Value
The null value represents the absence of an object reference.
String name = null;
Student student = null;// int age = null; // Compilation error- Reference variables can contain null.
- Primitive variables cannot contain null.
- Calling an instance member through a null reference can cause NullPointerException.
- Use null deliberately and handle it carefully.
Reference Assignment
Student first = new Student();
Student second = first;
second.name = "Alex";
System.out.println(first.name);first ──────┐
│
▼
┌───────────┐
│ Student │
│ name=Alex │
└───────────┘
▲
│
second ──────┘After second = first, both variables refer to the same object.
Primitive Assignment
int first = 10;
int second = first;
second = 20;
System.out.println(first);
System.out.println(second);10
20Primitive assignment copies the primitive value. Changing the second variable does not change the first variable.
Value vs Reference Behavior
PRIMITIVE ASSIGNMENT
int a = 10;
int b = a;
a ──► 10
b ──► 10
Independent primitive values
REFERENCE ASSIGNMENT
Student a = new Student();
Student b = a;
a ──┐
├──► Same Object
b ──┘Type Compatibility
Java checks whether the value being assigned is compatible with the declared type of the variable.
int age = 25;
double price = 99.99;
String name = "Alex";// int age = "25";
// boolean active = 1;
// char grade = "A";- Java checks assignments during compilation.
- Incompatible values usually produce compilation errors.
- Some numeric conversions happen automatically.
- Other conversions require explicit casting.
- Type conversion is covered in more detail in later lessons.
Choosing the Correct Data Type
WHAT KIND OF DATA?
Whole Number
│
├── Ordinary range ──► int
└── Very large value ─► long
Decimal Number
│
├── General calculation ─► double
└── Specific 32-bit need ─► float
Single UTF-16 Code Unit
│
└── char
True or False
│
└── boolean
Text
│
└── String
Object or Structured Data
│
└── Reference TypeMemory Considerations
Primitive types have defined value representations, while reference variables refer to objects whose memory requirements depend on the object and JVM implementation.
PRIMITIVE
Variable represents primitive value
REFERENCE
Variable stores reference
│
▼
Object has its own state- Do not assume every local variable always exists in one specific memory region.
- JVM implementations can optimize execution.
- Object layout can depend on the JVM.
- Use stack and heap diagrams as simplified learning models rather than absolute implementation guarantees.
Wrapper Classes
Each primitive type has a corresponding wrapper class that represents the primitive value as an object.
PRIMITIVE WRAPPER
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Booleanint primitive = 10;
Integer object = 10;Primitive vs Wrapper Types
PRIMITIVE
int value = 10;
Cannot be null
Not an object
WRAPPER
Integer value = 10;
Can be null
Is an object- Collections work with reference types rather than primitive types.
- Wrapper classes provide useful conversion and utility methods.
- Wrapper references can represent null.
- Generics require reference types.
Autoboxing
Autoboxing is the automatic conversion of a primitive value to its corresponding wrapper type.
int number = 10;
Integer object = number;int
10
│
│ AUTOBOXING
▼
Integer
10Unboxing
Unboxing is the automatic conversion of a wrapper object to its corresponding primitive value.
Integer object = 10;
int number = object;Integer
10
│
│ UNBOXING
▼
int
10- A wrapper reference can contain null.
- Unboxing null causes NullPointerException.
- Check nullable wrapper values before unboxing.
The var Keyword
Java supports local variable type inference using var. The compiler determines the variable type from the initializer.
var age = 25;
var price = 99.99;
var name = "Alex";var age = 25;
Compiler infers:
int
var price = 99.99;
Compiler infers:
double
var name = "Alex";
Compiler infers:
String- The compiler determines a real static type.
- The type does not change later.
- var can be used only in supported local-variable contexts.
- An initializer is required.
- Use var when it improves readability rather than hiding important type information.
Type Inference Rules
var count = 10;
var language = "Java";
var numbers = new int[]{1, 2, 3};// var value;
// var nothing = null;- var requires an initializer.
- The compiler must be able to infer the type.
- var is not a class field type.
- var is not a method parameter type.
- var is not a method return type.
- The inferred type remains fixed.
Common Data Type Errors
DATA TYPE ERRORS
├── Assigning String to int
├── Assigning Decimal to int
├── Missing L on Large long Literal
├── Missing f on float Literal
├── Using Double Quotes for char
├── Using Single Quotes for String
├── Assigning null to Primitive
├── Reading Uninitialized Local Variable
├── Integer Overflow
├── Integer Underflow
├── Assuming Floating Point is Exact
├── Using double for Exact Money Calculations
├── Unboxing null
├── Confusing Primitive and Wrapper Types
├── Assuming char Stores Every Unicode Character
└── Using var Where Type Cannot Be Inferred// int age = "25";// float price = 10.5;
float price = 10.5f;// char grade = "A";
char grade = 'A';Integer value = null;
// int number = value; // NullPointerExceptionBest Practices
- Choose a data type that clearly represents the meaning of the value.
- Use int for most ordinary whole numbers.
- Use long when values may exceed the int range.
- Use byte and short when their specific range or representation is useful.
- Use double for most general floating-point calculations.
- Use float when a specific 32-bit floating-point requirement exists.
- Do not assume floating-point arithmetic is exact.
- Use an exact decimal approach when financial rules require exact decimal arithmetic.
- Use char for a single UTF-16 code unit.
- Use String for text.
- Use boolean for true-or-false conditions.
- Do not use numeric values as substitutes for boolean values.
- Use uppercase L for long literals.
- Use f or F for float literals.
- Use underscores to improve readability of large numeric literals.
- Avoid unnecessary leading zeros in decimal integer literals.
- Understand the range of the selected numeric type.
- Consider overflow and underflow in calculations.
- Use Math.addExact and related methods when overflow detection is required.
- Remember that local variables require explicit assignment before use.
- Remember that fields receive default values.
- Remember that array elements receive default values.
- Use reference types for objects and structured data.
- Handle null carefully.
- Avoid unnecessary null values when a clearer design is available.
- Understand that primitive assignment copies values.
- Understand that reference assignment copies references.
- Remember that multiple references can refer to the same object.
- Use wrapper types when an object representation is required.
- Prefer primitives when null and object behavior are unnecessary.
- Be careful when unboxing nullable wrapper values.
- Use var only when the inferred type remains clear.
- Do not use var merely to hide complex or important type information.
- Use meaningful variable names together with meaningful types.
- Do not choose a smaller numeric type without a real reason.
- Do not assume smaller primitive types always make application code faster.
- Use standard library constants such as Integer.MAX_VALUE when appropriate.
- Use BigDecimal carefully for exact decimal arithmetic.
- Create BigDecimal from String when exact decimal construction matters.
- Understand that String is not a primitive type.
- Understand that arrays are reference types.
- Understand that enums are reference types.
- Understand that interfaces can be used as reference types.
- Do not confuse char with String.
- Do not assume one char can represent every Unicode code point.
- Use Character and String APIs when working with Unicode text.
- Use type conversion deliberately.
- Avoid unnecessary casts.
- Let the compiler help enforce type safety.
- Choose types based on domain meaning as well as numeric range.
- Document unusual type choices.
- Keep data representation consistent across related code.
- Use one clear representation for the same concept.
- Validate external input before storing it in typed variables.
- Remember that parsing text is different from casting.
- Review boundary values during testing.
- Test minimum and maximum numeric values where relevant.
- Test null behavior for wrapper and reference types.
- Prefer readable code over premature memory optimization.
Data Type Checklist
DATA TYPE CHECKLIST
[ ] Correct category selected
[ ] Primitive or reference type chosen intentionally
[ ] Numeric range is sufficient
[ ] int used for ordinary whole numbers
[ ] long used for values exceeding int range
[ ] Large long literal has L suffix
[ ] float literal has f suffix
[ ] double precision is sufficient
[ ] Exact decimal arithmetic considered where required
[ ] char used only for appropriate character data
[ ] String used for text
[ ] boolean used for true/false state
[ ] Local variable assigned before use
[ ] Default field values understood
[ ] Integer overflow considered
[ ] Integer underflow considered
[ ] Floating-point precision considered
[ ] null handled safely
[ ] Primitive assignment behavior understood
[ ] Reference assignment behavior understood
[ ] Shared object references considered
[ ] Wrapper type used only when needed
[ ] Nullable wrapper unboxing checked
[ ] var used only when type remains clear
[ ] Numeric literal is readable
[ ] Magic values replaced when appropriate
[ ] Unicode requirements considered
[ ] Boundary values tested
[ ] External input validated
[ ] Type matches domain meaning
[ ] Unnecessary casts avoidedCommon Misconceptions
- Java has exactly eight primitive data types.
- String is not a primitive type.
- Arrays are reference types.
- Classes define reference types.
- Interfaces can be used as reference types.
- Enums are reference types.
- Primitive variables cannot contain null.
- Reference variables can contain null.
- int is not always large enough for every whole number.
- long literals may require the L suffix.
- float literals usually require the f or F suffix.
- Floating-point literals are double by default.
- float and double do not represent every decimal value exactly.
- double is not automatically appropriate for exact financial calculations.
- char uses single quotes.
- String literals use double quotes.
- char represents one UTF-16 code unit.
- One char does not necessarily represent every Unicode character.
- boolean accepts only true or false.
- Java does not treat 0 as false.
- Java does not treat 1 as true.
- Local variables do not receive automatic default values.
- Fields do receive default values.
- Array elements do receive default values.
- Integer overflow can happen silently.
- Integer underflow can happen silently.
- Primitive assignment copies the primitive value.
- Reference assignment copies the reference value.
- Two reference variables can refer to the same object.
- Changing an object through one reference can be visible through another reference to the same object.
- Wrapper classes are objects.
- Wrapper references can contain null.
- Unboxing null can cause NullPointerException.
- Autoboxing does not turn Java into a dynamically typed language.
- var does not mean the variable has no type.
- var does not mean the type can change.
- The compiler infers a fixed static type for var.
- var requires an initializer.
- Smaller numeric types are not always the best choice.
- Choosing byte instead of int does not automatically improve ordinary application performance.
- Memory diagrams are simplified models.
- JVM implementations can optimize storage and execution.
- Parsing text is not the same as casting.
- Type safety prevents many errors before execution.
- A correct data type should match both the required range and the meaning of the data.
Practice Exercises
- Create one variable for each of the eight primitive types.
- Assign a valid value to each variable.
- Print all values.
- Explain why each value is valid for its type.
- Create byte, short, int, and long variables.
- Store appropriate values in each.
- Print the minimum and maximum values using wrapper class constants.
- Explain which type you would use for world population.
- Create the decimal value 10.
- Create the same value using binary.
- Create the same value using octal.
- Create the same value using hexadecimal.
- Print all four variables.
- Store Integer.MAX_VALUE in an int variable.
- Add 1.
- Print the result.
- Explain why the result changes to the minimum int value.
- Create a float variable.
- Create a double variable.
- Use the correct literal suffixes.
- Print both values.
- Explain which type provides more precision.
- Calculate 0.1 + 0.2 using double.
- Print the result.
- Compare it with 0.3.
- Research why binary floating-point representation causes the difference.
- Create a char containing A.
- Convert it to an int.
- Print the numeric value.
- Add 1 and convert the result back to char.
- Print the next character.
- Create an age variable.
- Create a boolean that checks whether age is at least 18.
- Print the result.
- Change the age and observe the new result.
- Create two int variables using assignment.
- Change the second variable.
- Observe that the first remains unchanged.
- Create two references to the same object.
- Modify the object through one reference.
- Observe the change through the other reference.
- Create an int primitive.
- Autobox it into Integer.
- Unbox it back into int.
- Create a null Integer.
- Explain what happens if you try to unbox null.
Common Interview Questions
What is a data type in Java?
A data type defines the kind of value a variable can store and the operations that can be performed on that value.
What are the two main categories of Java data types?
Primitive data types and reference data types.
How many primitive data types does Java have?
Java has eight primitive data types.
What are the eight primitive types?
byte, short, int, long, float, double, char, and boolean.
What is the default integer type in Java?
int is the default type for ordinary integer literals that fit within the int range.
What is the default floating-point type?
double.
What is the difference between float and double?
float is a 32-bit floating-point type, while double is a 64-bit floating-point type with greater precision.
Why does a float literal need f?
Because floating-point literals are double by default, so the f or F suffix explicitly creates a float literal.
Why does a large long literal need L?
Integer literals are treated as int when possible. A literal outside the int range must be explicitly marked as long using L or l.
What is integer overflow?
Integer overflow occurs when a calculation exceeds the maximum representable value of an integer type.
Can a primitive variable contain null?
No.
Can a reference variable contain null?
Yes.
Is String a primitive type?
No. String is a reference type.
Is an array primitive or reference type?
An array is a reference type.
What does char represent?
A char represents one 16-bit UTF-16 code unit.
Can boolean contain 0 or 1?
No. A Java boolean can contain only true or false.
Do local variables receive default values?
No. Local variables must be definitely assigned before use.
Do fields receive default values?
Yes.
What is autoboxing?
Autoboxing is automatic conversion from a primitive value to its corresponding wrapper type.
What is unboxing?
Unboxing is automatic conversion from a wrapper object to its corresponding primitive value.
What happens when null is unboxed?
A NullPointerException occurs.
What does var mean in Java?
var enables local variable type inference. The compiler infers a fixed static type from the initializer.
Frequently Asked Questions
Should I use byte instead of int whenever possible?
Not necessarily. int is generally the standard choice for ordinary whole-number values. Use byte when its specific range or representation is useful.
Should I always use double instead of float?
double is the usual choice for general decimal calculations, while float is useful when a specific 32-bit floating-point requirement exists.
Can int store decimal values?
No. int stores whole numbers only.
Can char store more than one character?
A char stores one UTF-16 code unit. Use String for text containing multiple code units.
Why is String not primitive?
String is a class whose instances are objects, although Java gives String literals special language support.
Can I assign an int to a long?
Yes. An int value can be widened to long automatically.
Can I assign a long to an int?
Not directly. A narrowing conversion requires an explicit cast and may lose information.
Why is 0.1 + 0.2 not always exactly 0.3?
Because many decimal fractions cannot be represented exactly using binary floating-point.
What should I use for money?
BigDecimal is commonly used when exact decimal arithmetic and explicit rounding behavior are required.
Can boolean be converted to int?
Java does not provide direct numeric conversion between boolean and integer types.
Can char be converted to int?
Yes. char is an integral type and can be widened to int.
What is the default value of String fields?
null.
What is the default value of boolean fields?
false.
What is the default value of int fields?
0.
Can var contain any type?
var can infer many local variable types, but the inferred type is fixed at compile time.
Can I declare var without a value?
No. An initializer is required so the compiler can infer the type.
Can var be used for fields?
No. var is used for local variable type inference in supported contexts.
Are wrapper classes primitive types?
No. Wrapper classes are reference types.
Why use Integer instead of int?
Integer is useful when an object type is required, when null is meaningful, or when working with generics and collections.
What should I learn after data types?
The next lesson covers Java operators.
Key Takeaways
- A data type defines what kind of value a variable can store.
- Data types help Java enforce type safety.
- Java data types are broadly divided into primitive and reference types.
- Java has exactly eight primitive data types.
- The integer primitive types are byte, short, int, and long.
- The floating-point primitive types are float and double.
- char is the character primitive type.
- boolean is the logical primitive type.
- byte is an 8-bit signed integer.
- short is a 16-bit signed integer.
- int is a 32-bit signed integer.
- long is a 64-bit signed integer.
- int is commonly used for ordinary whole numbers.
- long is used when values may exceed the int range.
- Large long literals require the L suffix.
- Uppercase L is preferred.
- Integer literals can be decimal, binary, octal, or hexadecimal.
- Binary literals begin with 0b or 0B.
- Octal literals begin with 0.
- Hexadecimal literals begin with 0x or 0X.
- Underscores can improve numeric literal readability.
- Integer overflow occurs above the maximum range.
- Integer underflow occurs below the minimum range.
- Integer overflow and underflow can happen silently.
- float is a 32-bit floating-point type.
- double is a 64-bit floating-point type.
- Floating-point literals are double by default.
- float literals usually require the f or F suffix.
- double provides more precision than float.
- Binary floating-point arithmetic is approximate.
- Many decimal fractions cannot be represented exactly in binary.
- Exact financial calculations often require an exact decimal approach.
- BigDecimal is commonly used for exact decimal arithmetic.
- char is a 16-bit unsigned integral type.
- char literals use single quotes.
- String literals use double quotes.
- char represents one UTF-16 code unit.
- Not every Unicode character fits in one char.
- Escape sequences represent special characters.
- char can participate in numeric operations.
- boolean contains only true or false.
- Java does not use 0 and 1 as boolean values.
- Boolean expressions produce true or false.
- Fields receive automatic default values.
- Array elements receive automatic default values.
- Local variables do not receive automatic default values.
- Local variables must be assigned before use.
- Reference variables refer to objects or arrays.
- Reference variables can contain null.
- Primitive variables cannot contain null.
- String is a reference type.
- Arrays are reference types.
- Classes define reference types.
- Interfaces can be used as reference types.
- Enums are reference types.
- null represents the absence of an object reference.
- Primitive assignment copies primitive values.
- Reference assignment copies reference values.
- Multiple references can refer to the same object.
- Changes to a shared mutable object can be visible through all references to that object.
- Type compatibility is checked by the compiler.
- Some numeric conversions are automatic.
- Other conversions require explicit casting.
- The correct type should match both the required range and the meaning of the data.
- Wrapper classes provide object representations of primitive values.
- Byte wraps byte.
- Short wraps short.
- Integer wraps int.
- Long wraps long.
- Float wraps float.
- Double wraps double.
- Character wraps char.
- Boolean wraps boolean.
- Autoboxing converts primitives to wrappers automatically.
- Unboxing converts wrappers to primitives automatically.
- Unboxing null causes NullPointerException.
- var provides local variable type inference.
- var does not create dynamic typing.
- The inferred type of var remains fixed.
- var requires an initializer.
- Use var only when it keeps code clear.
- Choose types deliberately.
- Understand numeric boundaries.
- Consider precision requirements.
- Handle null carefully.
- Use primitives and wrappers appropriately.
- Understanding data types prepares you for Java operators and expressions.
Summary
A data type defines the kind of value a variable can store and determines which operations are valid for that value. Java uses a strong static type system to detect many incompatible operations during compilation.
Java data types are broadly divided into primitive types and reference types. Primitive types represent fundamental values, while reference variables refer to objects and arrays.
Java has eight primitive types: byte, short, int, long, float, double, char, and boolean. Each type has a specific purpose and representation.
The integer types byte, short, int, and long represent whole numbers with different ranges. int is the standard choice for most ordinary whole numbers, while long is used for larger values.
The floating-point types float and double represent approximate real-number values. double provides greater precision and is the usual choice for general decimal calculations.
Floating-point arithmetic is not exact for every decimal fraction. Applications requiring exact decimal arithmetic, especially financial calculations, often use BigDecimal with explicit rounding rules.
The char type represents one UTF-16 code unit, while boolean represents true or false. Strings, arrays, classes, interfaces, and enums are reference types.
Fields and array elements receive automatic default values, but local variables must be explicitly assigned before they are read.
Primitive assignment copies primitive values, while reference assignment copies references. This means multiple reference variables can refer to the same mutable object.
Wrapper classes provide object representations of primitive values. Java supports automatic conversion between primitives and wrappers through autoboxing and unboxing.
The var keyword allows local variable type inference, but Java remains statically typed. The compiler determines a fixed type from the initializer.
Choosing the correct data type requires understanding the meaning of the data, the required numeric range, precision requirements, nullability, and how the value will be used.
- You understand what a data type is.
- You understand why Java needs data types.
- You know the two major data type categories.
- You understand primitive data types.
- You understand reference data types.
- You can compare primitive and reference types.
- You know all eight primitive types.
- You understand byte.
- You understand short.
- You understand int.
- You understand long.
- You can compare Java integer types.
- You know how to choose an integer type.
- You understand integer literals.
- You understand binary literals.
- You understand octal literals.
- You understand hexadecimal literals.
- You can use underscores in numeric literals.
- You understand integer overflow.
- You understand integer underflow.
- You understand floating-point types.
- You understand float.
- You understand double.
- You can compare float and double.
- You understand floating-point literals.
- You understand scientific notation.
- You understand floating-point precision.
- You understand why money calculations require care.
- You understand char.
- You understand character literals.
- You understand Unicode and UTF-16 code units.
- You understand escape sequences.
- You understand char numeric behavior.
- You understand boolean.
- You understand boolean expressions.
- You know primitive type sizes and ranges.
- You understand default field values.
- You understand why local variables have no automatic default values.
- You understand String as a reference type.
- You understand arrays as reference types.
- You understand classes and objects as reference types.
- You understand interface references.
- You understand enums as reference types.
- You understand null.
- You understand reference assignment.
- You understand primitive assignment.
- You can compare value and reference behavior.
- You understand type compatibility.
- You know how to choose the correct type.
- You understand wrapper classes.
- You can compare primitive and wrapper types.
- You understand autoboxing.
- You understand unboxing.
- You understand null unboxing risks.
- You understand the var keyword.
- You understand local type inference.
- You can identify common data type errors.
- You know the best practices for Java data types.
- You are ready to learn Java operators.