Monday, September 27, 2010

Java Interview Questions and Answers - 2

Q 11. Can there be an abstract class with no abstract methodsin it? (Core Java)
Answer
Yes

Q 12. Can an Interface be final? (Core Java)
Answer
No

Q 13. Can an Interface have an inner class? (Core Java)
Answer
Yes.
public interface abc {
static int i=0;
void dd();
class a1 {
a1() {
int j;
System.out.println("in interfia");
};
public static void main(String a1[]) {
System.out.println("in interfia"); } } }

Q 14. Can we define private and protected modifiers for variables in interfaces? (Core Java)
Answer
No
Q 15. What is the query used to display all tables names in SQL Server (Query analyzer)? JDBC)
Answer
select * from information_schema.tables

Q 16. What is Externalizable? (Core Java)
Answer Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Q 17. What modifiers are allowed for methods in an Interface? (Core Java)
Answer
Only public and abstract modifiers are allowed for methods in interfaces.

Q 18. What is a local, member and a class variable? (Core Java)
Answer
Variables declared within a method are "local" variables. Variables declared within the class i.e not within any methods are "member" variables (global variables).

Variables declared within the class i.e not within any methods and are defined as "static" are class variables

Q 19. How many types of JDBC Drivers are present and what are they? (JDBC)
Answer There are 4 types of JDBC Drivers
Type 1: JDBC-ODBC Bridge Driver
Type 2: Native API Partly Java Driver
Type 3: Network protocol Driver
Type 4: JDBC Net pure Java Driver

Q 20. What is the difference between ServletContext and PageContext? (JSP)
Answer
ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

Java Interview Questions and answers - 1

Q 01: Give a few reasons for using Java



  • Ans 01: Java is a fun language. Let’s look at some of the reasons:
    Built-in support for multi-threading, socket communication, and memory management (automatic garbage collection).

  • Object Oriented (OO).

  • Better portability than other languages across operating systems.
    Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, MI. EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardised APIs (Application Program Interfaces).



Q 02: What is the main difference between the Java platform and the other software platforms?



Ans 02: Java platform is a software-only platform, which runs on top of other hardware-based platforms like UNIX, NT etc.




The Java platform has 2 components:

  • Java Virtual Machine (JVM) – ‘JVM’ is a software that can be ported onto various hardware platforms. Byte codes are the machine language of the JVM.
  • Java Application Programming Interface (Java API) -


Q 03: What is the difference between C++ and Java?

Ans 03: Both C++ and Java use similar syntax and are Object Oriented, but:

  • Java does not support pointers. Pointers are inherently tricky to use and troublesome.
  • Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface inheritance, which allows an object to inherit many method signatures from different interfaces with the condition that the inheriting object must implement those inherited methods. The
    multiple interface inheritance also allows an object to behave polymorphically on those methods.
  • Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means you do not know when the objects are going to be finalized. Avoid using finalize() method to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to
    release these resources through the finalize() method.
  • Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework (Java collection framework – Refer Q14, Q15 in Java section).
  • All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions.
  • C++ requires explicit memory management, while Java includes automatic garbage collection.

Q 04: Explain Java class loaders? Explain dynamic class loading?

Ans 04: Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one
class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader.


Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.
Important: Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton.


Q 05: What are the advantages of Object Oriented Programming Languages (OOPL)?

Ans 05: The Object Oriented Programming Languages directly represent the real life objects like Car, Jeep, Account, Customer etc. The features of the OO programming languages like polymorphism, inheritance and encapsulation make it powerful. [Tip: remember pie which, stands for Polymorphism, Inheritance and Encapsulation are the 3 pillars of OOPL]

Q 06: How does the Object Oriented approach improve software development?

Ans 06: The key benefits are:

  • Re-use of previous work: using implementation inheritance and object composition.
  • Real mapping to the problem domain: Objects map to real world and represent vehicles, customers, products etc: with encapsulation.
  • Modular Architecture: Objects, systems, frameworks etc are the building blocks of larger systems.

The increased quality and reduced development time are the by-products of the key benefits discussed above. If 90% of the new application consists of proven existing components then only the remaining 10% of the code have to be tested from scratch.

Q 07: How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition? What is the difference between composition and aggregation?

Ans 07: The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.


Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.
Which one to use? The guide is that inheritance should be only used when subclass ‘is a’ superclass.

  • Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse. Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the superclass is modified.
  • Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code .


Q 08: What do you mean by polymorphism, inheritance, encapsulation, and dynamic binding?

A ns08: Polymorphism – means the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. In a nutshell, polymorphism is a bottom-up method call. The benefit of polymorphism is that it is very easy to add new classes of derived objects without breaking the calling code (i.e. getTotArea() in the sample code shown below) that uses the polymorphic classes or interfaces. When you send a message to an object even though you don’t know what specific type it is, and the right thing happens, that’s called polymorphism. The process used by objectoriented programming languages to implement polymorphism is called dynamic binding. Let us look at some sample code to demonstrate polymorphism


Inheritance – is the inclusion of behaviour (i.e. methods) and state (i.e. variables) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for code reuse. Any shared piece of business logic can be moved from the derived class into the base class as part of refactoring process to improve maintainability of your code by avoiding code duplication. The existing class is called the superclass and the derived class is called the subclass. Inheritance can also be
defined as the process whereby one object acquires characteristics from one or more other objects the same way children acquire characteristics from their parents.


Encapsulation – refers to keeping all the related members (variables and methods) together in an object. Specifying members as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way, which in turn makes future development and refactoring efforts easy.

Being able to encapsulate members of a class is important for security and integrity. We can protect variables from unacceptable values. The sample code below describes how encapsulation can be used to protect the MyMarks object from having negative values. Any modification to member variable “vmarks” can only be carried out through the setter method setMarks(int mark). This prevents the object “MyMarks” from having any negative values by throwing an exception.


Q 09: Why there are some interfaces with no defined methods (i.e. marker interfaces) in Java?

Ans 09: The interfaces with no defined methods act like markers. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently. Example Serializable


Q 10: When is a method said to be overloaded and when is a method said to be overridden?

Ans 10:
Method Overloading

Overloading deals with multiple methods in the same class with the same name but different method signatures.
class MyClass {
public void getInvestAmount(int rate) {…}
public void getInvestAmount(int rate, long principal)
{ … }
}
Both the above methods have the same method names but different method signatures, which mean the methods are overloaded.
Overloading lets you define the same operation in different ways for different data.
Method Overriding

Overriding deals with two methods, one in the parent class andthe other one in the child class and has the same name andsignatures.

class BaseClass{

public void getInvestAmount(int rate) {…}

}

class MyClass extends BaseClass {

public void getInvestAmount(int rate) { …}

}

Both the above methods have the same method names andthe signatures but the method in the subclass MyClassoverrides the method in the superclass BaseClass.

Overriding lets you define the same operation in differentways for different object types.