Java : Object with Examples

Object (Java SE 17 & JDK 17) API Examples.
You will find code examples on most Object methods.


Summary

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

Class diagram

final var str = "abcd";

System.out.println(str.equals("abcd")); // true
System.out.println(str.equals("XYZ")); // false

System.out.println(str.hashCode()); // 2987074
final int[] array = {1, 2, 3, 4};
System.out.println(array.toString()); // [I@34a1547b
System.out.println(Arrays.toString(array)); // [1, 2, 3, 4]
// Primitive Types are not Object.
final int num = 123;

// Compile error.
num.hashCode();
num.equals(123);

Constructors

Object ()

Constructs a new object.

final var obj = new Object();
System.out.println(obj); // java.lang.Object@84e9fc3
System.out.println(obj.hashCode()); // 139370435
System.out.println(obj.getClass()); // class java.lang.Object

Methods

protected Object clone ()

Creates and returns a copy of this object.

Please see also : Cloneable

record Sample(int num, String str) implements Cloneable {
    @Override
    public Sample clone() throws CloneNotSupportedException {
        return (Sample) super.clone();
    }
}

try {
    final var sample = new Sample(100, "abc");
    final var cloned = sample.clone();

    System.out.println("Cloned! : " + cloned);

} catch (CloneNotSupportedException e) {
    System.out.println("CloneNotSupportedException!");
}

// Result
// ↓
//Cloned! : Sample[num=100, str=abc]
final String[] array = {"aa", "bb", "cc"};
final String[] cloned = array.clone();

System.out.println(array != cloned); // true
System.out.println(Arrays.toString(array)); // [aa, bb, cc]
System.out.println(Arrays.toString(cloned)); // [aa, bb, cc]

// shallow copy
System.out.println(array[0] == cloned[0]); // true
System.out.println(array[1] == cloned[1]); // true
System.out.println(array[2] == cloned[2]); // true

boolean equals (Object obj)

Indicates whether some other object is "equal to" this one.

final var obj1 = new Object();
final var obj2 = new Object();

System.out.println(obj1.equals(obj2)); // false

System.out.println(obj1.hashCode()); // 361268035
System.out.println(obj2.hashCode()); // 871160466
final var s1 = new String("aaa");
final var s2 = new String("aaa");
final var s3 = new String("XXX");

System.out.println(s1 != s2); // true
System.out.println(s1 != s3); // true

System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false

System.out.println(s1.hashCode()); // 96321
System.out.println(s2.hashCode()); // 96321
System.out.println(s3.hashCode()); // 87384
final int[] array1 = {1, 2, 3, 4};
final int[] array2 = {1, 2, 3, 4};

System.out.println(array1 != array2); // true
System.out.println(array1.equals(array2)); // false
System.out.println(Arrays.equals(array1, array2)); // true

System.out.println(array1.hashCode()); // 2113748097
System.out.println(array2.hashCode()); // 629454893

System.out.println(Arrays.hashCode(array1)); // 955331
System.out.println(Arrays.hashCode(array2)); // 955331

protected void finalize ()

Deprecated. The finalization mechanism is inherently problematic.

Deprecated.

final Class<?> getClass ()

Returns the runtime class of this Object.

final var obj = new Object();
System.out.println(obj.getClass()); // class java.lang.Object

final var str = "abcd";
System.out.println(str.getClass()); // class java.lang.String

final int[] array = {1, 2, 3};
System.out.println(array.getClass()); // class [I

final var localTime = LocalTime.of(12, 30);
System.out.println(localTime.getClass()); // class java.time.LocalTime

int hashCode ()

Returns a hash code value for the object.

Please see equals(Object obj).

final void notify ()

Wakes up a single thread that is waiting on this object's monitor.

See also Object.wait API document for a spurious wakeup.

final long current = System.nanoTime();

final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var obj = new Object();
    final Callable<Void> task = () -> {
        try {
            System.out.println("task start : %f sec.".formatted(elapsedSec.getAsDouble()));
            synchronized (obj) {
                obj.wait();
            }
        } finally {
            System.out.println("task end : %f sec.".formatted(elapsedSec.getAsDouble()));
        }
        return null;
    };

    executorService.submit(task);

    Thread.sleep(2000);

    synchronized (obj) {
        obj.notify();
    }

    Thread.sleep(10);

} finally {
    executorService.shutdown();
    System.out.println("--- shutdown --- : %f sec.".formatted(elapsedSec.getAsDouble()));
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("termination %b : %f sec.".formatted(ret, elapsedSec.getAsDouble()));

// Result
// ↓
//task start : 0.002282 sec.
//task end : 2.009446 sec.
//--- shutdown --- : 2.025202 sec.
//termination true : 2.025536 sec.
final long current = System.nanoTime();

final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newFixedThreadPool(3);
try {
    final var obj = new Object();
    final Callable<Void> task = () -> {
        try {
            System.out.println("task start : %f sec.".formatted(elapsedSec.getAsDouble()));
            synchronized (obj) {
                obj.wait();
            }
        } finally {
            System.out.println("task end : %f sec.".formatted(elapsedSec.getAsDouble()));
        }
        return null;
    };

    for (int i = 0; i < 3; i++) {
        executorService.submit(task);
    }

    for (int i = 0; i < 3; i++) {
        Thread.sleep(2000);
        synchronized (obj) {
            obj.notify();
        }
    }

    Thread.sleep(10);

} finally {
    executorService.shutdown();
    System.out.println("--- shutdown --- : %f sec.".formatted(elapsedSec.getAsDouble()));
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("termination %b : %f sec.".formatted(ret, elapsedSec.getAsDouble()));

// Result
// ↓
//task start : 0.002332 sec.
//task start : 0.002360 sec.
//task start : 0.002291 sec.
//task end : 2.008064 sec.
//task end : 4.018629 sec.
//task end : 6.026974 sec.
//--- shutdown --- : 6.043236 sec.
//termination true : 6.043966 sec.

final void notifyAll ()

Wakes up all threads that are waiting on this object's monitor.

See also Object.wait API document for a spurious wakeup.

final long current = System.nanoTime();

final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newFixedThreadPool(3);
try {
    final var obj = new Object();
    final Callable<Void> task = () -> {
        try {
            System.out.println("task start : %f sec.".formatted(elapsedSec.getAsDouble()));
            synchronized (obj) {
                obj.wait();
            }
        } finally {
            System.out.println("task end : %f sec.".formatted(elapsedSec.getAsDouble()));
        }
        return null;
    };

    for (int i = 0; i < 3; i++) {
        executorService.submit(task);
    }

    Thread.sleep(2000);

    synchronized (obj) {
        obj.notifyAll();
    }

    Thread.sleep(10);

} finally {
    executorService.shutdown();
    System.out.println("--- shutdown --- : %f sec.".formatted(elapsedSec.getAsDouble()));
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("termination %b : %f sec.".formatted(ret, elapsedSec.getAsDouble()));

// Result
// ↓
//task start : 0.001954 sec.
//task start : 0.001982 sec.
//task start : 0.001954 sec.
//task end : 2.006767 sec.
//task end : 2.006766 sec.
//task end : 2.006766 sec.
//--- shutdown --- : 2.031935 sec.
//termination true : 2.032380 sec.

String toString ()

Returns a string representation of the object.

final var obj = new Object();
System.out.println(obj.toString()); // java.lang.Object@1012015a

final var str = "abcd";
System.out.println(str.toString()); // abcd

final var localTime = LocalTime.of(12, 30);
System.out.println(localTime.toString()); // 12:30

final var path = Path.of("R:", "java-work", "sample.txt");
System.out.println(path.toString()); // R:\java-work\sample.txt

final int[] array = {1, 2, 3, 4};
System.out.println(array.toString()); // [I@34a1547b
System.out.println(Arrays.toString(array)); // [1, 2, 3, 4]

final void wait ()

Causes the current thread to wait until it is awakened, typically by being notified or interrupted.

See also Object.wait API document for a spurious wakeup.

final long current = System.nanoTime();

final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var obj = new Object();
    final Callable<Void> task = () -> {
        try {
            System.out.println("task start : %f sec.".formatted(elapsedSec.getAsDouble()));
            synchronized (obj) {
                obj.wait();
            }
        } finally {
            System.out.println("task end : %f sec.".formatted(elapsedSec.getAsDouble()));
        }
        return null;
    };

    executorService.submit(task);

    Thread.sleep(2000);

    synchronized (obj) {
        obj.notify();
    }

    Thread.sleep(10);

} finally {
    executorService.shutdown();
    System.out.println("--- shutdown --- : %f sec.".formatted(elapsedSec.getAsDouble()));
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("termination %b : %f sec.".formatted(ret, elapsedSec.getAsDouble()));

// Result
// ↓
//task start : 0.002232 sec.
//task end : 2.006018 sec.
//--- shutdown --- : 2.021639 sec.
//termination true : 2.022081 sec.
final long current = System.nanoTime();

final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var obj = new Object();
    final Callable<Void> task = () -> {
        try {
            System.out.println("task start : %f sec.".formatted(elapsedSec.getAsDouble()));
            synchronized (obj) {
                obj.wait();
            }
        } catch (InterruptedException e) {
            System.out.println("InterruptedException! : %f sec.".formatted(elapsedSec.getAsDouble()));
        } finally {
            System.out.println("task end : %f sec.".formatted(elapsedSec.getAsDouble()));
        }
        return null;
    };

    final var future = executorService.submit(task);

    Thread.sleep(2000);

    future.cancel(true);

    Thread.sleep(10);

} finally {
    executorService.shutdown();
    System.out.println("--- shutdown --- : %f sec.".formatted(elapsedSec.getAsDouble()));
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("termination %b : %f sec.".formatted(ret, elapsedSec.getAsDouble()));

// Result
// ↓
//task start : 0.002510 sec.
//InterruptedException! : 2.012552 sec.
//task end : 2.012789 sec.
//--- shutdown --- : 2.027705 sec.
//termination true : 2.028265 sec.

final void wait (long timeoutMillis)

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

Please see wait(timeoutMillis, 0).

final void wait (long timeoutMillis, int nanos)

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

See also Object.wait API document for a spurious wakeup.

Please see also : wait()

final long current = System.nanoTime();

final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var obj = new Object();
    final Callable<Void> task = () -> {
        try {
            System.out.println("task start : %f sec.".formatted(elapsedSec.getAsDouble()));
            synchronized (obj) {
                obj.wait(2000, 100);
            }
        } catch (InterruptedException e) {
            System.out.println("InterruptedException! : %f sec.".formatted(elapsedSec.getAsDouble()));
        } finally {
            System.out.println("task end : %f sec.".formatted(elapsedSec.getAsDouble()));
        }
        return null;
    };

    executorService.submit(task);

    Thread.sleep(5000);

    synchronized (obj) {
        obj.notify();
    }

    Thread.sleep(10);

} finally {
    executorService.shutdown();
    System.out.println("--- shutdown --- : %f sec.".formatted(elapsedSec.getAsDouble()));
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("termination %b : %f sec.".formatted(ret, elapsedSec.getAsDouble()));

// Result
// ↓
//task start : 0.002279 sec.
//task end : 2.004025 sec.
//--- shutdown --- : 5.029167 sec.
//termination true : 5.029502 sec.

Related posts

To top of page