Thursday, September 1, 2016

OOPS Interview Questions And Answers

Basic Questions On OOPS In Interviews 



1. What is OOPS?
OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.
2. Write basic concepts of OOPS?
Following are the concepts of OOPS and are as follows:.
1.   Abstraction.
2.   Encapsulation.
3.   Inheritance.
4.   Polymorphism.
3. What is a class?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object.
4. What is an object?
Object is termed as an instance of a class, and it has its own state, behavior and identity.
5. What is Encapsulation?
Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data can be restricted to the members of that class.
Levels are Public,Protected, Private, Internal and Protected Internal.
6. What is Polymorphism?
Polymorphism is nothing butassigning behavior or value in a subclass to something that was already declared in the main class. Simply, polymorphism takes more than one form.
7. What is Inheritance?
Inheritance is a concept where one class shares the structure and behavior defined in another class. Ifinheritance applied on one class is called Single Inheritance, and if it depends on multiple classes, then it is called multiple Inheritance.
8. What are manipulators?
Manipulators are the functions which can be used in conjunction with the insertion (<<) and extraction (>>) operators on an object. Examples are endl and setw.
9. Define a constructor?
Constructor is a method used to initialize the state of an object, and it gets invoked at the time of object creation. Rules forconstructor are:.
·          Constructor Name should be same asclass name.
·          Constructor must have no return type.
10. Define Destructor?
Destructor is a method which is automatically called when the object ismade ofscope or destroyed. Destructor name is also same asclass name but with the tilde symbol before the name.
11. What is Inline function?
Inline function is a technique used by the compilers and instructs to insert complete body of the function wherever that function is used in the program source code.
12. What is avirtual function?
Virtual function is a member function ofclass and its functionality can be overridden in its derived class. This function can be implemented by using a keyword called virtual, and it can be given during function declaration.
Virtual function can be achieved in C++, and it can be achieved in C Languageby using function pointers or pointers to function.
13. What isfriend function?
Friend function is a friend of a class that is allowed to access to Public, private or protected data in that same class. If the function is defined outside the class cannot access such information.
Friend can be declared anywhere in the class declaration, and it cannot be affected by access control keywords like private, public or protected.
14. What is function overloading?
Function overloading is defined as a normal function, but it has the ability to perform different tasks. It allowscreation of several methods with the same name which differ from each other by type of input and output of the function.
Example
void add(int& a, int& b);
void add(double& a, double& b);
void add(struct bob& a, struct bob& b);
15. What is operator overloading?

Operator overloading is a function where different operators are applied and depends on the arguments. Operator,-,* can be used to pass through the function , and it has their own precedence to execute.

16. What is an abstract class?
An abstract class is a class which cannot be instantiated. Creation of an object is not possible with abstract class , but it can be inherited. An abstract class can contain only Abstract method. Java allows only abstract method in abstract class while for other language it allows non-abstract method as well.
17. What is a ternary operator?
Ternary operator is said to be an operator which takes three arguments. Arguments and results are of different data types , and it is depends on the function. Ternary operator is also called asconditional operator.
18. What is the use of finalize method?
Finalize method helps to perform cleanup operations on the resources which are not currently used. Finalize method is protected , and it is accessible only through this class or by a derived class.
19. What are different types of arguments?
A parameter is a variable used during the declaration of the function or subroutine and arguments are passed to the function , and it should match with the parameter defined. There are two types of Arguments.
·          Call by Value – Value passed will get modified only inside the function , and it returns the same value whatever it is passed it into the function.
·          Call by Reference – Value passed will get modified in both inside and outside the functions and it returns the same or different value.

20. What is super keyword?
Super keyword is used to invoke overridden method which overrides one of its superclass methods. This keyword allows to access overridden methods and also to access hidden members of the superclass.
It also forwards a call from a constructor to a constructor in the superclass.
21. What is method overriding?
Method overriding is a feature that allows sub class to provide implementation of a method that is already defined in the main class. This will overrides the implementation in the superclass by providing the same method name, same parameter and same return type.
22. What is an interface?
An interface is a collection of abstract method. If the class implements an inheritance, and then thereby inherits all the abstract methods of an interface.
23.   What is exception handling?
Exception is an event that occurs during the execution of a program. Exceptions can be of any type – Run time exception, Error exceptions. Those exceptions are handled properly through exception handling mechanism like try, catch and throw keywords.
24. What are tokens?
Token is recognized by a compiler and it cannot be broken down into component elements. Keywords, identifiers, constants, string literals and operators are examples of tokens.
Even punctuation characters are also considered as tokens – Brackets, Commas, Braces and Parentheses.
25. Difference between overloading and overriding?
Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the same method with different arguments , and it may or may not return the same value in the same class itself.
Overriding is the same method names with same arguments and return types associates with the class and its child class.

26. Difference between class and an object?
An object is an instance of a class. Objects hold any information , but classes don’t have any information. Definition of properties and functions can be done at class and can be used by the object.
Class can have sub-classes, and an object doesn’t have sub-objects.
27. What is an abstraction?
Abstraction is a good feature of OOPS , and it shows only the necessary details to the client of an object. Means, it shows only necessary details for an object, not the inner details of an object. Example – When you want to switch On television, it not necessary to show all the functions of TV. Whatever is required to switch on TV will be showed by using abstract class.
28. What are access modifiers?
Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are 5 types of access modifiers , and they are as follows:.
·           Private.
·          Protected.
·          Public.
·          Friend.
·          Protected Friend.
29. What is sealed modifiers?
Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers can also be applied to properties, events and methods. This modifier cannot be applied to static members.

30. How can we call the base method without creating an instance?
Yes, it is possible to call the base method without creating an instance. And that method should be,.
Static method.
Doing inheritance from that class.-Use Base Keyword from derived class.
31. What is the difference between new and override?
The new modifier instructs the compiler to use the new implementation instead of the base class function. Whereas, Override modifier helps to override the base class function.
32. What are the various types of constructors?
There are three various types of constructors , and they are as follows:.
–  Default Constructor – With no parameters.
–  Parametric Constructor – With Parameters. Create a new instance of a class and also passing arguments simultaneously.
–  Copy Constructor – Which creates a new object as a copy of an existing object.
33. What is early and late binding?
Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.
34. What is ‘this’ pointer?
THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which differentiates between the current object with the global object. Basically, it refers to the current object.
35. What is the difference betweenstructure and a class?
Structure default access type is public , but class access type is private. A structure is used for grouping data whereas class can be used for grouping data and methods. Structures are exclusively used for dataand it doesn’t require strict validation , but classes are used to encapsulates and inherit data which requires strict validation.
36. What is the default access modifier in a class?
The default access modifier of a class is Private by default.
37. What is pure virtual function?
A pure virtual function is a function which can be overridden in the derived classbut cannot be defined. A virtual function can be declared as Pure by using the operator =0.
38. What are all the operators that cannot be overloaded?
Following are the operators that cannot be overloaded -.
1.   Scope Resolution (:: )
2.   Member Selection (.)
3.   Member selection through a pointer to function (.*)

39. What is dynamic or run time polymorphism?
Dynamic or Run time polymorphism is also known as method overriding in which call to an overridden function is resolved during run time, not at the compile time. It means having two or more methods with the same name,same signature but with different implementation.
40. Do we require parameter for constructors?
No, we do not require parameter for constructors.
41. What is a copy constructor?
This is a special constructor for creating a new object as a copy of an existing object. There will be always only on copy constructor that can be either defined by the user or the system.
42. What does the keyword virtual represented in the method definition?
It means, we can override the method.
43. Whether static method can use non static members?
False.
44. What arebase class, sub class and super class?
Base class is the most generalized class , and it is said to be a root class.
Sub class is a class that inherits from one or more base classes.
Super class is the parent class from which another class inherits.
45. What is static and dynamic binding?
Binding is nothing but the association of a name with the class. Static binding is a binding in which name can be associated with the class during compilation time , and it is also called as early Binding.
Dynamic binding is a binding in which name can be associated with the class during execution time , and it is also called as Late Binding.
46. How many instances can be created for an abstract class?
Zero instances will be created for an abstract class.
47. Which keyword can be used for overloading?
Operator keyword is used for overloading.
48. What is the default access specifier in a class definition?
Private access specifier is used in a class definition.
49. Which OOPS concept is used as reuse mechanism?
Inheritance is the OOPS concept that can be used as reuse mechanism.
50. Which OOPS concept exposes only necessary information to the calling functions?

Data Hiding / Abstraction



High Level OOPS Interview Questions 



What is method overriding in OOP or Java? 

It's one of the magic of object oriented programming where the method is chose based upon an object at runtime. In order for method overriding, we need Inheritance and Polymorphism, as we need a method with the same signature in both superclass and subclass. A call to such method is resolved at runtime depending upon the actual object and not the type o variable. See the answer for more detailed discussion.


What is method hiding in Java? 
When you declare two static methods with same name and signature in both superclass and subclass then they hide each other i.e. a call to the method in the subclass will call the static method declared in that class and a call to the same method is superclass is resolved to the static method declared in the super class.


Is Java a pure object oriented language? if not why? 

Java is not a pure object-oriented programming language e.g. there are many things you can do without objects e.g. static methods. Also, primitive variables are not objects in Java. See the answer for a more detailed explanation.


What are rules of method overloading and overriding in Java? 

One of the most important rule of method overloading in Java is that method signature should be different i.e. either the number of arguments or the type of arguments. Simply changing the return type of two methods will not result in overloading, instead compiler will throw an error. On the other hand, method overriding has more rules e.g. name and return type must be same, method signature should also be same, the overloaded method cannot throw a higher exception etc. See the answer for a full list of rules related to method overloading and overriding in Java.


The difference between method overloading and overriding? 

Several differences but the most important one is that method overloading is resolved at compile time and method overriding is resolved at runtime. The compiler only used the class information for method overloading, but it needs to know object to resolved overridden method calls. This diagram explains the difference quite well, though
Can we overload a static method in Java? 
Yes, you can overload a static method in Java. You can declare as many static methods of the same name as you wish provided all of them have different method signatures. See the answer for more detailed explanation and code example.


Can we override static method in Java? 

No, you cannot override a static method because it's not bounded to an object. Instead, static methods belong to a class and resolved at compile time using the type of reference variable. But, Yes, you can declare the same static method in a subclass, that will result in method hiding i.e. if you use reference variable of type subclass then new method will be called, but if you use reference variable of superclass than old method will be called.


Can we prevent overriding a method without using the final modifier?
Yes, you can prevent the method overriding in Java without using the final modifier. In fact, there are several ways to accomplish it e.g. you can mark the method private or static, those cannot be overridden.

Can we override a private method in Java? 

No, you cannot. Since the private method is only accessible and visible inside the class they are declared, it's not possible to override them in subclasses. Though, you can override them inside the inner class as they are accessible there.


What is covariant method overriding in Java? 

In covariant method overriding, the overriding method can return the subclass of the object returned by original or overridden method. This concept was introduced in Java 1.5 (Tiger) version and it's very helpful in case original method is returning general type like Object class, because, then by using covariant method overriding you can return more suitable object and prevent client side type casting. One of the practical use of this concept is in when you override the clone() method in Java.


Can we change the return type of method to subclass while overriding? (answer)
Yes, you can, but only from Java 5 onward. This feature is known as co-variant method overriding and it was introduced in JDK 5 release. This is immensely helpful if original method return super-class e.g. clone() method return java.lang.Object. By using this, you can directly return the actual type, preventing client-side type casting of the result.


Can we change the argument list of an overriding method? 

No, you cannot. The argument list is part of the method signature and both overriding and overridden method must have the same signature.


Can we override a method which throws runtime exception without throws clause? 

Yes, there is no restriction on unchecked exception while overriding. On the other hand, in the case of checked exception, an overriding exception cannot throw a checked exception which comes higher in type hierarchy e.g. if original method is throwing IOException than overriding method cannot throw java.lang.Exception or java.lang.Throwable.


How do you call superclass version of an overriding method in sub class? 
You can call a superclass version of an overriding method in the subclass by using super keyword. For example to call the toString() method from java.lang.Object class you can call super.toString().


Can we override a non-static method as static in Java? 
Yes, you can override the non-static method in Java, no problem on them but it should not be private or final :)


Can we override the final method in Java? 

No, you cannot override a final method in Java, final keyword with the method is to prevent method overriding. You use final when you don't want subclass changing the logic of your method by overriding it due to security reason. This is 
why String class is final in Java. This concept is also used in template design pattern where template method is made final to prevent overriding.


Can we have a non-abstract method inside interface?
From Java 8 onward you can have a non-abstract method inside interface, prior to that it was not allowed as all method was implicitly public abstract. From JDK 8, you can add static and default method inside an interface.


What is the default method of Java 8? 

Default method, also known as extension method are new types of the method which you can add on the interface now. These method has implementation and intended to be used by default. By using this method, JDK 8 managed to provide common functionality related to 
lambda expression and stream API without breaking all the clients which implement their interfaces. If you look Java 8 API documentation you will find several useful default method on key Java interface like Iterator, Map etc.

What is an abstract class in Java? 

An abstract class is a class which is incomplete. You cannot create an instance of an abstract class in Java. They are provided to define default behavior and ensured that client of that class should adore to those contract which are defined inside the abstract class. In order to use it, you must extend and implement their abstract methods. BTW, in Java a class can be abstract without specifying any abstract method.


What is an interface in Java? What is the real user of an interface? 

Like an abstract class, the interface is also there to specify the contract of an API. It supports OOP abstraction concept as it defines only abstract behavior. It will tell that your program will give output but how is left to implementors. The real use of the interface to define types to leverage Polymorphism. See the answer for more detailed explanation and discussion.


The difference between Abstract class and interface? 

In Java, the key difference is that abstract class can contain non-abstract method but the interface cannot, but from Java 8 onward interface can also contain static and default methods which are non-abstract. See the answer for more detailed discussion as I have described a lot of points there

Can we make a class abstract without an abstract method?

Yes, just add abstract keyword on the class definition and your class will become abstract.


Can we make a class both final and abstract at the same time? 

No, you cannot apply both final and abstract keyword at the class same time because they are exactly opposite of each other. A final class in Java cannot be extended and you cannot use an abstract class without extending and making it a concrete class. As per Java specification, the compiler will throw an error if you try to make a class abstract and final at the same time.


Can we overload or override the main method in Java? 

No, since main() is a static method, you can only overload it, you cannot override it because the static method is resolved at compile time without needing object information hence we cannot override the main method in Java.


What is the difference between Polymorphism, Overloading, and Overriding? 

This is slight tricky OOP concept question because Polymorphism is the real concept behind on both Overloading and Overriding. Overloading is compile time Polymorphism and Overriding are runtime Polymorphism.


Can an interface extend more than one interface in Java?
Yes, an interface can extend more than one interface in Java, it's perfectly valid.


Can a class extend more than one class in Java?
No, a class can only extend another class because Java doesn't support multiple inheritances but yes, it can implement multiple interfaces.


What is the difference between abstraction and polymorphism in Java?
Abstraction generalizes the concept and Polymorphism allow you to use different implementation without changing your code. This diagram explains the abstraction quite well, though

What problem is solved by Strategy pattern in Java? 
Strategy pattern allows you to introduce new algorithm or new strategy without changing the code which uses that algorithm. For example, the Collections.sort() method which sorts the list of the object uses Strategy pattern to compare object. Since every object uses different comparison strategy you can compare various object differently without changing sort method.

Which OOP concept Decorator design Pattern is based upon? 
Decorator pattern takes advantage of Composition to provide new features without modifying the original class. A very good to-the-point question for the telephonic round. This is quite clear from UML diagram of Decorator pattern, as you can see the Component is associated with Decorator.

When to use Singleton design pattern in Java? 

When you need just one instance of a class and wants that to be globally available then you can use 
Singleton pattern. It's not free of cost though because it increase coupling between classes and make them hard to test. This is one of the oldest design pattern questions from Java interviews. Please see the answer for more detailed discussion.


What is the difference between State and Strategy Pattern? 

Though the structure or class diagram of State and Strategy pattern is same, their intent is completely different. State pattern is used to do something specific depending upon state while 
Strategy allows you to switch between algorithms without changing the code which uses it.


What is the difference between Association, Aggregation, and Composition in OOP? 

When an object is  related to another object it called association. It has two forms, aggregation, and composition. the former is the loose form of association where the related object can survive individual while later is a stronger form of association where a related object cannot survive individually. For example, the city is an aggregation of people but is the composition of body parts.


What is the difference between Decorator, Proxy and Adapter pattern in Java?

Again they look similar because their structure or class diagram is very similar but their intent is quite different. Decorator adds additional functionality without touching the class, Proxy provides access control and Adapter is used to make two incompatible interfaces work together. 


What is the 5 objects oriented design principle from SOLID? 

SOLID is the term given by Uncle Bob in his classic book, the 
CleanCode, one of the must-read books for programmers. In SOLID each character stands for one design principle:
S for Single Responsibility Principle
O for Open closed design principle
L for Liskov substitution principle
I for Interface segregation principle
D for Dependency inversion principle


What is the difference between Composition and Inheritance in OOP? 
This is another great OOPS concept question because it test what matters, both of them are very important from a class design perspective. Though, both Composition and Inheritance allows you to reuse code, former is more flexible than later. Composition allows the class to get an additional feature at runtime, but Inheritance is static. You can not change the feature at runtime by substitution new implementation. See the answer for more detailed discussion.


Question 1: What is Inheritance in Java? 

Answer: Inheritance is an Object oriented feature which allows a class to inherit behavior and data from other class. For example, a class Car can extend basic feature of Vehicle class by using Inheritance. One of the most intuitive examples of Inheritance in the real world is Father-Son relationship, where Son inherit Father's property. If you don't know, Inheritance is the quick way to become rich :)


Question 2: What are different types of Inheritance supported by Java? 
Answer: Java supports single Inheritance, multi-level inheritance and at some extent multiple inheritances because Java allows a class to only extend another class, but an interface in Java can extend multiple inheritances

Question 3: Why multiple Inheritance is not supported by Java? 

Answer: Java is introduced after C++ and Java designer didn't want to take some C++ feature which is confusing and not essential. They think multiple inheritances is one of them which doesn't justify complexity and confusion it introduces. You can also check why multiple inheritances are not supported in Java for more reasons and discussion around this.


Question 4: Why Inheritance is used by Java Programmers?
Answer: Inheritance is used for code reuse and leveraging Polymorphism by creating a type hierarchy. It's better to use Inheritance for type declaration but for code reuse composition is a better option because it's more flexible. See this article for learning more about why Composition is better than Inheritance.


Question 5: How to use Inheritance in Java? 

Answer: You can use Inheritance in Java by extending classes and implementing interfaces. Java provides two keywords extends and implements to achieve inheritance.  A class which is derived from another class is known as a subclass and an interface which is derived from another interface is called subinterface. A class which implements an interface is known as implementation.

Question 6: What is the syntax of Inheritance? 

Answer: You can use either extends of implements keyword to implement Inheritance in Java.  A class extends another class using extends keyword, an interface can extend another interface using extend keyword, and a class can implement an interface using implements keyword in Java.


Question 7: What is the difference between Inheritance and Encapsulation? 
Answer: Inheritance is an object oriented concept which creates a parent-child relationship. It is one of the ways to reuse the code written for parent class but it also forms the basis of Polymorphism. On the other hand, Encapsulation is an object oriented concept which is used to hide the internal details of a class e.g. HashMap encapsulate how to store elements and how to calculate hash values.


Question 8: What is the difference between Inheritance and Abstraction? (detailed answer)
Answer: Abstraction is an object oriented concept which is used to simply things by abstracting details. It helps in the designing system. On the other hand, Inheritance allows code reuse. You can reuse the functionality you have already coded by using Inheritance. See 
Head First Object Oriented Analysis and Desig  for more details



Question 9: What is the difference between Polymorphism and Inheritance?

Answer: Both Polymorphism and Inheritance goes hand on hand, they help each other to achieve their goal. Polymorphism allows flexibility, you can choose which code to run at runtime by overriding.  See the detailed answer for more details.


Question 10: What is the difference between Composition and Inheritance in OOP?

Answer: One of the good question to check the candidate's object-oriented programming skills. There are several differences between Composition and Inheritance in Java, some of them are following:

1. The Composition is more flexible because you can change the implementation at runtime by calling setXXX() method, but Inheritance cannot be changed i.e. you cannot ask a class to implement another class at runtime.

2. Composition builds HAS-A relationship while Inheritance builds IS-A relationship e.g. A Room HAS A Fan, but Mango IS-A Fruit.

3. The parent-child relationship is best represented using Inheritance but If you just want to use the services of another class use Composition. For more differences see 
5 reasons to favor composition over Inheritance


11. Can we override static method in Java? 

No, you cannot override a static method in Java because it's resolved at compile time. In order for overriding to work, a method should be virtual and resolved at runtime because objects are only available at runtime. This is one of the tricky Java questions, where interviewer tries to confuse you. A programmer is never sure about whether they can override or overload a static method in Java.


12. Can we overload a static method in Java?

Yes, you cannot overload a static method in Java. Overloading has nothing to do with runtime but the signature of each method must be different. In Java, to change the method signature, you must change either number of arguments, type of arguments or order of arguments.


13. Can we override a private method in Java? 

No,  you cannot override a private method in Java because the private method is not inherited by the subclass in Java, which is essential for overriding. In fact, a private method is not visible to anyone outside the class and, more importantly, a call to the private method is resolved at compile time by using Type information as opposed to runtime by using the actual object.


Question 14: What is method hiding in Java? 

Answer: Since the static method cannot be overridden in Java, but if you declare the same static method in subclass then that would hide the method from the superclass. It means, if you call that method from subclass then the one in the subclass will be invoked but if you call the same method from superclass then the one in superclass will be invoked. This is known as method hiding in Java.


Question 15: Can a class implement more than one interface in Java? 

Yes, A class can implement more than one interface in Java e.g. A class can be both Comparable and Serializable at the same time. This is why the interface should be the best use for defining Type as described in Effective Java. This feature allows one class to play a polymorphic role in the program.


Question 16: Can a class extends more than one class in Java? 
(detailed answer)
Answer: No, a class can only extend just one more class in Java.  Though Every class also, by default extend the java.lang.Object class in Java.


Question 17: Can an interface extends more than one interface in Java? 

Answer: Yes, unlike classes, an interface can extend more than one interface in Java. There are several example of this behavior in JDK itself e.g. 
java.util.List interface extends both Collection and Iterable interface to tell that it is a Collection as well as it allows iteration via Iterator.


18: What will happen if a class extends two interfaces and they both have a method with same name and signature? (detailed answer)
In this case, a conflict will arise because the compiler will not able to link a method call due to ambiguity. You will get a compile time error in Java.


Question 19: Can we pass an object of a subclass to a method expecting an object of the super class? 
(
answer)
Answer: Yes, you can pass that because subclass and superclass are related to each other by Inheritance which provides IS-A property.  I mean Banana is a Fruit so you can pass banana if somebody expect fruit. Now there are scenario, where you can't do e.g. when subclass violates the Liskov Substitution principle i.e. you cannot pass a plastic banana to someone expecting fruit :-), The eat() function will throw exception.


Question 20: What is the Liskov substitution principle? (detailed answer)
Answer: The Liskov substitution principle is one of the five object-oriented design principles, collectively know as 
SOLID principles. This design principle is L of SOLID acronym. The Liskov substitution principle states that in an object oriented program if a function or method is expecting an object of base class then  it should work fine with a derived class object as well. If it cannot function properly with derived class object then the derived class is violating the Liskov Substitution principle.

For example, if a method is expecting a List you can also pass 
ArrayList or LinkedList and it should work just fine because ArrayList and LinkedList both follow Liskov Substitution Principle, but the java.sql.Date which is a subclass of java.util.Date in Java violates Liskov Substitution Principle because you cannot pass an object of java.sql.Date class to a method which is expecting an object of java.util.Date, Why? because all time-related method will throw java.lang.UnsupportedOperationException.

Here is another example of violating The Liskov Substitution Principle, Square is a special type of Rectangle whose adjacent sides are equal but making Square extending Rectangle violates LSP principle. For more details on SOLID design principles, read 
Clean Code by Rober C. Martin, the inventor of SOLID principles.

Question 21: How to call a method of a subclass, if you are holding an object of the subclass in a reference variable of type superclass? 

Answer: You can call a method of the subclass by first casting the object hold by reference variable of  superclass into the subclass. Once you hold the object in subclass reference type, you can call methods from the subclass. See how type casting works in Java for more details.



Question: What does the following Java program print?
public class Test {
    public static void main(String[] args) {
        System.out.println(Math.min(Double.MIN_VALUE, 0.0d));
    }
}
Answer: This question is tricky because unlike the Integer, where MIN_VALUE is negative, both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers. The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the least among all double values. So unlike the obvious answer, this program will print 0.0 because Double.MIN_VALUE is greater than 0. I have asked this question to Java developer having experience up to 3 to 5 years and surprisingly almost 70% candidate got it wrong.


What will happen if you put return statement or System.exit () on try or catch block? Will finally block execute?
This is a very popular tricky Java question and it's tricky because many programmers think that no matter what, but the 
finally block will always execute. This question challenge that concept by putting a return statement in the try or catch block or calling System.exit() from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put a return statement in the try block or catch block but finally block won't run if you call System.exit() from try or catch block. 

Question: Can you override a private or static method in Java?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java. Anyway, 
you can not override a private or static method in Java, if you create a similar method with same return type and same method arguments in child class then it will hide the superclass method, this is known as method hiding.

Similarly, you cannot override a private method in sub class because it's not accessible there, what you do is create another private method with the same name in the child class. See Can you override a private method in Java or more details.



Question: What do the expression 1.0 / 0.0 will return? will it throw Exception? any compile time error?

Answer: This is another tricky question from Double class. Though Java developer knows about the double primitive type and Double class, while doing floating point arithmetic they don't pay enough attention to 
Double.INFINITY, NaN, and -0.0 and other rules that govern the arithmetic calculations involving them. The simple answer to this question is that it will not throwArithmeticExcpetion and return Double.INFINITY.

Also, note that the comparison 
x == Double.NaN always evaluates to false, even if x itself is a NaN. To test if x is a NaN, one should use the method call Double.isNaN(x) to check if given number is NaN or not. If you know SQL, this is very close to NULL there.

Btw, If you are running out of time for your interview preparation, you can also check out 
Java Programming Interviews exposed for more of such popular questions,

Does Java support multiple inheritances?
This is the trickiest question in Java if C++ can support direct multiple inheritances than why not Java is the argument Interviewer often give. Answer of this question is much more subtle then it looks like, because Java does support multiple inheritances of Type by allowing an interface to extend other interfaces, what Java doesn't support is multiple inheritances of implementation. This distinction also gets blur because of default method of Java 8, which now provides Java, multiple inheritances of behavior as well. See 
why multiple inheritances are not supported in Java to answer this tricky Java question.


What will happen if we put a key object in a HashMap which is already there?
This tricky Java question is part of another frequently asked question, How HashMap works in Java. HashMap is also a popular topic to create confusing and tricky question in Java. Answer of this question is if you put the same key again then it will replace the old mapping because HashMap doesn't allow duplicate keys. The Same key will result in the same hashcode and will end up at the same position in the bucket.

 Each bucket contains a linked list of Map.Entry object, which contains both Key and Value. Now Java will take the Key object from each entry and compare with this new key using equals() method, if that return true then value object in that entry will be replaced by new value. See How HashMap works in Java for more tricky Java questions from HashMap.



Question: What does the following Java program print?
public class Test {
    public static void main(String[] args) throws Exception {
        char[] chars = new char[] {'\u0097'};
        String str = new String(chars);
        byte[] bytes = str.getBytes();
        System.out.println(Arrays.toString(bytes));
    }
}

Answer: The trickiness of this question lies on character encoding and how String to byte array conversion works. In this program, we are first creating a String from a character array, which just has one character 
'\u0097', after that we are getting the byte array from that String and printing that byte. Since \u0097 is within the 8-bit range of byte primitive type, it is reasonable to guess that the str.getBytes() call will return a byte array that contains one element with a value of -105 ((byte) 0x97).

However, that's not what the program prints and that's why this question is tricky. As a matter of fact, the output of the program is operating system and locale dependent. On a Windows XP with the US locale, the above program prints [63], if you run this program on Linux or Solaris, you will get different values.

To answer this question correctly, you need to know about how Unicode characters are represented in Java char values and in Java strings, and what role character encoding plays in 
String.getBytes().

In simple word, t
o convert a string to a byte array, Java iterate through all the characters that the string represents and turn each one into a number of bytes and finally put the bytes together. The rule that maps each Unicode character into a byte array is called a character encoding. So It's possible that if same character encoding is not used during both encoding and decoding then retrieved value may not be correct. When we call str.getBytes() without specifying a character encoding scheme, the JVM uses the default character encoding of the platform to do the job.

The default encoding scheme is operating system and locale dependent. On Linux, it is 
UTF-8 and on Windows with a US locale, the default encoding is Cp1252. This explains the output we get from running this program on Windows machines with a US locale. No matter which character encoding scheme is used, Java will always translate Unicode characters not recognized by the encoding to 63, which represents the character U+003F (the question mark, ?) in all encodings.


If a method throws NullPointerException in the superclass, can we override it with a method which throws RuntimeException?
One more tricky Java questions from the overloading and overriding concept. The answer is you can very well throw superclass of RuntimeException in overridden method, but you can not do same if its checked Exception. See 
Rules of method overriding in Java for more details.


What is the issue with following implementation of compareTo() method in Java
public int compareTo(Object o){
   Employee emp = (Employee) o;
   return this.id - e.id;
}
where an id is an integer number.
Well, three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can't guarantee that id is positive or negative. the tricky part is, If id becomes negative than subtraction may overflow and produce an incorrect result. See How to override compareTo method in Java for the complete answer of this Java tricky question for an experienced programmer.



How do you ensure that N thread can access N resources without deadlock?
If you are not well versed in writing multi-threading code then this is a real tricky question for you. This Java question can be tricky even for the experienced and senior programmer, who are not really exposed to deadlock and race conditions. The key point here is ordering, if you acquire resources in a particular order and release resources in the reverse order you can prevent deadlock. See 
how to avoid deadlock in Java for a sample code example.



Question: Consider the following Java code snippet, which is initializing two variables and both are not volatile, and two threads T1 and T2 are modifying these values as following, both are not synchronized
int x = 0;
boolean bExit = false;

Thread 1 (not synchronized)
x = 1;
bExit = true;

Thread 2 (not synchronized)
if (bExit == true)
System.out.println("x=" + x);
Now tell us, is it possible for Thread 2 to print “x=0”?

Answer: It's impossible for a list of tricky Java questions to not contain anything from multi-threading. This is the simplest one I can get. Answer of this question is Yes, It's possible that thread T2 may print x=0.Why? because without any instruction to compiler e.g. synchronized or volatile, 
bExit=true might come before x=1 in compiler reordering. Also, x=1 might not become visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it?

 When I asked this question to a couple of programmers they answer differently, one suggests to make both threads synchronized on a common mutex, another one said make both variable volatile. Both are correct, as it will prevent reordering and guarantee visibility.

But the best answer is you just need to make 
bExit as volatile, then Thread 2 can only print “x=1”. x does not need to be volatile because x cannot be reordered to come after bExit=true when bExit is volatile.

What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced from Java 5. The main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken, but you can not reuse CountDownLatch in Java. See 
CyclicBarrier vs CountDownLatch in Java for more differences.


What is the difference between StringBuffer and StringBuilder in Java?

Classic Java questions which some people think tricky and some consider very easy. StringBuilder in Java was introduced in JDK 1.5 and the only difference between both of them is that StringBuffer methods e.g. length(), capacity() or append() are 
synchronized while corresponding methods in StringBuilder are not synchronized.

Because of this fundamental difference, concatenation of String using StringBuilder is faster than StringBuffer. Actually, it's considered the bad practice to use StringBuffer anymore, because, in almost 99% scenario, you perform string concatenation on the same thread. See 
StringBuilder vs StringBuffer for more differences.


Can you access a non-static variable in the static context?
Another tricky Java question from Java fundamentals. No, you can not access a non-static variable from the static context in Java. If you try, it will give compile time error. This is actually a common problem beginner in Java face when they try to access instance variable inside the main method. Because main is static in Java, and instance variables are non-static, you can not access instance variable inside main. See, 
why you can not access a non-static variable from static method to learn more about this tricky Java questions.

Bhanu Namikaze

Author & Editor

Bhanu Namikaze is an Ethical Hacker, Passionate Blogger, Web Developer, Student and Mechanical Engineer. He Enjoys writing articles, Blogging, Solving Errors, Surfing and Social Networking. Feel Free To Contact Me @ Bhanu.

0 comments:

Post a Comment

Popular Posts

Copyrights @ Interview Questions.Me - Blogger Templates Designed by Templateism - Distributed By Protemplateslab

  • (91) 5544 654942
  • Bhanu@HackingDream.net
  • Interview Questions

Copyrights @ Interview Questions.Me -A Site By Bhanu In Association With Hacking Dream