LearnFrenzy
Sign in Take a free test

Java Programming · Topic 16 of 28

Object Class and Wrapper Classes

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Object Class and Wrapper Classes · Study material

Every Java class – yours, the JDK's, arrays too – ultimately extends java.lang.Object, so every object has toString(), equals(), hashCode(), getClass() and clone(). Overriding the first three correctly decides whether your objects print readably, compare by content and work as keys in a HashMap or members of a HashSet. Alongside Object, java.lang provides the wrapper classes – Integer, Double, Character, Boolean and friends – which turn primitives into objects for collections and generics, and offer parsing, conversion and constants. Java converts between them automatically (autoboxing and unboxing), which is convenient but hides traps: == on two Integers, the Integer cache, null unboxing and Long vs Integer equality are classic interview puzzles. This page covers all of it, plus the Objects helper class and BigDecimal for money. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.

On this page

  • The methods of java.lang.Object
  • The equals and hashCode contracts
  • clone(): shallow and deep copies
  • Wrapper classes, autoboxing and unboxing
  • The Integer cache, == and null pitfalls
  • Parsing, conversion, Character, Objects and BigDecimal

The methods of Object

MethodDefault behaviourOverride?
toString()ClassName@hexHashalmost always
equals(Object)identity (==)for value-like classes
hashCode()identity-based numberwhenever equals is overridden
getClass()the run-time classno – it is final
clone()protected; shallow copy if the class is Cloneablerarely – prefer copy constructors
wait(), notify(), notifyAll()thread coordinationfinal – see Multithreading
finalize()deprecated for removalnever
import java.util.Objects;

class Employee {
    private final int id;
    private final String name;

    Employee(int id, String name) { this.id = id; this.name = name; }

    @Override
    public String toString() { return "Employee[" + id + ", " + name + "]"; }

    @Override
    public boolean equals(Object o) {                   // 1. same object?  2. same type?  3. same fields?
        if (this == o) return true;
        if (!(o instanceof Employee e)) return false;
        return id == e.id && Objects.equals(name, e.name);
    }

    @Override
    public int hashCode() { return Objects.hash(id, name); }   // equal objects MUST have equal hash codes
}

class Plain { }                                         // inherits Object's versions unchanged

public class Main {
    public static void main(String[] args) {
        Employee a = new Employee(7, "Asha"), b = new Employee(7, "Asha");
        System.out.println(a);                                         // toString() is called automatically
        System.out.println((a == b) + " " + a.equals(b) + " " + (a.hashCode() == b.hashCode()));
        System.out.println(a.getClass().getName() + " " + a.getClass().getSuperclass().getName());

        Plain p = new Plain(), q = new Plain();
        System.out.println(p.toString().startsWith("Plain@") + " " + p.equals(q) + " " + p.equals(p));
    }
}

Output

Employee[7, Asha]
false true true
Employee java.lang.Object
true false true

The equals and hashCode contracts

  • equals must be reflexive (a.equals(a)), symmetric, transitive, consistent, and a.equals(null) must be false.
  • hashCode: equal objects must return equal hash codes; unequal objects may share one (a collision).
  • Hash-based collections first find a bucket by hashCode, then compare with equals – so overriding equals without hashCode breaks HashSet and HashMap.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

class BadKey {                                  // equals WITHOUT hashCode – breaks hash collections
    final String code;
    BadKey(String c) { code = c; }
    @Override public boolean equals(Object o) { return o instanceof BadKey k && k.code.equals(code); }
}

class GoodKey {
    final String code;
    GoodKey(String c) { code = c; }
    @Override public boolean equals(Object o) { return o instanceof GoodKey k && k.code.equals(code); }
    @Override public int hashCode() { return code.hashCode(); }
}

public class Main {
    public static void main(String[] args) {
        Set<BadKey> bad = new HashSet<>();
        bad.add(new BadKey("IN")); bad.add(new BadKey("IN"));
        Set<GoodKey> good = new HashSet<>();
        good.add(new GoodKey("IN")); good.add(new GoodKey("IN"));

        Map<GoodKey, String> capitals = new HashMap<>();
        capitals.put(new GoodKey("IN"), "New Delhi");

        System.out.println(bad.size() + " " + good.size() + " " + capitals.get(new GoodKey("IN")));
        // Equal hash codes do NOT mean equal objects ("collisions" are allowed):
        System.out.println("Aa".hashCode() + " " + "BB".hashCode() + " " + "Aa".equals("BB"));
    }
}

Output

2 1 New Delhi
2112 2112 false

clone(): shallow and deep copies

Object.clone() copies every field as-is (a shallow copy), and works only if the class implements the marker interface Cloneable; otherwise it throws CloneNotSupportedException. Mutable fields such as lists end up shared, so you must copy them yourself for a deep copy. Many developers prefer copy constructors or factory methods instead.

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

class Team implements Cloneable {                    // Cloneable is a marker interface
    String name;
    List<String> members = new ArrayList<>();

    Team(String name) { this.name = name; }

    @Override
    public Team clone() {                            // covariant return, public access
        try {
            return (Team) super.clone();             // Object.clone(): a SHALLOW field-by-field copy
        } catch (CloneNotSupportedException e) {
            throw new AssertionError(e);
        }
    }

    Team deepCopy() {
        Team t = clone();
        t.members = new ArrayList<>(members);        // copy the mutable field as well
        return t;
    }
}

public class Main {
    public static void main(String[] args) {
        Team original = new Team("Alpha");
        original.members.add("Asha");

        Team shallow = original.clone();
        Team deep = original.deepCopy();
        shallow.name = "Beta";                       // String field: reassigned, independent
        shallow.members.add("Ravi");                 // list: SHARED with the original
        deep.members.add("Meena");

        System.out.println(original.name + " " + original.members);
        System.out.println(shallow.name + " " + shallow.members + " shared=" + (shallow.members == original.members));
        System.out.println(deep.name + " " + deep.members);
    }
}

Output

Alpha [Asha, Ravi]
Beta [Asha, Ravi] shared=true
Alpha [Asha, Meena]

Wrapper classes and autoboxing

Collections and generics work only with objects, so Java wraps primitives. Since Java 5 the compiler inserts the conversions: Integer x = 5 becomes Integer.valueOf(5) (boxing) and int y = x becomes x.intValue() (unboxing). All wrappers are immutable and final.

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

public class Main {
    public static void main(String[] args) {
        // Each primitive has a wrapper class: byte→Byte short→Short int→Integer long→Long
        // float→Float double→Double char→Character boolean→Boolean
        List<Integer> marks = new ArrayList<>();    // generics need objects, not primitives
        marks.add(78);                              // autoboxing: int → Integer.valueOf(78)
        marks.add(91);
        int total = 0;
        for (int m : marks) total += m;             // unboxing: Integer → intValue()

        Integer boxed = 42;
        double d = boxed;                           // unboxing + widening
        Character grade = 'A';
        Boolean passed = total > 150;

        System.out.println(total + " " + d + " " + grade + " " + passed);
        System.out.println(Integer.MAX_VALUE + " " + Integer.MIN_VALUE + " " + Long.MAX_VALUE + " " + Byte.MIN_VALUE + " " + (int) Character.MAX_VALUE);
        System.out.println(Integer.SIZE + " bits, " + Double.BYTES + " bytes, " + Integer.MAX_VALUE + 1 + " vs " + (Integer.MAX_VALUE + 1));
    }
}

Output

169 42.0 A true
2147483647 -2147483648 9223372036854775807 -128 65535
32 bits, 8 bytes, 21474836471 vs -2147483648

The Integer cache and other pitfalls

Integer.valueOf (and therefore autoboxing) returns cached objects for −128 to 127, so == happens to work for small values and fails for larger ones. Always compare wrappers with equals() (or unbox first). Unboxing null throws NullPointerException, and Long.equals(Integer) is false even for the same number.

public class Main {
    public static void main(String[] args) {
        Integer a = 127, b = 127;                     // Integer.valueOf caches -128 … 127
        Integer c = 128, d = 128;                     // outside the cache: different objects
        System.out.println((a == b) + " " + (c == d) + " " + c.equals(d) + " " + (c.intValue() == d));

        Long big = 10L;
        System.out.println(big.equals(10) + " " + big.equals(10L) + " " + (big == 10));   // 10 boxes to Integer

        Integer nothing = null;
        try {
            int x = nothing;                          // unboxing null → NullPointerException
            System.out.println(x);
        } catch (NullPointerException e) {
            System.out.println("NPE while unboxing null");
        }
    }
}

Output

true false true true
false true true
NPE while unboxing null

Parsing and converting

parseXxx returns a primitive, valueOf returns a wrapper, and both throw NumberFormatException for bad input. Integer and Long also convert to and from binary, octal and hex.

public class Main {
    public static void main(String[] args) {
        int i = Integer.parseInt("1024");             // String → primitive
        Integer j = Integer.valueOf("2048");          // String → wrapper (may use the cache)
        double price = Double.parseDouble("499.99");
        boolean flag = Boolean.parseBoolean("TRUE");  // case-insensitive; anything else is false
        long big = Long.parseLong("-9000000000");

        System.out.println(i + j + " " + price + " " + flag + " " + Boolean.parseBoolean("yes") + " " + big);
        System.out.println(Integer.toBinaryString(10) + " " + Integer.toHexString(255) + " " + Integer.toOctalString(8) + " " + Integer.parseInt("ff", 16) + " " + Integer.parseInt("-101", 2));
        System.out.println(String.valueOf(3.5) + "|" + Integer.toString(42) + "|" + Double.toString(1e-4) + "|" + Integer.bitCount(255));

        try {
            Integer.parseInt("12a");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

3072 499.99 true false -9000000000
1010 ff 10 255 -5
3.5|42|1.0E-4|8
For input string: "12a"

Common mistakes

  • Comparing Integer, Long or Double objects with ==.
  • Unboxing a null wrapper – from a map lookup or a nullable field.
  • Overriding equals but not hashCode, or using mutable fields in hashCode.
  • Writing equals(MyClass) instead of equals(Object).
  • Shallow clones that share mutable state.
  • Using double for money – use BigDecimal or a long count of paise.
  • new BigDecimal(0.1) instead of new BigDecimal("0.1").

Key points to remember

  • Object is the root of every class; override toString, equals and hashCode together.
  • Equal objects must have equal hash codes.
  • Object.clone() is shallow; deep copies need extra work.
  • Wrappers are immutable; boxing uses valueOf, unboxing uses xxxValue().
  • Integer cache: −128 to 127 – compare wrappers with equals.
  • parseInt → int, valueOf → Integer; both throw NumberFormatException.

Frequently asked questions

Why does Java have both int and Integer?

Primitives are fast and compact; wrappers are objects that can be null, stored in collections and used with generics.

Is autoboxing slow?

It creates objects outside the cache range, so in tight loops prefer primitives (and primitive streams such as IntStream).

Can I change the Integer cache size?

The upper bound can be raised with the JVM option -XX:AutoBoxCacheMax, but code should never rely on it.

Where can I learn more?

Read The Java Object Class and Java Wrapper Classes, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links