0% found this document useful (0 votes)
2 views20 pages

Java Merged

The finalize() method in Java was used for cleanup before an object is destroyed, but it has been deprecated in favor of try-with-resources for automatic resource management. Custom exceptions can be defined by extending Exception or RuntimeException, and the java.lang package contains fundamental classes like Object and String that are automatically imported. The Object class provides essential methods such as hashCode(), getClass(), toString(), and clone(), which are crucial for object manipulation and memory management in Java.

Uploaded by

elementzerozero1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

Java Merged

The finalize() method in Java was used for cleanup before an object is destroyed, but it has been deprecated in favor of try-with-resources for automatic resource management. Custom exceptions can be defined by extending Exception or RuntimeException, and the java.lang package contains fundamental classes like Object and String that are automatically imported. The Object class provides essential methods such as hashCode(), getClass(), toString(), and clone(), which are crucial for object manipulation and memory management in Java.

Uploaded by

elementzerozero1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

finalize():

The finalize() method in Java is (or rather was) a special method in the object class that the
Garbage Collector (GC) could call before an object is destroyed, giving it a last chance to
clean up resources.
In Java 9 and above , we use try-with-resources instead of finalize() for automatic
cleanup

example:
what happens :

a = null;
→ The object becomes eligible for garbage collection.
[Link]();
→ You request (not force) the JVM to start garbage collection.
→ The JVM decides when to actually run the GC thread.
[Link]("Main method completed");
→ This runs immediately in the main thread (normal program flow).
Meanwhile, the Garbage Collector runs in a background thread (separate from the main
thread).
When it finally runs, it may call your object’s finalize() method.

That’s why the finalize message usually appears after the main method finishes( i.e. the main
method message).

takeaway:
[Link]() only requests garbage collection — it doesn’t guarantee when it’ll happen.
That’s why you can’t rely on finalize() for timely cleanup — hence it was deprecated.

Garbage Collection (GC) runs:

Only when the JVM decides memory is low


At unpredictable times
Possibly never, if the program ends before GC runs

So if you rely on finalize() to release resources, they may stay locked or open for a long
time.

we use try-with-resources now a days ad more on that later.

Custom exception:
A custom exception is one that you define yourself, by creating a new class that extends
either:

Exception → for checked exceptions, or


RuntimeException → for unchecked exceptions.

This allows you to represent application-specific error conditions more clearly.

and while defining it

you add a constructor and write super keyword inside it.


( more on this later... )
[Link] package :

In earlier classes we did the program where we read a [Link] using classes like
BufferedReader , FileReader etc. there we had a import class like

We are telling the compiler:

“Hey, I’ll be using these classes in my code — they are defined inside the [Link]
package.”

so that you can create their objects or reference them directly by class name

(Example from Test_38_octo29.java)

Now, In our code we also use classes which we don't import manually
for example:

public static void main(String[] args) {


[Link]("Test")
}

here for String and System classes we don't have to import it manually because they are
part of a default imported package or automatically imported package class called [Link] .

and [Link] contains the most fundamental classes of Java — ones you use in almost
every program: - Object , String , System etc.

Object{}:
Object class is the root (superclass) of all classes in Java.
Every class you create directly or indirectly inherits from [Link] (yes, its part of
[Link] package)

class A {} // Automatically extends Object


class B extends A {} // So B also indirectly extends Object

Methods present in Object Class:

hashCode()
getClass()
toString()
clone()
equals()
wait()
wait(long timeout)
wait(long timeout, int nanos)
notify()
notifyAll()
finalize()

hashCode() :

It’s a method of [Link] (Object class).


The hashCode() method gives each object a unique integer ID (randomly generated by
JVM) and returns the integer hash code value.
uses of this method can be studied later on Java Collections Framework.
getClass():

the getClass() method is used to get the runtime class (i.e., the actual class object) of
an object.
It returns an object of the Class type — from the [Link] package.

Observation:

1. You run the compiler


javac Test_43_nov08.java
javac reads the source file Test_43_nov08.java .
2. .class files are produced
The compiler generates bytecode files:
Test_43_nov08.class
A_nov08.class
3. Then we run java Test_43_nov08.java
4. JVM checks if Test_43_nov08.class is present in the memory, if not The JVM's class
loader loads java_nov08.Test_43_nov08
5. Execution starts from main method
6. when A_nov08 a = new A_nov08(); this is what's happening internally:
ClassLoader loads A_nov08.class
and creates a Class object in the JVM (an instance of [Link] , yes there is
a class name Class ) that represents the metadata(contains information like class
name java_nov08.A_nov08 , method info, constructor info etc.) of A_nov08 .
7. then at Class c = [Link]();
getClass() returns runtime class of a ( Class object for A_nov08 , which got
created earlier)
since it returns that same Class object, we store it inside c which is from Class
type.
8. Finally [Link]() returns the fully qualified class name
( getName() belongs to the [Link] class.)

toString():
toString() in Java returns a unique string representation of an object. It’s defined in Object
class.
Observation:

When you print an object ( using [Link](c) ),


the toString() method is automatically called behind the scenes.
As you can see in the program above they both have the same value.

The output is java_nov08.C_nov08@4dd8dc3


and this is how it gets generated:

we already getClass() and getName( ) methods


as for [Link](hashCode()) it converts the object’s hash code (an int) into
a hexadecimal string ( hashCode() method studied in Java_05_11_25).
for the next example we override toString() in B_nov08 which indirectly extends to Object
class( like any other class):

Obviously the child class B_nov08 prioritizes its own method (overridden toString() ) and
hence the output.

when a program run this is what happens :

Step Class Loaded When Why


1 [Link] , System , Class , etc. Automatically Core runtime classes
2 java_nov08.Test_44_nov08 At program start Entry point ( main )
clone():
In Java, the clone() method is used to create and return a copy (clone) of an object. It
belongs to the Object class.

output:
Observation:

For the clone() method to successfully run in Java, a few specific things must be in place.

1. The class must implement the Cloneable interface


class A_nov09 implements Cloneable { ... }

Cloneable is a marker interface (no methods).


It tells the JVM: "Yes, this class allows cloning."
If you forget this, calling clone() will throw: [Link]

2. The clone() method must be overridden and made


accessible

@Override
public Object clone() throws CloneNotSupportedException {
return [Link]();
}

In Object class, clone() is protected, so you can’t call it directly from outside your
class.
You must override it (usually make it public ) to allow [Link]() to be called.
Inside it, you call [Link]() which goes to the super class of A_nov09 which is
object class and class the clone() where its located.

3. The method must handle (or declare)


CloneNotSupportedException

So you must
declare it: public static void main(String[] args) throws
CloneNotSupportedException public Object clone() throws
CloneNotSupportedException

4. Since [Link]() returns Object type which is a parent class


we type cast(cast = change) it back to A_nov09 class. Here’s the
breakdown in easier words:

@Override
public Object clone() throws CloneNotSupportedException {
return [Link]();
}

In the above snippet of code [Link]() creates a new object in memory that is
actually an instance of A_nov09 .
The method signature says it returns Object (capital O), so the returned reference is of
type Object (parent class).
We then type cast that Object reference back to A_nov09 :
A_nov09 a2 = (A_nov09) [Link](); // line 8

Type cast: tells the compiler “treat this Object as A_nov09 so I can access its fields and
methods.”

CloneNotSupportedException is a checked exception in Java since it extends Exception


(not RuntimeException ). It is thrown when an object’s clone() method is called, but the
class does not implement the Cloneable interface**.

Two other method that we used in the program:

we override the toString() method in the code so that you can get a meaningful,
human-readable output like id, name and age when you print the object.
we also use hashCode() to prove that both objects have the same field values but are
different objects in memory (since their hash codes differ).
Final:
Final is a keyword

when applied to a keyword you cant reassign a new value or the value cant be changed
when applied to a method, it cant be overridden
when applied to a class, it cant be inherited
Finally:
Finally is block

a finally block is a special block of code that always executes after a try / catch
block — whether or not an exception occurs.
It is usually used to perform cleanup tasks — things that must happen no matter what.
finalize():
finalize() method is a method of the Object class.
( more on this later.)

close():
The close() method in Java is used to release resources (like files, database connection
etc.)

(error in code)

(no error when [Link]() is with in finally block)

You might also like