OOPS concept interview questions
Q) What are "oops" concept in java technologies?
OOPs stands for Object Oriented Programming. The concepts in oops are similar to any other programming languages. Basically, it is program agnostic. The different OOps concepts are :
-> Polymorphism
-> Inheritance
-> Abstraction
-> Encapsulation
-> Aggregation
-> Composition
-> Association
Q). What is Polymorphism:
The ability to define a function in multiple forms is called Polymorphism. In java, c++ there are two types of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).
Mehtod overriding: Overriding occurs when a class method has the same name and signature as a method in parent class. When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time.
Overloading: Overloading is determined at the compile time. It occurs when several methods have same names with:
int add(int a,int b)
float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a) //now error conflict with the method int add(int a)
--------------------------------------------------------------------------------------
class FoodDetails {
String title;
setFood(String title){}
}
class ScienceFood extends FoodDetails{
setFood(String title){} //overriding
setFood(String title, String publisher,float price){} //overloading
}
Q). What is inheritance?
Inheritance allows a Child class to inherit properties from it's parent class.
In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class.
public class Parent {
public String parentName;
public String familyName;
protected void printMyName() {
System.out.println(“ My name is “+ chidName+” “ +familyName);
}
}
public class Child extends Parent {
public String childName;
public int childAge;
//inheritance
protected void printMyName() {
System.out.println(“ My child name is “+ chidName+” “ +familyName);
}
}
In above example the child has inherit its family name from the parent class just by inheriting the class. When child object is created printMyName() present in child class is called
Q).What is multiple inheritance and does java support?
If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not allow to extend multiple classes, to overcome this problem it allows to implement multiple Interfaces.
Q).What is an abstraction ?
Abstraction is a way of converting real world objects in terms of class. Its a concept of defining an idea in terms of classes or interface. For example creating a class Vehicle and injecting properties into it.
Example:-
public class Vehicle
{
public String colour;
public String model;
}
Q).What is Encapsulation ?
The encapsulation is achieved by combining the methods and attribute into a class. The class acts like a container encapsulating the properties. The users are exposed mainly public methods.The idea behind is to hide how thinigs work and just exposing the requests a user can do.
Q).What is Association ?
Association is a relationship where all object have their own lifecycle and there is no owner. Let's take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.
Q).What is Aggregation?
Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let's take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about "has-a" relationship.
Q).What is Composition ?
Composition is again specialize form of Aggregation and we can call this as a "death" relationship. It is a strong type of Aggregation. Child object dose not have their life cycle and if parent object deletes all child object will also be deleted. Let's take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete.
OOPs stands for Object Oriented Programming. The concepts in oops are similar to any other programming languages. Basically, it is program agnostic. The different OOps concepts are :
-> Polymorphism
-> Inheritance
-> Abstraction
-> Encapsulation
-> Aggregation
-> Composition
-> Association
Q). What is Polymorphism:
The ability to define a function in multiple forms is called Polymorphism. In java, c++ there are two types of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).
Mehtod overriding: Overriding occurs when a class method has the same name and signature as a method in parent class. When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time.
Overloading: Overloading is determined at the compile time. It occurs when several methods have same names with:
- Different method signature and different number or type of parameters.
- Same method signature but different number of parameters.
- Same method signature and same number of parameters but of different type
int add(int a,int b)
float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a) //now error conflict with the method int add(int a)
--------------------------------------------------------------------------------------
class FoodDetails {
String title;
setFood(String title){}
}
class ScienceFood extends FoodDetails{
setFood(String title){} //overriding
setFood(String title, String publisher,float price){} //overloading
}
Q). What is inheritance?
Inheritance allows a Child class to inherit properties from it's parent class.
In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class.
public class Parent {
public String parentName;
public String familyName;
protected void printMyName() {
System.out.println(“ My name is “+ chidName+” “ +familyName);
}
}
public class Child extends Parent {
public String childName;
public int childAge;
//inheritance
protected void printMyName() {
System.out.println(“ My child name is “+ chidName+” “ +familyName);
}
}
In above example the child has inherit its family name from the parent class just by inheriting the class. When child object is created printMyName() present in child class is called
Q).What is multiple inheritance and does java support?
If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not allow to extend multiple classes, to overcome this problem it allows to implement multiple Interfaces.
Q).What is an abstraction ?
Abstraction is a way of converting real world objects in terms of class. Its a concept of defining an idea in terms of classes or interface. For example creating a class Vehicle and injecting properties into it.
Example:-
public class Vehicle
{
public String colour;
public String model;
}
Q).What is Encapsulation ?
The encapsulation is achieved by combining the methods and attribute into a class. The class acts like a container encapsulating the properties. The users are exposed mainly public methods.The idea behind is to hide how thinigs work and just exposing the requests a user can do.
Q).What is Association ?
Association is a relationship where all object have their own lifecycle and there is no owner. Let's take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.
Q).What is Aggregation?
Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let's take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about "has-a" relationship.
Q).What is Composition ?
Composition is again specialize form of Aggregation and we can call this as a "death" relationship. It is a strong type of Aggregation. Child object dose not have their life cycle and if parent object deletes all child object will also be deleted. Let's take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete.
Some Key Concepts in Java
Q). Why is main() method static?
To access a static method class object is not needed. The method can be accessed directly with the help of ClassName. So when a program is started the jvm search for the class with main method and calls it without creating an object of the class.
Q).What is the difference between static and instance methods?
instance method belongs to the instance of a class therefore it requires an instance before it can be invoked, whereas static method belongs to the class itself and not to any class instance so it doesn't need an instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use static (early) binding.
When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time. On the other hand, when the JVM invokes a static method, it selects the method to invoke based on the actual class of the object, which may only be known at compile time.
Q).Can static block throw exception?
Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit. If System.exit() is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.
Q).What is difference between abstract class and interface?
Q).Explain with example to describe when to use abstract class and interface?
Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementaion for tyres will be provided.
public abstract class Car {
private final static TOTAL_TYRES=4;
public abstract String getCarName();
public final int getNoOfTyres(){
return TOTAL_TYRES;
}
}
Consider a scenario where Cars can have any number of tyres and other features can also be different. In this case interface will be created.
public interface Car {
public abstract String getCarName();
public abstract int getNoOfTyres();
}
Q).Does java support multiple interitance? Why?
Java doesnt support multiple inheritance but it provide a way through which it can enact it. Consider the scenario is C++.
Class A {
public void add(){
// some text
}
}
Class B {
public void add(){
// some text
}
}
Class C extends A,B {
public static void main(String arg[]){
C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.
}
This problem is called Diamond problem.
This problem in java is taken care with the use of interfaces
In Java similar problem would look like:
interface A{
add();
}
interface B{
add();
}
class C implements A,B{
add(){
// doesnt matter which interface it belong to
}
}
Q).Can this keyword be assigned null value ?
No
Q).What are the different types of references in java?
Java has a more expressive system of reference than most other garbage-collected programming languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. The java.lang.ref package defines three other types of references--soft, weak and phantom references. Each type of reference is designed for a specific use.
A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable) but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector. Semantically, a soft reference means "keep this object unless the memory is needed."
A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable anywhere else. Another possible application of weak references is the string intern pool. Semantically, a weak reference means "get rid of this object when nothing else references it."
A PhantomReference is used to reference objects that have been marked for garbage collection and have been finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is referenced by a phantom reference is calledphantom reachable. This allows for more flexible cleanup than is possible with the finalization mechanism alone. Semantically, a phantom reference means "this object is no longer needed and has been finalized in preparation for being collected."
Q).How to change the heap size of a JVM?
The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program
Q).What is difference between instanceof and isInstance(Object obj)?
a). instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.
b). instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.
Q).Java supports pass by value or pass by reference?
Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive data types or objects. For the data type the actual value is passed.
Java passes the references by value just like any other parameter. The pointer to the object is passed as value. Thus, method manipulation will alter the objects, since the references point to the original object but will not intialize the new object.
Example:
public void tricky(Point arg1, Point arg2) {
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args) {
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
OUTPUT
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.
Q).What is memory leak?
A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn't get garbage collected.
Q).What is the difference between equals() and ==?
== operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. But since the method can be overriden like for String class. equals() method can be used to compare the values of two objects.
String str1 = "MyName";
String str2 = new String("MyName");
String str3 = str2;
if(str1 == str2){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str1.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
Output:
Objects are not equal
Objects are equal
--------------------------------------------------------------------------------------------------
String str2 = "MyName";
String str3 = str2;
if(str2 == str3){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str3.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
Output:
Objects are equal
Objects are equal
To access a static method class object is not needed. The method can be accessed directly with the help of ClassName. So when a program is started the jvm search for the class with main method and calls it without creating an object of the class.
Q).What is the difference between static and instance methods?
instance method belongs to the instance of a class therefore it requires an instance before it can be invoked, whereas static method belongs to the class itself and not to any class instance so it doesn't need an instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use static (early) binding.
When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time. On the other hand, when the JVM invokes a static method, it selects the method to invoke based on the actual class of the object, which may only be known at compile time.
Q).Can static block throw exception?
Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit. If System.exit() is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.
Q).What is difference between abstract class and interface?
- A class is called abstract when it contains at least one abstract method. It can also contain n numbers of concrete method.Interface can contain only abstract( non implemented) methods.
- The abstract class can have public,private,protect or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesn't have any variables it only has constants.
- A class can extend only one abstract class but a class can implement multipleinterfaces.
- If an interface is implemented its compulsory to implement all of its methods but if an abstract class is extended its not compulsory to implement all methods.
- The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.
Q).Explain with example to describe when to use abstract class and interface?
Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementaion for tyres will be provided.
public abstract class Car {
private final static TOTAL_TYRES=4;
public abstract String getCarName();
public final int getNoOfTyres(){
return TOTAL_TYRES;
}
}
Consider a scenario where Cars can have any number of tyres and other features can also be different. In this case interface will be created.
public interface Car {
public abstract String getCarName();
public abstract int getNoOfTyres();
}
Q).Does java support multiple interitance? Why?
Java doesnt support multiple inheritance but it provide a way through which it can enact it. Consider the scenario is C++.
Class A {
public void add(){
// some text
}
}
Class B {
public void add(){
// some text
}
}
Class C extends A,B {
public static void main(String arg[]){
C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.
}
This problem is called Diamond problem.
This problem in java is taken care with the use of interfaces
In Java similar problem would look like:
interface A{
add();
}
interface B{
add();
}
class C implements A,B{
add(){
// doesnt matter which interface it belong to
}
}
Q).Can this keyword be assigned null value ?
No
Q).What are the different types of references in java?
Java has a more expressive system of reference than most other garbage-collected programming languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. The java.lang.ref package defines three other types of references--soft, weak and phantom references. Each type of reference is designed for a specific use.
A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable) but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector. Semantically, a soft reference means "keep this object unless the memory is needed."
A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable anywhere else. Another possible application of weak references is the string intern pool. Semantically, a weak reference means "get rid of this object when nothing else references it."
A PhantomReference is used to reference objects that have been marked for garbage collection and have been finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is referenced by a phantom reference is calledphantom reachable. This allows for more flexible cleanup than is possible with the finalization mechanism alone. Semantically, a phantom reference means "this object is no longer needed and has been finalized in preparation for being collected."
Q).How to change the heap size of a JVM?
The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program
Q).What is difference between instanceof and isInstance(Object obj)?
a). instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.
b). instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.
Q).Java supports pass by value or pass by reference?
Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive data types or objects. For the data type the actual value is passed.
Java passes the references by value just like any other parameter. The pointer to the object is passed as value. Thus, method manipulation will alter the objects, since the references point to the original object but will not intialize the new object.
Example:
public void tricky(Point arg1, Point arg2) {
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args) {
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
OUTPUT
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.
Q).What is memory leak?
A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn't get garbage collected.
Q).What is the difference between equals() and ==?
== operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. But since the method can be overriden like for String class. equals() method can be used to compare the values of two objects.
String str1 = "MyName";
String str2 = new String("MyName");
String str3 = str2;
if(str1 == str2){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str1.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
Output:
Objects are not equal
Objects are equal
--------------------------------------------------------------------------------------------------
String str2 = "MyName";
String str3 = str2;
if(str2 == str3){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str3.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
Output:
Objects are equal
Objects are equal
Java Exception Interview Questions...!!!
Q). What is an Exception?
Ans) The exception is said to be thrown whenever an exceptional event occurs in java which signals that something is not correct with the code written and may give unexpected result. An exceptional event is a occurrence of condition which alters the normal program flow. Exceptional handler is the code that does something about the exception.
Q). Exceptions are defined in which java package?
Ans) All the exceptions are subclasses of java.lang.Exception
Q). How are the exceptions handled in java?
Ans) When an exception occurs the execution of the program is transferred to an appropriate exception handler. The try-catch-finally block is used to handle the exception.
The code in which the exception may occur is enclosed in a try block, also called as a guarded region.
The catch clause matches a specific exception to a block of code which handles that exception.
And the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block
Ans) The exception is said to be thrown whenever an exceptional event occurs in java which signals that something is not correct with the code written and may give unexpected result. An exceptional event is a occurrence of condition which alters the normal program flow. Exceptional handler is the code that does something about the exception.
Q). Exceptions are defined in which java package?
Ans) All the exceptions are subclasses of java.lang.Exception
Q). How are the exceptions handled in java?
Ans) When an exception occurs the execution of the program is transferred to an appropriate exception handler. The try-catch-finally block is used to handle the exception.
The code in which the exception may occur is enclosed in a try block, also called as a guarded region.
The catch clause matches a specific exception to a block of code which handles that exception.
And the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block