Q . What are Checked Exceptions?
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. Checked exceptions must be caught at compile time.
Q.What are UnChecked Exceptions?
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. 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.
Q. What are different types of inner classes?
Nested top-level classes, Member classes, Local classes and Anonymous classes.
Q. Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either 'public' or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the 'modifier private is not allowed here'. This means that a top level class can not be private. Same is the case with protected.
Q. What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
Q .How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
Q .Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods. It is a Marker Interface.
Q. How can I customize the serialization process? i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
Q .What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serialized.
Example Scenario:
Q.When you serialize an object, what happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized along with the original object.
Q.What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException. We are talking about Objects of Inner classes here. If a class has an inner class, then the inner class must also implement Serializable interface.
Q. Why do we need wrapper classes?
It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these reasons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.
Q.What are runtime exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
Q.Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable.
Q. Is synchronised a modifier? indentifier? what is it?
It's a modifier. Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Same is the case with Synchronized Statements as well.
Q .What is singleton class? where is it used?
Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private).
Q .What is the use of Singleton classes?
Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons - for example, we may only want a single instance of a pool of database connections.
Q .What is transient variable?
Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.
Q .Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.
Q. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
Q. What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
Q.Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects. Garbage Collector only executes finalize() method, after the object is not in use, just before garbage collecting it.
Q.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.
Q. What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
Q .How many times may an object's finalize() method be invoked by the garbage collector?
An object's finalize() method may only be invoked once by the garbage collector. Just before garbage collecting it.
Q.What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.
Q .What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
Q. What are the avilable methods in Object class?
public boolean equals(Object obj)
public int hashcode()
public final Class getClass()
public String toString()
protected Object clone() throws CloneNotSupportedException
protected void finalize() throws Throwable
public final void wait() throws InterruptedException
public final void wait(long timeout) throws InterruptedException
public final void wait(long timeout,int nanos) throws InterruptedException
public final void notify()
public final void notifyAll()
Q. Why Strings are immutable in java?
There are various reasons to make String immutable.
•String pool
•Thread Safe
•Security
•Class Loading
•Cache hash value
String literals will go into String Constant Pool.
•For objects JVM used String constant pool which is for efficient memory management in java. Unlike other Java Objects, instead of managing String object on heap area, they introduced String constant pool. One of important characteristic of String constant pool is that it does not create same String object if there is already String constant in the pool.
Security: Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
•Synchronization and concurrency:
making String immutable automatically makes them thread safe thereby solving the synchronization issues.
•Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
•Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
Q. Five different ways to create objects in java?
There are four different ways to create objects in java:
1. Using new keyword
2. Using Class.forName():
3. Using clone():
4. Using Object Deserialization:
5. Using newIntance() method
Using new keyword: This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object=new Object();
Using Class.forName():
•If we know the name of the class & if it has a public default constructor we can create an object in this way.
•Syntax:
•Myobject obj=(MyObject) class.forName("object").newInstance();
Using clone():
•The clone() can be used to create a copy of an existing object.
•Syntax:
•MyObject obj=new MyObject();
•MyObject object=(MyObject )obj.clone();
Using Object Deserialization:
•Object deserialization is nothing but creating an object from its serialized form.
•Syntax:
•objectInputStream istream=new objectInputStream(some data);
•MyObject object=(MyObject) instream.readObject();
Using newInstance() method
Object obj = DemoClass.class.getClassLoader().loadClass("DemoClass").newInstance();
Java Program on creating object using new keyword:
public class Employee
{
private int id;
private String name;
Employee(int id,String name){
this.id=id;
this.name=name;
}
public void display(){
System.out.println(id+" "+name);
}
public static void main (String args[]){
Emploee e=new Employee(1,"Indhu");
Employee e1=new Employee(2,"Sindhu");
e.display();
e1.display();
}
}
Output:
Indhu
Sindhu
Java Program on creating object using clone() method:
public class Empcloneable implements Cloneable {
int a;
String name;
Empcloneable(int a,String name){
this.a=a;
this.name=name;
}
public Empcloneable clone() throws CloneNotSupportedException{
return (Empcloneable) super.clone();
}
public static void main(String[] args) {
Empcloneable e=new Empcloneable(2,"Indhu");
System.out.println(e.name);
try {
Empcloneable b=e.clone();
System.out.println(b.name);
} catch (CloneNotSupportedException e1) {
e1.printStackTrace();
}
}
}
Output:
Indhu
Indhu
Java Program on creating object using Deserialization:
import java.io.*;
public class Files {
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/E/employee.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{ System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
}
}
Output:
Name:Indhu
Java Program on creating object using class.forName();
public class Sample{
public static void main(String args[]){
try {
Class s= Class.forName("com.instanceofjava.Sample");
Sample obj=(Sample) s.newInstance();
System.out.println(obj.hashcode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
2007759836
How many ways we can iterate list in java?
We can iterate list in 6 different ways in java.
1.For Loop
2.Enhanced For Loop
3. While Loop
4.Iterator
5.Collections stream() util (Java8 feature)
6.ListIterator
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. Checked exceptions must be caught at compile time.
Q.What are UnChecked Exceptions?
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. 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.
Q. What are different types of inner classes?
Nested top-level classes, Member classes, Local classes and Anonymous classes.
Q. Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either 'public' or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the 'modifier private is not allowed here'. This means that a top level class can not be private. Same is the case with protected.
Q. What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
Q .How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
Q .Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods. It is a Marker Interface.
Q. How can I customize the serialization process? i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
Q .What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serialized.
Example Scenario:
Serialization in Java
Serialization is the process of converting an object's state (including its references) to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. Simple......Converting an object to bytes and bytes back to object. So when is serialization used? Serialization is used when you want to persist the object. It is also used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In general, serialization is used when we want the object to exist beyond the lifetime of the JVM.
Lets see couple of different scenarios (examples) where we use serialization.
- 1. Banking example: When the account holder tries to withdraw money from the server through ATM, the account holder information along with the withdrawl details will be serialized (marshalled/flattened to bytes) and sent to server where the details are deserialized (unmarshalled/rebuilt the bytes)and used to perform operations. This will reduce the network calls as we are serializing the whole object and sending to server and further request for information from client is not needed by the server.
- 2. Stock example: Lets say an user wants the stock updates immediately when he request for it. To achieve this, everytime we have an update, we can serialize it and save it in a file. When user requests the information, deserialize it from file and provide the information. This way we don't need to make the user wait for the information until we hit the database, perform computations and get the result.
Here are some uses of serialization
- To persist data for future use.
- To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
- To "flatten" an object into array of bytes in memory.
- To exchange data between applets and servlets.
- To store user session in Web applications.
- To activate/passivate enterprise java beans.
- To send objects between the servers in a cluster.
Q .What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.Q.When you serialize an object, what happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized along with the original object.
Q.What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException. We are talking about Objects of Inner classes here. If a class has an inner class, then the inner class must also implement Serializable interface.
Q. Why do we need wrapper classes?
It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these reasons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.
Q.What are runtime exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
Q.Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable.
Q. Is synchronised a modifier? indentifier? what is it?
It's a modifier. Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Same is the case with Synchronized Statements as well.
Q .What is singleton class? where is it used?
Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private).
Q .What is the use of Singleton classes?
Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons - for example, we may only want a single instance of a pool of database connections.
Q .What is transient variable?
Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.
Q .Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.
Q. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
Q. What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
Q.Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects. Garbage Collector only executes finalize() method, after the object is not in use, just before garbage collecting it.
Q.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.
Q. What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
Q .How many times may an object's finalize() method be invoked by the garbage collector?
An object's finalize() method may only be invoked once by the garbage collector. Just before garbage collecting it.
Q.What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.
Q .What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
Q. What are the avilable methods in Object class?
public boolean equals(Object obj)
public int hashcode()
public final Class getClass()
public String toString()
protected Object clone() throws CloneNotSupportedException
protected void finalize() throws Throwable
public final void wait() throws InterruptedException
public final void wait(long timeout) throws InterruptedException
public final void wait(long timeout,int nanos) throws InterruptedException
public final void notify()
public final void notifyAll()
Q. Why Strings are immutable in java?
There are various reasons to make String immutable.
•String pool
•Thread Safe
•Security
•Class Loading
•Cache hash value
String literals will go into String Constant Pool.
•For objects JVM used String constant pool which is for efficient memory management in java. Unlike other Java Objects, instead of managing String object on heap area, they introduced String constant pool. One of important characteristic of String constant pool is that it does not create same String object if there is already String constant in the pool.
Security: Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
•Synchronization and concurrency:
making String immutable automatically makes them thread safe thereby solving the synchronization issues.
•Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
•Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
Q. Five different ways to create objects in java?
There are four different ways to create objects in java:
1. Using new keyword
2. Using Class.forName():
3. Using clone():
4. Using Object Deserialization:
5. Using newIntance() method
Using new keyword: This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object=new Object();
Using Class.forName():
•If we know the name of the class & if it has a public default constructor we can create an object in this way.
•Syntax:
•Myobject obj=(MyObject) class.forName("object").newInstance();
Using clone():
•The clone() can be used to create a copy of an existing object.
•Syntax:
•MyObject obj=new MyObject();
•MyObject object=(MyObject )obj.clone();
Using Object Deserialization:
•Object deserialization is nothing but creating an object from its serialized form.
•Syntax:
•objectInputStream istream=new objectInputStream(some data);
•MyObject object=(MyObject) instream.readObject();
Using newInstance() method
Object obj = DemoClass.class.getClassLoader().loadClass("DemoClass").newInstance();
Java Program on creating object using new keyword:
public class Employee
{
private int id;
private String name;
Employee(int id,String name){
this.id=id;
this.name=name;
}
public void display(){
System.out.println(id+" "+name);
}
public static void main (String args[]){
Emploee e=new Employee(1,"Indhu");
Employee e1=new Employee(2,"Sindhu");
e.display();
e1.display();
}
}
Output:
Indhu
Sindhu
Java Program on creating object using clone() method:
public class Empcloneable implements Cloneable {
int a;
String name;
Empcloneable(int a,String name){
this.a=a;
this.name=name;
}
public Empcloneable clone() throws CloneNotSupportedException{
return (Empcloneable) super.clone();
}
public static void main(String[] args) {
Empcloneable e=new Empcloneable(2,"Indhu");
System.out.println(e.name);
try {
Empcloneable b=e.clone();
System.out.println(b.name);
} catch (CloneNotSupportedException e1) {
e1.printStackTrace();
}
}
}
Output:
Indhu
Indhu
Java Program on creating object using Deserialization:
import java.io.*;
public class Files {
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/E/employee.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{ System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
}
}
Output:
Name:Indhu
Java Program on creating object using class.forName();
public class Sample{
public static void main(String args[]){
try {
Class s= Class.forName("com.instanceofjava.Sample");
Sample obj=(Sample) s.newInstance();
System.out.println(obj.hashcode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
2007759836
How many ways we can iterate list in java?
We can iterate list in 6 different ways in java.
1.For Loop
2.Enhanced For Loop
3. While Loop
4.Iterator
5.Collections stream() util (Java8 feature)
6.ListIterator
Thanks for sharing this informative content , Great work
ReplyDeleteLeanpitch provides online training in Product prototyping during this lockdown period everyone can use it wisely.
icp-cat training