Board Formulas
β˜• JavaπŸ“… Day 4

Data Types in Java

Primitive vs reference types, sizes, defaults, and type casting rules in Java.

🎯

Learning objectives

  • β†’Distinguish primitive types from reference types
  • β†’Choose the right size type for a value
  • β†’Perform implicit and explicit type casting safely

πŸ’‘ Key points

  • Two families: primitives (8) and reference types (classes, arrays, interfaces).
  • Primitives store values; references store memory addresses to objects.
  • Implicit (widening) cast is automatic: byte β†’ short β†’ int β†’ long β†’ float β†’ double.
  • Explicit (narrowing) cast requires (type) syntax and may lose data.

πŸ’» Code examples(3)

#1All 8 primitives
java
byte    b = 100;
short   s = 20000;
int     i = 1_000_000;
long    l = 9_000_000_000L;
float   f = 3.14f;
double  d = 3.141592653589793;
char    c = 'J';
boolean flag = true;
Underscore in numeric literals is a readability aid. L suffix = long, f suffix = float.
#2Widening (implicit)
java
int i = 100;
long l = i;        // int β†’ long, automatic
double d = l;      // long β†’ double, automatic
Small type into a larger one β€” Java handles it for you.
#3Narrowing (explicit)
java
double d = 9.99;
int i = (int) d;   // i = 9 (fractional part dropped)
long big = 300L;
byte b = (byte) big;  // wraps around β€” data loss!
Cast is mandatory. Fractional part is truncated (not rounded). Values outside range wrap silently.

🎯 Practice

Q1. What is the default value of an instance variable of type boolean?+

false

Q2. Why does `int x = 3.14;` fail to compile?+

3.14 is a double literal. Assigning double to int is a narrowing conversion β†’ needs explicit cast: int x = (int) 3.14;

Q3. Difference between primitive int and reference type Integer?+

int is a raw value in stack memory, cannot be null, no methods. Integer is an object wrapper on the heap β€” can be null, has methods like parseInt(), used in collections.

πŸ“ Notes

Reference types

Anything that's not one of the 8 primitives is a reference type: classes (String, Scanner), arrays (int[]), interfaces (List).

String name = "Java";   // reference to a String object
int[] scores = {90, 85, 78};

Reference variables can be null; primitives cannot.

Autoboxing / Unboxing

Java auto-converts between primitive and wrapper:

Integer x = 5;    // autobox: int β†’ Integer
int y = x;        // unbox: Integer β†’ int

Useful in collections: List<Integer> β€” cannot hold int directly.