🧠 Java Quiz

Java Data Types

Java has two families of types: primitives and references.

Primitive types (8 of them)

Primitives store actual values directly in memory. They're fast, fixed-size, and have a default value if not initialized in a class.

TypeSizeRangeDefaultExample
byte8 bits−128 to 1270byte b = 100;
short16 bits−32,768 to 32,7670short s = 30000;
int32 bits≈ ±2.1 billion0int i = 1_000_000;
long64 bits≈ ±9.2 × 10¹⁸0Llong l = 99999999L;
float32 bits~7 decimal digits0.0ffloat f = 3.14f;
double64 bits~15 decimal digits0.0double d = 3.14159;
boolean1 bittrue / falsefalseboolean ok = true;
char16 bitsUnicode character'\u0000'char c = 'A';
Default for everyday code Use int for whole numbers, double for decimals, boolean for true/false, String for text. Reach for long, byte, short, or float only when you have a specific reason.

Numeric literals

Literal forms
int hex = 0xFF;            // hexadecimal = 255
int binary = 0b1010;        // binary = 10
int million = 1_000_000;    // underscores for readability
long big = 123456789L;       // L suffix for long
float rate = 3.14f;          // f suffix for float

Reference types

Anything that's not a primitive is a reference type. Variables of reference types store a pointer to the object, not the object itself. Objects live on the heap; references can be null.

Reference types
String name = "Raman";                    // String
int[] numbers = {1, 2, 3};                 // array
var list = new ArrayList<String>();        // custom class
String empty = null;                       // can be null

Type casting

Converting between types. Two flavors:

Implicit (widening) — automatic

Widening
int i = 100;
long l = i;          // int → long, automatic
double d = i;        // int → double, automatic

Explicit (narrowing) — risk of data loss

Narrowing
double d = 3.99;
int i = (int) d;      // 3 (decimal lost — truncated, not rounded)

long big = 9_000_000_000L;
int small = (int) big;  // data loss — exceeds int range

Wrapper classes

Each primitive has a corresponding object wrapper: intInteger, doubleDouble, booleanBoolean. Use them when you need to put a primitive into a collection like List<Integer> (collections only hold objects).

Java auto-converts between primitives and wrappers (called autoboxing and unboxing) — it just works.