Java JEE FAQ

Post date: Mar 8, 2016 4:15:12 AM

There are some common questions which are discussed regularly, often developers face challenges around these topics and often they have to choose from among some choices. These frequently asked questions are given here:

Q. Is Java pure object oriented language?

Mostly (but debatable)

Primitive types in Java are not objects. Values of primitive types are either stored directly in fields (for objects) or on the stack (for methods). Objects are generally stored in heap. Due to these primitive types, many people didn't consider it pure object oriented.

Q. Why primitives?

Java designers kept primitive types for performance reasons.

With Java 5.0, autoboxing, compiler converts primitives to corresponding wrapper object types, when a primitive is:

Passed as a parameter to a method that requires an object of the corresponding wrapper class.

Assigned to a variable of the corresponding wrapper class.

Benefits of autoboxing and unboxing: Easy to read and clean code.

Q. What is Spring AOP?

Applications have to deal with subjects other than pure business logic for example logging, security, transactions. Take an example of logging, if logging statements are written along with business logic or take another example security check is required before execution of statements in a method you will have to write code to handle security with business logic. This makes business logic less readable and more cluttered.

Example: code without AOP:

class MyClass{

... data members

... log stream

public static void operation1(){

...log at starting of operation

...perform business logic

...log at the end of operation

}

public int operation2(){

...log at starting of operation

...perform business logic

...log at the end of operation

}

}

These subjects need to be handled at various layers or across application (one class to another and so on) so these are called cross cutting concerns.

If you want to make your code less cluttered and more readable you would like to keep pure business logic separate from logic/code for cross cutting concerns and you would like to still make some arrangement such that even without directly mingling logging code in a method of function, logging happens (logging method is called). For this to happen you will have to set some rules and create a smaller code or framework which understands the rules and invokes logging at the defined points. This way you will take care of aspects (cross cutting concerns) separately out of your main business logic. This type of programming is called Aspect Oriented Programming.

Example: code with AOP

class MyClass{

... data members

public static void operation1(){

...perform business logic

}

public int operation2(){

...perform business logic

}

}

There can be several ways to implement the code for logging aspect so that logging happens before (or after what ever you want) execution of an operation (for example operation1 ). This is done by implementing a class which takes care of it.

Write aspect class annotated with @Aspect annotation and write point-cut expressions to match joint-point methods.

Example: Aspect and pointcut expression

@Aspect

public class MyClassAspect {

@Before("execution(* MyClass.operation1(..))") //point-cut expression

public void logBeforeV1(JoinPoint joinPoint)

{

System.out.println("MyClassAspect.logBeforeV1() : " + joinPoint.getSignature().getName());

}

}

Many languages support Aspect Oriented Programming (completely or not it depends) and there are frameworks which help implementing AOP in those programming languages. Spring provides mechanism to do aspect oriented programming and the framework in Spring which handles this is called Spring AOP. When we talk about Object Oriented Programming, we have classes as a unit of modularity , in AOP aspect is the unit of modularity. Aspects help in modularization of concerns (for an example logging)

AOP concepts (or terminology)

Aspect: is a class that implements application concerns that cut across multiple classes (for example concern logging) . Aspects can be a class configured through Spring XML configuration or we can use Spring AspectJ integration to define a class as Aspect using @Aspect annotation.

Join Point: specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join points is always the execution of a method.

Advice: methods that are executed when a certain join point with matching pointcut is reached in the application. Following are some of the advice types: “around”, “before” and “after” .

Pointcut: expressions that is matched with join points to determine whether advice needs to be executed or not.

Target Object: object on which advices are applied. In Spring AOP it is always a proxied object.

AOP proxy: Proxy classes with target classes and advice invocations are called AOP proxy classes.

Weaving: process of linking aspects with other objects to create the advised proxy objects. Spring AOP performs weaving at the runtime.

Introduction:

What does Spring provides, what is the relationship of Dependency Injection, Inversion of Control and AOP ? Read few lines bellow and figure out if this is clear or not:

    • Spring IoC container does not depend on AOP, You can use IoC without using AOP.

    • Spring AOP currently supports only method execution join points. Support for field interception could be added with the help of languages like AspectJ. In short Spring doesn't provide everything defined in AOP.

Following is from Spring documentation: "Spring AOP’s approach to AOP differs from that of most other AOP frameworks. The aim is not to provide the most complete AOP implementation (although Spring AOP is quite capable). Rather, the aim is to provide a close integration between AOP implementation and Spring IoC, to help solve common problems in enterprise applications"

[Source: https://docs.spring.io/spring/docs/5.1.3.BUILD-SNAPSHOT/spring-framework-reference/core.html#aop-api ]

Q. When not to use Hibernate?

Q. What is the difference between reflection and annotation.

Q. What is serialization.

Q. What is Server stickiness?

Q. Are prepared statements precompiled at JDBD or in database?

Q: Singleton is single in a single classloader, single JVM or all JVMs in a machines Singleton?

If there are two war files deployed on same tomcat with hibernate session factory used in both the wars, the session factory will have two single. Singleton is single for a class loader. If there are more than class loaders then more than one singleton will be created.

Q. What is the difference between JVM and JRE

Q. Difference between Serializable and Externalizable interface in Java?

Difference between Serializable and Externalizable interface:

* provided all the classes it reaches have implemented serializable interface.

Which one is better?

There is no straight forward answer to this question. It depends on what is your objective and context. Unless there is a pain and an issue why would you like to write code which is already done for you? So unless you see problems with default serialization mechanism you won't want to use externalizable.

By default you can start with most of the classes implementing serializable interface.

Some of the classes where you see there is deep hierarchy of inheritance above your class (parent classes) and also there are many unwanted instance variables in the class as well as its hierarchy and serializable class itself is almost self sufficient you can create them with externalizable interface. Here are some rules to go for externalizable interface:

If you need complete control on serialization process

If bandwidth and time consumption is very important for you

If lots of serialization and deserialization of the class is expected

Serializable interface:

What is it?

Serializable is a markup interface which means is has no methods to implement. If we want an object to be able to serialize, the class should implement Serializable interface. Since there are no methods in this interface, it means the writer of the class will not have to implement any method from this interface.

What is the use of this interface ?

It works as an indicator for the serialization mechanism. Serialization mechanism understands that the object can be serialized if it has implemented serializable interface.

How does serialization work with Serializable interface?

Serialization algorithm writes out the description (metadata) of the class (of object which is to be serializable). It then traverses through the super class (classes up the hierarchy until it reaches top level Object class) and writes the description of the classes it finds.

After writing the description (metadata), it writes actual data starting from the top to bottom (supermost class to the class of the object to be serialzed).

To recover the object reflection is used.

Some of the rules related to serialization

    • Static and transient fields are not serialized, remaining fields are serialized.

    • Serializable class should have access to no argument constructor of super class. This is used to reconstruct the object [of super class](deserialization)

    • Deserialization of the serializable class is done using the stream.

    • If super class has implemented Serializable interface, you don't need to implement it in the child class to make it serializable.

    • You need to define serial version uid or it is automatically created. Automatic serial version id is based on all the fields, methods etc of the class. If class changes the UID also changes. This requires significant time..

    • Trying to serialize some classes(which can't be serializable) will throw exception of type NotSerializableException, these classes include: Image, Thread, Socket, and InputStream

    • If you add following two methods(exact signature) in serializable class, the default serialization will not happen but these methods will be used to serialize the object:

private void writeObject(java.io.ObjectOutputStream out) throws IOException;

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

To avoid automatic serialization, you can use above private methods to throw the NotSerializableException in your class.

private void writeObject(ObjectOutputStream out) throws IOException{

throw new NotSerializableException("Not Serialize");

}

Interesting resources

https://docs.oracle.com/javase/tutorial/javabeans/advanced/persistence.html

http://www.javaworld.com/article/2072752/the-java-serialization-algorithm-revealed.html

http://www.onjava.com/pub/a/onjava/excerpt/JavaRMI_10/index.html?page=1

Externalizable Interface:

What is it?

It is an interface which allows you to implement serialization and deserialization logic of your choice. Externalizable has two methods (it is not like serializable which is a marker interface only without any method). If you use externalizable interface for your serialization objects you will have to implement two methods: writeExternal and readExternal.

Externalizable interface extends Serializable interface. writeExternal and readExternal supersede customized implementations of writeObject and readObject methods. In case Externalizable interface is used Serializable class should have access to no argument constructor of super class. This is used to reconstruct the object (deserialization)

During deserialization an instance is created using the public no-arg constructor, then the readExternal method is called.

What is the use of it?

To mark an object that it can be serializable. If you need control of what should be serialized, concerned about bandwidth consumption during serialization and deserialization, this interface can be used.

How does it work?

Object to be stored is checked if it has implemented Externalizable interface or not. If it has implemented Externalizable interface, writeExternal method is used to save the object. During reconstruction an instance of the object is created using public no-arg constructor. After this readExternal method is called.

Interesting resources:

https://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html

http://www.jusfortechies.com/java/core-java/externalization.php

Q. In order to use any object as key in HashMap which methods should we implement?

Ans. equals() and hashcode() methods are already defined in class Object and these two methods are required/used in a Key. It is not mandatory for us to override them(these two methods) if we are happy with their default implementation. Which means if default implementation make sense and serve the purpose then use them.

For a class to be a good key, default implementation of equals may not be good due to business requirements and in that case we may have to provide our own implementation of equals() method by overriding default equals() method for the class which we want to use as a key.

Default implementation(coming from Object class) of equals() method returns true only when two objects are exactly the same. Following is default implementation of equals() method in Object class:

public boolean equals(Object obj) {

return (this == obj);

}

It means default implementation of equals is same as comparing two references of same object with == operator.

You may find some Java Classes have changed the default equals and hash code methods by overriding them so don't consider them default methods.

Note: Java String, Integer and others similar classes have overridden equals methods to check content of two objects for example from Integer class:

public boolean equals(Object obj) {

if (obj instanceof Integer) {

return value == ((Integer)obj).intValue();

}

return false;

}

The expectation from or objective of equals() method is to compare two objects if they have same content. Objective of == comparison is to check if two objects are exactly the same, two references pointing to same object same memory location.

Having expectations only(from equals() method) and not implementing it that way won't make it like that. If you rely on default coming from Object class it will be same as ==

If two objects are equal they should produce same hashcode and that is why if you have overridden equals method you should also override hashcode accordingly ( use same attributes of an object to generate hashCode() and equals() both)

Why do we need to implement these two methods for key?

equals()

When an Object is to be put in HashMap first a check happens to see if Key already exists or not. If Key already exists the value will be stored with that Key and already stored Object(value) with that Key will be returned:

Code:

HashMap map =new HashMap();

map.put("first", "Value of first");

Object objReturned= map.put("first", "changed first");

System.out.println(objReturned.toString());

Output: Value of first

If Key doesn't exists, a new entry is created with the Key Value pair. [if you are wondering what will be the return of put method in this case, answer is obviously null :) ]

This check "if Key is already present or not" requires comparing a new entry to be done with existing entires and to compare we need equals method.

hashcode()

HashTable based collection keep the objects in different buckets. Bucketing is kind of indexing the objects for their faster retrieval. This index is hashcode of the object.

This method is used to get a unique integer for given object. It is used to determin the index of bucket location. By default, Object’s hashCode() method provides an integer representation of memory address where object is stored.

Why both equals and hashcode are required to be overriden together?

When you put an object to a HashMap the hash code of the key is calculated, this hashcode is used to determine where to store the object internally. During lookup of an object also a key is used. The hash code of this key is calculated and used to determine where to search for the object.

The hash code indicates an area ( bucket ) internally. It is possible for different key objects to produce same hascode hence the hash code itself is no guarantee that we have found the right key. After finidng the area or bucket the bucket is searched (all keys with the same hash code) and key's equals() method is used to find the right key. After getting the right key, correct value can be retunred. It means both the methods are required.

What will happen if we only implement equals or only implement hashcode (not both together)? Let us take an example and try to understand.

There is a class Subscriber and it has fields as follows: accountId, firstName, lastName, accountType etc.

Case1: Only equlas is overriden not hashcode:

Since first step is to create hashcode and reach to the bucket (either put or get an entry from the HashMap). Even if two objects are logically reprensting same subscriber the default hashcode will be computed on whole information of the object and for subs1 and subs2 two different hascode will be created hence they may go into two different buckets and during search too different buckets will be targetted which is not what we want.

Case2: Only hashcode is overridden not equals:

You have considered accountId as important field to include in hashcode. If you create an object of Account as follows:

Subscriber subs1 = new Subscriber(12345, "James", "Bond", "yearly");

and you put it in a HashMap

HashMap map = new HashMap();

map.put(subs1, 5000);

Now if you create another object

Subscriber subs2 = new Subscriber(12345, "James", "Bond", "monthly");

and you put it in the map:

map.put(subs2, 5000);

Although we are refering to same objects from our business point of view and they should be stored as one Key but what will happen?

In case of subs2 after creating the hashcode and reaching to the bucket a search will be performend to find if subs2 exists or not. Since it is a new object (not exactly the same even if it is logically same subscriber) and default equals will say it is a new object not already stored and will create another entry for it. This is wrong. If we would have implemented equals with important field as accountId or so the comparison would have been true and subs2 would have been replaced by subs2.

Interesting resources:

http://www.ibm.com/developerworks/library/j-jtp05273/

http://javapapers.com/core-java/java-hashtable/

http://javacracker.com/importance-of-hashcode-and-equals-methods/

https://en.wikipedia.org/wiki/Hash_table

http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java

https://dzone.com/articles/java-hashing

https://www.artima.com/lejava/articles/equality.html

Q. What are the parameters affecting performance of a HashMap?

There are two parameters that affect performance of a HashMap:

Initial capacity

Capacity means number of buckets. Initial capacity is capacity at the time of hashtable is created. By default initial capacity is 16

Load Factor

When to automatically increase the hashtable. "When" means how much the table is allowed to grow before increasing the capacity. By default load factor is .75

How does it grow?

When entries in hashtable reach to a certain number ( = CurrentCapacity X LoadFactor), the table is rehashed and number of buckets become approximately twice. During rehashing internal structure of the table is rebuilt.

How performance is affected by load factor and initial capacity?

There are two types of operations we perform on this type of collection (all types of collections too):

Storing the data (adding the values: put() )and reading the data ( iterating over a collection). Performance may be important during these operations.

Performance at the time of iterating over a collection depends on time required to perform the iteration and this time is proportional to capacity ( buckets ) and size (number of entries) of the collection. Hence if initial capacity is too high time to iterate will be higher.

Load factor value should be such that it reduces number of hashing required. As a rule of thumb .75 is a good balance between time and space cost. If you set very high value for load factor, you may decrease the space overhead (no frequent rehashing as a result of no frequent space increase required) but lookup time will be increased.

If you keep initial capacity = Required Capacity/Load Factor There won't be any rehashing required.

(Above may not be suggested in all the cases but just an idea when rehashing won't happen at all.)

Special Note:

Java SE 7u6: introduced an improved, alternative hash function for the map and collections derived from map.

  • HashMap

  • Hashtable

  • HashSet

  • LinkedHashMap

  • LinkedHashSet

  • WeakHashMap

  • ConcurrentHashMap

When there are large number of key hash collisions are encountered the alternate hash function improves the performance of these map implementations. By default alternate has function is disabled. To enable it a system property should be set to a number greater than -1 (-1 disables the alternate has function).

  • System property: jdk.map.althashing.threshold

  • Value range: From -1 to 2147483647, inclusive

  • Default value: -1

When a map reaches this threshhold value map uses the alternate hasfunction.

Java SE 8: Above system property and alternative hash function are removed from Java SE 8. There is a performance improvement for HashMap objects where there are lots of collisions in the keys by storing their entries in a balanced tree instead of a linked list

Q. What is immutable? How can we write immutable object?

Once created immutable objects can not be modified. Take an example String is immutable, once it is create and then you assign another string to the reference variable, the previous String object remain and reference variable starts pointing to another object

String s= "abc";

s= "xyz";

Often immutable are also final in Java, they are made final to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

Q. What is the difference between: String as new() & literal?

String s = new String("xyz");

String object is created in heap and not added in to string pool ( call String.intern() method to put into String pool explicitly.)

String s = "xyz";

String literal is created in String pool (an area in the PermGen area of heap)

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

Q. What is difference between StringBuffer and StringBuilder in Java ?

StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized.

Q. What is the difference between ArrayList and Vector ?

Q. How do you handle error condition while writing stored procedure or accessing stored procedure from java?

Stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

Q. What is difference between Executor.submit() and Executer.execute() method ?

There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

Q. When do you override hashcode and equals() ?

Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap.

Q. What will be the problem if you don't override hashcode() method ?

You will not be able to recover your object from hash Map if that is used as key in HashMap.

Q. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?

Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

Q. Does not overriding hashcode() method has any performance implication ?

A poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

Q. What do you understand by thread-safety ? Why is it required ? And finally, how to achieve thread-safety in Java Applications ?

Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes guarantee of visibility of memory operations across the Threads.

Let's first discuss about Memory Barrier which are the base for our further discussions. There are two type of memory barrier instructions in JMM - read barriers and write barrier.

A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory, so that changes made by other threads becomes visible to the current Thread.

A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads.

JMM semantics for synchronized

When a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory)

Thus modifications to a shared state using synchronized block by one Thread, is guaranteed to be visible to subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of synchronized code block.

JMM semantics for Volatile fields

Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block. So the visibility of volatile field is guaranteed by the JMM. Moreover afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both). Thus when Thread A writes to a volatile variable V, and afterwards Thread B reads from variable V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B.

Let's try to understand the same using the following code

Data data = null;

volatile boolean flag = false;

Thread A

-------------

data = new Data();

flag = true; <-- writing to volatile will flush data as well as flag to main memory

Thread B

-------------

if(flag==true){ <-- as="" barrier="" data.="" flag="" font="" for="" from="" perform="" read="" reading="" volatile="" well="" will="">

use data; <!--- data is guaranteed to visible even though it is not declared volatile because of the JMM semantics of volatile flag.

}

Q. What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?

This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

Q. Can you override private or static method in Java ?

You can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding.

Q. What will happen if we put a key object in a HashMap which is already there ?

This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys.

Q. If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?

You can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception.

Q. What is the issue with following implementation of compareTo() method in Java

public int compareTo(Object o){

Employee emp = (Employee) emp;

return this.id - o.id;

}

Q. How do you ensure that N thread can access N resources without deadlock

If you acquire resources in a particular order and release resources in reverse order you can prevent deadlock.

Q. What is difference between CyclicBarrier and CountDownLatch in Java

Introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

Q. Can you access non static variable in static context?

No you can not access static variable in non static context in Java.

Q. What does the following Java program print?

public class Test {

public static void main(String[] args) {

System.out.println(Math.min(Double.MIN_VALUE, 0.0d));

}

}

Unlike the Integer, where MIN_VALUE is negative, both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers. The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the least among all double values. So unlike the obvious answer, this program will print 0.0 because Double.MIN_VALUE is greater than 0.

Q. What will happen if you put return statement or System.exit () on try or catch block? Will finally block execute?

Finally block will execute even if you put a return statement in the try block or catch block but finally block won't run if you call System.exit form try or catch.

Q. Can you override a private or static method in Java?

You can not override a private or static method in Java, if you create a similar method with same return type and same method arguments in child class then it will hide the super class method, this is known as method hiding. Similarly, you cannot override a private method in sub class because it's not accessible there, what you do is create another private method with the same name in the child class. See: "Can you override a private method in Java?" for more details.

Q. What do the expression 1.0 / 0.0 will return? will it throw Exception? any compile time error?

Answer: This is another tricky question from Double class. Though Java developer knows about the double primitive type and Double class, while doing floating point arithmetic they don't pay enough attention to Double.INFINITY, NaN, and -0.0 and other rules that govern the arithmetic calculations involving them. The simple answer to this question is that it will not throw ArithmeticExcpetion and return Double.INFINITY. Also, note that the comparison x == Double.NaN always evaluates to false, even if x itself is a NaN. To test if x is a NaN, one should use the method call Double.isNaN(x) to check if given number is NaN or not. If you know SQL, this is very close to NULL there.

Q. Does Java support multiple inheritances?

This is the trickiest question in Java if C++ can support direct multiple inheritance than why not Java is the argument Interviewer often give. Answer of this question is much more subtle then it looks like, because Java does support multiple inheritances of Type by allowing an interface to extend other interfaces, what Java doesn't support is multiple inheritances of implementation. This distinction also gets blur because of default method of Java 8, which now provides Java, multiple inheritances of behavior as well. See Why multiple inheritance is not supported in Java to answer this tricky Java question.

Q. What will happen if we put a key object in a HashMap which is already there?

This tricky Java question is part of another frequently asked question, How HashMap works in Java. HashMap is also a popular topic to create confusing and tricky question in Java. Answer of this question is if you put the same key again then it will replace the old mapping because HashMap doesn't allow duplicate keys. The Same key will result in the same hashcode and will end up at the same position in the bucket. Each bucket contains a linked list of Map.Entry object, which contains both Key and Value. Now Java will take Key object form each entry and compare with this new key using equals() method, if that return true then value object in that entry will be replaced by new value. See How HashMap works in Java for more tricky Java questions from HashMap.

Q. What does the following Java program print?

public class Test {

public static void main(String[] args) throws Exception {

char[] chars = new char[] {'\u0097'};

String str = new String(chars);

byte[] bytes = str.getBytes();

System.out.println(Arrays.toString(bytes));

}

}

The trickiness of this question lies on character encoding and how String to byte array conversion works. In this program, we are first creating a String from a character array, which just has one character '\u0097', after than we are getting byte array from that String and printing that byte. Since \u0097 is within the 8-bit range of byte primitive type, it is reasonable to guess that the str.getBytes() call will return a byte array that contains one element with a value of -105 ((byte) 0x97). However, that's not what the program prints and that's why this question is tricky. As a matter of fact, the output of the program is operating system and locale dependent. On a Windows XP with the US locale, the above program prints [63], if you run this program on Linux or Solaris, you will get different values.

To answer this question correctly, you need to know about how Unicode characters are represented in Java char values and in Java strings, and what role character encoding plays in String.getBytes(). In simple word, to convert a string to a byte array, Java iterate through all the characters that the string represents and turn each one into a number of bytes and finally put the bytes together. The rule that maps each Unicode character into a byte array is called a character encoding. So It's possible that if same character encoding is not used during both encoding and decoding then retrieved value may not be correct. When we call str.getBytes() without specifying a character encoding scheme, the JVM uses the default character encoding of the platform to do the job. The default encoding scheme is operating system and locale dependent. On Linux, it is UTF-8 and on Windows with a US locale, the default encoding is Cp1252. This explains the output we get from running this program on Windows machines with a US locale. No matter which character encoding scheme is used, Java will always translate Unicode characters not recognized by the encoding to 63, which represents the character U+003F (the question mark, ?) in all encodings.

Q. If a method throws NullPointerException in the superclass, can we override it with a method which throws RuntimeException?

One more tricky Java questions from the overloading and overriding concept. The answer is you can very well throw superclass of RuntimeException in overridden method, but you can not do same if its checked Exception. See Rules of method overriding in Java for more details.

Q. What is the issue with following implementation of compareTo() method in Java

public int compareTo(Object o){

Employee emp = (Employee) emp;

return this.id - o.id;

}

where the id is an integer number.

Well, three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can't guarantee that id is positive or negative. the tricky part is, If id becomes negative than subtraction may overflow and produce an incorrect result. See How to override compareTo method in Java for the complete answer of this Java tricky question for an experienced programmer.

Q. Consider the following Java code snippet

It is initializing two variables and both are not volatile, and two threads T1 and T2 are modifying these values as following, both are not synchronized

int x = 0;

boolean bExit = false;

Thread 1 (not synchronized)

x = 1;

bExit = true;

Thread 2 (not synchronized)

if (bExit == true)

System.out.println("x=" + x);

Now tell us, is it possible for Thread 2 to print “x=0”?

Answer: It's impossible for a list of tricky Java questions to not contain anything from multi-threading. This is the simplest one I can get. Answer of this question is Yes, It's possible that thread T2 may print x=0.Why? because without any instruction to compiler e.g. synchronized or volatile, bExit=true might come before x=1 in compiler reordering. Also, x=1 might not become visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it? When I asked this question to a couple of programmers they answer differently, one suggests to make both threads synchronized on a common mutex, another one said make both variable volatile. Both are correct, as it will prevent reordering and guarantee visibility. But the best answer is you just need to make bExit as volatile, then Thread 2 can only print “x=1”. x does not need to be volatile because x cannot be reordered to come after bExit=true when bExit is volatile.

Q.When Singleton doesn't remain Singleton in Java?

Q.is it possible to load a class by two ClassLoader?

Q.is it possible for equals() to return false, even if contents of two Objects are same?

Q.Why compareTo() should be consistent to equals() method in Java?

Q.When do Double and BigDecimal give different answers for equals() and compareTo() == 0.

Q.How does "has before" apply to volatile work?

Q.Why is 0.1 * 3 != 0.3,

Q.Why is (Integer) 1 == (Integer) 1 but (Integer) 222 != (Integer) 222 and which command arguments change this.

Q.What happens when exception is thrown by a Thread?

Q.Difference between notify() and notifyAll() call?

Q.Difference between System.exit() and System.halt() method?

Q.Does following code legal in Java? is it example of method overloading or overriding?

public String getDescription(Object obj){

return obj.toString;

}

public String getDescription(String obj){

return obj;

}

and

public void getDescription(String obj){

return obj;

}

Q. Why String is immutable in Java?

(Security, String pool implementation)

Q. Can abstract class have constructor in Java?

Yes

Q. Which two methods is overridden by an Object, intended to be used as key in HashMap?

Equals and hashCode

Q. Difference between wait and sleep in Java?

Wait release lock, sleep keep it.

Q. Difference between List and Set in Java

List is ordered, allows duplicates and indexed, Set is unordered, don't allow duplicates.

Q. How do you make a class Immutable in Java?

Make it final, final fields without setter, state is only set in constructor, no leak of internal reference, copy data for mutable members, read more.

Q. Which data type you should use to represent currency in Java?

Q. When to use abstract class and interface in Java?

Q. Difference between ArrayList and LinkedList in Java?

Former is fast, backed by array, while later is backed by linked-list, queue, former also supports index based access at O(1), while later provides search at cost of O(n) time.

Q. Difference between Overloading and Overriding in Java?

Former take place at compile time, later happens at runtime, only virtual method can be overridden, static, final and private method can't be overridden in Java.

Q. What kind of reference types are exists in Java? Differences?

Strong reference, Weak references, Soft reference and Phantom reference. Except strong, all other reference allows object to be garbage collected. For example, if an object hash only weak reference, than it's eligible for GC, if program needs space

Q. Difference between checked and unchecked exception in Java?

Former is checked by compiler and it's handling is enforced by mandating try-catch or try-finally block. Later is not checked by compiler but can be caught using try-catch or try-finally block. For example, java.io.IOException, java.sql.SQLException are checked exception, while java.lang.NullPointerException and java.lang.ArrayIndexOutOfBoundsException are example of unchecked exception in Java

Q. Does Java array is instance of Object?

Yes, and this is stark difference from array in C/C++, though it doesn't have any method, it has an attribute called length, which denotes size of array.

Q. Does List<Number> can hold Integers?

Yes

Q. Can we pass ArrayList<Number> to a method which accepts List<Number> in Java?

Yes

Q. Can we pass ArrayList<Integer> to a method which accepts List<Number>?

No

Q. How to fix that?

Use wildcards e.g. List<? extends Number>

Q.What is volatile variable in Java?

Guarantees happens before relationship, variable's value is read by main memory.

Q. Difference between CountDownLatch and CyclicBarrier in Java?

Former can not be reused once count reaches zero, while later can be reused even after barrier is broken, for in-depth discussion, see this post.

Q. Does BlockingQueue is thread-safe?

Yes, take() and put() method of this class guarantees thread-safety, no need to externally synchronize this class for adding and retrieving objects.

Q. Why wait and notify method should be called in loop?

To prevent doing task, if condition is not true and thread is awake due to false alarms, checking conditions in loop ensures that processing is only done when business logic allows.

Q. What is difference between "abc".equals(unknown string) and unknown.equals("abc")?

Former is safe from NullPointerException,

Q. What is marker or tag interface in Java?

An interface, which presence means an instruction for JVM or compiler e.g. Serializable, from Java 5 onwards Annotation is better suited for this job.

Q. Difference between Serializable and Externalizable interface in Java?

Later provides more control over serialization process, and allow you to define custom binary format for your object, later is also suited for performance sensitive application.

Q. Can Enum types implement interface in Java?

Yes

Q. Can Enum extend class in Java?

No, because Java allows a class to only extend one class and enum by default extends java.lang.Enum.

Q. How to prevent your class from being subclassed?

Make it final or make constructor private

Q. Can we override Static method in Java? Compilation error?

No, it can only be hidden, no compilation error

Q. Difference between StringBuffer and StringBuilder in Java?

Former is synchronized, and slow, while later is not synchronized and fast.

Q. 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.

Q. 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.

Q. 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.

Q. 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.

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

Both Hashtable and 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.

Q. 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.

Q. 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.

Q. 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.

Q. How can we make Hashmap synchronized?

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

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

There are multiple aspects to this decision:

•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.

•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.

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

Vector and 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.

Q. 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.

Q. 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)

Q. 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.

Q. 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.

Q. 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.

Q. 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

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

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() and 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().

Q. 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.

Q. 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.

Set and 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.

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

List interface has three main implementation classes

•Vector

•ArrayList

•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.

Q. 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.

Q. Where will you use ArrayList and Where will you use LinkedList? Or Which one to use when (ArrayList / LinkedList).

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.

Q. 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.

Q. What are available drivers in JDBC?

JDBC technology drivers fit into one of four categories:

1. A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important.

2.A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

3.A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.

4.A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

Q. What are the types of statements in JDBC?

The JDBC API has 3 Interfaces, (1. Statement, 2. PreparedStatement, 3. CallableStatement ). The key features of these are as follows: Statement

•This interface is used for executing a static SQL statement and returning the results it produces.

• The object of Statement class can be created using Connection.createStatement() method.

PreparedStatement •A SQL statement is pre-compiled and stored in a PreparedStatement object.

•This object can then be used to efficiently execute this statement multiple times.

• The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface.

CallableStatement •This interface is used to execute SQL stored procedures.

• This extends PreparedStatement interface.

• The object of CallableStatement class can be created using Connection.prepareCall() method.

Q. What is a stored procedure? How to call stored procedure using JDBC API?

Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters. Stored procedures can be called using CallableStatement class in JDBC API. Below code snippet shows how this can be achieved.

CallableStatement cs = con.prepareCall("{call MY_STORED_PROC_NAME}");

ResultSet rs = cs.executeQuery();

Q. What is Connection pooling? What are the advantages of using a connection pool?

Connection Pooling is a technique used for sharing the server resources among requested clients. It was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provides access to a database.

Getting connection and disconnecting are costly operation, which affects the application performance, so we should avoid creating multiple connection during multiple database interactions. A pool contains set of Database connections which are already connected, and any client who wants to use it can take it from pool and when done with using it can be returned back to the pool.

Apart from performance this also saves you resources as there may be limited database connections available for your application.

Q. How to do database connection using JDBC thin driver ?

This is one of the most commonly asked questions from JDBC fundamentals, and knowing all the steps of JDBC connection is important.

import java.sql.*;

class JDBCTest {

public static void main (String args []) throws Exception

{

//Load driver class

Class.forName ("oracle.jdbc.driver.OracleDriver");

//Create connection

Connection conn = DriverManager.getConnection

("jdbc:oracle:thin:@hostname:1526:testdb", "scott", "tiger");

// @machineName:port:SID, userid, password

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("select 'Hi' from dual");

while (rs.next())

System.out.println (rs.getString(1)); // Print col 1 => Hi

stmt.close();

}

}

Q. What does Class.forName() method do?

Method forName() is a static method of java.lang.Class. This can be used to dynamically load a class at run-time. Class.forName() loads the class if its not already loaded. It also executes the static block of loaded class. Then this method returns an instance of the loaded class. So a call to Class.forName('MyClass') is going to do following

- Load the class MyClass.

- Execute any static block code of MyClass.

- Return an instance of MyClass.

JDBC Driver loading using Class.forName is a good example of best use of this method. The driver loading is done like this

Class.forName("org.mysql.Driver");

All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static initializer method registerDriver() which can be called in a static blocks of Driver class. A MySQL JDBC Driver has a static initializer which looks like this:

static {

try {

java.sql.DriverManager.registerDriver(new Driver());

} catch (SQLException E) {

throw new RuntimeException("Can't register driver!");

}

}

Class.forName() loads driver class and executes the static block and the Driver registers itself with the DriverManager.

Q. Which one will you use Statement or PreparedStatement?

By Java API definitions: Statement is a object used for executing a static SQL statement and returning the results it produces. PreparedStatement is a SQL statement which is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. There are few advantages of using PreparedStatements over Statements

1.Since its pre-compiled, Executing the same query multiple times in loop, binding different parameter values each time is faster. (What does pre-compiled statement means? The prepared statement(pre-compiled) concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution.)

2.In PreparedStatement the setDate()/setString() methods can be used to escape dates and strings properly, in a database-independent way.

3.SQL injection attacks on a system are virtually impossible when using PreparedStatements.

Q. What does setAutoCommit(false) do?

A JDBC connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit mode using below command

con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until you explicitly call the commit method. A Simple transaction with use of autocommit flag is demonstrated below. con.setAutoCommit(false);

PreparedStatement updateStmt =

con.prepareStatement( "UPDATE EMPLOYEE SET SALARY = ? WHERE EMP_NAME LIKE ?");

updateStmt.setInt(1, 5000); updateSales.setString(2, "Jack");

updateStmt.executeUpdate();

updateStmt.setInt(1, 6000); updateSales.setString(2, "Tom");

updateStmt.executeUpdate();

con.commit();

con.setAutoCommit(true);

Q. What are database warnings and How can I handle database warnings in JDBC?

Warnings are issued by database to notify user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. In JDBC SQLWarning is an exception that provides information on database access warnings. Warnings are silently chained to the object whose method caused it to be reported. Warnings may be retrieved from Connection, Statement, and ResultSet objects. Handling SQLWarning from connection object

//Retrieving warning from connection object

SQLWarning warning = conn.getWarnings();

//Retrieving next warning from warning object itself

SQLWarning nextWarning = warning.getNextWarning();

//Clear all warnings reported for this Connection object.

conn.clearWarnings();

Handling SQLWarning from Statement object //Retrieving warning from statement object

stmt.getWarnings();

//Retrieving next warning from warning object itself

SQLWarning nextWarning = warning.getNextWarning();

//Clear all warnings reported for this Statement object.

stmt.clearWarnings();

Handling SQLWarning from ResultSet object //Retrieving warning from resultset object

rs.getWarnings();

//Retrieving next warning from warning object itself

SQLWarning nextWarning = warning.getNextWarning();

//Clear all warnings reported for this resultset object.

rs.clearWarnings();

The call to getWarnings() method in any of above way retrieves the first warning reported by calls on this object. If there is more than one warning, subsequent warnings will be chained to the first one and can be retrieved by calling the method SQLWarning.getNextWarning on the warning that was retrieved previously. A call to clearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object. Trying to call getWarning() on a connection after it has been closed will cause an SQLException to be thrown. Similarly, trying to retrieve a warning on a statement after it has been closed or on a result set after it has been closed will cause an SQLException to be thrown. Note that closing a statement also closes a result set that it might have produced.

Q. What is Metadata and why should I use it?

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC technology ("JDBC driver") that is used with it. Below is a sample code which demonstrates how we can use the DatabaseMetaData

DatabaseMetaData md = conn.getMetaData();

System.out.println("Database Name: " + md.getDatabaseProductName());

System.out.println("Database Version: " + md.getDatabaseProductVersion());

System.out.println("Driver Name: " + md.getDriverName());

System.out.println("Driver Version: " + md.getDriverVersion());

The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns. Below a sample code which demonstrates how we can use the ResultSetMetaData ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");

ResultSetMetaData rsmd = rs.getMetaData();

int numberOfColumns = rsmd.getColumnCount();

boolean b = rsmd.isSearchable(1);

Q. What is the difference between RowSet and ResultSet?

RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset's command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet. There are two clear advantages of using RowSet over ResultSet

•RowSet makes it possible to use the ResultSet object as a JavaBeans component. As a consequence, a result set can, for example, be a component in a Swing application.

•RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.

Q. Connected vs Disconnected RowSet, which one should I use and when?

Connected RowSet

A RowSet object may make a connection with a data source and maintain that connection throughout its life cycle, in which case it is called a connected rowset. A rowset may also make a connection with a data source, get data from it, and then close the connection. Such a rowset is called a disconnected rowset. A disconnected rowset may make changes to its data while it is disconnected and then send the changes back to the original source of the data, but it must reestablish a connection to do so. Example of Connected RowSet: A JdbcRowSet object is a example of connected RowSet, which means it continually maintains its connection to a database using a JDBC technology-enabled driver.

Disconnected RowSet

A disconnected rowset may have a reader (a RowSetReader object) and a writer (a RowSetWriter object) associated with it. The reader may be implemented in many different ways to populate a rowset with data, including getting data from a non-relational data source. The writer can also be implemented in many different ways to propagate changes made to the rowset's data back to the underlying data source. Example of Disconnected RowSet: A CachedRowSet object is a example of disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA).

Q. What is the benefit of having JdbcRowSet implementation? Why do we need a JdbcRowSet like wrapper around ResultSet?

The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet

• This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time.

•It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object.

Q. What is immutable object in Java? Can you change values of a immutable object?

A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable objects from the Java Development Kit. Immutable objects simplify your program due to following characteristics :

•Immutable objects are simple to use test and construct.

•Immutable objects are automatically thread-safe.

•Immutable objects do not require a copy constructor.

•Immutable objects do not require an implementation of clone.

•Immutable objects allow hashCode to use lazy initialization, and to cache its return value.

•Immutable objects do not need to be copied defensively when used as a field.

•Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection).

•Immutable objects have their class invariant established once upon construction, and it never needs to be checked again.

•Immutable objects always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state.

Q. How to create a immutable object in Java? Does all property of immutable object needs to be final?

To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

Q. What is difference between String, StringBuffer and StringBuilder? When to use them?

The main difference between the three most commonly used String classes as follows.

•StringBuffer and StringBuilder objects are mutable whereas String class objects are immutable.

•StringBuffer class implementation is synchronized while StringBuilder class is not synchronized.

•Concatenation operator "+" is internally implemented by Java using either StringBuffer or StringBuilder.

Criteria to choose among String, StringBuffer and StringBuilder •If the Object value will not change in a scenario use String Class because a String object is immutable.

•If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).

•If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

Q. Why String class is final or immutable?

It is very useful to have strings implemented as final or immutable objects. Below are some advantages of String Immutability in Java

•Immutable objects are thread-safe. Two threads can both work on an immutable object at the same time without any possibility of conflict.

•Security: the system can pass on sensitive bits of read-only information without worrying that it will be altered

• You can share duplicates by pointing them to a single instance.

•You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret that makes Java substring implementation very fast.

•Immutable objects are good fit for becoming Hashtable keys. If you change the value of any object that is used as a hash table key without removing it and re-adding it you will lose the object mapping.

•Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth.

•If String were not final, you could create a subclass and have two strings that look alike when "seen as Strings", but that are actually different.

Q. Is Java Pass by Reference or Pass by Value?

The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java. The difficult thing can be to understand that Java passes "objects as references" passed by value.

Also see :

https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

http://www.javadude.com/articles/passbyvalue.htm

Q. What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error?

This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception. Two important types of OutOfMemoryError are often encountered

1.

java.lang.OutOfMemoryError: Java heap space

The quick solution is to add these flags to JVM command line when Java runtime is started: -Xms1024m -Xmx1024m

2.

java.lang.OutOfMemoryError: PermGen space

The solution is to add these flags to JVM command line when Java runtime is started: -XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled

Long Term Solution: Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks. You can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place.

Q. What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?

Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. Finally block is NOT called in following conditions

•If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.

•if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

•If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.

Q. Why there are two Date classes; one in java.util package and another in java.sql?

From the JavaDoc of java.sql.Date:

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. To conform with the definition of SQL DATE, the millisecond values wrapped inside a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero.

Explanation: A java.util.Date represents date and time of day, a java.sql.Date only represents a date (the complement of java.sql.Date is java.sql.Time, which only represents a time of day, but also extends java.util.Date).

Q. What is Marker interface? How is it used in Java?

The marker interface is a design pattern, used with languages that provide run-time type information about objects. It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies methods that an implementing class must support, a marker interface does not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. There can be some hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. Java utilizes this pattern very well and the example interfaces are

•java.io.Serializable - Serializability of a class is enabled by the class implementing the java.io.Serializable interface. The Java Classes that do not implement Serializable interface will not be able to serialize or deserializ their state. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

•java.rmi.Remote - The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available remotely.

• java.lang.Cloneable - A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

•javax.servlet.SingleThreadModel - Ensures that servlets handle only one request at a time. This interface has no methods.

• java.util.EvenListener - A tagging interface that all event listener interfaces must extend.

The "instanceof" keyword in java can be used to test if an object is of a specified type. So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.

Q. Why main() in java is declared as public static void main? What if the main method is declared as private?

Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application static - When the JVM makes are call to the main method there is not object existing for the class being called therefore it has to have static method to allow invocation from class. void - Java is platform independent language therefore if it will return some value then the value may mean different to different platforms so unlike C it can not assume a behavior of returning value to the operating system. If main method is declared as private then - Program will compile properly but at run-time it will give "Main method not public." error.

Q. What Does Distributable Tag Means In Web.xml ?

In Java world, JEE applications use the concept of distributable web applications to provide session-failover and enable load balancing.

You can set a JEE application to support session replication by adding distributable tag in web.xml file.

<distributable />

Q. What Are The Requirements for making a Java EE application session replication Enabled?

Setting distributable tag in web.xml just enables the application to support session replication, however it does not guarantee that your application will work fine in a session replicated environment.

JEE Application developer needs to make sure following things are taken care during web application development.

•All attributes/objects that are saved in HTTP Session are serializable. This means all your custom objects and child objects of that should be serializable.

•Making changes to any session attribute should be done using session.setAttribute() method. If you have reference to a java object that was previously set in session, you must call session.setAttribute() method every time you make any change to the object.