Protected: Software versions I have used

This content is password protected. To view it please enter your password below:

Interview Blockers


Q:If class A has a method
public void foo throws Exception E, Exception F
and
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
and
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?
A:
response.setHeader(“Pragma”,”no-cache”);
response.setHeader(“Cache-Control”,”no-store”);

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?
A: SET, SORTED SET, LIST, MAP, SORTED MAP, ITERATOR, LIST ITERATOR

What are the types of classloaders?
http://javapapers.com/core-java/java-class-loader/

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
      Class.forName("pkg.Bar");
      }
}
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.

http://www.journaldev.com/1933/java-servlet-filter-example-tutorial

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

https://www.sitepoint.com/how-to-implement-javas-hashcode-correctly/
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.

Tips For Sun Certification

Modifiers
Access modifiers for instance variables and methods
a. public
b. private
c. protected
d. none (default / package)
Access modifiers for classes
a. public
b. none
Modifiers for classes, methods and instance variables
Classes:
a. abstract
b. final
Methods
a. abstract
b. final
c. native
d. synchronized
e. static
Instance Variables
a. final
b. static
c. transient
d. volatile
Local variables
The only allowed modifier is final. Otherwise none.

A table of information on integer data types

TYPE       BITS     BYTES       RANGE              CAPACITY
byte       8        1           -2^7 to (2^7)-1    2^8
short      8x2      2          -2^15 to (2^15)-1   2^16
int        8x4      4          -2^31 to (2^31)-1   2^32
long       8x8      8          -2^63 to (2^63)-1   2^64
-------------------------------------------------------------
char       8x2      2           0 to 2^16-1        2^16

Tip: An int type can hold 4 bytes. That is 4×8=32 bits.
Can range from minus 2 to the power (32-1) TO 2 to the power (32-1) minus 1.
Capacity: -2^31 to (2^31)-1 is exactly 2 to the power 32 values including the 0.

Allowed implicit assignments for Integer Types

byte->short->int->long
char->int->long

For example a byte can be assigned to a short implicitly without giving a compile time error.
A char and a short can both be safely assigned to an int type. And so forth.

TIP

o A class with abstract methods must itself be declared abstract.

o A static method can only access static instance members (members denote methods, instance variables, inner classes).

Scope or Visibility of methods

diff class    diff class/   extended class extended class
/same package /diff package /same package /diff package
private      X                X              X             X
default     YES               X              YES           X
protected   YES               X              YES          YES
public      YES              YES             YES          YES

VISIBILTIY:
private ->default ->protected ->public
TIP
· Automatic variables (local variables) are not initialized by the system; every automatic variable must be explicitly initialized before being used. Otherwise a compile time error occurs.
· Final arrays itself cannot change their original reference but all the elements of the array can be assigned new values.
· Reading may be informative, but the inquisitive mind seeks practical answers. So there is no other way to crack the certification than getting your hands dirty with code. And try to avoid using an IDE.
Inheritance
If class greenheads extends class vegetable and class vegetable extends class food and class food extends class eatable; and class meat extends class food then we have the following scenario:
Vegetable and meat both extend eatable as well as food. And greenheads extend vegetable, food and eatable; meat extends both food and eatable.

TIPS
When an object is cast to something that is not its original class type, a class cast exception occurs.
The compiler will not let you make a cast if there is no chance for the cast to succeed.
Suppose you have an array of Employee objects called staff[] that includes a couple of Manager objects that extends Employee, and you have an unrelated class called Cat.

Cat bert= (Cat) staff[i]; // will give a compile time error
Manager boss= (Manager)staff[i];//will compile fine
//but will give a runtime error when staff[i] is just Employee

In this case ClassCastException) occurs if staff[i] does not happen to be a Manager object.
All runtime errors are unchecked.
Exceptions
Checked exceptions and unchecked exceptions inherit from class Exception.
Exception class and errors inherit from Throwable. Checked exceptions have to be caught or declared else the code will not compile. Unchecked exceptions can be caught with a catch clause but it is not imperative to do so. They will cause a program to terminate if not caught. Run time exceptions usually represent program bugs. Programmers can however throw a run time exception under specific conditions and then catch them to perform some other activity.


TIPS
· instanceof operator returns true if the object is an instance of the named class or any of its subclasses.
· None of the components inside a loop construct are compulsory
Eg.

for(;;);

is perfectly legal and executes an infinite loop.
· Any number type may be compared with another number type. For instance a float may be compared with an int type.
· Strings that have the same value at compile time, share the same memory space and hence when compared with == will return true. (== checks whether the storage locations are same, in case of objects).
· Strings that are created at run time do not share the same memory and the test with == will return false.
· The switch construct can only accept data types that can be converted to int. Going by the discussion at the beginning of this post, that includes byte, short, char and int itself.

String java= “Java”
String va= “va”;
if(java==(“Ja”+va))//returns false
{//this is a runtime check
}
if(java== “Ja”+ “va”)//returns true
{//this is a compile time check
}

The nuances of inheritance
If class Child inherits from class Parent and both Parent and Child have methods called bawl() and instance variables called temper then :

Parent p = new Child();//Child is the father of man?

p.bawl() will invoke the bawl() in the Child class
p.temper will be the value of temper in the Parent class.

A funny expression
Will the following piece of code compile?


int i=1;do while(i!=0){}while(i>1);

On further observation the above expression can be expanded into

do{
//at least one execution being do while loop
while(i!=0)
{
//might not execute even once being while loop
}
}while(i>1);

Overloading and Overriding
Overloaded methods have the same method name but a different parameter list. (different signature) They may or may not have the same return type.
Overridden methods on the other hand have same name, same parameter list and same return type.(Signature+return type)
TIPS
· The overridden method must have the same or more accessibility than the parent method.
· It must throw the same or subset of the exceptions thrown by the parent method.

Math functions
sqrt(0.0) returns 0.0
sqrt(-1) returns NaN or the java equivalent of NotANumber

Collections
· All sorted collections begin with Tree
· All mapped collections begin with Map and use keys
· HashMap is a non synchronized Hashtable
· ArrayList is a non synchronized Vector
· Maps allow duplicates and use a key
Summary on Collections

Non duplicating , Unordered SET
Duplicating, Ordered LIST
Duplicating, Ordered with Keys MAP

Non Duplicating, Sorted SORTEDSET -TreeSet
Duplicating, Sorted, with Keys SORTEDMAP -TreeMap

Concrete classes that implement the LIST interface includes ArrayList.
A List is an duplicating, ordered Collection
A Vector is similar to an ArrayList, except that it is synchronized.

Concrete classes that implement SET include HashSet
A HashSet is a non-duplicating, unordered collection..

Concrete classes that implement the SORTED SET interface include TreeSet.
A TreeSet is a non-duplicating, ordered collection that contains unique elements.

Concrete classes that implement the MAP interface include HashMap
A HashMap is a duplicating, unordered collection that contains key value pairs.
A Hashtable is similar to a HashMap except that it is synchronized and does not allow null values.

HashSet allows only one null key, but HashMap can allow one null key + multiple null values. A HashSet is implemented in terms of a HashMap. It’s a mapping between the key and PRESENT object.

Concerte classs that implement the SORTED MAP interface include TreeMap
A TreeMap is a duplicating, ordered collection that contains key value pairs. Keys must be unique.