EnumSet is one of the specialized implementation of Set interface for an enumeration type, introduced in Java 1.5 along with enumeration type itself. Programmer often stores Enum into common collection classes e.g. HashSet or ArrayList, mostly because they are unaware of this little gem. Even I wasn't aware of this class few years ago until I come across one of the finest books for Java programmers, Effective Java. It has an Item on EnumSet, which highlight some typical use-cases for this collection class instead of using int variable and bitwise operator. Since Enum constants are unique and have pre-defined length, as you can not define a new enum constant at runtime; it allows Java API designer to highly optimize EnumSet. If you look closely, EnumSet also teaches you a couple of good design practices to create flexible and maintainable code. For example, EnumSet is an abstract class, and it provides lots of static factory method to create an instance of EnumSet e.g. EnumSet.of(...). This method takes advantage of method overloading and variable argument to provide Set of only provided Enum constants. Second good thing is there are two concrete subclasses of EnumSet e.g. RegularEnumSet and JumboEnumSet, but both are package-private, which means a client can not use them directly. The only way to use them is via EnumSet. At runtime, depending upon the key size of requested Enum, implementation automatically decide which implementation to use. This provides you immense flexibility and control to roll out a new better version of EnumSet implementation without any change on the client side. Anyway, this article is not just about design lessons from this class but more importantly how and when to use EnumSet in Java program. I have shared a simple example to demonstrate the power of EnumSet, which you will see in next section.
If you are using Hibernate for implementing persistence layer in Java and JEE application from couple of years then you would have seen this notorious NullPointerException while executing HQL named queries, Exception in thread “main” java.lang.NullPointerException at org.hibernate.hql.ast.ParameterTranslationsImpl .getNamedParameterExpectedType (ParameterTranslationsImpl.java:63). Hibernate has some poor logging in case of Exception, which has caused me hours to debug a simple problem. By looking at NullPointerException below (look full stacktrace below), I had no clue that it's coming because of a missing space on HQL (Hibernate Query language) query. You can also take a look if you can figure this out :
Write a Java program to find first non repeated character in a String is a common question on coding tests. Since String is a popular topic in various programming interviews, It's better to prepare well with some well-known questions like reversing String using recursion, or checking if a String is palindrome or not. This question is also in the same league. Before jumping into solution, let's first understand this question. You need to write a function, which will accept a String and return first non-repeated character, for example in world "hello" , except 'l' all are non-repeated, but 'h' is the first non-repeated character. Similarly in word "swiss" 'w' is the first non-repeated character. One way to solve this problem is creating a table to store count of each character, and then picking the first entry which is not repeated. Key thing to remember is order, your code must return first non-repeated letter. By the way, In this article, we will see 3 examples to find first non repeated character from a String. Our first solution uses LinkedHashMap to store character count, since LinkedHashMap maintains insertion order and we are inserting character in the order they appear in String, once we scanned String, we just need to iterate through LinkedHashMap and choose the entry with value 1. Yes, this solution require one LinkedHashMap and two for loops. Our second solution is a trade-off between time and space, to find first non repeated character in one pass. This time, we have used one Set and one List to keep repeating and non-repeating character separately. Once we finish scanning through String, which is O(n), we can get the magic character by accessing List which is O(1) operator. Since List is an ordered collection get(0) returns first element. Our third solution is also similar, but this time we have used HashMap instead of LinkedHashMap and we loop through String again to find first non-repeated character. In next section, we will the code example and unit test for this programming question. You can also see my list of String interview Questions for more of such problems and questions from Java programming language.
WeakReference and SoftReference were added into Java API from long time but not every Java programmer is familiar with it. Which means there is a gap between where and how to use WeakReference and SoftReference in Java. Reference classes are particularly important in context of How Garbage collection works. As we all know that Garbage Collector reclaims memory from objects which are eligible for garbage collection, but not many programmer knows that this eligibility is decided based upon which kind of references are pointing to that object. This is also main difference between WeakReference and SoftReference in Java. Garbage collector can collect an object if only weak references are pointing towards it and they are eagerly collected, on the other hand Objects with SoftReference are collected when JVM absolutely needs memory. These special behaviour of SoftReference and WeakReference makes them useful in certain cases e.g. SoftReference looks perfect for implementing caches, so when JVM needs memory it removes object which have only SoftReference pointing towards them. On the other hand WeakReference is great for storing meta data e.g. storing ClassLoader reference. If no class is loaded then no point in keeping reference of ClassLoader, a WeakReference makes ClassLoader eligible for Garbage collection as soon as last strong reference removed. In this article we will explore some more about various reference in Java e.g. Strong reference and Phantom reference.
There are two ways to search an element in a List class, by using contains() method or by using Collections.binarySearch() method. There are two versions of binarySearch() method, one which takes a List and Comparator and other which takes a List and Comparable. This method searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If List is not sorted, then results are undefined. If the List contains multiple elements equal to the specified object, there is no guarantee which one will be returned. This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons. In the end this method returns the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. This means that return value will be >= 0 if and only if the key is found. Since common implementation of List interface e.g. ArrayList, Vector, CopyOnWriteArrayList and Stack implements RandomAccess interface, they can be used for performing binary search, but there are other implementations like LinkedList, which doesn't implement java.util.RandomAccess, hence not suitable for binary search operation. Since binary search can only be performed in sorted list, you also need to sort your collection before doing search, which may potentially impact performance, especially if your List is big and not in sorted order already.
Finally Java 8 is here, after more than 2 years of JDK 7, we have a much expected Java 8 with lots of interesting feature. Though Lambda expression is the most talked item of coming Java 8 release, it wouldn't have been this much popular, if Collections were not improved and Stream API were not introduced. Java 8 is bringing on new Streams API java.util.stream package, which allow you to process elements of Java Collections in parallel. Java is inheritably sequential and there is no direct mean to introduce parallel processing at library level, stream API is going to fill that gap. By using this, you can filter elements of collection on given criterion e.g. if you have a List of orders, you can filter buy orders with sell orders, filter orders based upon there quantity and price and so on. You can also perform two of most popular functional programming functions e.g. map and reduce. java.util.stream class provides function such mapToInt(), mapToLong(), and map function to apply an operation on all elements of Collections. By the way, these are just few of gems of Stream API, I am sure you will find several more, when you start exploring lambda expression and java.util.stream package. In this tutorial, we will see 2 examples of using Java 8 Stream with Collections classes. I have chosen List for these example, but you can use any Collection e.g. Set, LinkedList etc. By the way, use of Stream is not limited to Collections only, you can even use an array, a generator function, or an I/O channel as source. In most cases, a Stream pipeline in Java 8 consists a source, followed by zero or more intermediate stream operations e.g. filter() or map(); and a terminal operation such as forEach() or reduce().
Today we will take a look on another simple programming exercise, write a program to check if a number is binary in Java. A number is said to be binary if it only contains either 0 or 1, for example 1010 is binary number but 1234 is not. You can not any library method to solve this problem, you need to write a function to check if given number is binary, you can use basic constructs of Java programming language e.g. operators, keywords, control statements etc. If you are a regular reader of Javarevisited, then you know that I love to share simple programming problems here, because they serve two purposes, first they help beginners to apply their basic knowledge to do something which looks challenging at first, and second they serve as good coding questions to differentiate candidates on Java interviews between who can program and who can not. FizzBuzz is one of such problems but their are lot many, e.g. Prime numbers, Fibonacci series or factorial. But if you truly want to test your candidate then you need to give them some questions which are not so popular. If a candidate can apply his programming knowledge to a problem he is seeing first time, he is probably going to perform better than the candidate who has already seen the problem. That's why I was always looking at programming problems, which are not difficult to solve but has some element of freshness and not so common. This problem of checking whether a number is binary or not is not very different from converting a decimal to binary, but it will pose challenge for those programmers who can't code. By the way, if you are looking for simple programming problems, you can check my list of Top 30 programming interview questions, their I have shared questions from several popular topics including String, Array, Data Structure and Logic.
JDK 1.7 release had introduced several useful features, despite most of them being syntactic sugar, there use can greatly improve readability and code quality. One of such feature is introduction of underscore in numeric literals. From Java 7 onwards you can write a long digit e.g. 10000000000 to a more readable 10_000_000_000 in your Java source code. One of the most important reason of using underscore in numeric literal is avoiding subtle mistakes which is hard to figure out by looking at code. It's hard to notice a missing zero or extra zero between 10000000000 and 1000000000, than 10_000_000_000 and 1_000_000_000. So if you are dealing with big numbers in Java source code, use underscore in numbers to improve readability. By the way, there are rules to use underscore in numeric literals, as they are also a valid character in identifier, you can only use them in between digits, precisely neither at the start of numeric literal nor at the end of numeric literals. In next couple of section, we will learn how underscore in numeric literal is implemented and rules to use them in numerical literals.
Programmer often mistook copy constructors provided by various collection classes, as a mean to clone Collection e.g. List, Set, ArrayList, HashSet or any other implementation. What is worth remembering is that, copy constructor of Collection in Java only provides shallow copy and not deep copy, which means objects stored in both original List and cloned List will be same and point to same memory location in Java heap. One thing, which adds into this misconception is shallow copy of Collections with Immutable Objects. Since Immutable can't be changed, It's Ok even if two collections are pointing to same object. This is exactly the case of String contained in pool, update on one will not affect other. Problem arise, when we use Copy constructor of ArrayList to create a clone of List of Employees, where Employee is not Immutable. In this case, if original collection modifies an employee, that change will also reflect into cloned collection. Similarly if an employee is modified in cloned collection, it will also appeared as modified in original collection. This is not desirable, in almost all cases, clone should be independent of original object. Solution to avoid this problem is deep cloning of collection, which means recursively cloning object, until you reached to primitive or Immutable. In this article, we will take a look at one approach of deep copying Collection classes e.g. ArrayList or HashSet in Java. By the way, If you know difference between shallow copy and deep copy, it would be very easy to understand how deep cloning of collection works.
MQ Series Interview Questions and Answers are collection of some of the questions asked on various MQ implementation e.g. IBM WebSphere MQ, Active MQ or Sonic MQ from different core Java and Enterprise Java (JEE) interviews. Most of these questions are from websphere MQ as it's the one which is most popular in large organization, especially in finance domain. By the way messaging is a key aspect of any enterprise application and you will always see some form of messaging between different systems in a organization. For example, In finance world, most of the middle office to back office communication happens over messaging middle-ware like TIBCO or MQ Series. Its one of the popular Message Oriented Middleware used in Core Java and Enterprise Java application deployed on IBM WebSphere Server, which means if your organization is using IBM WebSphere as application server, you are likely see WebSphere MQ there. By the way that's not the only one messaging solution available, you have couple of choices depending upon requirement e.g. Tibco Rendezvous for high speed messaging, Tibco EMS for a JMS based messaging, mostly for durable messages and MQ series as well. It's long time I have written any article on messaging after my articles based on Tibco messaging, along with some Tibco Interview Questions e.g. difference between Tibco RV and Tibco EMS. In this messaging article, focus will on MQ Series and in particular WebSphere MQ. These 10 WebSphere MQ interview Question and Answers will certainly help you to prepare better for any Java interview which expect experience on MQ Series.
Sometime knowledge of a specific Java feature can improve code quality, Covariant method overriding is one of such feature. Covariant method overriding was introduced in Java 5, but it seems it lost between other more powerful features of that release. Surprisingly not many Java programmer knows about Covariant overriding, including myself, until I read, one of the best Java book on Collection framework, Java Generics and Collection. Covariant method overriding helps to remove type casting on client side, by allowing you to return subtype of actually return type of overridden method. Covariant overriding can be really useful, while overriding methods which returns object e.g. clone() method. Since clone() return object every client needs to cast on to appropriate subclass, not any more. By using Java 5 covariant overriding, we can directly return subtype instead of object, as we will seen in examples of this article. This feature is not a star feature like Generics or Enum, but it's definitely something worth knowing, given overriding methods are integral part of Java programming. I have discussed a bit about this feature earlier in difference between overriding and overloading article, and here I will show couple of more examples to justify it's usage.