Interview Blockers

Q:If class A has a method
public void foo throws Exception E, Exception F
class B extends A has the method
public void foo throws Exception E, Exception F, Exception G
Will the code compile?
A: No, an overriden method cannot throw more exceptions than the method in the parent class.

Q:If class A has a method
private void foo
class B extends A
has a method
public void foo
will the code compile?
A: Yes an overridden method can be made more accessible than the method in the parent class

Q:What is the difference between an include file directive and a jsp:include action?
A:The file included using the directive is included before the jsp is compiled while the file included using the action is included after the jsp is compiled. In other words include directive includes static content at compile time and action include includes static or dynamic content at run time.

Q:How will you avoid caching in JSP?

Q:What is the return type of ejbFindByPrimaryKey() in the entity bean class and the return type of findByPrimaryKey() in the Home interface of the entity bean
A: The bean class method will return a primarykey type while the home interface method will return a bean type

Q:How will you implement a custom taglib?
A: The class should extend TagSupport and implement doStartTag() or doEndTag() methods. Then write an xml file with tld extension to describe this class and declare the tld file in web.xml.

Q: How does java implement session tracking? What is the default mechanism used by java for session tracking?
A: Java implements Session tracking using cookies or url rewriting. The default mechanism is use of cookies. When cookies are disabled url rewriting is used.

Q: What is a DynaForm?
A: A struts form bean can be defined in struts-config.xml without explicitly writing a Java class for the form bean. This is called a DynaForm.

Q: Name any three top level interfaces in the Collection API?

What are the types of classloaders?

Bootstrap Class Loader – loads classes that are part of JRE. It’s a native implementation.

Extensions Class Loader – load classes that are part of JRE extensions in lib\ext folder.

Systems Class Loader – loads classes that are on the Java classpath.

Difference between ClassNotFoundException and NoClassDefFoundError
ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime. However, they occur at different scenarios.ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath. NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.NoClassDefFoundError is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

So if you have code like this…
public class Foo {
   public class methodA() {
       //lines of code
       pkg.Bar b = new pkg.Bar();
Now, let’s say you don’t have pkg.Bar class available during compile, you will obviously get a compile time error.
If you have the pkg.Bar class available during compile, that’s good.
However, if you don’t have it at runtime (e.g. you missed bundling it into the war file), then you will get a NoClassDefFoundError when you run the application.
Ok, now if you are using java reflection like this:
public class Foo{
   public class methodA() {
      //lines of code
Now, let’s say you don’t have pkg.Bar class available during compile time, you will not get a compile time error.  This is because you don’t have a hard reference. You are simply passing a string into that method.
If you don’t have it at runtime (e.g. you missed bundling it into the war file), then you will get a ClassNotFoundException when you run the application.

NoClassDefFoundError – available at compile time, missing at runtime, available at compile time; not loaded by class loader at runtime using Class.forName -> ClassNotFoundException.

What are the advantages of using enum?

Enums in Java 5+ are basically classes that have a predefined set of instances. They are intended as a replacement for, say, a collection of integer constants. They are preferably to constants as they can enforce type safety. The advantages are:
1. Type safety. You can declare a function argument, return type, class member or local variable to be a particular Enum type and the compiler will enforce type safety; Enums are basically classes.
2. They can implement interfaces, have behavior and so on.

Why do we need Servlet Filter?
We can manage session in web application and if we want to make sure that a resource is accessible only when user session is valid, we can achieve this using servlet session attributes. The approach is simple but if we have a lot of servlets and jsps, then it will become hard to maintain because of redundant code. If we want to change the attribute name in future, we will have to change all the places where we have session authentication.
That’s why we have servlet filter. Servlet Filters are pluggable java components that we can use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.
Some common tasks that we can do with servlet filters are:
a. Logging request parameters to log files.
b. Authentication and autherization of request for resources.
c. Formatting of request body or header before sending it to servlet.
d. Compressing the response data sent to the client.
e. Alter response by adding some cookies, header information etc.
f. Servlet filters are pluggable and configured in deployment descriptor (web.xml) file. g. Servlets and filters both are unaware of each other and we can add or remove a servlet filter just by editing web.xml.
h. We can have multiple filters for a single resource and we can create a chain of filters for a single resource in web.xml
How do you implement java hash code correctly?
Computing hash codes is something like compressing equality to an integer value: Equal objects must have the same hash code and for performance reasons it is best if as few non-equal objects as possible share the same hash. This means that hashCode must always be overridden if equals is. Only one thing we should care about: Equal objects should have the same hash code.
When implementing hashCode:

1. Use a the same fields that are used in equals (or a subset thereof).
2. Better not include mutable fields.
3. Consider not calling hashCode on collections.
4. Use a common algorithm unless patterns in input data counteract them.
5. Remember that hashCode is about performance, so don’t waste too much energy unless profiling indicates necessity.

This is how hashCode works: Instances with the same hash code are not necessarily equal but equal instances have the same hash code. HashMap is a collection class that uses this technique. When an element is added, its hash code is used to compute the index in an internal array (called a bucket). If other, non-equal elements have the same hash code, they end up in the same bucket and must be bundled together, e.g. by adding them to a list. When an instance is given to contains, its hash code is used to compute the bucket. Only elements therein are compared to the instance. This way, very few, ideally no equals comparisons are required to implement contains.

How is hashing implemented in Hashtables?

A Hashtable internally contains buckets in which it stores the key/value pairs. When you pass a key/value to the Hashtable , it queries the key’s hashcode. The Hashtable uses that code to determine the bucket in which to place the key/value. By using the hashcode this way, the Hashtable can also quickly determine in which bucket it has placed the value when you try to retrieve it. In Java, the Hashtable responds to a collision by placing multiple values into the same bucket. Creating your own unique hashcodes for your class is not enough, they have to well distributed to avoid hash collisions.

What is hash collision?

In an HashMap the key is an object, that contains hashCode() and equals(Object) methods. When you insert a new entry on the Map, it checks whether the hashCode is already known. Then, it will iterate through all objects with this hashcode, and test their equality with .equals(). If an equal object is found, the new value replace the old one. If not, it will create a new entry in the map. Usually, talking about maps, you use collision when two objects have the same hashCode but they are different. They are internally stored in a list.

How does Java avoid Hash Collisions?

Hash tables deal with collisions in one of two ways.
Option 1: By having each bucket contain a linked list of elements that are hashed to that bucket. This is why a bad hash function can make lookups in hash tables very slow.
Option 2: If the hash table entries are all full then the hash table can increase the number of buckets that it has and then redistribute all the elements in the table. The hash function returns an integer and the hash table has to take the result of the hash function and mod it against the size of the table that way it can be sure it will get to bucket. So by increasing the size, it will rehash and run the modulo calculations which if you are lucky might send the objects to different buckets.
Java uses both option 1 and 2 in its hash table implementations.

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is a significant difference between them on how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1, which uses synchronized methods to achieve thread-safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. The only difference between Hashtable and Synchronized Map is that latter is not a legacy and you can wrap any Map to create it’s synchronized version by using Collections.synchronizedMap() method. ConcurrentHashMap is specially designed for concurrent use i.e. more than one thread. Unlike Hashtable and Synchronized Map, it never locks whole Map, instead, it divides the map into segments and locking is done on those. Though it performs better if a number of reader threads are greater than the number of writer threads.

Null values in Hashtable

As specified in JDK documentation, Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. When HashMap was created, it was specifically designed to handle null values as keys and handles them as a special case. To successfully store and retrieve objects from a Hashtable, the objects used as keys must implement the hashCode method and the equals method. Since null isn’t an object, you can’t call .equals() or .hashCode() on it, so the Hashtable can’t compute a hash to use it as a key.

Internal Representation of an Array

Internally an ArrayList uses an Object[]. As you add items to an ArrayList, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: