Java Interview Questions

January 18, 2012

Collections

  1. What is Java Collections API?

Java Collections framework API is a unified architecture for representing and manipulating collections. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming. In nutshell, this API does 6 things at high level

    • Reduces programming efforts. – Increases program speed and quality.
    • Allows interoperability among unrelated APIs.
    • Reduces effort to learn and to use new APIs.
    • Reduces effort to design new APIs.
    • Encourages & Fosters software reuse.

To be specific, There are six collection java interfaces. The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and SortedMap, do not extend Collection, as they represent mappings rather than true collections.

  1. What is an Iterator?

Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

  1. What is the difference between java.util.Iterator and java.util.ListIterator?

Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

  1. What is HashMap and Map?

Map is Interface which is part of Java collections framework. This is to store Key Value pair, and Hashmap is class that implements that using hashing technique.

  1. Difference between HashMap and HashTable? Compare Hashtable vs HashMap?

Both Hashtable & HashMap provide key-value access to data. The Hashtable is one of the original collection classes in Java (also called as legacy classes). HashMap is part of the new Collections Framework, added with Java 2, v1.2. There are several differences between HashMap and Hashtable in Java as listed below

    • The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
    • HashMap does not guarantee that the order of the map will remain constant over time. But one of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable.
    • HashMap is non synchronized whereas Hashtable is synchronized.
    • Iterator in the HashMap is fail-fast while the enumerator for the Hashtable isn’t. So this could be a design consideration.
  1. What does synchronized means in Hashtable context?

Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

  1. What is fail-fast property?

At high level – Fail-fast is a property of a system or software with respect to its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process.

When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: “failing immediately and visibly” sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production.

In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.

  1. Why doesn’t Collection extend Cloneable and Serializable?

From Sun FAQ Page: Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that’s backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable. If the client doesn’t know the actual type of a Collection, it’s much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one. Note on Some Important Terms

    • Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
    • Fail-fast is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.
  1. How can we make Hashmap synchronized?

HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);

  1. Where will you use Hashtable and where will you use HashMap?

There are multiple aspects to this decision: 1. The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one. 2. If there is a possibility in future that – there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in terms of possible future changes.

  1. Difference between Vector and ArrayList? What is the Vector class?

Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Both the classes are member of Java collection framework, therefore from an API perspective, these two classes are very similar. However, there are still some major differences between the two. Below are some key differences

    • Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2
    • Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.
    • ArrayList has no default size while vector has a default size of 10.
    • The Enumerations returned by Vector’s elements method are not fail-fast. Whereas ArraayList does not have any method returning Enumerations.
  1. What is the Difference between Enumeration and Iterator interface?

Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:

    1. Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove().
    2. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration interface does not support this feature.
    3. Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.
  1. Why Java Vector class is considered obsolete or unofficially deprecated? or Why should I always use ArrayList over Vector?

You should use ArrayList over Vector because you should default to non-synchronized access. Vector synchronizes each individual method. That’s almost never what you want to do. Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don’t need to. It’s a very flawed approach to have synchronized access as default. You can always decorate a collection using Collections.synchronizedList – the fact that Vector combines both the “resized array” collection implementation with the “synchronize every operation” bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

Vector also has a few legacy methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don’t check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization – with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won’t be easy to replace it with a different List implementation.

Despite all above reasons Sun may never officially deprecate Vector class. (Read details Deprecate Hashtable and Vector)

  1. What is an enumeration?

An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

  1. What is the difference between Enumeration and Iterator?

The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.

  1. Where will you use Vector and where will you use ArrayList?

The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.

  1. What is the importance of hashCode() and equals() methods? How they are used in Java?

The java.lang.Object has two methods defined in it. They are – public boolean equals(Object obj) public int hashCode(). These two methods are used heavily when objects are stored in collections.

There is a contract between these two methods which should be kept in mind while overriding any of these methods.

The Java API documentation describes it in detail. The hashCode() method returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable or java.util.HashMap. The general contract of hashCode is:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. The equals(Object obj) method indicates whether some other object is “equal to” this one. The equals method implements an equivalence relation on non-null object references:

It is reflexive: for any non-null reference value x, x.equals(x) should return true.

It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

A practical Example of hashcode() & equals(): This can be applied to classes that need to be stored in Set collections. Sets use equals() to enforce non-duplicates, and HashSet uses hashCode() as a first-cut test for equality. Technically hashCode() isn’t necessary then since equals() will always be used in the end, but providing a meaningful hashCode() will improve performance for very large sets or objects that take a long time to compare using equals().

  1. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?

Many developers are concerned about the performance difference between java.util.Array.sort() java.util.Collections.sort() methods. Both methods have same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have a array available with you and you want to sort it.

  1. What is java.util.concurrent BlockingQueue? How it can be used?

Java has implementation of BlockingQueue available since Java 1.5. Blocking Queue interface extends collection interface, which provides you power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. An ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic “bounded buffer” (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked.

  1. Set & List interface extend Collection, so Why doesn’t Map interface extend Collection?

Though the Map interface is part of collections framework, it does not extend collection interface. This is by design, and the answer to this questions is best described in Sun’s FAQ Page: This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa). If a Map is a Collection, what are the elements? The only reasonable answer is “Key-value pairs”, but this provides a very limited (and not particularly useful) Map abstraction. You can’t ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to. Collection could be made to extend Map, but this raises the question: what are the keys? There’s no really satisfactory answer, and forcing one leads to an unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three “Collection view operations” on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That’s why we don’t have a map view operation on Lists.

  1. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?

a. Vector b. ArrayList c. LinkedList ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

  1. What is the difference between ArrayList and LinkedList? (ArrayList vs LinkedList.)

java.util.ArrayList and java.util.LinkedList are two Collections classes used for storing lists of object references Here are some key differences:

    • ArrayList uses primitive object array for storing objects whereas LinkedList is made up of a chain of nodes. Each node stores an element and the pointer to the next node. A singly linked list only has pointers to next. A doubly linked list has a pointer to the next and the previous element. This makes walking the list backward easier.
    • ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there’s no fast way to access the Nth element of the list.
    • Adding and deleting at the start and middle of the ArrayList is slow, because all the later elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.
    • Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers.
    • ArrayList may also have a performance issue when the internal array fills up. The arrayList has to create a new array and copy all the elements there. The ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer. Hence if we can guess the number of elements that we are going to have, then it makes sense to create a arraylist with that capacity during object creation (using construtor new ArrayList(capacity)). Whereas LinkedLists should not have such capacity issues.
  1. Where will you use ArrayList and Where will you use LinkedList? Or Which one to use when (ArrayList / LinkedList).

Below is a snippet from SUN’s site. The Java SDK contains 2 implementations of the List interface – ArrayList and LinkedList. If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList. But you pay a big price in performance. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList.

  1. What is performance of various Java collection implementations/algorithms? What is Big ‘O’ notation for each of them ?

Each java collection implementation class have different performance for different methods, which makes them suitable for different programming needs.

    • Performance of Map interface implementations

Hashtable

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

HashMap

This implementation provides constant-time [ Big O Notation is O(1) ] performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
Iteration over collection views requires time proportional to the “capacity” of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

TreeMap

The TreeMap implementation provides guaranteed log(n) [ Big O Notation is O(log N) ] time cost for the containsKey, get, put and remove operations.

LinkedHashMap

A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.

    • Performance of Set interface implementations

HashSet

The HashSet class offers constant-time [ Big O Notation is O(1) ] performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance’s size (the number of elements) plus the “capacity” of the backing HashMap instance (the number of buckets). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

TreeSet

The TreeSet implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

LinkedHashSet

A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.

    • Performance of List interface implementations

LinkedList

- Performance of get and remove methods is linear time [ Big O Notation is O(n) ] – Performance of add and Iterator.remove methods is constant-time [ Big O Notation is O(1) ]

ArrayList

- The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. [ Big O Notation is O(1) ]
- The add operation runs in amortized constant time [ Big O Notation is O(1) ] , but in worst case (since the array must be resized and copied) adding n elements requires linear time [ Big O Notation is O(n) ]
- Performance of remove method is linear time [ Big O Notation is O(n) ]
- All of the other operations run in linear time [ Big O Notation is O(n) ]. The constant factor is low compared to that for the LinkedList implementation.

Can you think of a questions which is not part of this post? Please don’t forget to share it with me in comments section & I will try to include it in the list.

February 13, 2010

Difference between web server and application server?

Filed under: Java Interview Questions — Sachin Kakkar @ 4:05 am
A Web server serves pages for viewing in a Web browser, while an application server provides methods that client applications can call.
The Web server
A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.
The application server
As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object (or a function in the procedural world).
Webserver is used only for jsp and servlets and for static functionality it has limited functionality and it doesn’t provide any security persistence and it doesn’t support EJB and JMS and JAAS like other functionality whereas Application server provide all functionalities
In simple words, Application Server = Web Server + EJB Container

Why can’t we make jsp as a controller and action servlet in struts?

Filed under: Uncategorized — Tags: , , , , , — Sachin Kakkar @ 3:09 am

When JSP compiles, internally the jsp compiler converts it to  servlets and compiles servlets java file and generartes the class file. Every time it will do the same thing, so it may take several time. It may cause performance issue.

Most of the applications are created in MVC design pattern to seperate the functions of differnetcomponents and handle the complexity of applications. JSP and Servlets are the server sidecomponents which can respond to the client request.

Servlets are the basic components for request handling in Web Server. They contains pure Java code. Everything that needs to be done to generate the proper user response (which is genarally HTML code) needs to be done through coding. As a single servlet cannot respond each and every request by itself as client request varies in type (e.g. enquiry, update request, add etc) the request and response object is passed onto different servlets with little task completed by each servlet. This controlling part is easier to write in java. So Servlet is used as controller.

JSP is again a servlet which has syntax more like to HTML with java support. Whatever user is going to see as result of his request is HTML. Programmer can easily write html tags inside JSP to render html. This is very economical to change also. So all this code is written JSP which is (generally) the final link in Servlet chaining.

In simple words, Controller (servlet) has pure Java code while View (JSP) has HTML code.

why string is immutable ?

Filed under: Java Interview Questions — Tags: , , , — Sachin Kakkar @ 3:00 am

In java, Strings are handling in Pool format.

For example:

String str1 = “xyz”;

This string(str1) will be stored into memory in particular address. When we defining new String with same array of characters like

String str2 = “xyz”;

Now JVM will check in String Pool where there is same characters are available or not. If two Strings are match the JVM will refer str1 address to str2. Now the str1 and str2 referring the same characters in same memory location. This is a good idea for increasing memory efficiency.

When we change the str1 characters, the changes will be reflected to str2. Because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.

Making String immutable, makes it thread safe and thus imporves performance.

Once a string object is created no changes can be made to it. If a string is modified in code a new object will be

created. That is why string is immutable.

February 9, 2010

What is the Difference between jar, ear and war?

Filed under: Java Interview Questions — Tags: , , , , , , , — Sachin Kakkar @ 3:21 pm

.jar files: These files are with the .jar extension. The .jar files contain the libraries, resources and accessories files like property files.

.war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, java script and other files for necessary for the development of web applications.

.ear files: WAR(Web module) + JAR(can be EJB module or application client module). An EAR(Enterprise archive) is a top-level container which contains modules like: EJB modules, web modules, application client modules etc.

January 12, 2010

What’s the difference between “JDK” and “JRE”?

Filed under: Uncategorized — Tags: , , , , , — Sachin Kakkar @ 7:56 am

The “JDK” is the Java Development Kit.the JDK is bundle of software that you can use to develop Java based software. The “JRE” is the Java Runtime Environment.the JRE is an implementation of the Java Virtual Machine which actually executes Java programs.

Each JDK contains one (or more) JRE’s along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.

JRE is a subset of JDK.

  • Two steps for a java program ie.,compile and interpret.
  • JDK does compilation but JRE can’t.
  • Both JRE and JDK does interpretaion.

JVM :

The use of the JVM : – To convert the byte code into the machine specific code. So the JVM converts the byte code(ie the code which we get when we compile the .java class) into the code that your machine/OS understands. JVM is machine specific. So JVM for windows will be different from JVM for Mac or Unix. JVM is one of the most crucial part in the java engine. It is due to JVM only that we say java code is “Compile Once, Run Anywhere” programming language.

The byte code generated when we compile the code will be the same doesn’t matter we compiled the code in Windows OS or some other. However JVM makes sure that the byte code should be interpreted properly in the OS under concerned so interpret the byte code differently for different OS.

January 11, 2010

RSA7 and Local WebSphere Test Environment Performance Tips

Filed under: RAD & Websphere — Tags: , , , , , — Sachin Kakkar @ 8:09 am
If you’re encountering slowness in either your RSA IDE or in the embedded WebSphere Test Environment, here several strategies that may help:
 
RSA7 Performance
  • In c:\Program Files\IBM\SDP70\jdk\bin run this: “java -Xshareclasses:destroyAll”.  This will delete a cache file in C:\Documents and Settings\<username>\Local Settings\Application Data\javasharedresources.
  • Run “C:\Program Files\IBM\SDP70>eclipse –clean”  This is supposed to clean up some other cached data.
  • Edit eclipse.ini (C:\Program Files\IBM\SDP70\eclipse.ini) to change the “-Xshareclasses:singleJVM,keep” line to “-Xshareclasses:none”
  • Edit eclipse.ini to have larger max heap (e.g. 768m), and set min heap equal to max.
  • Try increasing the MaxPermSize in eclipse.ini (e.g. 512M).
  • Update RSA7 to the latest fixpack.
  • Try disabling automatic build; use Ctrl-B instead.
  • If using JIBX, try removing the JIBX compiler from the  builder list and running manually when needed.
  • Try disabling the “AOP Reference Model Builder” builder if you’re using Spring IDE. 
WAS 6.1 Test Environment Performance
  • Update the WAS test env to the latest fixpack.
  • Verify that automatic publishing is turned off.
  • Restart applications via the “Restart” menu option instead of the “Publish” option on the application server.
  • Set the min / max heap for WAS JVM to same size and larger, like 768 or 1024
Both
  • Be aware that virus scan real time protection on most computers will significantly degrade disk IO.   Also be especially careful that no scheduled scan is currently running.
  • Also beware that laptops running PointSec full disk encryption can expect at least a 50% degradation in disk IO performance vs. a non-encrypted file system.
  • If you have at least 3GB of memory, try reducing paging file size to very low to minimize paging.

January 4, 2010

Servlet

Filed under: Java Interview Questions — Sachin Kakkar @ 11:29 am

What is the difference between GenericServlet and HttpServlet?

Ans: – GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets. Of course, it turns out that there’s no such thing as FTP servlets, but they were trying to plan for future growth when they designed the spec. Maybe some day there will be another subclass, but for now, always use HttpServlet.

In short GenericServlet is protocol independent, whereas HttpServlet is protocol dependent

In GenericServlets you cannot use Cookies or HttpSession.Session tracking is not possible, redirection is not possible.

Http servlets overrides doGet and doPost methods. Generic servlet overides service method.

1.generic servlet is superclass for HttpServlet.

2.httpservlet class can also have service() method.it’s not necessary that you can only have doGet() and doPost() method defined.

3.Generic servlet is used for small data transfer whereas HttpServlet is used for huge data transfer.

GenericServlet is might not used be for the http services and may be used for the FTP services , and it is protocol independant where as HttpServlet is Protocol dependant.HttpServlet is subclass to GenericServlet. GenericServlet extends java.lang.Object and implements servlet ,ServletConfig , Serializable interface.


January 4, 2009

Core Java Interview Questions

Filed under: Uncategorized — Tags: , , , , , , , — Sachin Kakkar @ 4:53 am

This site is developed for all IT people who work in the field of Java.

This site covers all Core Java, J2EE and Sql’s Frequently Asked Questions that are asked in most technical interviews.

Core Java Interview Questions:

  1. What is a class? A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
  2. What is an object? An object is a software bundle of variables and related methods. An instance of a class depicting the state and behavior at that particular time in real world.
  3. What is a method? Encapsulation of a functionality which can be called to perform specific tasks.
  4. What is encapsulation? Explain with an example. Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object
  5. What is inheritance? Explain with an example. Inheritance in object oriented programming means that a class of objects can inherit properties and methods from another class of objects.
  6. What is polymorphism? Explain with an example. In object-oriented programming, polymorphism refers to a programming language’s ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language
  7. Is multiple inheritances allowed in Java? No, multiple inheritance is not allowed in Java.
  8. What is interpreter and compiler? Java interpreter converts the high level language code into a intermediate form in Java called as byte code, and then executes it, where as a compiler converts the high level language code to machine language making it very hardware specific
  9. What is JVM? The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)
  10. What are the different types of modifiers? There are access modifiers and there are other identifiers. Access modifiers are public, protected and private. Other is final and static.
  11. What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly.
  12. What is a wrapper class? They are classes that wrap a primitive data type so it can be used as a object
  13. What is a static variable and static method? What’s the difference between two? The modifier static can be used with a variable and method. When declared as static variable, there is only one variable no matter how instances are created, this variable is initialized when the class is loaded. Static method do not need a class to be instantiated to be called, also a non static method cannot be called from static method.
  14. What is garbage collection? Garbage Collection is a thread that runs to reclaim the memory by destroying the objects that cannot be referenced anymore.
  15. What is abstract class? Abstract class is a class that needs to be extended and its methods implemented, aclass has to be declared abstract if it has one or more abstract methods.
  16. What is meant by final class, methods and variables? This modifier can be applied to class method and variable. When declared as final class the class cannot be extended. When declared as final variable, its value cannot be changed if is primitive value, if it is a reference to the object it will always refer to the same object, internal attributes of the object can be changed.
  17. What is interface? Interface is a contact that can be implemented by a class, it has method that need implementation.
  18. What is method overloading? Overloading is declaring multiple method with the same name, but with different argument list.
  19. What is method overriding? Overriding has same method name, identical arguments used in subclass.
  20. What is singleton class? Singleton class means that any given time only one instance of the class is present, in one JVM.
  21. What is the difference between an array and a vector? Number of elements in an array are fixed at the construction time, whereas the number of elements in vector can grow dynamically.
  22. What is a constructor? In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed.
  23. What is casting? Conversion of one type of data to another when appropriate. Casting makes explicitly converting of data.
  24. What is the difference between final, finally and finalize? The modifier final is used on class variable and methods to specify certain behavior explained above. And finally is used as one of the loop in the try catch blocks, It is used to hold code that needs to be executed whether or not the exception occurs in the try catch block. Java provides a method called finalize( ) that can be defined in the class. When the garbage collector is ready to release the storage ed for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the objects memory. So finalize( ), gives you the ability to perform some important cleanup at the time of garbage collection.
  25. What are are packages? A package is a collection of related classes and interfaces providing access protection and namespace management.
  26. What is a super class and how can you call a super class? When a class is extended that is derived from another class there is a relationship is created, the parent class is referred to as the super class by the derived class that is the child. The derived class can make a call to the super class using the keyword super. If used in the constructor of the derived class it has to be the first statement.
  27. What is meant by a Thread? Thread is defined as an instantiated parallel process of a given program.
  28. What is multi-threading? Multi-threading as the name suggest is the scenario where more than one threads are running.
  29. What are two ways of creating a thread? Which is the best way and why? Two ways of creating threads are, one can extend from the Java.lang.Thread and can implement the rum method or the run method of a different class can be called which implements the interface Runnable, and the then implement the run() method. The latter one is mostly used as first due to Java rule of only one class inheritance, with implementing the Runnable interface that problem is sorted out.
  30. What is deadlock? Deadlock is a situation when two threads are waiting on each other to release a resource. 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.
  31. What are the three types of priority? MAX_PRIORITY which is 10, MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.
  32. What is the use of synchronizations? Every object has a lock, when a synchronized keyword is used on a piece of code the, lock must be obtained by the thread first to execute that code, other threads will not be allowed to execute that piece of code till this lock is released.

33. How could Java classes direct program messages to the system console, but error messages, say to a file?


A. The class System has a variable out that represents the standard output, and the variable err that represent the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream(“output.txt”)); System.setErr(st); System.setOut(st);


34. What’s the difference between an interface and an abstract class?


A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.


35. Why would you use a synchronized block vs. synchronized method?


A. Synchronized blocks place locks for shorter periods than synchronized methods.


36. Explain the usage of the keyword transient?


A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

37. How can you force garbage collection?


A. You can’t force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.


38. How do you know if an explicit object casting is needed?


A. If you assign a super class object to a variable of a subclass’s data type, you need to do explicit casting. For example:

Object a; Customer b; b = (Customer) a;


When you assign a subclass to a variable having a sup class type, the casting is performed automatically.


39. What’s the difference between the methods sleep() and wait()


A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.


40. Can you write a Java class that could be used both as an applet as well as an application?


A. Yes. Add a main() method to the applet.


41. What’s the difference between constructors and other methods?


A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.


42. Can you call one constructor from another if a class has multiple constructors?


A. Yes. Use this() syntax.


43. Explain the usage of Java packages.


A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.


44. If a class is located in a package, what do you need to change in the OS environment to be able to use it?


A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let’s say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you’d need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:

c:\>java com.xyz.hr.Employee


45. What’s the difference between J2SDK 1.5 and J2SDK 5.0?


A. There’s no difference, Sun Microsystems just re-branded this version.

46. What would you use to compare two String variables – the operator == or the method equals()?


A. I’d use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

47. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?


A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception’s subclasses have to be caught first.


48. Can an inner class declared inside of a method access local variables of this method?


A. It’s possible if these variables are final.


49. What can go wrong if you replace && with & in the following code:

String a=null; if (a!=null && a.length()>10) {…}

A. A single ampersand here would lead to a NullPointerException.


50. What’s the main difference between a Vector and an ArrayList


A. Java Vector class is internally synchronized and ArrayList is not.

51. When should the method invokeLater()be used?


A. This method is used to ensure that Swing components are updated through the event-dispatching thread.

52 . How can a subclass call a method or a constructor defined in a super class?


A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass’s constructor.

53. What’s the difference between a queue and a stack?


A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

54. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?


A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

55. What comes to mind when you hear about a young generation in Java?


A. Garbage collection.

56. What comes to mind when someone mentions a shallow copy in Java?


A. Object cloning.

57. If you’re overriding the method equals() of an object, which other method you might also consider?


A. hashCode()

(more…)

January 24, 2007

Some Interview Questions on String.

Filed under: Uncategorized — Sachin Kakkar @ 5:23 am

Que:-1 Difference Between String and String Buffer?

Ans:- String is a Collection or array of Characters.when u create a string object u r creating a string that can’t be changed. this approach is used becoz fixed, immutable strings can be implemented more efficiently then the muttable (Changeable Ones ) strings.

StringBuffer – StringBuffer Represents growable and writeable character sequences.StringBuffer may have characters and substrings inserted in the middle or append to end.

StringBuffer allocates room for 16 additional Characters when no specific buffer length is requested, becoz reallocation is a costly process in terms of time.

Que:-2  difference between verses (==) and .equals().

Ans.  .equals() is used for comparing values of a string objects and verses ( ==) is used to compare there memory reference.

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.