Core Java
core3DataTypes
- Path
- pkg1core/core3DataTypes.java
- Package
- pkg1core
- Study order
- 2
- Run
- Single-file source launch
- Command
- java pkg1core/core3DataTypes.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core3DataTypes.java5 * --------------6 * The 8 primitive types, their ranges, wrappers, casting, and overflow.7 *8 * EXPLANATION:9 * - Primitives store raw values directly (fast, no object overhead).10 * - Each primitive has a wrapper class (Integer, Double, ...) used in generics/collections.11 * - Autoboxing converts primitive <-> wrapper automatically.12 * - Widening (int->long) is implicit; narrowing (long->int) needs a cast and may lose data.13 */14public class core3DataTypes {15 public static void main(String[] args) {16 byte b = 127; // 8-bit17 short s = 32_000; // 16-bit (underscores improve readability)18 int i = 2_000_000_000; // 32-bit19 long l = 9_000_000_000L; // 64-bit (L suffix)20 float f = 3.14f; // 32-bit (f suffix)21 double d = 3.141592653589793; // 64-bit22 char c = 'J'; // 16-bit UTF-1623 boolean flag = true;24 25 System.out.println("byte=" + b + " short=" + s + " int=" + i + " long=" + l);26 System.out.println("float=" + f + " double=" + d + " char=" + c + " boolean=" + flag);27 28 // Ranges via wrapper constants29 System.out.println("int range: " + Integer.MIN_VALUE + " .. " + Integer.MAX_VALUE);30 System.out.println("long max: " + Long.MAX_VALUE);31 32 // Overflow: wraps around silently (a classic interview gotcha)33 int max = Integer.MAX_VALUE;34 System.out.println("MAX_VALUE + 1 overflows to: " + (max + 1));35 36 // Widening (implicit) and narrowing (explicit cast)37 long widened = i; // int -> long, safe38 int narrowed = (int) l; // long -> int, may lose data39 System.out.println("widened=" + widened + " narrowed=" + narrowed);40 41 // Autoboxing / unboxing42 Integer boxed = i; // int -> Integer43 int unboxed = boxed; // Integer -> int44 System.out.println("boxed=" + boxed + " unboxed=" + unboxed);45 46 // Integer cache gotcha: values -128..127 are cached47 Integer x = 127, y = 127, p = 128, q = 128;48 System.out.println("127==127 (cached): " + (x == y));49 System.out.println("128==128 (not cached): " + (p == q) + " use .equals(): " + p.equals(q));50 }51}