Skip to main content

Language Features

Wrapper Classes

Complete lesson for Wrapper Classes using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Wrapper Classes

Section: Language Features. Java wrapper classes — all eight wrappers, autoboxing and unboxing, conversions between String, primitive and wrapper, built-in methods, the Integer cache, and the classic null and == traps.

What are wrapper classes?

  • A wrapper class is a class whose object holds one primitive value. It "wraps" an int, double, char, and so on inside an object.
  • Java has eight primitive types and eight matching wrapper classes in java.lang (so no import is needed).
  • All wrapper classes are final (cannot be extended) and immutable (the value inside never changes).
  • Real-life analogy: a gift box. The primitive is the gift; the wrapper is the box that lets you put it on a shelf (a collection), label it, or leave the box empty (null).
public class WrapperIntro {
    public static void main(String[] args) {
        int marks = 90;                       // primitive: just a value
        Integer boxedMarks = marks;           // wrapper object holding 90

        System.out.println(boxedMarks);                 // 90
        System.out.println(boxedMarks.getClass());      // class java.lang.Integer
        System.out.println(boxedMarks.doubleValue());   // 90.0 (methods available)
    }
}

Why we need wrapper classes

  • Collections and generics work only with objects: you write List<Integer>, never List<int>.
  • A wrapper can be null, which is useful for "no value yet" (for example an optional database column or a missing map entry).
  • Wrappers provide utility methods and constants: Integer.parseInt, Integer.MAX_VALUE, Character.isDigit, Double.isNaN.
  • APIs that accept Object (reflection, equals, Object[], serialization) need reference types.
  • Frameworks such as JPA / Hibernate, Jackson, and Spring use wrapper types for nullable fields and form inputs.

Primitive types and their wrapper classes

  • Two names differ from the primitive: int becomes Integer and char becomes Character. The rest just capitalize the first letter.
  • Void is a ninth placeholder class that represents the void keyword (used in reflection and Callable<Void>).
PrimitiveWrapper classSizeDefault (primitive field)Default (wrapper field)Range constants
byteByte8 bits0nullByte.MIN_VALUE = -128, Byte.MAX_VALUE = 127
shortShort16 bits0null-32768 to 32767
intInteger32 bits0null-2147483648 to 2147483647
longLong64 bits0Lnullabout -9.22 x 10^18 to 9.22 x 10^18
floatFloat32 bits0.0fnullFloat.MAX_VALUE = 3.4028235E38
doubleDouble64 bits0.0nullDouble.MAX_VALUE = 1.7976931348623157E308
charCharacter16 bitsNUL character (code 0)null0 to 65535 (UTF-16 code unit)
booleanBooleanJVM dependentfalsenullBoolean.TRUE, Boolean.FALSE

Wrapper class hierarchy

  • The six numeric wrappers extend the abstract class java.lang.Number, which provides intValue(), longValue(), doubleValue(), and friends.
  • Character and Boolean extend Object directly, because they are not numbers.
  • Every wrapper implements Comparable (so they sort naturally) and Serializable.
  • Because of Number, you can write one method double total(List<? extends Number> list) that sums integers, longs, and doubles.
java.lang.Object
 ├── java.lang.Number(abstract)
 │     ├── Byte
 │     ├── Short
 │     ├── Integer
 │     ├── Long
 │     ├── Float
 │     └── Double
 ├── java.lang.Character
 └── java.lang.Boolean

Autoboxing and unboxing

  • Autoboxing (Java 5+): the compiler converts a primitive to its wrapper automatically. Integer x = 5; becomes Integer x = Integer.valueOf(5);.
  • Unboxing: the compiler converts a wrapper back to a primitive. int y = x; becomes int y = x.intValue();.
  • It is pure compiler work; the bytecode still calls valueOf and intValue.
Where it happensExampleWhat the compiler inserts
AssignmentInteger a = 10;Integer.valueOf(10)
Method argumentlist.add(25);list.add(Integer.valueOf(25))
Return valueInteger f() { return 7; }return Integer.valueOf(7);
ArithmeticInteger c = a + b;Integer.valueOf(a.intValue() + b.intValue())
Comparison with primitiveif (a > 5)a.intValue() > 5
Incrementa++;a = Integer.valueOf(a.intValue() + 1); (new object)
Enhanced for loopfor (int n : list)n = it.next().intValue()
import java.util.ArrayList;
import java.util.List;

public class BoxingDemo {
    public static void main(String[] args) {
        Integer boxed = 42;                 // autoboxing
        int raw = boxed;                    // unboxing

        List<Integer> scores = new ArrayList<>();
        scores.add(75);                     // autoboxing into the list
        scores.add(90);

        int total = 0;
        for (int s : scores) total += s;    // unboxing in the loop
        System.out.println(raw + " " + total); // 42 165
    }
}

Ways to create wrapper objects

WayExampleReturnsNotes
AutoboxingInteger a = 100;IntegerSimplest; uses valueOf internally (cache applies)
valueOf(primitive)Integer.valueOf(100)IntegerRecommended explicit way; uses the cache
valueOf(String)Integer.valueOf("100")IntegerParses text; throws NumberFormatException on bad input
parseXxx(String)Integer.parseInt("100")int (primitive)Use when you need the primitive
Constructornew Integer(100)IntegerDeprecated since Java 9, marked for removal since Java 16; always a new object

Conversions between String, primitive, and wrapper

FromToMethodExample
StringprimitiveXxx.parseXxx(s)int n = Integer.parseInt("25");
StringwrapperXxx.valueOf(s)Double d = Double.valueOf("3.5");
primitivewrapperXxx.valueOf(p) or autoboxingLong l = Long.valueOf(9L);
wrapperprimitivexxxValue() or unboxingint n = boxed.intValue();
primitiveStringString.valueOf(p) or Xxx.toString(p)String s = String.valueOf(42);
wrapperStringobj.toString()String s = boxed.toString();
wrapperother primitiveNumber methodsdouble d = boxed.doubleValue();
String (other base)intparseInt(s, radix)Integer.parseInt("ff", 16) = 255
intbinary / hex / octal StringtoBinaryString, toHexString, toOctalStringInteger.toBinaryString(10) = 1010
charint digitCharacter.getNumericValue(c)Digit character 7 gives 7
public class Conversions {
    public static void main(String[] args) {
        int age = Integer.parseInt("21");          // String -> int
        Double price = Double.valueOf("499.99");   // String -> Double
        Integer boxed = Integer.valueOf(age);      // int -> Integer
        long big = boxed.longValue();              // Integer -> long
        String text = String.valueOf(age);         // int -> String

        System.out.println(age + 1);               // 22
        System.out.println(price * 2);             // 999.98
        System.out.println(big + text);            // 2121
        System.out.println(Integer.parseInt("1010", 2));   // 10
        System.out.println(Integer.toHexString(255));      // ff
    }
}

Common Integer methods and constants

  • Long, Short, and Byte have the same method names with their own types (Long.parseLong, Short.parseShort, ...).
Method / constantTypePurposeExample result
Integer.parseInt(s)staticString to intparseInt("42") = 42
Integer.parseInt(s, radix)staticParse in another baseparseInt("777", 8) = 511
Integer.valueOf(x)staticint or String to Integer (cached)valueOf("7") = 7
Integer.toString(i)staticint to String"42"
Integer.toBinaryString(i)staticBinary texttoBinaryString(5) = 101
Integer.toHexString(i)staticHex texttoHexString(255) = ff
Integer.toOctalString(i)staticOctal texttoOctalString(8) = 10
Integer.compare(a, b)staticNegative, zero, or positivecompare(3, 7) = -1
Integer.max(a, b) / min / sumstaticHandy as method referencesInteger::sum in reduce
Integer.bitCount(i)staticNumber of 1 bitsbitCount(7) = 3
Integer.reverse(i)staticReverse the bit orderUsed in bit puzzles
Integer.signum(i)staticSign as -1, 0, or 1signum(-9) = -1
Integer.decode(s)staticParse with prefix 0x, #, or 0decode("0x1F") = 31
intValue(), longValue(), doubleValue()instanceUnwrap to a primitiveboxed.doubleValue()
equals(obj)instanceValue equality (same type only)a.equals(b)
compareTo(other)instanceNatural orderinga.compareTo(b)
hashCode()instanceReturns the int value itselfInteger.valueOf(5).hashCode() = 5
Integer.MAX_VALUE / MIN_VALUEconstantLargest / smallest int2147483647 / -2147483648
Integer.SIZE / BYTESconstantBits / bytes in an int32 / 4

Common Character methods

  • All of these are static and take a char (or an int code point).
MethodPurposeTypical use
Character.isDigit(ch)Is it 0-9 (or another Unicode digit)?Validate a PIN or phone number
Character.isLetter(ch)Is it a letter?Validate a name
Character.isLetterOrDigit(ch)Letter or digit?Username rules
Character.isAlphabetic(cp)Alphabetic, including more Unicode scriptsInternational text
Character.isUpperCase(ch) / isLowerCase(ch)Check casePassword strength checks
Character.isWhitespace(ch)Space, tab, newline, ...Word counting
Character.toUpperCase(ch) / toLowerCase(ch)Change caseCase-insensitive compare
Character.getNumericValue(ch)Digit character to its int valueSum of digits from a String
Character.toString(ch) / String.valueOf(ch)char to StringBuilding text
Character.compare(a, b)Compare two charsSorting

Common Double, Float, and Boolean methods

Method / constantPurposeNote
Double.parseDouble(s)String to doubleAccepts "1e3", "NaN", "Infinity"
Double.valueOf(s)String to DoubleNo cache for Double / Float
Double.isNaN(d)Is it Not-a-Number?d == Double.NaN is always false; use this
Double.isInfinite(d) / isFinite(d)Check for infinity1.0 / 0 is Infinity, not an exception
Double.compare(a, b)Safe compareHandles NaN and -0.0 consistently
Double.MAX_VALUELargest doubleAbout 1.8 x 10^308
Double.MIN_VALUESmallest positive double4.9E-324, not the most negative value
Float.parseFloat(s)String to floatSame family of methods as Double
Boolean.parseBoolean(s)String to booleantrue only for "true" in any case; anything else (even null) is false
Boolean.valueOf(b)Returns Boolean.TRUE or Boolean.FALSENever creates new objects
Boolean.logicalAnd / logicalOr / logicalXorBoolean operators as methodsUseful in reduce
Boolean.getBoolean(name)Reads a system propertyTrap: it does not parse the string

The wrapper cache (Integer cache)

  • Autoboxing and valueOf reuse pre-created objects for small values, so == may seem to work for them and then fail for bigger values.
  • Integer a = 100, b = 100; gives a == b true. Integer c = 200, d = 200; gives c == d false. Always compare values with equals or unbox first.
  • The Integer cache upper bound can be raised with -XX:AutoBoxCacheMax=<size>, but code must never depend on it.
WrapperCached valuesEffect of == for cached values
ByteAll values (-128 to 127)Always the same object
Short-128 to 127Same object only inside the range
Integer-128 to 127 (upper bound configurable)Same object only inside the range
Long-128 to 127Same object only inside the range
Character0 to 127 (ASCII)Same object only for ASCII
BooleanTRUE and FALSEAlways the same two objects
Float / DoubleNo cacheEvery boxing creates a new object
public class CacheDemo {
    public static void main(String[] args) {
        Integer a = 127, b = 127;
        Integer c = 128, d = 128;
        System.out.println(a == b);        // true  (cached object)
        System.out.println(c == d);        // false (two objects)
        System.out.println(c.equals(d));   // true  (value comparison)
        System.out.println(c.intValue() == d.intValue()); // true
    }
}

Differences between primitive types and wrapper classes

PointPrimitive (int)Wrapper (Integer)
What it isRaw valueObject holding a value
Stored inStack (locals) or inside the owning objectHeap object; variable holds a reference
Memory4 bytes for intAbout 16 bytes object plus a 4 to 8 byte reference
Can be null?NoYes
Default as a field0null
Use in generics / collectionsNot allowedRequired (List<Integer>)
MethodsNoneintValue(), compareTo(), equals(), statics like parseInt
Comparing with ==Compares valuesCompares references (use equals)
SpeedFastestSlower: allocation, indirection, GC
Typical useLoops, math, countersCollections, nullable fields, APIs needing objects
L2

Advanced — Wrapper Classes

Null unboxing and NullPointerException

  • Unboxing calls intValue() behind the scenes, so unboxing null throws NullPointerException.
  • Common sources: Map.get for a missing key, a nullable database column, or a JSON field that was absent.
  • Fix: check for null, use getOrDefault, Objects.requireNonNullElse, or keep the value as a wrapper until you know it is present.
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class NullUnboxing {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("pen", 10);

        // int n = stock.get("book");                 // NullPointerException
        int n1 = stock.getOrDefault("book", 0);       // 0
        Integer maybe = stock.get("book");
        int n2 = Objects.requireNonNullElse(maybe, 0); // 0 (Java 9+)
        System.out.println(n1 + n2);
    }
}

The ternary operator unboxing trap

  • If one branch of ?: is a wrapper and the other is a primitive, the whole expression becomes the primitive type.
  • So the wrapper branch is unboxed, and if it is null you get a NullPointerException even though you assign to a wrapper.
  • Fix: make both branches wrappers (Integer.valueOf(0)) or use an if statement.
public class TernaryTrap {
    public static void main(String[] args) {
        Integer cached = null;
        boolean useCache = true;

        // Integer bad = useCache ? cached : 0;   // NPE: type is int, cached is unboxed
        Integer ok = useCache ? cached : Integer.valueOf(0); // null, no exception
        System.out.println(ok);
    }
}

Overloading with boxing: widening beats boxing beats varargs

  • When choosing an overload, the compiler tries three phases in order: exact match or widening, then boxing / unboxing, then varargs.
  • So m(5) prefers m(long) (widening) over m(Integer) (boxing), and m(Integer) over m(int...).
  • Widening then boxing is not allowed: an int cannot become a Long.
public class OverloadBoxing {
    static void m(long x)    { System.out.println("long"); }
    static void m(Integer x) { System.out.println("Integer"); }
    static void m(int... x)  { System.out.println("varargs"); }

    static void n(Long x)    { System.out.println("Long"); }

    public static void main(String[] args) {
        m(5);          // long     (widening wins)
        // n(5);       // error: int cannot be converted to Long
        n(5L);         // Long
    }
}

List.remove(int) vs remove(Object)

  • List<Integer> has two remove methods. remove(1) matches remove(int index) with no boxing, so it removes by position.
  • To remove the value 1, pass an object: list.remove(Integer.valueOf(1)).
  • This is one of the most common wrapper bugs in interviews and real code.
import java.util.ArrayList;
import java.util.List;

public class RemoveTrap {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(10, 1, 20, 1));
        nums.remove(1);                    // removes index 1 (the value 1 at position 1)
        System.out.println(nums);          // [10, 20, 1]
        nums.remove(Integer.valueOf(10));  // removes the value 10
        System.out.println(nums);          // [20, 1]
    }
}

equals across wrapper types

  • equals returns true only when both objects are the same wrapper type with the same value.
  • Integer.valueOf(1).equals(1L) is false, because 1L boxes to Long.
  • This breaks map lookups: a Map<Long, String> queried with an int key boxes to Integer and finds nothing.
import java.util.HashMap;
import java.util.Map;

public class EqualsTypes {
    public static void main(String[] args) {
        Long id = 127L;
        System.out.println(id.equals(127));    // false: 127 boxes to Integer
        System.out.println(id.equals(127L));   // true
        System.out.println(id == 127);         // true: unboxes id, compares values

        Map<Long, String> users = new HashMap<>();
        users.put(1L, "Asha");
        System.out.println(users.get(1));      // null (Integer key)
        System.out.println(users.get(1L));     // Asha
    }
}

Wrappers are immutable

  • count++ on an Integer does not change the object. It creates (or fetches from the cache) a new Integer and rebinds the variable.
  • Passing an Integer to a method and changing it there never affects the caller.
  • For a mutable counter use int, AtomicInteger, LongAdder, or map.merge(key, 1, Integer::sum).
import java.util.concurrent.atomic.AtomicInteger;

public class ImmutableWrapper {
    static void bump(Integer x) { x++; }                 // changes only the local copy
    static void bump(AtomicInteger x) { x.incrementAndGet(); }

    public static void main(String[] args) {
        Integer a = 5;
        bump(a);
        System.out.println(a);          // 5

        AtomicInteger b = new AtomicInteger(5);
        bump(b);
        System.out.println(b.get());    // 6
    }
}

Performance: avoid hidden boxing

  • Each boxing outside the cache allocates an object. In a hot loop that means millions of short-lived objects and extra garbage collection.
  • Classic mistake: Long sum = 0L; in a loop. Every sum += i unboxes, adds, and boxes a new Long.
  • Use primitive streams (IntStream, mapToInt, sum()) instead of Stream<Integer> when doing math.
  • For huge numeric collections, use arrays or primitive collection libraries instead of List<Integer>.
import java.util.List;

public class BoxingCost {
    public static void main(String[] args) {
        long t1 = System.nanoTime();
        Long slow = 0L;
        for (long i = 0; i < 10_000_000; i++) slow += i;   // boxes every iteration
        long t2 = System.nanoTime();
        long fast = 0L;
        for (long i = 0; i < 10_000_000; i++) fast += i;   // pure primitive
        long t3 = System.nanoTime();
        System.out.println("Long: " + (t2 - t1) / 1_000_000 + " ms, long: " + (t3 - t2) / 1_000_000 + " ms");

        List<Integer> marks = List.of(70, 85, 90);
        int total = marks.stream().mapToInt(Integer::intValue).sum(); // no boxing in sum
        System.out.println(total);                                    // 245
    }
}

Parsing pitfalls and NumberFormatException

  • parseInt throws NumberFormatException for empty strings, spaces, decimals ("3.5"), or values out of range. Call trim() on user input first.
  • A leading + or - is allowed: parseInt("+7") is 7.
  • parseInt(null) also throws NumberFormatException, while Double.parseDouble(null) throws NullPointerException.
  • Java 8 added unsigned helpers: Integer.parseUnsignedInt, Integer.toUnsignedString, Integer.divideUnsigned.
public class SafeParse {
    static int parseOr(String s, int fallback) {
        if (s == null) return fallback;
        try {
            return Integer.parseInt(s.trim());
        } catch (NumberFormatException e) {
            return fallback;
        }
    }

    public static void main(String[] args) {
        System.out.println(parseOr(" 42 ", -1));   // 42
        System.out.println(parseOr("4.2", -1));    // -1
        System.out.println(parseOr("abc", -1));    // -1
        System.out.println(parseOr(null, -1));     // -1
    }
}
L3

Tricky Interview Points

Q1) What is a wrapper class?

Answer A final, immutable class in java.lang that wraps one primitive value inside an object, such as Integer for int and Character for char.

Q2) Why do we need wrapper classes?

Answer Collections and generics need objects, wrappers can represent null (no value), they provide utility methods and constants, and many APIs accept only Object.

Q3) List all primitive types and their wrapper classes.

Answer byte-Byte, short-Short, int-Integer, long-Long, float-Float, double-Double, char-Character, boolean-Boolean.

Q4) What are autoboxing and unboxing?

Answer Autoboxing is the automatic conversion of a primitive to its wrapper (via valueOf). Unboxing is the reverse (via xxxValue). Both were added in Java 5 and are done by the compiler.

Q5) parseInt vs valueOf?

Answer Integer.parseInt(String) returns a primitive int. Integer.valueOf(String or int) returns an Integer object and uses the -128 to 127 cache.

Q6) Why is Integer 127 == Integer 127 true but 128 == 128 false?

Answer Autoboxing uses Integer.valueOf, which caches -128 to 127. == compares references: the cached values share one object, while 128 creates two separate objects.

Q7) Which wrapper classes have a cache?

Answer Byte (all values), Short, Integer, and Long (-128 to 127), Character (0 to 127), and Boolean (TRUE / FALSE). Float and Double have no cache.

Q8) What happens when you unbox null?

Answer A NullPointerException, because unboxing calls intValue() on a null reference.

Q9) Are wrapper classes mutable?

Answer No. They are immutable and final. Operations like count++ create a new object and rebind the variable.

Q10) What is the parent class of numeric wrappers?

Answer The abstract class java.lang.Number. Character and Boolean extend Object directly.

Q11) Why are wrapper constructors deprecated?

Answer new Integer(5) always allocates and skips the cache. They were deprecated in Java 9 and marked for removal in Java 16; use valueOf or autoboxing instead.

Q12) What does list.remove(1) do on a List<Integer>?

Answer It removes the element at index 1, because remove(int) matches without boxing. Use list.remove(Integer.valueOf(1)) to remove the value 1.

Q13) Given m(long) and m(Integer), which does m(5) call?

Answer m(long). Overload resolution tries widening before boxing, and boxing before varargs.

Q14) Does Long.valueOf(1).equals(1) return true?

Answer No. The argument 1 boxes to Integer, and equals requires the same wrapper type. Use 1L or compare primitive values.

Q15) What is the difference between Boolean.parseBoolean and Boolean.getBoolean?

Answer parseBoolean converts a string ("true" in any case gives true). getBoolean reads a system property with that name and returns true only if the property is set to "true".

Q16) Is autoboxing free?

Answer No. Outside the cache it allocates objects, adds GC pressure, and can hide NullPointerExceptions. Prefer primitives and primitive streams in hot loops.

Q17) int vs Integer: which should a JPA entity id or optional form field use?

Answer Integer (or Long), because it can be null before the record is saved or when the user leaves the field empty. A primitive would silently default to 0.

L4

Simple Programs

All wrapper classes: MIN, MAX, and SIZE

public class WrapperRanges {
    public static void main(String[] args) {
        System.out.println("Byte    : " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE + ", " + Byte.SIZE + " bits");
        System.out.println("Short   : " + Short.MIN_VALUE + " to " + Short.MAX_VALUE + ", " + Short.SIZE + " bits");
        System.out.println("Integer : " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + ", " + Integer.SIZE + " bits");
        System.out.println("Long    : " + Long.MIN_VALUE + " to " + Long.MAX_VALUE + ", " + Long.SIZE + " bits");
        System.out.println("Float   : " + Float.MIN_VALUE + " to " + Float.MAX_VALUE + ", " + Float.SIZE + " bits");
        System.out.println("Double  : " + Double.MIN_VALUE + " to " + Double.MAX_VALUE + ", " + Double.SIZE + " bits");
        System.out.println("Character: " + (int) Character.MIN_VALUE + " to " + (int) Character.MAX_VALUE + ", " + Character.SIZE + " bits");
    }
}

Boxing and unboxing every primitive

public class BoxAll {
    public static void main(String[] args) {
        Byte b = 10;            byte b2 = b;
        Short s = 200;          short s2 = s;
        Integer i = 3000;       int i2 = i;
        Long l = 40000L;        long l2 = l;
        Float f = 5.5f;         float f2 = f;
        Double d = 6.75;        double d2 = d;
        Character c = 'J';      char c2 = c;
        Boolean ok = true;      boolean ok2 = ok;

        System.out.println(b2 + " " + s2 + " " + i2 + " " + l2);
        System.out.println(f2 + " " + d2 + " " + c2 + " " + ok2);
    }
}

Number converter: decimal to binary, octal, and hex

import java.util.Scanner;

public class NumberConverter {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int n = sc.nextInt();
        System.out.println("Binary : " + Integer.toBinaryString(n));
        System.out.println("Octal  : " + Integer.toOctalString(n));
        System.out.println("Hex    : " + Integer.toHexString(n).toUpperCase());
        System.out.println("Back   : " + Integer.parseInt(Integer.toBinaryString(n), 2));
    }
}

Character analysis of a string

public class CharStats {
    public static void main(String[] args) {
        String text = "Java 21 Rocks! Learn @ LCG";
        int upper = 0, lower = 0, digits = 0, spaces = 0, others = 0;

        for (char ch : text.toCharArray()) {
            if (Character.isUpperCase(ch)) upper++;
            else if (Character.isLowerCase(ch)) lower++;
            else if (Character.isDigit(ch)) digits++;
            else if (Character.isWhitespace(ch)) spaces++;
            else others++;
        }
        System.out.println("Upper=" + upper + " Lower=" + lower + " Digits=" + digits
                + " Spaces=" + spaces + " Others=" + others);
    }
}

Sum numbers from text input safely

public class SumFromText {
    public static void main(String[] args) {
        String csv = "10, 20, abc, 30, , 4.5, -5";
        int sum = 0;
        for (String part : csv.split(",")) {
            String t = part.trim();
            try {
                sum += Integer.parseInt(t);
            } catch (NumberFormatException e) {
                System.out.println("Skipping invalid value: \"" + t + "\"");
            }
        }
        System.out.println("Sum = " + sum);   // 55
    }
}

Sum a List<Integer> that contains null

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class NullSafeSum {
    public static void main(String[] args) {
        List<Integer> marks = Arrays.asList(80, null, 95, 70, null);

        // int bad = 0; for (int m : marks) bad += m;   // NullPointerException

        int total = 0;
        for (Integer m : marks) {
            if (m != null) total += m;
        }
        int streamTotal = marks.stream().filter(Objects::nonNull).mapToInt(Integer::intValue).sum();
        System.out.println(total + " " + streamTotal);   // 245 245
    }
}

Word frequency with Map<String, Integer>

import java.util.Map;
import java.util.TreeMap;

public class WordFreq {
    public static void main(String[] args) {
        String text = "java is fun and java is powerful";
        Map<String, Integer> freq = new TreeMap<>();
        for (String w : text.split("\\s+")) {
            freq.merge(w, 1, Integer::sum);   // boxing handled by merge
        }
        System.out.println(freq);  // {and=1, fun=1, is=2, java=2, powerful=1}
    }
}

Wrapper traps in one program

import java.util.ArrayList;
import java.util.List;

public class WrapperTraps {
    public static void main(String[] args) {
        Integer a = 1000, b = 1000;
        System.out.println(a == b);              // false: compares references
        System.out.println(a.equals(b));         // true

        List<Integer> list = new ArrayList<>(List.of(5, 3, 1));
        list.remove(1);                          // removes index 1 (value 3)
        System.out.println(list);                // [5, 1]

        Long big = 10L;
        System.out.println(big.equals(10));      // false: Integer vs Long

        System.out.println(Boolean.parseBoolean("TRUE")); // true
        System.out.println(Boolean.getBoolean("TRUE"));   // false: reads system property

        System.out.println(Double.MIN_VALUE > 0); // true: smallest positive value
    }
}
L5

Problem Solving Tricks

  • Never compare wrappers with ==. Use equals, Integer.compare, or unbox after a null check.
  • Remember the two odd names: int is Integer and char is Character.
  • Use parseXxx when you want a primitive and valueOf when you want an object.
  • Cache ranges to remember: -128 to 127 for Byte, Short, Integer, Long; 0 to 127 for Character; none for Float and Double.
  • Before unboxing a value from a Map, database, or JSON, ask "can this be null?" and use getOrDefault if so.
  • On List<Integer>, remove(1) removes an index; remove(Integer.valueOf(1)) removes a value.
  • Use mapToInt(Integer::intValue).sum() instead of reduce(0, Integer::sum) to avoid boxing.
  • Never write Long sum = 0L as a loop accumulator; use long.
  • Character has no parseChar; use s.charAt(0) after checking the length.
  • Double.MIN_VALUE is the smallest positive double. For the most negative use -Double.MAX_VALUE.
  • Boolean.getBoolean reads a system property. To convert text use Boolean.parseBoolean.
L6

Practice Programs List

  1. Print MIN_VALUE, MAX_VALUE, and SIZE for all eight wrapper classes.
  2. Box and unbox each primitive type once and print the results.
  3. Loop i from 120 to 135 and print whether Integer.valueOf(i) == Integer.valueOf(i); explain where it changes.
  4. Read a number as a String, convert it to int, and print it in binary, octal, and hexadecimal.
  5. Convert the binary string "110101" and the hex string "1F" to decimal.
  6. Parse "3.14" to double and handle NumberFormatException for "pi".
  7. Write int safeUnbox(Integer x, int fallback) and test it with null.
  8. Count uppercase, lowercase, digits, spaces, and special characters in a sentence using Character methods.
  9. Find the sum of digits in a String such as "a1b2c3" using Character.getNumericValue.
  10. Sum an ArrayList<Integer> that contains null values without throwing an exception.
  11. Show the List.remove(int) vs remove(Object) difference with a list of integers.
  12. Write overloaded methods m(long), m(Integer), and m(int...) and predict which one m(10) calls.
  13. Time a loop that sums into Long vs long for 10 million iterations and compare.
  14. Write a method double total(List<? extends Number> nums) and call it with lists of Integer and Double.