Monday, February 8, 2010

Common Interview Questions

1)    Is JVM a compiler or an interpreter? - Interpreter

2)    What is reflection?
    - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.

3)    What is the finalize method do?
     - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.

4)    What is garbage collection? What is the process that is responsible for doing that in java?
     - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process

5)    What kind of thread is the Garbage collector thread?
     - It is a daemon thread.

6)    What is the final keyword denotes?
     - final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.

7)    What is the major difference between LinkedList and ArrayList?
     - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.

8)    What is nested class?
     - If all the methods of a inner class is static then it is a nested class.

9)    What is inner class?
     - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.

10) What is composition?
     - Holding the reference of the other class within some other class is known as composition.

11) What is aggregation?
     - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.

12) What is the basic difference between the 2 approaches to exception handling.
1.try catch block and
2. specifying the candidate exceptions in the throws clause?
     
      In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

13) Is it necessary that each try block must be followed by a catch block?
              
            It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

14) If I write return at the end of the try block, will the finally block still execute?

Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.



15)  If I write System.exit (0); at the end of the try block, will the finally block still execute?
 
No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

Java Interview Questions

1. What is the diff b/w Mutable and Immutable? Where do you use them?

 

If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)

 

2. What is the diff b/w Composition and Aggregation?(UML Related Question)

 

Both aggregation and composition are special kinds of associations. Aggregation is used to represent ownership or a whole/part relationship, and composition is used to represent an even stronger form of ownership. With composition, we get coincident lifetime of part with the whole. The composite object has sole responsibility for the disposition of its parts in terms of creation and destruction. In implementation terms, the composite is responsible for memory allocation and deallocation.

 

Moreover, the multiplicity of the aggregate end may not exceed one; i.e., it is unshared. An object may be part of only one composite at a time. If the composite is destroyed, it must either destroy all its parts or else give responsibility for them to some other object. A composite object can be designed with the knowledge that no other object will destroy its parts.

 

Composition can be used to model by-value aggregation, which is semantically equivalent to an attribute. In fact, composition was originally called aggregation-by-value in an earlier UML draft, with “normal” aggregation being thought of as aggregation-by-reference. The definitions have changed slightly, but the general ideas still apply. The distinction between aggregation and composition is more of a design concept and is not usually relevant during analysis.

 

Finally, a word of warning on terminology. While UML uses the terms association, aggregation, and composition with specific meanings, some object-oriented authors use one or more of these terms with slightly different interpretations. For example, it is fairly common to see all three UML relationships grouped under a single term, say composition, and then to discuss object-oriented relationships as being either inheritance (generalization) or composition.

 

Major Difference:

Aggregation - Without whole part can exist.
Composition - Without whole part can't exit.

Aggregation -
One class is a kind of another class.
Composition - One class has another class

Aggregation - In Design If you remove whole part can exist (BUT In Code No diff.).
Composition - In Design If you remove whole part can also be removed automatically (in RSA) (BUT In code no diff).

 

3. What are the Key Diff b/w JDk 1.5 and JDk 1.6 ? What are the new things added in JDK 1.6?

 

Java 1.6 was released to overcome a few shortcomings and provide enhanced features when compared to Java 1.5

Details of 1.6 are mentioned below.

Advantages to running applications on Java SE 6

  • Applications run faster on the desktop and servers
  • New 'Dynamic Attach' diagnostics simplify troubleshooting
  • Expanded Solaris DTrace support provides additional value on Solaris
  • Improved 'native' look and feel across Solaris, Linux, and Windows
  • First Java platform with full support for Windows Vista

Benefits in upgrading developer environments to Sun's Java SE 6

  • JavaScript integrated and included with the platform
  • Scripting languages framework extends support for Ruby, Python, and other languages
  • Complete light-weight platform for web services, right out of the box
  • Simplified GUI design and expanded native platform support
  • Full JDBC4 implementation providing improved XML support for Databases
  • Java DB included with the JDK, a free to use and deploy Java Database
  • Full support by NetBeans IDE 5.5
  • Sun Developer Services available to help build more robust applications

Diff b/w JDk 1.4 and JDk 1.5?

 

Below are the major enhancement for JDK 1.5 version

Language Features
1. Generics
2. Enhanced for loop
3. Autoboxing/Unboxing
4.Type Safe Enums
5. Varargs
6. Static import
7. Annotations

 

J2SE 5.0 tiger [originally numbered 1.5]
- Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion).
- Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities.
- Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as integer).
- Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern).
- Swing: new skinnable look and feel, called synth.
- Var args: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string... Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.
- Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any iterable, such as the standard collection classesfix the previously broken semantics of the java memory model, which defines how threads interact through memory.
- Automatic stub generation for rmi objects.
- Static imports concurrency utilities in package java.util.concurrent.
- Scanner class for parsing data from various input streams and buffers.
- Assertions
- StringBuilder class (in java.lang package)
- Annotations

 

4. What is the Concept of Multiple Threading?

 

Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system.

 

5. What are different thread States?

  • New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
         
  • Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 
         
  • Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
         
  • Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
  • Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

6. How would you allocate priorities for different Threads?

 

In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads . Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.  

Priorities are integer values from 1 (lowest priority given by the constant Thread.MIN_PRIORITY) to 10 (highest priority given by the constant Thread.MAX_PRIORITY). The default priority is 5(Thread.NORM_PRIORITY).  

 

 Constant

 Description

 Thread.MIN_PRIORITY

 The maximum priority of any thread (an int value of 10)

 Thread.MAX_PRIORITY

 The minimum priority of any thread (an int value of 1)

 Thread.NORM_PRIORITY

 The normal priority of any thread (an int value of 5)


 The methods that are used to set the priority of thread shown as:

 

 Method

 Description

 setPriority() 

This is method is used to set the priority of thread.  

 getPriority() 

This method is used to get the priority of thread.

 

When a Java thread is created, it inherits its priority from the thread that created it.  At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution.

In Java runtime system, preemptive scheduling algorithm is applied. If at the execution time a thread with a higher priority and all other threads are runnable then the runtime system chooses the new higher priority thread for execution. On the other hand, if two threads of the same priority are waiting  to be executed by the CPU then the round-robin algorithm is applied in which the scheduler chooses one of them to run according to their round of time-slice.

Thread Scheduler

In the implementation of threading scheduler usually applies one of the two following strategies:

  • Preemptive scheduling – If the new thread has a higher priority then current running thread leaves the runnable state and higher priority thread enter to the runnable state.
       
  • Time-Sliced (Round-Robin) Scheduling – A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.

 

7. What is the diff b/w HashMap and HashSet? What is the Structural difference b/w them?

 

A HashMap provides fast access to a mapping from a unique key to a value.  Keys are  unordered, which makes it faster than the TreeMap, where the keys are ordered. 

A HashSet is fast access to unique values only (there are no keys because it is not a mapping, it's just the values).  HashSet values are unordered, which makes it faster than the TreeSet, where the values are ordered.
HashMap class implements Map interface where as HashSet class implements Set interface.

when to use a HashMap and when a HashSet.

 

When you have a set of items to store you would use the HashSet.
When you need to store a number of key-value pairs then you would use HashMap.

 

8. Can you have private variables in Interface?

 

An interface is a a set of abstract methods.We can declare a method but we cant provide any implementation to the methods in the interface.

Interface has to be implemented by some one else. whatever the variables you define in the interface are public by default and methods are public and abstract.

 

If we use private for an instance varible, and provide a class implementing this interface, we will get a exception, because of Private variable. So we can’t have private access modifiers inside an interface.

 

What is Abstract Class ? Do you use "abstract" Keyword for methods in the interface?

 

Abstract will specify a method which is not implemented in an abstract base class, and that must be implemented in a concrete subclass.

 

 

So, Methods declared in interfaces are by default both public and abstract.

Yet, one could:

public interface myInterface{ 
     public abstract void myMethod(); 
} 
All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods 
(it could be—it's just not necessary).
Key Points Of Abstract Class :
we cannot creat object of abstract class.
we cannot create constructor of abstract class.

************* 9. In which context you use Interface and in which context you use Abstract Class?

 

The general rule is if you are creating something that provides common functionality to unrelated classes, use an interface.

If you are creating something for objects that are closely related in a hierarchy, use an abstract class.

 

1)  When u want to inherit the properties of base class only (not other resources) go for Abstract class.
 When u want to inherit the properties of base class and other resources go for Interfaces.

 

2) abstract class is used if you are willing to restrict the creation of an instance.
interface is used if you are willing to write different functionalities in different implementations.

 

3) Abstract provides both methods with and without body. Adding new methods in abstract class in middle of development life cycle won't break existing sub classes. unless these methods are declared as mustoverride. If there are frequent addition of new methods properties and so on. one should use abstract..

Whereas on the other hand interface can fill gap of multiple inheritance. One can implement from more than one interface. Not same with Abstract. One can inherit from only one abstract class.

 

4) abstract classes are designed with implemantion gaps for sub-class to fill in.

interfaces are sintacticlly similar to classes but they lack insance variables & methods.

abstract classes can also have both abstract methods & non-abstract methods. where as in interface methods are abstract only & variables are implicitly static & final.

 

10. Can interface have Inner Class? yes, Interface can have inner class

 

Yes.

        public interface abc
        {
               static int i=0; void dd();
               class a1
               {
                       a1()
                       {
                               int j;
                               System.out.println("inside");
                       };
                       public static void main(String a1[])
                       {
                               System.out.println("in interfia");
                       }
               }
        }

11. What is deployment descriptor?

 

A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.

 

12. How will you set the Session Timeout in 10min. if there is no active client for 10min?

 

to set session time out from a servlet

request.getSession().setMaxInactiveInterval(int seconds)

 

In a JSP Page : session.setMaxInactiveInterval(600);  <!------enter the interval in milliseconds----->

 

The other way is to define session timeout in web.xml as follows:

 

<session-config>
<session-timeout>10</session-timeout>    <!----- 10 minutes -------->
</session-config>

 

13. What are filters?

 

 A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.

 

Filters can be used to transform the response from a servlet or a JSP page. A common task for the web application is to format data sent back to the client. Increasingly the clients require formats (for example, WML) other than just HTML. To accommodate these clients, there is usually a strong component of transformation or filtering in a fully featured web application. Many servlet and JSP containers have introduced proprietary filter mechanisms, resulting in a gain for the developer that deploys on that container, but reducing the reusability of such code. With the introduction of filters as part of the Java Servlet specification, developers now have the opportunity to write reusable transformation components that are portable across containers.

Filters can perform many different types of functions. We'll discuss examples of the italicized items in this paper:

 

  • Authentication-Blocking requests based on user identity.
  • Logging and auditing-Tracking users of a web application.
  • Image conversion-Scaling maps, and so on.
  • Data compression-Making downloads smaller.
  • Localization-Targeting the request and response to a particular locale.
  • XSL/T transformations of XML content-Targeting web application responses to more that one type of client.

 

14. What is JAXP?

JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.

 

15. What is UML Modeling?

 

The Unified Modeling Language (UML) is used to specify, visualize, modify, construct and document the artifacts of an object-oriented software intensive system under development.[1] UML offers a standard way to visualize a system's architectural blueprints, including elements such as:

 

actors
business processes
(logical) components
activities
programming language statements
database schemas, and
reusable software components.

 

UML combines best techniques from data modeling (entity relationship diagrams), business modeling (work flows), object modeling, and component modeling. It can be used with all processes, throughout the software development life cycle, and across different implementation technologies.

 

16. What is a Sequence Diagram?

 

Sequence diagram: shows how objects communicate with each other in terms of a sequence of messages. Also indicates the lifespans of objects relative to those messages.

 

File:Sequenz diagramm-1.png

 

17. What is WSDL file?

 

WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information.

WSDL (Web Services Description Language) is an XML-based language for describing Web services and how to access them.

 

18. What should you provide for a Client to consume a Web Service? What is the input to consume a Web Service?

        WSDL file.

 

19. What is a Templete?

 

To minimize the impact of layout changes, we need a mechanism for including layout in addition to content; that way, both layout and content can vary without modifying files that use them. That mechanism is JSP templates.

 

Template mechanism for JavaServer Pages (JSP) is that, like layout managers, encapsulates layout so it can be reused instead of replicated.

 

20. What is the concept of XSLT? What is the Key aspect of XSLT? What are the rules that you need to follow?

 

  • XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents.
  • XSLT stands for XSL Transformations.XSLT is the most important part of XSL.
  • XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.
  • XSLT uses XPath to find information in an XML document. XPath is used to navigate through elements and attributes in XML documents.
  • In the transformation process, XSLT uses XPath to define parts of the source document that should match one or more predefined templates. When a match is found, XSLT will transform the matching part of the source document into the result document.

Database Questions

 

21. If you define a Primary key, do you need to define index for that?

 Ans : No

  • Rows in a base table are uniquely identified by the value of the primary key defined for the table. The primary key for a table is composed of the values of one or more columns.
  • Primary keys are automatically indexed to facilitate effective information retrieval.
  • The primary key index is the most effective access path for the table.
  • Other columns or combinations of columns may be defined as a secondary index to improve performance in data retrieval. Secondary indexes are defined on a table after it has been created (using the CREATE INDEX statement).
  • An example of when a secondary index may be useful is when a search is regularly performed on a non-keyed column in a table with many rows, defining an index on the column may speed up the search. The search result is not affected by the index but the speed of the search is optimized.
  • It should be noted, however, that indexes create an overhead for update, delete and insert operations because the index must also be updated.
  • Indexes are internal structures which cannot be explicitly accessed by the user once created. An index will be used if the internal query optimization process determines it will improve the efficiency of a search.
  • SQL queries are automatically optimized when they are internally prepared for execution. The optimization process determines the most effective way to execute each query, which may or may not involve using an applicable index.

22. What is Outer Join and Inner Join?

 

INNER JOIN : It returns all rows from both tables where there is a match. ie. in the resulting table all the rows and colums will have values.

OUTER JOIN : The resulting table may have empty colums. Outer join may be either LEFT or RIGHT

 

OUTER JOINS, (LEFT, RIGHT, FULL)
If a set is a subset of another or both contain subsets of each other then an outer join can provide which members are in both or in only ony table.

A Left outer join will combine all results of the first set (left) with the matching results of the second set and assign nulls where there is no matching member from the second (right) set.

A Right outer join is the opposite and combines all results from the right and the matching ones from the left.

A Full outer join is the equivalent of a union of left and right joins where it will create a resulting set which might have some members with information from the left set, some with information from the right set and some with both.

 

23. What is Delete and Truncate commands?

 

 Delete table is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow.

• Truncate table also deletes all the rows in a table, but it won’t log the deletion of each row, instead it logs the de-allocation of the data pages of the table, which makes it faster. Of course, truncate table cannot be rolled back.

• Truncate table is functionally identical to delete statement with no “where clause” both remove all rows in the table. But truncate table is faster and uses fewer system and transaction log resources than delete.

• Truncate table removes all rows from a table, but the table structure and its columns, constraints, indexes etc., remains as it is.

• In truncate table the counter used by an identity column for new rows is reset to the seed for the column.

• If you want to retain the identity counter, use delete statement instead.

• If you want to remove table definition and its data, use the drop table statement.

• You cannot use truncate table on a table referenced by a foreign key constraint; instead, use delete statement without a where clause. Because truncate table is not logged, it cannot activate a trigger.

• Truncate table may not be used on tables participating in an indexed view.

 

24. What is a Deadlock?

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

 

A simple deadlock situation is one in which a two threads are waiting. Each thread waiting for a resource which is held by the other waiting thread. [In Java, this resource is usually the object lock obtained by the synchronized keyword.]

 

25. What is a Transaction?

 

One or more SQL statements that mark the completion of a task is called a transaction.
It is a operation on
database / table. which has to be confirmed after completion. It may be single sql stm or multiple stm

 

Transaction is a set of DML statements end up once a commit or rollback statements are encountered

 

26. What are Transaction Isolation Levels? What is their Significance?

 

In case of multiple transactions running in server container or within server transaction context/boundary, special care is to be taken on database side as Database is a shared resource, across multiple transactions.

 

So Isolation level is related to how transactions are isolated from data store/database.

 

Four types of isolation levels as follows:
1. TRANSACTION_READ_COMMITTED

2. TRANSACTION_READ_UNCOMMITTED

3. TRANSACTION_REPEATABLE_READ

4. TRANSACTION_SERIALIZABLE

 

27. What are Creational Patterns?

All the creational patterns define the best possible way in which an object can be instantiated. These describes the best way to CREATE object instances.

 

There are five types of Creational Patterns.
1. Factory Pattern
2. Abstract Factory Pattern
3. Builder Pattern
4. Prototype Pattern
5. Singleton Pattern

 

28. What are the design patterns you have worked?

29. Have you used ANT ? Did you write build Scripts?

30. Did you used hibernate for DAO Pattern?

31. What is the diff b/w Struts 1 and Struts 2?