general java questions

Upload: shipraa7

Post on 03-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 General Java Questions

    1/34

    How HashMap works in Java

    How HashMap works in Java or sometime how get method work in HashMap is commoninterview questions now days. Almost everybody who worked in Java knows what hashMap

    is, where to use hashMap or difference between hashtable and HashMap then why thisinterview question becomes so special? Because of the breadth and depth this question

    offers. It has become very popular java interview question in almost any senior or mid-senior level java interviews.

    Questions start with simple statement

    "Have you used HashMap before" or "What is HashMap? Why do we use it Almost everybody answers this with yes and then interviewee keep talking about commonfacts about hashMap like hashMap accpt null while hashtable doesn't, HashMap is notsynchronized, hashMap is fast and so on along with basics like its stores key and valuepairs etc.This shows that person has used hashMap and quite familiar with the functionalityHashMap offers but interview takes a sharp turn from here and next set of follow upquestions gets more detailed about fundamentals involved in hashmap. Interview here youand come back with questions like

    "Do you Know how hashMap works in Java or"How does get () method of HashMap works in Java"And then you get answers like I don't bother its standard Java API, you better look codeon java; I can find it out in Google at any time etc.But some interviewee definitely answer this and will say "HashMap works on principleof hashing, we have put () and get () method for storing and retrieving data fromhashMap. When we pass an object to put () method to store it on hashMap, hashMapimplementation callshashcode() method hashMap key object and by applying that hashcode on its own hashingfuntion it identifies a bucket location for storing value object , important part here isHashMap stores both key+value in bucket which is essential to understand the retrievinglogic. if people fails to recognize this and say it only stores Value in the bucket they will failto explain the retrieving logic of any object stored in HashMap . This answer is very muchacceptable and does make sense that interviewee has fair bit of knowledge how hashingworks and how HashMap works in Java.But this is just start of story and going forward when depth increases a little bit and when

    you put interviewee on scenarios every java developers faced day by day basis. So nextquestion would be more likely about collision detection and collision resolution in JavaHashMap e.g

    "What will happen if two different objects have same hashcode? Now from here confusion starts some time interviewer will say that since Hashcode isequal objects are equal and HashMap will throw exception or not store it again etc. then

    you might want to remind them about equals and hashCode() contract that two unequalobject in Java very much can have equal hashcode. Some will give up at this point andsome will move ahead and say "Since hashcode () is same, bucket location would be same

    and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, valueobject will be stored in next node of linked list." great this answer make sense to methough there could be some other collision resolution methods available this is simplestand HashMap does follow this.

    But story does not end here and final questions interviewer ask like

    "How will you retreive if two different objects have same hashcode? HmmmmmmmmmmmmmInterviewee will say we will call get() method and then HashMap uses keys hashcode tofind out bucket location and retrieves object but then you need to remind him that thereare two objects are stored in same bucket , so they will say about traversal in linked listuntil we find the value object , then you ask how do you identify value object becauseyou don't value object to compare ,So until they know that HashMap stores both Keyand Value in linked list node they won't be able to resolve this issue and will try and fail.

    But those bunch of people who remember this key information will say that after finding

    http://www.blogger.com/http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://www.blogger.com/
  • 7/28/2019 General Java Questions

    2/34

    bucket location , we will call keys.equals() method to identify correct node in linked listand return associated value object for that key in Java HashMap. Perfect this is thecorrect answer.

    In many cases interviewee fails at this stage because they get confused betweenhashcode () and equals () and keys and values object in hashMap which is prettyobvious because they are dealing with the hashcode () in all previous questions and equals() come in picture only in case of retrieving value object from HashMap.Some good developer point out here that using immutable, final object with proper equals() and hashcode () implementation would act as perfect Java HashMap keys and improveperformance of Java hashMap by reducing collision. Immutability also allows caching

    there hashcode of different keys which makes overall retrieval process very fast andsuggest that String and various wrapper classes e.g Integer provided by Java CollectionAPI are very good HashMap keys.

    Now if you clear all this java hashmap interview question you will be surprised by this veryinteresting question "What happens On HashMap in Java if the size of the Hashmapexceeds a given threshold defined by load factor ?". Until you know how hashmapworks exactly you won't be able to answer this question.if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is

    .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creatinganother new bucket array of size twice of previous size of hashmap, and then start puttingevery old element into that new bucket array and this process is called rehashing becauseit also applies hash function to find new bucket location.

    If you manage to answer this question on hashmap in java you will be greeted by "do yousee any problem with resizing of hashmap in Java" , you might not be able to pickthe context and then he will try to give you hint about multiple thread accessing the javahashmap and potentially looking for race condition on HashMap in Java.

    So the answer is Yes there is potential race condition exists while resizing hashmap inJava, if two thread at the same time found that now Java Hashmap needs resizing andthey both try to resizing. on the process ofresizing of hashmap in Java , the element inbucket which is stored in linked list get reversed in order during there migration to newbucket because java hashmap doesn't append the new element at tail instead it appendnew element at head to avoid tail traversing. if race condition happens then you will endup with an infinite loop. though this point you can potentially argue that what the hell

    makes you think to use HashMap in multi-threaded environment to interviewer :)

    I like this question because of its depth and number of concept it touches indirectly, if youlook at questions asked during interview this HashMap questions has verifiedConcept of hashingCollision resolution in HashMapUse of equals () and hashCode () method and there importance?

    Benefit of immutable object?race condition on hashmap in JavaResizing of Java HashMap

    Just to summarize here are the answers which does makes sense for above questions

    How HashMAp works in Java

    HashMap works on principle of hashing, we have put () and get () method for storing andretrieving object form hashMap.When we pass an both key and value to put() method tostore on HashMap, it uses key object hashcode() method to calculate hashcode and theyby applying hashing on that hashcode it identifies bucket location for storing value object.While retrieving it uses key object equals method to find out correct key value pair andreturn value object associated with that key. HashMap uses linked list in case of collisionand object will be stored in next node of linked list.Also hashMap stores both key+value tuple in every node of linked list.

    What will happen if two different HashMap key objects have same hashcode?

    They will be stored in same bucket but no next node of linked list. And keys equals ()method will be used to identify correct key value pair in HashMap.

  • 7/28/2019 General Java Questions

    3/34

    How to avoid deadlock in Java Threads

    How to avoid deadlock in Java is one of the question which is flavor of the season formultithreading , asked more at a senior level and with lots of follow up questions , thoughquestion looks very basic but most of developer get stuck once you start going deep.

    questions starts with "What is deadlock?"answer is simple , when two or more threads waiting for each other to release lock and getstuck for infinite time , situation is called deadlock . it will only happen in caseof multitasking.

    How do you detect deadlock in Java ?

    though this could have many answers , my version is first I would look the code if I seenested synchronized block or calling one synchronized method from other or trying to getlock on different object then there is good chance of deadlock if developer is not verycareful.

    other way is to find it when you actually get locked while running the application , try to

    take thread dump , in Linux you can do this by command "kill -3" , this will print status ofall the thread in application log file and you can see which thread is locked on whichobject.

    other way is to use jconsole , jconsole will show you exactly which threads are get lockedand on which object.

    once you answer this , they may ask you to write code which will result in deadlock ?here is one of my version

    public void method1(){synchronized(String.class){System.out.println("Aquired lock on String.class object");

    synchronized (Integer.class) {System.out.println("Aquired lock on Integer.class object");}}}

    public void method2(){synchronized(Integer.class){System.out.println("Aquired lock on Integer.class object");

    synchronized (String.class) {System.out.println("Aquired lock on String.class object");}}

    }

    If method1() and method2() both will be called by two or many threads , there is a goodchance of deadlock because if thead 1 aquires lock on Sting object while executingmethod1() and thread 2 acquires lock on Integer object while executing method2() bothwill be waiting for each other to release lock on Integer and String to proceed further

    which will never happen.

    now interviewer comes to final part , one of the most important in my view , How tofix deadlock ? or How to avoid deadlock in Java ?

    if you have looked above code carefully you may have figured out that real reason

    for deadlock is not multiple threads but the way they access lock , if you provide an

    ordered access then problem will be resolved , here isthe fixed version.

    http://javarevisited.blogspot.in/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.in/2010/10/what-is-deadlock-in-java-how-to-fix-it.html
  • 7/28/2019 General Java Questions

    4/34

    public void method1(){

    synchronized(Integer.class){System.out.println("Aquired lock on Integer.class object");

    synchronized (String.class) {System.out.println("Aquired lock on String.class object");}}

    }

    public void method2(){synchronized(Integer.class){System.out.println("Aquired lock on Integer.class object");

    synchronized (String.class) {System.out.println("Aquired lock on String.class object");}

    }}

    Now there would not be any deadlock because both method is accessing lock on Integerand String object in same order . so if thread A acquires lock on Integer object , thread Bwill not proceed until thread A releases Integer lock , same way thread A will not beblocked even if thread B holds String lock because now thread B will not expect thread Ato release Integer lock to proceed further.

    Example of Synchronization in Java using synchronized method and blockSynchronization in Java is an important concept since Java is a multi-threaded language

    where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of

    java class becomes extremely important. Synchronization in Java is possible by using javakeyword "synchronized"and "volatile. Concurrent access of sharedobjects in Javaintroduces to kind of errors: thread interference and memory consistency errors and toavoid these errors you need to properly synchronize your java object to allow mutualexclusive access of critical section to two threads.

    Why do we need Synchronization in Java?

    If your code is executing in multi-threaded environment you need synchronization forobjects which are shared among multiple threads to avoid any corruption of state or anykind of unexpected behavior. Synchronization in Java will only be needed if shared objectis mutable. if your shared object is read only or immutable object you don't need

    synchronization despite running multiple threads. Same is true with what threads aredoing with object if all the threads are only reading value then you don'trequire synchronization in java. JVM guarantees thatJava synchronized code willonly be executed by one thread at a time.

    In Summary Java Synchronized Keyword provides following functionality essentialfor concurrent programming :

    1) synchronized keyword in java provides locking which ensures mutual exclusive accessof shared resource and prevent data race.2) synchronized keyword also prevent reordering of code statement by compiler which cancause subtle concurrent issue if we don't use synchronized orvolatile keyword.3) synchronized keyword involve locking and unlocking. before entering into synchronizedmethod or block thread needs to acquire the lock at this point it reads data from main

    memory than cache and when it release the lock it flushes write operation into mainmemory which eliminates memory inconsistency errors.

    http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.htmlhttp://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.htmlhttp://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.htmlhttp://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html
  • 7/28/2019 General Java Questions

    5/34

    Synchronized keyword in Java

    Prior to Java5 synchronized keyword in java was only way to provide synchronizationof shared object. Any code written in synchronized block in java will be mutualexclusive and can only be executed by one thread at a time. You can have both staticsynchronized method and non static synchronized methodand synchronized blocks in javabut we can not have synchronized variable in java. Using synchronized keyword withvariable is illegal and will result in compilation error. Instead of java synchronized variableyou can have java volatile variable, which will instruct JVM threads to read value of volatilevariable from main memory and dont cache it locally.Block synchronization in java is

    preferred over method synchronization in java because by using blocksynchronization you only need to lock the critical section of code instead of whole method.Since java synchronization comes with cost of performance we need to synchronize onlypart of code which absolutely needs to be synchronized.

    Example of synchronized method in Java

    Using synchronized keyword along with method is easy just apply synchronizedkeyword in front of method. What we need to take care is that static synchronized methodlocked on class object lock and non static synchronized method locks on current object(this). So its possible that both static and non static java synchronized method running inparallel. This is the common mistake a naive developer do while writing javasynchronized code.

    public class Counter{

    private static int count = 0;

    public static synchronized int getCount(){return count;

    }

    public synchoronized setCount(int count){this.count = count;

    }

    }

    In this example ofjava synchronization code is not properly synchronizedbecause both

    getCount() and setCount() are not getting locked on same object and can run in parallelwhich results in getting incorrect count. Here getCount() will lock in Counter.class objectwhile setCount() will lock on current object (this). To make this code properly synchronizedin java you need to either make both method static or non static or use java synchronizedblock instead of java synchronized method.

    Example of synchronized block in Java

    Using synchronized block in java is also similar to using synchronized keyword inmethods. Only important thing to note here is that if object used to lock synchronizedblock of code, Singleton.class in below example is null then java synchronized block willthrow a NullPointerException.

    public class Singleton{private static volatile Singleton _instance;

    public static Singleton getInstance(){

    if(_instance == null){

    synchronized(Singleton.class){

    if(_instance == null)_instance = new Singleton();}

  • 7/28/2019 General Java Questions

    6/34

    }return _instance;

    }

    This is a classic example of double checked locking in Singleton. In this example of javasynchronized code we have made only critical section (part of code which is creatinginstance of singleton) synchronized and saved some performance because if you makewhole method synchronized every call of this method will be blocked while you only needto create instance on first call. To read more aboutSingleton in Javasee here.

    Important points of synchronized keyword in Java1. Synchronized keyword in Java is used to provide mutual exclusive access ofa shared resource with multiple threads in Java. Synchronization in java guarantees thatno two threads can execute a synchronized method which requires same locksimultaneously or concurrently.

    2. You can use java synchronized keyword only on synchronized method or synchronized

    block.

    3. When ever a thread enters into java synchronized method or block it acquires alock and whenever it leaves java synchronized method or block it releases the lock. Lockis released even if thread leaves synchronized method after completion or due to any Erroror Exception.

    4. Java Thread acquires an object level lock when it enters into an instance synchronizedjava method and acquires a class level lock when it enters into static synchronized java

    method.

    5.java synchronized keyword is re-entrant in nature it means if a java synchronizedmethod calls another synchronized method which requires same lock then current threadwhich is holding lock can enter into that method without acquiring lock.

    6. Java Synchronization will throw NullPointerException if object used injava

    synchronized block is null e.g. synchronized (myInstance) will throwsNullPointerException if myInstance is null.

    7. One Major disadvantage of java synchronized keyword is that it doesn'tallow concurrent read which you can implement usingjava.util.concurrent.locks.ReentrantLock.

    8. One limitation of java synchronized keyword is that it can only be used to controlaccess of shared object within the same JVM. If you have more than one JVM and need tosynchronized access to a shared file system or database, the java synchronized keyword isnot at all sufficient. You need to implement a kind of global lock for that.

    9. Java synchronized keyword incurs performance cost. Synchronized method in

    Java is very slow and can degrade performance. So use synchronization in java when itabsolutely requires and consider using java synchronized block for synchronizing criticalsection only.

    10. Java synchronized block is better than java synchronized method in javabecause by using synchronized block you can only lock critical section of code and avoidlocking whole method which can possibly degrade performance. A good example of javasynchronization around this concept is getInstance() method Singleton class. See here.

    11. Its possible that both static synchronized and non static synchronized methodcan run simultaneously or concurrently because they lock on different object.

    12. From java 5 after change in Java memory model reads and writes are atomic forall variables declared using volatile keyword (including long and double variables)

    http://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.html
  • 7/28/2019 General Java Questions

    7/34

    and simple atomic variable access is more efficient instead of accessing these variables viasynchronized java code. But it requires more care and attention from the programmer toavoid memory consistency errors.

    13. Java synchronized code could result in deadlock or starvation while accessingby multiple thread if synchronization is not implemented correctly. To knowhow to avoiddeadlock in javasee here.

    14. According to the Java language specification you can not use java synchronizedkeyword with constructorits illegal and result in compilation error. So you can notsynchronized constructor in Java which seems logical because other threads cannot see

    the object being created until the thread creating it has finished it.

    15. You cannot apply java synchronized keyword with variables and can not usejava volatile keyword with method.

    16. Java.util.concurrent.locks extends capability provided by java synchronized keywordfor writing more sophisticated programs since they offer more capabilitiese.g. Reentrancy and interruptible locks.

    17.java synchronized keyword also synchronizes memory. In fact java synchronizedsynchronizes the whole of thread memory with main memory.

    18. Important method related to synchronization in Java are wait(), notify() andnotifyAll() which is defined in Object class.

    19. Do not synchronize on non final field on synchronized block in Java. becausereference of non final field may change any time and then different thread mightsynchronizing on different objects i.e. no synchronization at all. example of synchronizingon non final field :

    private String lock = new String("lock");synchronized(lock){System.out.println("locking on :" + lock);}any if you write synchronized code like above in java you may getwarning "Synchronization on non-final field" in IDE like Netbeans and InteliJ

    20. Its not recommended to use String object as lock in java synchronizedblock becausestring is immutable objectand literal string and interned string gets storedin String pool. so by any chance if any other part of code or any third party library usedsame String as there lock then they both will be locked on same object despite beingcompletely unrelated which could result in unexpected behavior and bad performance.instead of String object its advised to use new Object() for Synchronization in Java onsynchronized block.

    private static final String LOCK = "lock"; //not recommended

    private static final Object OBJ_LOCK = new Object(); //better

    public void process() {synchronized(LOCK) {

    ........

    }}

    21. From Java library Calendar and SimpleDateFormat classes are not thread-safe andrequires external synchronization in Java to be used in multi-threaded environment.

    Probably most important point about synchronization in Java is that in the absence ofsynchronized keyword or construct compiler, JVM and hardware are free to makeoptimization, assumption, reordering or caching of code and variable which can cause

    http://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.html
  • 7/28/2019 General Java Questions

    8/34

    subtle concurrency bugs in code. By introducing synchronization may be either usingvolatile or synchronized keyword we instruct compiler or JVM to not to do that

    Difference between HashMap and HashSet in Java

    HashMap vs HashSet is the most frequently asked question during anycore java interview

    andinterview is not said completed until they will not cover the CollectionFramework andmulti-threading interviewand collections are uncompletedwithout Covering Hash Set and Hash Map.Both HashMap and HashSet are part of collection framework which allows us to work withcollection of objects. Collection Framework has their own interfaces and implementationclasses. Basically collection is divided as Set Interface, List and Queue Interfaces. Allthis interfaces have their own property also apart from they get from collection like Set

    allows Collection of objects but forbids duplicate value, List allows duplicate along withindexing.Queue woks on FCFS algorithm.

    First we have one look on What HashMap and Hashset is then will go for Differencesbetween HashSet and HashMap

    What is HashSet in Java?

    HashSet is implementation ofSet Interface which does not allow duplicate value all themethods which are in CollectionFramework are also in Set Interface by default butwhen we are talking about Hash set the main thing is objects which are going to be storedin HashSet mustoverride equals()andhashCode() method so that we can checkfor equality and no duplicate value are stored in our set.if we have created our own objects

    we need to implement hashCode() and equal() in such a manner that will be able tocompare objects correctly when storing in a set so that duplicate objects are not stored,ifwe have not override this method objects will take default implementation of this method.

    public boolean add(Object o) Method is used to add element in a set which returnsfalse if its a duplicate value in case of HashSet otherwise returns true if added

    successfully.

    What is HashMap?

    HashMap is a implementation of Map Interface, which maps a key to value.Duplicatekeys are not allowed in a map.Basically map Interface has two implementation classesHashMap and TreeMap the main difference is TreeMap maintains order of the objects butHashMap will not.HashMap allows null values and null keys.HashMap is notsynchronized,but collection framework provide methods so that we can make themsynchronized if multiple threads are going to access our hashmap and one thread isstructurally change our map.

    public Object put(Object Key,Object value) method is used to add element in map.

    You can read more about HashMap in my articleHow HashMap works inJavaandDifference between HashMap and hashtable in Java

    Difference between HashSet and HashMap in Java

    Following are some differences between HashMap and Hashset:

    Hash Map Hash Set

    HashMap is a implementation of Map

    interface

    HashSet is an implementation of Set

    Interface

    HashMap Stores data in form of keyvalue pair

    HashSet Store only objects

    http://javarevisited.blogspot.in/2011/09/difference-hashmap-vs-hashset-java.htmlhttp://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.htmlhttp://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.htmlhttp://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.htmlhttp://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.htmlhttp://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.htmlhttp://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.htmlhttp://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.htmlhttp://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.htmlhttp://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.htmlhttp://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.htmlhttp://javarevisited.blogspot.in/2011/09/difference-hashmap-vs-hashset-java.html
  • 7/28/2019 General Java Questions

    9/34

    Put method is used to add element in

    map

    Add method is used to add element is

    Set

    In hash map hashcode value iscalculated using key object

    Here member object is used forcalculating hashcode value which canbe same for two objects so equal ()method is used to check for equality

    ifit returns false that means twoobjects are different.

    HashMap is faster than hashsetbecause unique key is used to accessobject

    HashSet is slower than Hashmap

    What is the difference between Enumeration and Iterator ?

    What are differences between Enumeration and Iterator This question is from earlyages of interview , I have not seen this question on recent interviews but it was commonduring 2006-2007 , now days questions like implementation of HashMap,

    ConcurrentHashMap etc has take its place, nonetheless its very usefulto know fundamental difference between Iterator and Enumeration. Some time its

    also asked as Iterator vs Enumeration or Enumeration vs Iterator which is same.important point to note is that both Iterator and Enumeration provides way to traverse ornavigate through entire collection in java

    Between Enumeration and Iterator, Enumeration is older and its there from JDK1.0 while

    iterator was introduced later. Iterator can be used withJava arraylist,java hashmapkeyset and with any other collection classes.

    Another similarity between Iterator and Enumeration in Java is that functionality ofEnumeration interface is duplicated by the Iterator interface.

    Only major difference between Enumeration and iterator is 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 by using Iterator we canmanipulate the objects like adding and removing the objects from collection e.g. Arraylist.

    Also Iterator is more secure and safe as compared to Enumeration because it does notallow other thread to modify the collection object while some thread is iterating over it andthrows ConcurrentModificationException.This is by far most important fact for me fordeciding between Iterator vs Enumeration in Java.

    In Summary both Enumeration and Iterator will give successive elements, but Iterator isnew and improved version where method names are shorter, and has new method calledremove. Here is a short comparison:

    Enumeration

    hasMoreElement()nextElement()N/A

    IteratorhasNext()next()remove()

    So Enumeration is used when ever we want to make Collection objects as Read-only.

    How to implement Thread in JAVAIn my opinion Thread is the most wonderful feature of JAVA and I remember when I

    started learning JAVA in one of programming class in India how important Thread wasportrait and how much emphasis given on clear understanding of multi threading. Itsindeed still popular and one of most sought after skill in JAVA.

    http://javarevisited.blogspot.in/2010/10/what-is-difference-between-enumeration.htmlhttp://javarevisited.blogspot.com/2011/06/converting-array-to-arraylist-in-java.htmlhttp://javarevisited.blogspot.com/2011/06/converting-array-to-arraylist-in-java.htmlhttp://javarevisited.blogspot.com/2011/06/converting-array-to-arraylist-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/06/converting-array-to-arraylist-in-java.htmlhttp://javarevisited.blogspot.in/2010/10/what-is-difference-between-enumeration.html
  • 7/28/2019 General Java Questions

    10/34

    In thiscore java tutorialI will share my experience on different way of implementingThread in Java; this is also a very common core java interview questionand asked mostlyduring junior level java interview.

    There are two ways of implementing threading in JAVA1) By extending java.lang.Thread class, or2) By implementing java.lang.Runnable interface.

    Before we go into implementation details I just like to cover when we use thread? so weuse thread if we want some part of code is executed parallel and we put that code insiderun() method of either Thread class or Runnable interface.

    Actually public void run () method is defined in Runnable interface and sincejava.lang.Thread class implements Runnable interface it gets this method automatically. Iremember by first java multi threading example which was an animation program wheremultiple threads were used in Applet to create animation of words falling from top left,middle and top right of the page. That was pretty exciting at that time because till then Ionly know program which takes input from command prompt and print output oncommand prompt.

    So now the interview question "Which way of implementing Thread is better? ExtendingThread class or implementing Runnable method?In my opinion implementing Runnable is better because in Java we can only extend oneclass so if we extend Thread class we can not extendany other class while by implementing Runnable interface we still have that option openwith us.

    Second reason which make sense to me is more on OOPS concept according to OOPS if weextend a class we provide some new feature or functionality , So if the purpose is just touse the run() method to define code its better to use Runnable interface.

    till then we have just created a thread , Thread will not start until you call the start()method of java.lang.Thread class. When we call start () method Java Virtualmachine execute run () method of that Thread class into separate Thread other thancalling thread. Anybody guess what will happen if we call the run() method directly insteadof calling start() method ?

    Thatanother interesting interview questionand answer is simple there would be any Erroror Exception run() method will simply be executed in the same Thread and new Thread willnot be created. Another follow up question would be what will happen if you call start ()method twice in same Thread object e.g.

    mythread.start();mythread.start();// this line will throw IllegalThreadStateException

    //implementing Thread by extending Thread classclass MyThread extends Thread{

    public void run(){

    System.out.println("I am executing by Thread: " +Thread.currentThread().getName());

    }}

    //implementing Thread by implementing Runnable interfaceclass MyRunnable implements Runnable{

    public void run(){System.out.println("I am executing by Thread: " +

    Thread.currentThread().getName());}

    http://javarevisited.blogspot.com/search/label/core%20javahttp://javarevisited.blogspot.com/search/label/core%20javahttp://javarevisited.blogspot.com/search/label/core%20javahttp://javarevisited.blogspot.com/search/label/core%20java%20interview%20questionhttp://javarevisited.blogspot.com/search/label/core%20java%20interview%20questionhttp://javarevisited.blogspot.com/search/label/core%20java%20interview%20questionhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/search/label/core%20java%20interview%20questionhttp://javarevisited.blogspot.com/search/label/core%20java
  • 7/28/2019 General Java Questions

    11/34

    }

    //starting Thread

    Thread mythread = new MyThread();mythread.setName("T1");Thread myrunnable = new Thread(new MyRunnable(),"T2");

    mythread.start();myrunnable.start();

    TIP1: Its not guaranteed that mythread will start before myrunnable it dependsupon Thread scheduler.TIP2: Thread will be said to go on dead state once execution of run () methodfinished and you cannot start that thread again.

    What is Race Condition in multithreading 2 Examples in Java

    Race condition in Java is a type of concurrency bug or issue which is introduced in your

    program because parallel execution of your program by multiple threads at same time,Since Java is a multi-threaded programming language hence risk of Race condition ishigher in Java which demands clear understanding of what causes a race condition andhow to avoid that. Anyway Race conditions are just one of hazards or risk presentedby use of multi-threading in Java just likedeadlock in Java.Race conditions occurswhen two thread operate on same object without proper synchronization and thereoperation interleaves on each other. Classical example of Race condition is

    incrementing a counter since increment is not an atomic operation and can be furtherdivided into three steps like read, update and write. if twothreadstries to increment countat same time and if they read same value because of interleaving of read operation of onethread to update operation of another thread, one count will be lost when one threadoverwrite increment done by other thread. atomic operations are notsubject to raceconditions because those operation cannot be interleaved. This is alsoa popular multi-threading interview questionsduring core java interviews. In this article we will see how

    to find race condition in Java and two sample code patterns which often causesrace conditions in Java.

    How to find Race Conditions in JavaFinding Race conditions in any language is most difficult job and Java is no different,though since readability of Java code is very good and synchronized constructs are welldefined heaps to find race conditions by code review. finding race conditions by unittesting is not reliable due to random nature of race conditions. since race conditionssurfaces only some time your unit test may passed without facing any race condition. onlysure shot way to find race condition is reviewing code manually or using code review toolswhich can alert you on potential race conditions based on code pattern and use ofsynchronization in Java. I solely rely oncode reviewand yet to find a suitable tool forexposing race condition in java.

    Code Example of Race Condition in Java

    Based on my experience in Java synchronization and where we use synchronized keywordI found that two code patterns namely "check and act" and "read modify write" cansuffer race condition if not synchronized properly. both cases rely on natural assumptionthat a single line of code will be atomic and execute in one shot which is wrong e.g. ++ isnot atomic.

    "Check and Act" race condition pattern

    classical example of "check and act" race condition in Java is getInstance() method ofSingleton Class, remember that was one questions which we have discussed on 10Interview questions on Singleton pattern in Java as "How to write thread-safe Singleton inJava". getInstace() method first check for whether instance is null and than initialized theinstance and return to caller. Whole purpose of Singleton is that getInstance should alwaysreturn same instance of Singleton. if you call getInstance() method from two thread

    http://javarevisited.blogspot.in/2012/02/what-is-race-condition-in.htmlhttp://javarevisited.blogspot.in/2012/02/what-is-race-condition-in.htmlhttp://javarevisited.blogspot.in/2012/02/what-is-race-condition-in.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-implement-thread-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-implement-thread-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-implement-thread-in-java.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/09/code-review-checklist-best-practice.htmlhttp://javarevisited.blogspot.com/2011/09/code-review-checklist-best-practice.htmlhttp://javarevisited.blogspot.com/2011/09/code-review-checklist-best-practice.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.htmlhttp://javarevisited.blogspot.com/2011/09/code-review-checklist-best-practice.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.htmlhttp://javarevisited.blogspot.com/2011/02/how-to-implement-thread-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.in/2012/02/what-is-race-condition-in.html
  • 7/28/2019 General Java Questions

    12/34

    simultaneously its possible that while one thread is initializing singleton after null check,another thread sees value of _instance reference variable as null (quite possible in java)especially if your object takes longer time to initialize and enters into critical section whicheventually results in getInstance()returning two separate instance of Singleton. This may

    not happen always because a fraction of delay may result in value of _instance updated inmain memory. here is a code example

    public Singleton getInstance(){if(_instance == null){ //race condition if two threads sees _instance= null_instance = new Singleton();}

    }

    an easy way to fix "check and act" race conditions is to synchronized keyword andenforce locking which will make this operation atomic and guarantees that block or methodwill only be executed by one thread and result of operation will be visible to all threadsoncesynchronized blockscompleted or thread exited form synchronized block.

    read-modify-update race conditionsThis is another code pattern in Java which cause race condition, classical example is the

    non thread safe counter we discussed inhow to write thread safe class in Java. this is alsoa very popular multi-threading question where they ask you to find bugson concurrent code. read-modify-update pattern also comes due to impropersynchronization ofnon-atomic operations or combination of two individual atomicoperationswhich is not atomic together e.g. put if absent scenario. consider below code

    if(!hashtable.contains(key)){hashtable.put(key,value);}

    here we only insert object into hashtable if its not already there. point is both contains()and put() are atomic but still this code can result in race condition since both operationtogether is not atomic. consider thread T1 checks for conditions and goes inside ifblock now CPU is switched from T1 to thread T2 which also checks condition and goesinside if block. now we have two thread inside if block which result in either T1 overwritingT2 value or vice-versa based on which thread has CPU for execution. In order to fix thisrace condition in Java you need to wrap this code inside synchronized block which

    makes them atomic together because no thread can go inside synchronized block if onethread is already there.

    Java Web Services Interview Questions and Answers: Overview

    Q. What are the different application integration styles?

    A. There are a number of different integration styles like

    1. Shared database

    2. batch file transfer

    3. Invoking remote procedures (RPC)

    4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).

    http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.htmlhttp://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.htmlhttp://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.htmlhttp://javarevisited.blogspot.com/2012/01/how-to-write-thread-safe-code-in-java.htmlhttp://javarevisited.blogspot.com/2012/01/how-to-write-thread-safe-code-in-java.htmlhttp://javarevisited.blogspot.com/2012/01/how-to-write-thread-safe-code-in-java.htmlhttp://javarevisited.blogspot.com/2012/01/how-to-write-thread-safe-code-in-java.htmlhttp://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html
  • 7/28/2019 General Java Questions

    13/34

    Q. What are the different styles of Web Services used for application integration?

    A.SOAP WS and RESTful Web Service

    Q. What are the differences between both SOAP WS and RESTful WS?

    A.

    The SOAP WS supports both remote procedure call (i.e. RPC) and messageoriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPCintegration style.

    The SOAP WS is transport protocol neutral. Supports multiple protocols likeHTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific.Supports only HTTP or HTTPS protocols.

    http://1.bp.blogspot.com/-PzRrLNGPU9U/TzSyk9vzpYI/AAAAAAAAASk/wsDCrNTg9FM/s1600/integration-styles.JPG
  • 7/28/2019 General Java Questions

    14/34

    The SOAP WS permits only XML data format.You define operations, which tunnelsthrough the POST. The focus is on accessing the named operations and exposing theapplication logic as a service. The REST permits multiple data formats like XML, JSON data,text, HTML, etc. Any browser can be used because the REST approach uses the standardGET, PUT, POST, and DELETE Web operations. The focus is on accessing the namedresources and exposing the data as a service. REST has AJAX support. It can use the

    XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete)operations.

    GET - represent()

    POST - acceptRepresention()

    PUT - storeRepresention()

    DELETE - removeRepresention()

    SOAP based reads cannot be cached. REST based reads can be cached. Performsand scales better.

    SOAP WS supports both SSL security and WS-security, which adds some enterprisesecurity features like maintaining security right up to the point where it is needed,maintaining identities through intermediaries and not just point to point SSL only, securing

    different parts of the message with different security algorithms, etc. The REST supportsonly point-to-point SSL security. The SSL encrypts the whole message, whether all of it issensitive or not.

    The SOAP has comprehensive support for both ACID based transactionmanagement for short-lived transactions and compensation based transactionmanagement for long-running transactions. It also supports two-phase commit acrossdistributed resources. The REST supports transactions, but it is neither ACID compliantnor can provide two phase commit across distributed transactional resources as it islimited by its HTTP protocol.

    The SOAP has success or retry logic built in and provides end-to-end reliabilityeven through SOAP intermediaries. REST does not have a standard messaging system,and expects clients invoking the service to deal with communication failures by retrying.

    Q. How would you decide what style of Web Service to use? SOAP WS or REST?

    A. In general, a REST based Web service is preferred due to its simplicity, performance,

    scalability, and support for multiple data formats. SOAP is favored where service requires

    comprehensive support for security and transactional reliability.

    The answer really depends on the functional and non-functional requirements. Asking the

    questions listed below will help you choose.

    Does the service expose data or business logic? (REST is a better choice forexposing data, SOAP WS might be a better choice for logic).Do the consumers and theservice providers require a formal contract? (SOAP has a formal contract via WSDL)

    Do we need to support multiple data formats?

    Do we need to make AJAX calls? (REST can use the XMLHttpRequest)

    Is the call synchronous or asynchronous?

    Is the call stateful or stateless? (REST is suited for statless CRUD operations)

    What level of security is required? (SOAP WS has better support for security)

    What level of transaction support is required? (SOAP WS has better supportfor transaction management)

    Do we have limited band width? (SOAP is more verbose)

    Whats best for the developers who will build clients for the service? (RESTis easier to implement, test, and maintain)

  • 7/28/2019 General Java Questions

    15/34

    Q. What tools do you use to test your Web Services?

    A.SoapUI tool for SOAP WS and the Firefox "poster" plugin for RESTFul services.

    Q. What is the difference between SOA and a Web service?

    A.

    SOA is a software design principle and an architectural pattern for implementing loosely

    coupled, reusable and coarse grained services. You can implement SOA using any

    protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc.

    Messages can be in XML or Data Transfer Objects (DTOs).

    Web service is an implementation technology and one of the ways to implement SOA.

    You can build SOA based applications without using Web services for example by usingother traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web

    services offer is the standards based and platform-independent service via HTTP, XML,

    SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies

    such as J2EE and .NET.

    Q. Web services when you can use traditional style middle-ware such as RPC, CORBA, RMI

    and DCOM?

    A.

    The traditional middle-wares tightly couple connections to the applications and it can

    break if you make any modification to your application. Tightly coupled applications are

    hard to maintain and less reusable. Generally do not support heterogeneity. Do not work

    across Internet. Can be more expensive and hard to use.

    Web Services support loosely coupled connections. The interface of the Web service

    provides a layer of abstraction between the client and the server. The loosely coupled

    applications reduce the cost of maintenance and increases re-usability. Web Services

    present a new form of middle-ware based on XML and Web. Web services are language

    and platform independent. You can develop a Web service using any language and deployit on to any platform, from small device to the largest supercomputer. Web service uses

    language neutral protocols such as HTTP and communicates between disparate

    applications by passing XML messages to each other via a Web API. Do work across

    internet, less expensive and easier to use.

    Q. What are the different approaches to developing a SOAP based Web service?

    A. 2 approaches.

    The contract-first approach, where you define the contract first with XSD and

    WSDL and the generate the Java classes from the contract.

  • 7/28/2019 General Java Questions

    16/34

    The contract-last approach where you define the Java classes first and thengenerate the contract, which is the WSDL file from the Java classes.

    Note: The WSDL describes all operations that the service provides, locations of the

    endpoints (i.e.e where the services can be invoked), and simple and complex elements

    that can be passed in requests and responses.

    Q. What are the pros and cons of each approach, and which approach would you prefer?

    A.

    Contract-first Web service

    PROS:

    Clients are decoupled from the server, hence the implementation logic can berevised on the server without affecting the clients.

    Developers can work simultaneously on client and server side based on thecontract both agreed on.

    You have full control over how the request and response messages are constructed-- for example, should "status" go as an element or as an attribute? The contract clearlydefines it. You can change OXM (i.e. Object to XML Mapping) libraries without having toworry if the "status" would be generated as "attribute" instead of an element. Potentially,even Web service frameworks and tool kits can be changed as well from say Apache Axisto Apache CXF, etc

    CONS:

    More upfront work is involved in setting up the XSDs and WSDLs. There are toolslike XML Spy, Oxygen XML, etc to make things easier. The object models need to bewritten as well.

    Developers need to learn XSDs and WSDLs in addition to just knowing Java.

    Contract-last Web service

    PROS:

    Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. Theservices are created quickly by exposing the existing service logic with frameworks/toolsets. For example, via IDE based wizards, etc.

    The learning curve and development time can be smaller compared to theContract-first Web service.

    CONS:

    The development time can be shorter to initially develop it, but what about the ongoing maintenance and extension time if the contract changes or new elements need to beadded? In this approach, since the clients and servers are more tightly coupled, the future

    changes may break the client contract and affect all clients or require the services to beproperly versioned and managed.

  • 7/28/2019 General Java Questions

    17/34

    In this approach, The XML payloads cannot be controlled. This means changingyour OXM libraries could cause something that used to be an element to become anattribute with the change of the OXM.

    So, which approach will you choose?

    The best practice is to use "contract-first", and here is the link that explains this much

    better with examples --> contract-first versus contract-last web servicesIn a nutshell, the

    contract-last is more fragile than the "contract-first". You will have to decide what is most

    appropriate based on your requirements, tool sets you use, etc.

    JavaScript Interview Questions and Answers: Overview

    Like me, many have a love/hate relationship with JavaScript. Now a days, JavaScript is

    very popular with the rich internet applications (RIA). So, it really pays to know JavaScript.

    JavaScript is a client side (and server side with node.js) technology that is used todynamically manipulate the DOM tree. There are a number of JavaScript based

    frameworks like jQuery available to make your code more cross browser compatible and

    simpler. Firstly, it is much easier to understand JavaScript if you stop comparing it with

    Java or understand the key differences. Both are different technologies.

    If you need more motivation to learn JavaScript, look at the Node.js, which is a software

    system designed for writing highly-scalable internet applications in JavaScript, using

    event-driven, asynchronous I/O to minimize overhead.

    Q. What is the difference between Java and JavaScript?

    A. Don't be fooled by the term Java in both. Both are quite different technologies. The key

    differences can be summarized as follows:

    JavaScript variables are dynamically typed, whereas the Java variables arestatically typed.

    ?

    123

    4

    var myVar1 = "Hello"; //string typevar myVar2 = 5; //number typevar myVar3 = new Object( ); //empty object type

    var myVar4 = {}; //empty object type -- JSON (JavaScript Object Notation) style.

    In JavaScript properties and methods are dynamically added, whereas Java uses atemplate called a class. ThemyVar3 empty object dynamically adds properties and amethod.

    ?

    123

    456

    myVar3.firstName = "Test1"; // add a property to objectmyVar3.lastName = "Test2"; // add a property to object// add a method

    myVar3.someFunction = function( ) {//.

    }

    http://static.springsource.org/spring-ws/site/reference/pdf/spring-ws-reference.pdfhttp://static.springsource.org/spring-ws/site/reference/pdf/spring-ws-reference.pdfhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://static.springsource.org/spring-ws/site/reference/pdf/spring-ws-reference.pdf
  • 7/28/2019 General Java Questions

    18/34

    JavaScript function can take variable arguments. You can call the function shownbelow as myFunction( ), myFunction(20), or myFunction(20,5).

    ?

    1

    23

    function myFunction( value ) {

    //.. do something here}

    JavaScript has an implicit keyword known as the "arguments", which holds all thepassed arguments. It also has a "length" property as in arguments.length to displaythe number of arguments. Technically an "arguments" is not an array as it does nothave the methods like push, pop, or split that an array has. Here is an example.

    ?

    123

    45678910

    myFunction(5,10,15,20);

    function myFunction(value) {

    //value is 5;//arguments[0] is 5//arguments[1] is 10//arguments[2] is 15//arguments[3] is 20//arguments.length is 4

    }

    JavaScript objects are basically like name/value pairs stored ina HashMap.

    For example, a JavaScript object is represented in JSON style as shown below.

    ?

    123456789101112

    var personObj = {firstName: "John",lastName: "Smith",age: 25,printFullName: function() {

    document.write(this.firstName + " " + this.lastName);} ,

    printAge: function () {document.write("My age is: " + this.age);

    }}

    You can invoke the methods as shown below

    ?

    123

    personObj.printFullName();

    personObj.printAge();

    JavaScript functions are objects as well. Like objects, the functions can be storedto a variable, passed as arguments, nested within each other, etc. In the above example,nameless functions are attached to variables "printFullName" and "printAge" and invokedvia these variables. A function that is attached to an object via a variable is known as a"method". So,printFullName andprintAge are methods.

    http://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.html
  • 7/28/2019 General Java Questions

    19/34

    Technically, what is done with the "add" and "sum" functions is that we have created anew function object and attached them to the variables "add" and sum. As you can see inthe example below, the "add" variable is assigned to variable "demo", and the function isinvoked via demo(2,5) within the "sum" function.

    ?

    1234567

    891011

    function add(val1, val2) {var result = val1 + val2;alert("The result is:" + result);return result;

    }

    var demo = add;

    function sum() {var output = demo(5, 2);

    }

    Now the above temp.js under tutorial/js folder can be invoked from an HTML file under

    tutorial/html as shown below.

    ?

    12345678910111213

    1415161718

  • 7/28/2019 General Java Questions

    20/34

    1234

    567891011

    1213141516

  • 7/28/2019 General Java Questions

    21/34

    Timer functions like

    ?

    1?

    1234

    var id = setTimeout(function, delay); // Initiates a single timer which will call the specified function after thvar id = setInterval(function, delay); // Similar to setTimeout but continually calls the function (with a delayclearInterval(id); // Accepts a timer ID (returned by either of the aforementioned functions) aclearTimeout(id);

    Ajax responses asynchronously invoking a callback function when theresponse is sent back from the server. It is asynchronous because, you don't know howlong a server will take to process the ajax request and then to send the response.

    to execute within the same thread. Even though all the above time based events appear tobe run concurrently, they are all executed one at a time by queuing all these events. Thisalso mean that if a timer is blocked from immediately executing, it will be delayed until thenext possible point of execution making it to wait longer than the desired delay. This mightalso cause the intervals executewith no delay.

    Having said this, HTML5 specifies Web Workers, which is a standardized API for multi-threading JavaScript code.

    Here are the key points to remember:

    4. JavaScript variables are dynamically typed.

    5. In JavaScript properties and methods are dynamically added.

    6. JavaScript function can take variable arguments.

    7. JavaScript objects are basically like name/value pairs stored ina HashMap.

    8. JavaScript functions are objects as well.

    Here are some working examples: For the examples shown below, the HTML files are

    stored under /html sub-folder and JavaScript files are stored under /js sub-folder. Theconsole.log() statements are written to your browser's web console. For example, infirefox, you can view the web console via tools - Web Developer - Web Console. Make surethat the version of Firefox you use has this option. The Web Console is handy fordebugging as well.

    Example 1: two input values are either added or concatenated depending on their types.If both values of type number then add them, otherwise just concatenate the values. Takenote of the JavaScript keywords and functions like typeof, isNaN(..), Number(..),parseInt(..), etc. The "document" is part of the DOM tree representing an HTML documentin memory. The method "getElementById(...)" will return the relevant "input" elementfrom the DOM tree, and "value" will return the input value that was entered.?1234567

    89101112

    1314

    15

  • 7/28/2019 General Java Questions

    22/34

    16171819

    20212223242526

    2728

    ?123456

    789101112131415161718192021

    function addOrConcat() {var val1 = document.getElementById("val1").value; //stringvar val2 = document.getElementById("val2").value; //stringvar result = document.getElementById("result"); //object

    var ans = -1; //number

    //if val1 and val2 are numbers, add themif(!isNaN(val1) && typeof parseInt(val2) == 'number') {

    ans = Number(val1) + Number(val2); //add numbers}else {

    ans = val1 + val2; //string concat}

    result.innerHTML = "Result is: " + ans;//write to browser console.console.log("val1 is of type " + typeof val1);console.log("result is of type " + typeof result);console.log("ans is of type " + typeof ans);

    }Example 2: Very similar to Example 1, but uses objects, and passes the relevant valuesfrom the call within HTML itself. It also uses the toString( ) method to convert a function

    object to display its source code.?12345

    678

    9101112

    13141516171819202122

    2324

  • 7/28/2019 General Java Questions

    23/34

    25262728

    ?123456

    789101112131415

    16171819202122232425

    function addOrConcat(val1,val2) {

    var evalObj = new Object(); //create an empty object

    evalObj.input1 = val1; // add a property of type stringevalObj['input2'] = val2; // add a property of type string

    evalObj.result = document.getElementById("result"); // add a property of type object

    //add a methodevalObj.evaluate = function() {

    if(!isNaN(this.input1) && typeof parseInt(this.input2) == 'number') {this.ans = Number(this.input1) + Number(this.input2); //add numbers

    }else {this.ans = evalObj.input1 + this.input2; //string concat

    }

    this.result.innerHTML = "Result is: " + this.ans;

    }

    evalObj.evaluate(); //call the method evaluate and "this" refers to evalObjconsole.log(evalObj.evaluate.toString());

    }Example 3: Similar to Example 2, with minor modifications to the JavaScript file todemonstrate keywords like "arguments"?1234

    567891011

    121314

    15161718

    19202122232425

    function addOrConcat() {

    var evalObj = new Object(); // create an empty object

    evalObj.input1 = arguments[0]; // this is value1evalObj['input2'] = arguments[1]; // this is value2evalObj.result = document.getElementById("result"); // add a property of type object

    //add a methodevalObj.evaluate = function() {

    if(!isNaN(this.input1) && typeof parseInt(this.input2) == 'number') {this.ans = Number(this.input1) + Number(this.input2); //add numbers

    }else {

    this.ans = evalObj.input1 + this.input2; //string concat}

    this.result.innerHTML = "Result is: " + this.ans;

    }

    evalObj.evaluate(); //call the method evaluate and "this" refers to evalObjconsole.log(evalObj.evaluate.toString());

    }

    http://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.htmlhttp://java-success.blogspot.in/2012/01/javascript-interview-questions-and.html
  • 7/28/2019 General Java Questions

    24/34

    Service Oriented Architecture(SOA) Interview QuestionsByadmin - Posted on 26 August 2009

    What are the main benefits of SOA ?

    SOA helps create greater alignment between IT and line of business while generating

    more flexibility - IT flexibility to support greater business flexibility. Your business

    processes are changing faster and faster and global competition requires the flexibility that

    SOA can provide.

    SOA can help you get better reuse out of your existing IT investments as well as the new

    services you're developing today. SOA makes integration of your IT investments easier by

    making use of well-defined interfaces between services. SOA also provides an architectural

    model for integrating business partners, customers and suppliers services into an

    enterprises business processes. This reduces cost and improves customer satisfaction

    What is a reusable Service?

    It is an autonomous, reusable, discoverable, stateless functionality that has the necessary

    granularity, and can be part of a composite application or a composite service.

    A reusable service should be identified with a business activity described by the service

    specifications (design-time contract).A service's constraints, including security, QoS, SLA, usage policies, may be defined by

    multiple run-time contracts, multiple interfaces (the WSDL for a SOAP Web Service), and

    multiple implementations (the code).

    A reusable service should be governed at the enterprise level throughout its entire

    lifecycle, from design-time through run-time. Its reuse should be promoted through a

    prescriptive process, and that reuse should be measured.

    Talking about Service identification, which approach between top-down and

    bottom-up methodologies encourages re-use and mantainance ?

    Since the top-down approach is business-driven it can be practical to separate the

    different concerns of business and IT on different plans, providing a common ground in

    between. So in most situations it the most appropriate if you want to improve reuse and

    ROI in the medium/long term. Anyway

    How can you achieve loose coupling in a soa ?

    One strategy for achieving loose coupling is to use the service interface (the WSDL for a

    SOAP Web Service) to limit this dependency, hiding the service implementation from

    the consumer. Loose coupling can be addressed by encapsulating the service

  • 7/28/2019 General Java Questions

    25/34

    functionalities in a manner that limits the impact of changes to the implementation on the

    service interface. However, at some point you will need to change the interface and

    manage versioning without impacting service consumers, in addition to managing multiple

    security constraints, multiple transports, and other considerations

    Do you recall any pattern which could be use to leverage loose coupling ?

    The Mediation pattern, using an enterprise service bus (ESB), will help in achieving this.

    Mediation will take loose coupling to the highest level. It will establish independence

    between consumers and providers on all levels, including message formats, message types

    (including SOAP, REST, XML, binary) and transport protocols (including HTTP, HTTPS,

    JMS).

    Architecturally speaking this means the separation of concerns between consumers and

    providers on the transport, message type, and message format levels.

    The Service of a SOA should be engineered as stateless or stateful ?

    Service should be stateless. It may have a context within its stateless execution, but it

    will not have an intermediary state waiting for an event or a call-back. The retention of

    state-related data must not extend beyond a request/response on a service. This is

    because state management consumes a lot of resources, and this can affect the scalability

    and availability that are required for a reusable service.

    What is composition of a Service ?

    Composition is the process by which services are combined to produce composite

    applications or composite services. A composite application consists of the aggregation of

    services to produce an enterprise portal or enterprise process. A composite service consists

    of an aggregation of services that produces another reusable service. It's just like combining

    electronic components to create a computer motherboard, and then using that

    motherboard in a computer. Think of the motherboard as a reusable composite service that

    is a component of the computer, and of the computer as the composite application.

    How do I integrate my Legacy applications with SOA ?

    Legacy applications are frequently at the core of your IT environment. With the right skills

    and tools, you need to identify discrete elements within your legacy applications and

    "wrap" them in standards-based interfaces and use them as services within your SOA.

    How does the ESB fits in this picture ?

    The Enterprise Service Bus is a core element of any SOA. ESBs provide the "any to any"

    connectivity between services within your own company, and beyond your business to

    connect to your trading partners. But SOA does not stop at just implementing an ESB.

  • 7/28/2019 General Java Questions

    26/34

    Depending on what your goals are, you may want to use an ESB to connect other services

    within your SOA such as information services, interaction services and business process

    management services. Additionally, you will need to consider development services and IT

    service management services. The SOA reference architecture can help you lay out an SOA

    environment that meets your needs and priorities. The ESB is part of this reference

    architecture and provides the backbone of an SOA but it should not be considered an SOA

    by itself.

    What are the common pitfalls of SOA ?

    One of the most common pitfalls is to view SOA as an end, rather than a means to an end.

    Developers who focus on building an SOA solution rather than solving a specific business

    problem are more likely to create complex, unmanageable, and unnecessary

    interconnections between IT resources.

    Another common pitfall is to try to solve multiple problems at once, rather than solving

    small pieces of the problem. Taking a top-down approachstarting with major

    organization-wide infrastructure investmentsoften fails either to show results in a

    relevant timeframe or to offer a compelling return on investment.

    What's the difference between services and components?Services are logical grouping of components to achieve business functionality. Components

    are implementation approaches to make a service. The components can be in JAVA, C#,

    C++ but the services will be exposed in a general format like Web Services.What are ends, contract, address, and bindings?These three terminologies on which SOA service stands. Every service must expose one or

    more ends by which the service can be available to the client. End consists of three

    important things where, what and how:-

    Contract is an agreement between two or more parties. It defines the protocol how client

    should communicate with your service. Technically, it describes parameters and return

    values for a method.

    An Address indicates where we can find this service. Address is a URL, which points to the

    location of the service.

    Bindings determine how this end can be accessed. It determines how communications is

    done. For instance, you expose your service, which can be accessed using SOAP over HTTP

    or BINARY over TCP. So for each of these communications medium two bindings will be

    created.

    Below figure, show the three main components of end. You can see the stock ticker is the

    service class, which has an end hosted onwww.soa.comwith HTTP and TCP binding

    support and using Stock Ticker interface type.

    http://www.soa.com/http://www.soa.com/http://www.soa.com/http://www.soa.com/
  • 7/28/2019 General Java Questions

    27/34

    The concept of SOA is nothing new, however why everyone started to talk about

    SOA only in the last years ?

    Yes I agree the basic concept of SOA aren't new, however some technology technology

    changes in the last 10 years made service-oriented architecture more practical and

    applicable to more organizations than it was previously. Among this:

    Universally-accepted industry standards such as XML, its many variants, and Web-services standards have contributed to the renewed interest in SOA.

    Data governance frameworks, which are important to a successful SOA implementation,have well test and refined over the years.

    A variety of enabling technologies and tools (e.g., modeling, development,infrastructure/middleware, management, and testing) have matured.

    Understanding of business and business strategies has grown, shifting attention from

    technology to the people, cultural changes, and process that are key business success

    factors.

    What is the most important skill you need to adopt SOA ? technical or cultural ?

    Surely cultural. SOA does require people to think of business and technology differently.

    Instead of thinking of technology first (e.g., If we implement this system, what kinds of

    things can we do with it?), practitioners must first think in terms of business functions, or

    services (e.g., My company does these business functions, so how can I set up my IT system

    to do those things for me most efficiently?).It is expected that adoption of SOA will change

    business IT departments, creating service-oriented (instead of technology-oriented) IT

    organizations.

    Is SOA really needed on your opinion?SOA is not for everyone. While SOA delivers significant benefits and cost savings, SOA

    does require disciplined enforcement of centralized governance principals to be successful.

    For some organizations, the cost of developing and enforcing these principals may be

    higher than the benefits realized, and therefore not a sound initiative.

  • 7/28/2019 General Java Questions

    28/34

    (B) What is SOA?

    SOA stands for service oriented architecture. Before we define SOA lets first define a

    service. In real world service is what we pay for and we get the intended service. For

    instance you go to a hotel and order food. Your order first goes to the counter and then it

    goes to the kitchen where the food is prepared and finally the waiter serves the food.

    Figure: - Hotel and services

    So in order to order a item from a hotel you need the three logical departments / services

    to work together (counter, kitchen and waiter).

    In the same manner in software world these services are termed as business services. They

    are self contained and logical. So let's first define a business service, SOA definition will be

    just an extension of the same.

    Definition of business service: - It's a logical encapsulation of self contained businessfunctionality.

    For instance figure 'order system' shows a simple ordering system which is achieved by

    different services like payment gateway, stock system and delivery system coming

    together. All the services are self contained and logical. They are like black boxes. In short

    we do not need to understand the internal details of how the business service works. For

    the external world it's just a black box which takes messages and serves accordingly. For

    instance the 'payment gateway' business service takes message 'check credit' and gives out

    output does the customer have credit or not. For the 'order system' business service

    'payment gateway' service is a black box.

  • 7/28/2019 General Java Questions

    29/34

    Figure: - Order system

    Now let's revise some bullet points of SOA before we arrive to a definition of SOA.

    . SOA components are loosely coupled. When we say loosely coupled means every service

    is self contained and exist in alone logically. For instance we take the 'payment gateway'

    service and attach it to a different system.

    . SOA services are black boxes. In SOA services hide there inner complexities. They only

    interact using messages and send services depending on those messages. By visualizing

    services as black boxes services become more loosely coupled.

    . SOA service should be self defined: - SOA services should be able to define themselves.

    . SOA Services are maintained in a listing: - SOA services are maintained in a central

    repository. Applications can search the services in the central repository and use them

    accordingly.

    . SOA components can be orchestrated and linked to achieve a particular functionality .

    SOA services can be used/orchestrated in a plug and play manner. For instance figure

    'Orchestration' shows two services 'Security service' and 'Order processing service'. You can

    achieve two types of orchestrations from it one you can check the user first and then

    process order or vice-versa. Yes you guessed right using SOA we can manage work flow

    between services in a loosely coupled fashion.

  • 7/28/2019 General Java Questions

    30/34

    Figure: - Orchestration

    So let us define SOA.

    SOA is a architecture for building business applications using loosely coupled services which

    act like black boxes and can be orchestrated to achieve a specific functionality by linkingtogether.

    (I) In SOA do we need to build systems from scratch?

    No. If you need to integrate or make an existing system as a business service, you just need

    to create loosely coupled wrappers which will wrap your custom systems and expose the

    systems functionality in generic fashion to the external world.

    (I) Can you explain business layers and plumbing layers in SOA?

    In SOA we can divide any architecture in two layers. The first which has direct relevance to

    business as it carries out business functions. The second layer is a technical layer which

    talks about managing computer resources like database, web server etc. This division is

    needed to identify a service. Consider the figure 'Simple order system'. It has various

    components which interact with each other to complete the order system functionality.

    Figure: - Simple order System

    The simple order system can be divided in to two layers (see figure 'business and plumbing

    layer' one which is business related and second which is more technical related. You can

    see the plumbing layer consisting of data access layer , AJAX , yes more of technical stuff.

  • 7/28/2019 General Java Questions

    31/34

    Figure: - Business layer and plumbing layer

    (I) what's the difference between services and components?

    Services are logical grouping of components to achieve business functionality. Components

    are implementation approaches to make a service. The components can be in JAVA, C#,

    C++ but the services will be exposed in a general format like Web Services.

    (A) Can you describe the complete architecture of SOA?

    Figure 'Architecture of SOA' shows a complete view of a SOA. Please note this architecture

    diagram is not tied up with implementation of Microsoft, IBM etc. It's a general

    architecture. Any vendor who implements SOA needs to fulfill the below SOA components.

    How they do it is completely their own technological implementation.

  • 7/28/2019 General Java Questions

    32/34

    Figure: - Architecture of SOA

    The main goal of SOA is to connect disparate systems. In order that these disparate system

    work they should messages to each other. ESB (Enterprise service bus) acts like a reliable

    post office which guarantees delivery of messages between systems in a loosely coupled

    manner. ESB is a special layer which delivers messages between applications. In the figure

    we have shown a huge plump pipe. It's not hardware or some wire etc. It's a group of

    components/software which helps you to send and receive messages between the disparate

    applications. Do not try to code your own ESB, you can think of buying one from Microsoft,

    IBM, Oracle, progress etc.

    SOA registry is like a reference database of services. It describes what each services do,

    where are they located and how can they communicate. It's a central reference of meta-

    data for services.

    SOA workflow allows us to define work flow using the services in SOA registry. We will read

    more about BPM in the further questions.

    Service broker reads the work flow and takes services from the SOA registry and ties them

    together. Service brokers are normally middleware like EAI (Enterprise application

    Integration) products. You can get a list of decent EAI from Sun, Microsoft, and IBM etc.

    Process manager is nothing but the collection of SOA registry, SOA workflow and service

    broker.

    SOA supervisor is traffic cop ensuring that services do not have issues. It deals mainly withperformance issues of the system so that appropriate service levels are met. If any of the

  • 7/28/2019 General Java Questions

    33/34

    services have performance problems it sends messages to the proper infrastructure to fix

    the issue.

    Note: - The above explanation is of general architecture for SOA. Any vendor

    (Microsoft, IBM, SUN etc) who gives solution for SOA should have the above

    components in some or other manner. As this is a Software architecture book, we will

    not be covering specific vendor implementation. We would advise the reader to map

    the same to their vendor products for better understanding.

    (I) Can you explain a practical example in SOA?

    (I) What are ends, contract, address, and bindings?

    These three terminologies on which SOA service stands. Every service must expose one or

    more ends by which the service can be available to the client. End consists of three

    important things where, what and how:-

    . Contract (What)

    Contract is an agreement between two or more parties. It defines the protocol how client

    should communicate with your service. Technically, it describes parameters and return

    values for a method.

    . Address (Where)

    An Address indicates where we can find this service. Address is a URL, which points to the

    location of the