Core Java FAQ
Check the arraylist whether its contains values without using ".size()" and "!=null"?
Using isEmpty(); we can check the arraylist contains values are not
—————
What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control
the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors
—————
What is serialization? Explain with example?
Serialization involves saving the current state of an object to a stream, and restoring an equivalent object from that stream.
For an object to be serialized, it must be an instance of a class that implements either the Serializable or Externalizable interface. Both interfaces only permit the saving of data associated with an object's variables.
They depend on the class definition being available to the Java Virtual Machine at reconstruction time in order to construct the object.
The Serializable interface relies on the Java runtime default mechanism to save an object's state.
Writing an object is done via the writeObject() method in the ObjectOutputStream class (or the ObjectOutput interface).
Writing a primitive value may be done through the appropriate write<datatype>() method.
Reading the serialized object is accomplished using the readObject() method of the ObjectInputStream class, and primitives may be read using the various read<datatype>() methods.
The Externalizable interface specifies that the implementing class will handle the serialization on its own, instead of relying on the default runtime mechanism.
This includes which fields get written (and read), and in what order.
The class must define a writeExternal() method to write out the stream, and a corresponding readExternal() method to read the stream.
Inside of these methods the class calls ObjectOutputStream writeObject(), ObjectInputStream readObject(), and any necessary write<datatype>() and read<datatype>() methods, for the desired fields.
class DataOrder implements Serializable{
String apples, peaches, pears, cardnum, custID;
double icost;
int itotal;
}
Saving the current state of an object to a stream
DataOrder orders = new DataOrder();
FileOutputStream fos =
new FileOutputStream(orders);
ObjectOutputStream oos =
new ObjectOutputStream(fos);
oos.writeObject(order);
restoring an equivalent object from that stream
FileInputStream fis =
new FileInputStream(orders);
ObjectInputStream ois =
new ObjectInputStream(fis);
order = (DataOrder)ois.readObject();
—————
If I write System.exit (0); at the end of the try block, will the finally block still execute?
No ,in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.
—————
What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
—————
What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
—————
What are the different ways to handle exceptions?
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.
—————
Different types of Exception in java?
Checked Exception :A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Un-Checked Exception:Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be
Chained Exception :An application often responds to an exception by throwing another exception. In effect, the first exception causes the second exception. It can be very helpful to know when one exception causes another. Chained Exceptions help the programmer do this.The following are the methods and constructors in Throwable that support chained exceptions.
Throwable getCause() Throwable initCause(Throwable) Throwable(String, Throwable) Throwable(Throwable)
The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception. getCause returns the exception that caused the current exception, and initCause sets the current exception's cause.The following example shows how to use a chained exception.
try { } catch (IOException e) { throw new SampleException("Other IOException", e); }
In this example, when an IOException is caught, a new SampleException exception is created with the original cause attached and the chain of exceptions is thrown up to the next higher level exception handler.
—————
What is garbage collection and what are the garbage collection algorithm avilable?
The JVM's heap stores all objects created by an executing Java program.
Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time.
Garbage collection is the process of automatically freeing objects that are no longer referenced by the program.
This frees the programmer from having to keep track of when to free allocated memory,
thereby preventing many potential bugs and headaches.
The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away.
Other word we can say memory recycling.
When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects.
The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects.
In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed.
Algorithms:Any garbage collection algorithm must do two basic things.
First, it must detect garbage objects.
Second, it must reclaim the heap space used by the garbage objects and make it available to the program.
Garbage detection is ordinarily accomplished by defining a set of roots and determining reachability from the roots.
An object is reachable if there is some path of references from the roots by which the executing program can access the object.
The roots are always accessible to the program. Any objects that are reachable from the roots are considered live.
Objects that are not reachable are considered garbage, because they can no longer affect the future course of program execution.
a. Reference counting collectors
Reference counting was an early garbage collection strategy.
here a reference count is maintained for each object.
When an object is first created its reference count is set to one.
When any other object or root is assigned a reference to that object, the object's count is incremented.
When a reference to an object goes out of scope or is assigned a new value, the object's count is decremented.
Any object with a reference count of zero can be garbage collected.
When an object is garbage collected, any objects that it refers to has their reference counts decremented.
In this way the garbage collection of one object may lead to the subsequent garbage collection of other objects.
b. Tracing collectors
Tracing garbage collectors trace out the graph of object references starting with the root nodes.
Objects that are encountered during the trace are marked in some way.
Marking is generally done by either setting flags in the objects themselves or by setting flags in a separate bitmap.
After the trace is complete, unmarked objects are known to be unreachable and can be garbage collected.
The basic tracing algorithm is called mark and sweep.
This name refers to the two phases of the garbage collection process.
In the mark phase, the garbage collector traverses the tree of references and marks each object it encounters.
In the sweep phase unmarked objects are freed, and the resulting memory is made available to the executing program.
In the JVM the sweep phase must include finalization of objects.
c. Compacting collectors
Garbage collectors of JVMs will likely have a strategy to combat heap fragmentation.
Two strategies commonly used by mark and sweep collectors are compacting and copying.
Both of these approaches move objects on the fly to reduce heap fragmentation.
Compacting collectors slide live objects over free memory space toward one end of the heap.
In the process the other end of the heap becomes one large contiguous free area.
All references to the moved objects are updated to refer to the new location.
d. Copying collectors
Copying garbage collectors move all live objects to a new area.
As the objects are moved to the new area, they are placed side by side,
thus eliminating any free spaces that may have separated them in the old area.
The old area is then known to be all free space.
The advantage of this approach is that objects can be copied as they are discovered by the traversal from the root nodes.
There are no separate mark and sweep phases.
Objects are copied to the new area on the fly, and forwarding pointers are left in their old locations.
The forwarding pointers allow objects encountered later in the traversal that refer to already copied objects to know the new location of the copied objects.
—————
What is marker interface ?
interfaces with no methods are known as marker interfaces. Marker interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality.
—————
Topic: Core Java FAQ
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
Date: 23/12/2023
Subject: Mr.
—————
