How HashMap works in Java?
This collection interview questions is mostly asked during AVP Role interviews on Investment-Banks and has lot of followup questions based on response of interviewee e.g. Why HashMap keys needs to be immutable, what is race conditions on HashMap and how HashMap resize in Java. For explanation and answers of these questions Please see earlier link.
What is difference between fail-fast and fail-safe Iterators?
This is relatively new collection interview questions and can become trick if you hear the term fail-fast and fail-safe first time. Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because they try to immediately throw Exception when they encounter failure. On the other hand fail-safe Iterators works on copy of collection instead of original collection
What is difference between Synchronized Collection and ConcurrentCollection?
Java5 has added several new ConcurrentCollection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue etc, which has made Interview questions on Java Collection even trickier. Java Also provided way to get Synchronized copy of collection e.g. ArrayList, HashMap by using Collections.synchronizedMap() Utility function.One Significant difference is that ConccurentCollections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization.
What is difference between Iterator and Enumeration?
This is a beginner level collection interview questions and mostly asked during interviews of Junior Java developer up to experience of 2 to 3 years Iterator duplicate functionality of Enumeration with one addition of remove() method and both provide navigation functionally on objects of Collection.Another difference is that Iterator is more safe than Enumeration and doesn't allow another thread to modify collection object during iteration except remove() method and throws ConcurrentModificaitonException.
Difference between HashMap and Hashtable?
This is another Classical Java Collection interview asked on beginner’s level and most of Java developer has a predefined answer for this interview questions e.g. HashMap is not synchronized while hashtalbe is not or hashmap is faster than hashtable etc. What could go wrong is that if he placed another followup question like how hashMap works in Java or can you replace Hashtable with ConcurrenthashMap etc.
When do you use ConcurrentHashMap in Java?
This is another advanced level collection interview questions in Java which normally asked to check whether interviewer is familiar with optimization done on ConcurrentHashMap or not. ConcurrentHashMap is better suited for situation where you have multiple readers and one
Writer or fewer writers since Map gets locked only during write operation. If you have equaled number of reader and writer than ConcurrentHashMap will perform in line of hashtable or synchronized hashMap.
What is difference between Set and List in Java?
Another classical Java Collection interview popular on telephonic round or first round of interview. Most of Java programmer knows that Set doesn't allowed duplicate while List does and List maintains insertion order while Set doesn't. What is key here is to show interviewer that you can decide which collection is more suited based on requirements.
How do you Sort objects on collection?
This Collection interview question serves two purpose it not only test an important programming concept Sorting but Also utilty class like Collections which provide several methods for creating synchronized collection and sorting. Sorting is implemented using Comparable and Comparator in Java and when you call Collections.sort() it gets sorted based on natural order specified in CompareTo method while Collections.sort(Comparator) will sort objects based on compare() method of Comparator.
What is difference between Vector and ArrayList?
One more beginner level collection interview questions, this is still very popular and mostly asked in telephonic round. ArrayList in Java is one of the most used Collection class and most interviewer asked questions on ArrayList.See Difference between Vector and ArrayList for answer of this interview question.
What is difference between HashMap and HashSet?
This collection interview questions is asked in conjunction with hashmap vs hashtable.
READ COMPLETE POST...




1) If two objects are equal by equals() method then there hashcode returned by hashCode() method must be same.

2) Whenever hashCode() mehtod is invoked on the same object more than once within single execution of application, hashCode() must return same integer provided no information or fields used in equals and hashcode is modified. This integer is not required to be same during multiple execution of application though.

3) If two objects are not equals by equals() method it is not require that there hashcode must be different. Though it’s always good practice to return different hashCode for unequal object. Different hashCode for distinct object can improve performance of hashmap or hashtable by reducing collision.

To better understand concept of equals and hashcode and what happens if you don’t override them properly I would recommend understanding of How HashMap works in Java

Overriding hashCode method in Java
Override java hashcode exampleWe will follow step by step approach for overriding hashCode method. This will enable us to understand the concept and process better.

1) Take a prime hash e.g. 5, 7, 17 or 31 (prime number as hash, results in distinct hashcode for distinct object)
2) Take another prime as multiplier different than hash is good.
3) Compute hashcode for each member and add them into final hash. Repeat this for all members which participated in equals.
4) Return hash

  Here is an example of hashCode() method

   @Override
    public int hashCode() {
        int hash = 5;
        hash = 89  hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 89  hash + (int) (this.id ^ (this.id >>> 32));
        hash = 89  hash + this.age;
        return hash;
    }

It’s always good to check null before calling hashCode() method on members or fields to avoid NullPointerException, if member is null than return zero. Different data types has different way to compute hashCode.Integer members are simplest we just add there value into hash, for other numeric data-type are converted into int and then added into hash
READ COMPLETE POST...




Head First jQuery
I am big fan of Head first series, having already read couple of there best titles like Head first design pattern, I didn't take me long to purchase my first jQuery book, Head First jQuery and as always I am pretty satisfied. There are lot of good things about this book, but one thing which differentiate this jQuery book with others is quality of exercise. Head first examples are more like real life projects than a trivial example from no where, you feel doing real work, while following this jQuery book. Apart from that, they also provides code including HTML and CSS and promotes best practices around structuring your HTML documents and Cascading style sheets. Another worth mentioning thing about this jQuery book is focusing on most important details and bringing them forward, if you are in hurry, then this is the book to follow. You will also find lots of puzzles, interesting questions, fireside talk (simply fantastic for comparative learning) and usual head first ways to teach concepts. In short a must read jQuery book for any beginner, which is familiar with HTML, CSS and bit of JavaScript. If you are completely new in web development and not very confident with HTML, CSS or JavaScript then you can also take a look Head First HTML and CSS and Head First JavaScript, completely worth of money. I think you might also get a discounted offer, if you buy more than one books on Amazon.

jQuery in Action - Manning
Similar to head first series, another series which I like is Manning "Action" series, they have published several best selling titles under this series and "jQuery in Action, Second Edition" is one of them. I read this book because of there authors Bear Bibeault and Yehuda Katz, which are real jQuery and JavaScript experts and knows subtle details of both. Yehuda Katz has been contributing to jQuery and heading up there plug-in development team, while Bear Bibeault is very senior in the area of web application development and already co-author books like Ajax in Practice. This jQuery book is really good for both beginners and developer with some experience, it's well structured with lots of useful examples, which are easy to follow. One of thing, which I personally like is there explanation of jQuery Event handling and how that works internally using JavaScript. They have also done a good job on explaining, how jQuery can be used to Crete web pages, which can handle cross browser compatibility issues. In short, one of the best jQuery book in the market.

Learning jQuery Third Edition
"Learning jQuery 1.3 : Better Interaction Design and Web Development with Simple JavaScript Techniques" By Karl Swedberg and Jonathan Chaffer is another good jQuery books for beginners. This book teach jQuery in really nice ways, building on your previous experience and knowledge, there contextual examples and explanation, makes it easy to learn and comprehend jQuery functions. Though this book assumes, you should have a fair knowledge of HTML and CSS, and comfortable with the syntax of JavaScript, no knowledge of jQuery is assumed, which is what works in beginners favors. I wouldn't say a must read jQuery book, if you have already read previous two books, but if you connect with this book, after reading sample chapters, than it's worth buying.

jQuery Cookbook
jQuery Cookbook: Solutions & Examples for jQuery Developers by Cody Lindley is an ideal book for both jQuery beginners and JavaScript experts alike. It's a cookbook, which starts with fundamentals and then explores more practical uses cases with tested solution and using best practices to overcome common web development issues. Like Head First and "Action" series, Cookbook series from O'Reilly is also a popular series and can be a valuable addition to any web developer's bookshelf. Since jQuery cookbook is written to accommodate common problems and there tried and tested solution, three is good chance that you will find solution of your practical problems there. In short, if you like cookbooks and enjoy reading them, than this is one of the best jQuery book for you.

jQuery: Novice to Ninja
jQuery:Novice to Ninja By Earle Castledine and Craig Sharkie is a comprehensive jQuery book of 480 pages. First Edition of this book was hugely popular and now Second Edition is also available. I haven't read this book completely, but whatever I read, I found them really interesting. This books mixes JavaScript best practices and explains subtle details with ease. This also presents lots of advanced stuff including jQuery plug-ins, which is good, once you are familiar with basics. Overall, I suggest reading couple of sample chapters and if you connect with this book, than consider buying it. By the way don't god with title, from novice to Ninja, don't expect to become master of jQuery by just reading this book :), you need to lot of jQuery coding, before coming close to efficiently use them.
READ COMPLETE POST...




An abstract class is something which is incomplete and you can not create instance of abstract class. If you want to use it you need to make it complete or concrete by extending it. A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from abstract class or interface it has implemented or extended. By the way Java has concept of abstract classes, abstract method but a variable can not be abstract in Java. Popular example of abstract class in Java is ActionListener which has abstract method called actionPerformed(ActionEvent ae). This method is called when an ActionEvent is fired like when you click on JButton. Its common in java to attach ActionListener with JButton by implementing abstract method actionPerformed(ActionEvent ae) using Anonymous class, as shown in below Example :

JButton  ok = new JButton("OK");
ok.addActionListener(new ActionListener(){
           public void  actionPerformed(ActionEvent ae){
               //code to handle event
           }
});


An abstract method in Java doesn't have body , its just a declaration. In order to use abstract method you need to override that method in SubClass.

so when do you use abstraction ? 
when Yo  know something needs to be there but  not sure how exactly it should look like.

e.g. when I am creating a class called Vehicle, I know there should be methods like start() and Stop() but don't know start and stop mechanism of every vehicle since they could have different start and stop mechanism e..g some can be started by kick or some can be by pressing buttons .
READ COMPLETE POST...




Once we know ,what is SSL, https and Certificates we are ready to setup SSL and https in tomcat web server. As I explained you need to have some certificate (inside keystore)  in tomcat/conf folder which tomcat will present, when a connection is made via https. If you use Spring security you can use some of test certificates present in there sample applications otherwise you need to generate by yourselves. You can request certificates from your windows support team or by using tools like IBM IkeyMan and keytool command to put them into truststore and keystore.

Once you have certificate ready, Open your server.xml from tomcat/conf folder and search for Connector which defines https, it may be commented ,better look for this string "Define a SSL HTTP/1.1 Connector on port 8443". Once found replace with following setup which is different for tomcat 6 and tomcat 7

SSL Configuration for Tomcat 6 :

<Connector protocol="org.apache.coyote.http11.Http11Protocol"
            port="8443" minSpareThreads="5" maxSpareThreads="75"
            enableLookups="true" disableUploadTimout="true"
            acceptCount="100"  maxThreads="200"
            scheme="https" secure="true" SSLEnabled="true"
            clientAuth="false" sslProtocol="TLS"
            keystoreFile="${catalina.home}/conf/server.jks"
            keystoreType="JKS" keystorePass="changeit"    />

You also need to make one more configuration change for setting up SSLEngine="off" from "on" like in below text:

<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="off" />


Look for this String on top of Server.xml

SSL Configuration for Tomcat 7
SSL Setup in Tomcat7 is relatively easy as compared to Tomcat7, as you only need to make one configuration change for replacing SSL Connector with following settings :


  <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"

             maxThreads="150" scheme="https" secure="true"
             clientAuth="false" sslProtocol="TLS"
             keystoreFile="${catalina.home}/conf/server.jks"
             keystoreType="JKS" keystorePass="changeit"    />



Settings which may vary if you setup your own certificate is keystorFile which points to a keystore, which stores certificates, keyStoreType I am using "jks", which stands for “Java Key Store” and keystorepass, which is password for opening key store file. That's it now your tomcat 6 or tomcat 7 is ready to server https client. Though you may need to configure https for your web application ,if you not done already.

How to configure Java web application for https
If you want your J2EE web application to be accessed over SSL using https protocol, you can include following settings in application's web.xml :


    <security-constraint>
        <web-resource-collection>
            <web-resource-name>HelloSSL</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>


This Security setting will enable HTTPS for all URL directed your application. you can also selective enable https settings for some URL by tweaking URL pattern.
READ COMPLETE POST...




HashMap is fast and so on along with basics like its stores key and value pairs etc. This shows that person has used HashMap  and quite familiar with the functionality HashMap offers but interview takes a sharp turn from here and next set of follow-up questions gets more detailed about fundamentals involved with HashMap in Java . Interviewer struck back with questions like

And then you get answers like I don't bother its standard Java API, you better look code on Java source or Open JDK; I can find it out in Google at any time etc. But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap. When we pass Key and Value object  to put() method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic. If people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in Java HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge on how hashing works and how HashMap  works in Java. But this is just start of story and confusion increases when you put interviewee on scenarios faced by Java developers on day by day basis. Next question could be about collision detection and collision resolution in Java HashMap  e.g.

"What will happen if two different objects have same hashcode?”
Now from here onwards real confusion starts, Some time candidate will say that since hashcode is equal, both objects are equal and HashMap  will throw exception or not store them again etc, Then you might want to remind them about equals() and hashCode() contract  that two unequal object in Java can have same hashcode. Some will give up at this point and few will move ahead and say "Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList. Great this answer make sense though there are many collision resolution methods available this is simplest and HashMap in Java does follow this. But story does not end here and interviewer asks

"How will you retrieve Value object  if two Keys will have same hashcode?”
how HashMap works internally in JavaInterviewee will say we will call get() method and then HashMap uses Key Object's hashcode to find out bucket location and retrieves Value object but then you need to remind him that there are two Value objects are stored in same bucket , so they will say about traversal in LinkedList until we find the value object , then you ask how do you identify value object because you don't  have value object to compare ,Until they know that HashMap  stores both Key and Value in LinkedList node or as Map.Entry they won't be able to resolve this issue and will try and fail.


In many cases interviewee fails at this stage because they get confused between hashCode() and equals() or keys and values object in Java HashMap  which is pretty obvious 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 in Java. 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 improve performance of Java HashMap  by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap.
READ COMPLETE POST...




 1) Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.

2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.

3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.

4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.

5) Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.

6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.
READ COMPLETE POST...




1) You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
This thread interview questions is mostly asked in first round or phone screening round of interview and purpose of this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of this multi-threading questions is simple it can be achieved by using join method of Thread class.


2) What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it?
The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. This java threads interview question is getting increasingly popular and more and more follow-up questions come based upon answer of interviewee. I would strongly suggest reading Locks before appearing for any java multi-threading interview because now days Its  heavily used to build cache for electronic trading system on client and exchange connectivity space.


3) What are differences between wait and sleep method in java?
Another frequently asked thread interview question in Java mostly appear in phone interview. Only major difference is wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution. See my post wait vs sleep in Java for more differences


4) Write code to implement blocking queue in Java?
This is relatively tough java multi-threading interview question which servers many purpose, it checks whether candidate can actually write Java code using thread or not, it sees how good candidate is on understanding concurrent scenarios and you can ask lot of follow-up question based upon his code. If he uses wait() and notify() method to implement blocking queue, Once interviewee successfully writes it  you can ask him to write it again using new java 5 concurrent classes etc.


5) Write code to solve the Produce consumer problem in Java?
Similar to above questions on thread but more classic in nature, some time interviewer ask follow up questions How do you solve producer consumer problem in Java, well it can be solved in multiple way, I have shared one way to solve producer consumer problem using BlockingQueue in Java , so be prepare for surprises. Some time they even ask to implement solution of dining philosopher problem as well.

6) Write a program which will result in deadlock? How will you fix deadlock in Java?
Java thread interview questions and answers This is my favorite java thread interview question because even though deadlock is quite common while writing multi-threaded concurrent program many candidates not able to write deadlock free code and they simply struggle. Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can be replace with 2 for simplest case and higher number to make question more intimidating. see  How to avoid deadlock in java  for more information on deadlock in Java.


7) What is atomic operation? What are atomic operations in Java?
Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :) You can read more about java synchronization here.


8) What is volatile keyword in Java? How to use it? How is it different from synchronized method in Java?
Thread questions based on volatile keyword in Java has become more popular after changes made on it on Java 5 and Java memory model. It’s good to prepare well about how volatile variables ensures visibility, ordering and consistency in concurrent environment.


9) What is race condition? How will you find and solve race condition?
Another multi-threading question in Java which appear mostly on senior level interviews. Most interviewer grill on recent race condition you have faced and how did you solve it and some time they will write sample code and ask you detect race condition. See my post on Race condition in Java for more information. In my opinion this is one of the best java thread interview question and can really test the candidate's experience on solving race condition or writing code which is free of data race or any other race condition. Best book to get mastery of this topic is "Concurrency practices in Java'".


10) How will you take thread dump in Java? How will you analyze Thread dump?
In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather simple and focus thread interview question but can get tricky if he ask how you analyze it. Thread dump can be useful to analyze deadlock situations as well.

Some More FAQs:
 1)  Difference between green thread and native thread in Java?
2)  Difference between thread and process?
3)  What is context switching in multi-threading?
4)  Difference between deadlock and livelock, deadlock and starvation?
5)  What thread-scheduling algorithm is used in Java?
6)  What is thread-scheduler in Java?
7)  How do you handle un-handled exception in thread?
8)  What is thread-group, why its advised not to use thread-group in Java?
9)  Why Executor framework is better than creating and managing thread by application ?
10) Difference between Executor and Executors in Java?
10) How to find which thread is taking maximum cpu in windows and Linux server?
READ COMPLETE POST...




 1) Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable,  they are always created inside heap space in Java.

2) Each Thread in Java has there own stack which can be specified using -Xss JVM parameter, similarly you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -Xmx is maximum size of java heap. to learn more about JVM options see my post 10 JVM option Java programmer should know.

3) If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space. Read more about how to deal with java.lang.OutOfMemoryError  in my post 2 ways to solve OutOfMemoryError in Java.

4) If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is lot lesser than size of  heap memory in Java.

5) Variables stored in stacks are only visible to the owner Thread, while objects created in heap are visible to all thread. In other words stack memory is kind of private memory of Java Threads, while heap memory is shared among all threads
READ COMPLETE POST...




1) Since Array is an index based data-structure searching or getting element from Array with index is pretty fast. Array provides O(1) performance for get(index) method but remove is costly in ArrayList as you need to rearrange all elements. On the Other hand LinkedList doesn't provide Random or index based access and you need to iterate over linked list to retrieve any element which is of order O(n).

2) Insertions  are easy and fast in LinkedList as compared to ArrayList because there is no risk of resizing array and copying content to new array if array gets full which makes adding into ArrayList of O(n) in worst case, while adding is O(1) operation in LinkedList in Java. ArrayList also needs to update its index if you insert something anywhere except at the end of array.

3) Removal is like insertions better in LinkedList than ArrayList.

4) LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next  and previous node.

5) Your application can live without Random access. Because if you need nth element in LinkedList you need to first traverse up to nth element O(n) and than you get data from that node.
 
6) Your application is more insertion and deletion driver and you insert or remove more than retrieval. Since insertion or removal doesn't involve resizing its much faster than ArrayList.
READ COMPLETE POST...




Java C C++  Interview  Top 30 Programs - Programming Questions Frequently Asked Programs
1) Write code to check a String is palindrome or not?
2) Write a method which will remove any given character from a String?
3) Print all permutation of String both iterative and Recursive way?
4) Write a function to find out longest palindrome in a given string?
5) In an array 1-100 numbers are stored, one number is missing how do you find it?
6) In an array 1-100 exactly one number is duplicate how do you find it?
7) In an array 1-100 many numbers are duplicates, how do you find it?
8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.
9) How do you find second highest number in an integer array?
10) How do you find middle element of a linked list in single pass?
11) How do you find 3rd element from last in single pass?
12) How do you find if there is any loop in singly linked list? How do you find the start of the loop?
13) How do you reverse a singly linked list?
14) How do you find depth of binary tree?
15) Write code to print InOrder traversal of a tree?
16) Print out all leaf node of a binary tree?
17) Write a program to sort numbers using quick sort?
18) Write a program to implement binary search algorithm
19) How do you sort Java object using Comparator?
19) Write code to check whether a no is power of two or not?
20) Write a program to check whether a no is palindrome or not?
21) Write code to check whether a no is Armstrong no or not
22) Write a program to find all prime number up to a given numbers?
23) Write function to compute Nth Fibonacci number? Both iterative and recursive?
24) Write a program to find out if two rectangles R1 and R2 are overlapping?
35) You need to write a function to climb n steps you can climb either 1 step at a time or 2 steps a time, write a function to return number of ways to climb a ladder with n step.
26) Write code for Generate Random No in a range from min to max?
27) Write program for word-wrap which should work on any screen size?
28) Design an algorithm to find the frequency of occurrence of a word in an article?
29) Write a program to implement blocking queue in Java?
30) Write a program for producer-consumer problem?
READ COMPLETE POST...




1) Strings are immutable and final in Java
Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method,  It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality.
 
2) Strings are maintained in String Pool

Advanced Java String tutorial and example programmers As I Said earlier String is special class in Java and all String literal e.g. "abc"  (anything which is inside double quotes are String literal in Java) are maintained in a separate String pool, special memory location inside Java memory, more precisely inside PermGen Space. Anytime you create a new String object using String literal, JVM first checks String pool and if an object with similar content available, than it returns that and doesn't create a new object. JVM doesn't perform String pool check if you create object using new operator.
3) Use Equals methods for comparing String in Java

String class overrides equals method and provides a content equality, which is based on characters, case and order. So if you want to compare two String object, to check whether they are same or not, always use equals() method instead of equality operator. Like in earlier example if  we use equals method to compare objects, they will be equal to each other because they all contains same contents. Here is example of comparing String using equals method.
 
4) Use SubString to get part of String in Java

Java String provides another useful method called substring(), which can be used to get parts of String. basically you specify start and end index and substring() method returns character from that range. Index starts from 0 and goes till String.length()-1. By the way String.length() returns you number of characters in String, including white spaces like tab, space. One point which is worth remembering here is that substring is also backed up by character array, which is used by original String. This can be dangerous if original string object is very large and substring is very small, because even a small fraction can hold reference of complete array and prevents it from being garbage collected even if there is no other reference for that particular String.
 
5) "+" is overloaded for String concatenation

Java doesn't support Operator overloading but String is special and + operator can be used to concatenate two Strings. It can even used to convert int, char, long or double to convert into String by simply concatenating with empty string "". internally + is implemented using StringBuffer prior to Java 5 and StringBuilder from Java 5 onwards. This also brings point of using StringBuffer or StringBuilder for manipulating String. Since both represent mutable object they can be used to reduce string garbage created because of temporary String.
     
6) Use trim() to remove white spaces from String

String in Java provides trim() method to remove white space from both end of String. If trim() removes white spaces it returns a new String otherwise it returns same String. Along with trim() String also provides replace() and replaceAll() method for replacing characters from String. replaceAll method even support regular expression.

7) Use split() for splitting String using Regular expression

String in Java is feature rich. it has methods like split(regex) which can take any String in form of regular expression and split the String based on that. particularly useful if you dealing with comma separated file (csv) and wanted to have individual part in a String array.
READ COMPLETE POST...




1) Head First Java
Head First Java is the best Java book for any programmer who are new in both programming and Java. The head first way of explanation is quite a phenomena and I really enjoyed whenever I read there books. I found them most interesting Java programming books for beginners but they are equally good for intermediate as well. Head first Java covers essential Java programming knowledge about class, object, Thread, Collection, language feature like Generics, Enum, variable arguments or autoboxing etc. They also has some advanced section on Swing, networking and Java IO which makes them complete package for Java beginners. This should be your first Java book if you are learning from scratch.
2) Head First Design Pattern
Head First Design Pattern is another top class Java book from Head First lab, I guess, this is so far there best title. When I started reading this book back in 2006, I didn't much about design patterns in Java , how they solve common problems, how to apply design pattern, what benefits they provide and all sort of basic things but after reading this Java book I benefited immensely. There is first chapter on Inheritance and Composition, which is simply fantastic and promote best practices by first introducing problem and then solution. They also have lots of bullet points, exercises, memory maps which help you to understand design patterns much quickly. If you want to learn core Java design patterns and Object oriented design principle, this is the first Java book you should refer. Head First design pattern is written by Kathy Sierra and team.
3) Concurrency Practice in Java
Java Concurrency in Practice is another classic from Joshua Bloch, Doug Lea and team. Probably the best Java book in Concurrency and multi-threading and one of the must read for core Java developers. Strength of Concurrency Practice in Java are
1) This book is very detailed and capture minor details of multi-threading and concurrency as well.
2) Focus, instead of focusing on core Java classes this book focus on concurrency issues and problems like deadlock, starvation, thread-safety, race conditions and then present ways to solve them using Java concurrency classes. This book is excellent resource to learn and master Java concurrency package and classes  like CountDownLatch, CyclicBarrier, BlockingQueue or Semaphore. This is the biggest reason I like to read this Java book and read again and again.
3) One more strong point of Concurrency practice in Java is No nonsense Examples, examples in this book are clear, concise and intelligent
4) Explanation : book is good on explaining what is wrong and why its wrong and how to make it right which is essential for Java book to succeed.
4)Java performance from Binu John
Another good Java book which is my personal favorite. As we are moving gradually started from beginners level to intermediate and senior level. Java performance Book is all about performance monitoring, profiling and tools used for Java performance monitoring. This is another, must read Java book, if you are serious about performance in Java programming language. This is not a usual programming book, Instead It provides details about JVM, Garbage Collection, Java heap monitoring and profiling application. I lover there chapter on JVM overview and its must read to learn about JVM in simple language. Just remember this Java book is advanced in nature and expect that reader has experience in Java. Beginners and intermediate programmer can also benefit from this book but Its good to have some Java experience on your belt before reading this book. So far best Java book on performance monitoring.
5) Head First Object Oriented Analysis and Design
Another good book on Java programming and design principles from Head First series. Head first Object Oriented Analysis and design book can be read in conjunction with Head First Design patterns. This book focus on Object oriented design principles like favor composition over inheritance, programming for interface than implementation, DRY etc. One part of learning Java is writing good code and following best practices and this book is great in educating programmers about them. knowledge gained from this book is applicable to many object oriented programming language and will overall improve your understanding of code and design principles.
READ COMPLETE POST...





import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
  * Java Program to sort List of object in reverse order. We will see examples of
  * sorting Array List in reverse order of both default ordering as well as any
  * custom ordering imposed by Compartor.
  *
  * @author Javin Paul
  */
public class CollectionSorting {

    private static final Logger logger = LoggerFactory.getLogger(CollectionSorting.class);
 
    public static void main(String args[]) {
     
        // Creating and initializing Collection to sort in reverse order
        // Integer will be sorted in reverse numeric order
        List<Integer> collection = new ArrayList<Integer>();
        collection.add(101);
        collection.add(201);
        collection.add(105);
        collection.add(302);
     
        logger.debug("Current order in Collection : " + collection);
     
        // Sorting Collection in reverse order
        Collections.sort(collection, Collections.reverseOrder());
     
        logger.debug("Sorted on Reverse order in Collection : {}", collection);
     
        // Sorting List of String in reverse Order
        List<String> alphabets = Arrays.asList("A", "B", "C", "D");
     
        logger.debug("Current order in List of String : {}", alphabets);
     
        // Sorting List in reverse Order
        Collections.sort(alphabets, Collections.reverseOrder());
     
        logger.debug("List of String sorted in reverse order {}", alphabets);
    }

}
Output
 [main] DEBUG CollectionSorting  - Current order in Collection : [101, 201, 105, 302]
 [main] DEBUG CollectionSorting  - Sorted on Reverse order in Collection : [302, 201, 105, 101]
READ COMPLETE POST...




Can two object which are not equal have same hashCode?
YES, two object, which are not equal by equals() method can still return same hashCode. By the way, this is one of the confusing bit of equals and hashcode contract.

How does get() method of HashMap works, if two keys has same hashCode?
This is the follow-up of previous interview questions on equals and hashcode, in fact some time this leads to discussion of the earlier point. When two key return same hashcode, they end-up in same bucket. Now, in order to find the correct value, you used keys.equals() method to compare with key stored in each Entry of linked list there. Remember to point out keys.equals() method, because that's what interviewer is looking for. You can also see here for full list of interview question on Java HashMap.

Where have you written equals() and hashCode in your project?
This is to see, if developer has even written these methods or not. Of course almost all of Java programmer are exposed to this, you can point out value objects, Hibernate entities from your domain, where you have overridden equals and hashCode. Always gives examples from your domain and from your project, rather than a trivial example from a test program, because if Interviewer is asking this question, it means he is interested in examples form your domain.

Suppose your Class has an Id field, should you include in equals()? Why?
This question is asked to one of my reader as Hibernate Interview question, well including id is not a good idea in equals() method because this method should check equality based upon content and business rules. Also including id, which is mostly a database identifier and not available to transient object until they are saved into database.

What happens if equals() is not consistent with compareTo() method?
This is an interesting questions, which asked along with equals() and hashCode() contract. Some java.util.Set implementation e.g. SortedSet or it's concrete implementation TreeSet uses compareTo() method for comparing objects. If compareTo() is not consistent means doesn't return zero, if equals() method returns true, the it may break Set contract, which is not to avoid any duplicates.

What happens if you compare an object with null using equals()?
When a null object is passed as argument to equals() method, it should return false, it must not throw NullPointerException, but if you call equals method on reference, which is null it will throw NullPointerException. That’s why it’s better to use == operator for comparing null e.g. if(object != null) object.equals(anohterObject). By the way if you comparing String literal with another String object than you better call equals() method on literal rather than known object to avoid NPE, one of those simple tricks to avoid NullPointerException in Java.

What is difference in using instanceof and getClass() method for checking type inside equals?
This question was asked multiple times, sometime by looking at your equals() and hashCode implementation. Well key difference comes from point that instanceof operator returns true, even if compared with sub class e.g. Subclass instanceof Super class is true, but with getClass() it's false. By using getClass() you ensure that your equals() implementation doesn't return true if compared with sub class object. While if you use instanceof operator, you end up breaking symmetry rule for equals which says that if a.equals(b) is true than b.equals(a) should also be true. Just replace a and b with instance of Super class and Sub class, and you will end up breaking symmetry rule for equals() method.

How do you avoid NullPointerException, while comparing two Strings in Java?
Since when compared to null, equals return false and doesn't throw NullPointerException, you can use this property to avoid NPE while using comparing String. Suppose you have a known String "abc" and you are comparing with an unknown String variable str, then you should call equals as "abc".equals(str), this will not throw Exception in thread Main: java.lang.NullPointerException, even if str is null. On the other hand if you call str.equals("abc"), it will throw NPE. So be careful with this. By the way this is one of the Java coding best practices, which Java developer should follow, while using equals() method.

What is difference between "==" and equals() method in Java?
One of the most classical interview question on equals(). It has been asked numerous times during in past decade. I have also covered this question already. See here for detailed discussion on how it affect equality checking of String and Integer in auto boxing world.
READ COMPLETE POST...




import java.util.Scanner;

/**
 * Simple Java Program to check or find if a number is Armstrong number or not.
 * An Armstrong number of three digit is a number whose sum of cubes of its digit is equal
 * to its number. For example 153 is an Armstrong number of 3 digit because 1^3+5^3+3^3 or   1+125+27=153
 * @author Javin
 */
public class ArmstrongTest{

  
    public static void main(String args[]) {
  
        //input number to check if its Armstrong number
        System.out.println("Please enter a 3 digit number to find if its an Armstrong number:");
        int number = new Scanner(System.in).nextInt();
    
        //printing result
        if(isArmStrong(number)){
            System.out.println("Number : " + number + " is an Armstrong number");
        }else{
            System.out.println("Number : " + number + " is not an Armstrong number");
        }

  
    }

    /*
     * @return true if number is Armstrong number or return false
     */

READ COMPLETE POST...




String is the primary and probably most common thing you come across on any programming language and so is with any programming interview. There is almost always a question on String whether its related to length or replace but I have always find one or two String programming questions on interviews.
1) Write code to check a String is palindrome or not?
Palindrome are those String whose reverse is equal to original.This can be done by following technique demonstrated in How to reverse String in Java without using API
2) Write a method which will remove any given character from a String?
3) Print all permutation of String both iterative and Recursive way?
4) Write a function to find out longest palindrome in a given string?

Some more String related Questions which mostly appear in Java programming interviews:
Difference between String and StringBuffer in Java
Why String is final in Java
How to Split String in java
Why Char array is preferred over String for storing password?

Programming questions on Array
programming questions asked in interview, programming interview questions and answersArray is one of the topics where most of programming questions is asked. There are many and many programming questions on Array and here I have included only some of them which is not very difficult to solve but some of array programming question can be extremely challenging, so well prepare this topic.

5) In an array 1-100 numbers are stored, one number is missing how do you find it?
6) In an array 1-100 exactly one number is duplicate how do you find it?
This article contains a trick to find duplicates in Array using Java programming language
7) In an array 1-100 many numbers are duplicates, how do you find it?
trick in this programming questions is by using hashmap or hashtable , we can store number as key and its occurrence as value, if number is already present in hashtable then increment its value or insert value as 1 and later on print all those numbers whose values are more than one.

READ COMPLETE POST...




Here is my list of 10 riddles, puzzles, logical and lateral thinking questions. Try to solve it by yourself before searching for answers in Google, they are not that tough or difficult. Easy answers spoils purpose of puzzles, so don’t look at them, until you are going for interview very next day.


1) There are 27 coins and a two-pan balance. All coins has same weight except for one, which is heavier than all others. All coins looks identical. What is the minimum number of weighing required to certainly find out heavier coin?

2) There are two sticks which takes one hour to burn from one end to other. The sticks do not burn at a constant rate i.e. some part may burn faster than others. You need to measure 45 minutes by using these two sticks and a lighter.

3) Two persons are walking into a railway tunnel. Upon crossing 2/3rd of the tunnel, they saw train is coming from opposite direction. Each person ran for a different end of tunnel with speed of 10 km per hour. Fortunately, both persons escaped from the tunnel just right time i.e.. at the time train would have run through them. Assuming train was running with a constant speed and both persons reacted immediately, Find out speed of train.

4) There are thee switches outside of a closed room to operate three different light bulb inside the room. You can only go into the room once and you need to determine which switch belongs to which bulb. Just to make it clear, room is perfectly locked and its not possible to determine whether lights are on from outside the room.

5) You have 10 Jars filled with marbles. Each marble weighs 10 gm, except one Jar which contains defective marbles which weighs 9 gm. Given a scale to weigh, How do you find Jar with defective marbles in just one measurement. Here scale is modern day electronic scale to measure weight.

6) A person shoots her wife. Then holds her under water for 5 minutes. Finally, he hangs her. But after 10 minutes they both go out together and enjoy a wonderful dinner together. How can this be?

7) A father and son are going in a car and suddenly there car met accident. Father died on the spot but the child rushed to the hospital. When he arrives in the hospital, doctor says, "I can't operate on this child, he is my son!" How can this be?

READ COMPLETE POST...




import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
  * Java Program to sort List of object in reverse order. We will see examples of
  * sorting Array List in reverse order of both default ordering as well as any
  * custom ordering imposed by Compartor.
  *
  * @author Javin Paul
  */
public class CollectionSorting {

    private static final Logger logger = LoggerFactory.getLogger(CollectionSorting.class);
 
    public static void main(String args[]) {
     
        // Creating and initializing Collection to sort in reverse order
        // Integer will be sorted in reverse numeric order
        List<Integer> collection = new ArrayList<Integer>();
        collection.add(101);
        collection.add(201);
        collection.add(105);
        collection.add(302);
     
        logger.debug("Current order in Collection : " + collection);
     
READ COMPLETE POST...




As I said earlier, main motivation of using SLF4J in your code to write log statements is, to make your program, independent of any particular logging library, which might require different configuration than you already have, and introduce more maintenance headache. But apart from that, there is one more feature of SLF4J API, which convinced me to use SL4J over my long time favorite Log4j, that is know as place holder and represented as {} in code. Placeholder is pretty much same as %s in format() method of String, because it get substituted  by actual string supplied at runtime. This not only reduce lot of String concatenation in your code, but also cost of creating String object. This is true even if you might not need that, depending upon your log level in production environment e.g. String concatenation on DEBUG and INFO levels. Since Strings are immutable and they are created in String pool, they consume heap memory and most of the time they are not needed e.g. an String used in DEBUG statement is not needed, when your application is running on ERROR level in production. By using SLF4J, you can defer String creation at runtime, which means only required Strings will be created. If you have been using log4j then you already familiar with a workaround of putting debug statement inside if() condition, but SLF4J placeholders are much better than that.
This is how you would do in Log4j, but surely this is not fun and reduce readability of code by adding unnecessary boiler-plate code.

READ COMPLETE POST...


 
HOME | Freshers | Exp | Java | SQL | Walkins | OffCampus | BankJobs
=*= PRIVACY POLICY And DISCLAIMER =*=
Some of the stuff contained this site are found on internetThis site is not responsible for publishing all available Information as well accuracy, please check posted Information with its original sources, e.g. News Papers/ Websites etc.We collect all the Information form the Internet.
Software My Zimbio
Copyright © 2013 Career+ Blog +Google | Disclaimer | Privacy Policy | Contact