Lab 02: Variables & Primitives

🎯 Objective

Understand Java's primitive data types, variable declaration, and type casting between numeric types.

📚 Background

Java has 8 primitive types: byte, short, int, long, float, double, char, and boolean. Unlike objects, primitives are stored directly in memory. Understanding when to use each type and how to safely cast between them is fundamental to Java programming.

⏱️ Estimated Time

30 minutes

📋 Prerequisites

  • Completed Lab 1 (Hello World)

  • Basic understanding of data types

🛠️ Tools Used

  • Docker (innozverse-java:latest)

  • javac, java

🔬 Lab Instructions

Step 1: Declare and use integer types

📸 Verified Output:

Step 2: Floating-point and boolean types

📸 Verified Output:

💡 float has ~7 decimal digits of precision; double has ~15. Always use double unless memory is critical.

Step 3: Widening (implicit) type conversion

📸 Verified Output:

Step 4: Narrowing (explicit) type casting

📸 Verified Output:

💡 (int) 9.99 truncates to 9, not rounds to 10. Use Math.round() to round.

Step 5: Arithmetic and integer overflow

📸 Verified Output:

Step 6: String conversion and parsing

📸 Verified Output:

Step 7: var — local variable type inference (Java 10+)

📸 Verified Output:

Step 8: Final variables (constants)

📸 Verified Output:

✅ Verification

📸 Verified Output: i=42 d=42.0 back=9

🚨 Common Mistakes

  • Missing L suffix: long x = 9999999999 → compile error; use 9999999999L

  • Missing f suffix: float x = 3.14 → compile error; use 3.14f

  • Integer overflow: int + 1 silently wraps around; cast to long for large numbers

  • Casting truncates: (int) 9.9 is 9, not 10

📝 Summary

Java's 8 primitive types cover integers (byte/short/int/long), floats (float/double), text (char), and logic (boolean). Widening conversions are automatic; narrowing requires explicit casts. Use final for constants and var for type inference.

🔗 Further Reading

Last updated