We often hear advice that catching Throwable or Error is bad practice and Java developer should avoid catching these, but have you thought Why? If language allows you to catch anything which is instance of java.lang.Throwable, then what is the problem of catching them or their subclass java.lang.Error? If they are bad, shouldn't Java itself has prohibited them from catching? Well this all looks good on theory, but not in real world programming. As I said before in Java Exception best practices post, Ideally you should never catch Throwable or in particular Error. There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable. When you do this, no body knows what kind of Error this method is going to throw, and until you know what is the problem, how can you resolve that. Main purpose of providing Exception handling mechanism is to handle error situation properly, but you can't a provide a solution which can solve all problems. That's why we have specific Exception classes e.g. FileNotFoundException, IllegalArgumentException, IOException and so on. So if you don't know how to resolve or handle error, there is no point catching Throwable, all it make your code hard to read and comprehend. Remember, each error handling code is driven by business/audit/reporting or quality requirement and catching Throwable just obscure those logics.
Friday, February 28, 2014
Wednesday, February 26, 2014
Java 8 release is just a couple of weeks away, scheduled at 18th March 2014, and there is lot of buzz and excitement about this path breaking release in Java community. One of feature, which is synonymous to this release is lambda expressions, which will provide ability to pass behaviours to methods. Prior to Java 8, if you want to pass behaviour to a method, then your only option was Anonymous class, which will take 6 lines of code and most important line, which defines the behaviour is lost in between. Lambda expression replaces anonymous classes and removes all boiler plate, enabling you to write code in functional style, which is some time more readable and expression. This mix of bit of functional and full of object oriented capability is very exciting development in Java eco-system, which will further enable development and growth of parallel third party libraries to take advantage of multi-processor CPUs. Though industry will take its time to adopt Java 8, I don't think any serious Java developer can overlook key features of Java 8 release e.g. lambda expressions, functional interface, stream API, default methods and new Date and Time API. As a developer, I have found that best way to learn and master lambda expression is to try it out, do as many examples of lambda expressions as possible. Since biggest impact of Java 8 release will be on Java Collections framework its best to try examples of Stream API and lambda expression to extract, filter and sort data from Lists and Collections. I have been writing about Java 8 and have shared some useful resources to master Java 8 in past. In this post, I am going to share you 10 most useful ways to use lambda expressions in your code, these examples are simple, short and clear, which will help you to pick lambda expressions quickly.
Monday, February 24, 2014
Displaying financial amount in respective currency is common requirement in Java based E-commerce applications. For example if you are selling products on-line globally, you will show price of product in their local currency rather than USD or some other currency. Storing price in every currency is not a good option because of maintenance, and more realistically fluctuation in exchange rates. That's why many of these application prefer stores price of books, electronic goods or whatever product they are selling in USD, and responsibility of converting that price to local currency and displaying is left to client side code. If your client is Java based client e.g. Swing GUI , Java FX client, or a JSP web page, you can use java.text.NumberFormat class to format currency in Java. NumberFormat class allows you to display price in multiple currency depending upon Locale supported by your Java version. All you need to do is to get correct Currency Instance based upon Locale, for example to display amount in US dollar, call NumberFormat.getCurrencyInstance() method with Locale as Locale.US, similarly to display currency as UK pound sterling, pass Locale.UK and for displaying money in Japanese Yen, pass Locale.JAPAN. Once you get the correct instance of currency formatter, all you need to do is call their format() method by passing your number. We will see an example of converting one currency to other and displaying amount in multiple currency in Java. It's actually very much similar to formatting date in Java, so if you are familiar to that part, it would be easy to format currency as well.
Friday, February 21, 2014
Some of the most dreaded error in Java based client server based application is networking related error, e.g. java.net.BindException: Cannot assign requested address: JVM_Bind. I have faced this issue, while working with web servers like Tomcat, Jetty, and Weblogic before, but yesterday it came again, when one of my colleague faced this issue in Windows. As soon as Java programmers sees java.net.BindException, they come to conclusion that it's issue with two process listening on same port, and often mistook it for Java.net.BindException: Address already in use: JVM_Bind:8080, which is slightly different than this. If you look Java documentation for java.net.BindExcpetion, you will find this "Signals that an error occurred while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned." It's the second part, which is more interesting in case of java.net.BindException: Cannot assign requested address: JVM_Bind.
Wednesday, February 19, 2014
In this article, I am sharing 30 core Java technical questions, from screening and phone round of interviews. In telephonic interviews, questions are short, fact based and Interviewer expects some keyword in answers. Accordingly, I have given very short answers to these question, only main points; just to make this as revision post. I am expecting every Java programmer to know answers of all these Java technical questions, if he has more than 4 to 5 years experience. it's only freshers, and junior developers who needs to do bit of research to understand topics well. I have tried to include all classical and hugely popular, frequently asked questions from different topics like String, multi-threading, collection, design pattern, object oriented design, garbage collection, generics and advanced Java concurrency questions. Since core Java interviewer's normally don't ask questions on JSP, Servlets and other JEE technologies, I have not included them into this list. Sole purpose of this list is to given freshers and less experienced developers an idea of what kind of core Java technical questions are asked on phone interviews. For curious ones, I have also included links for more detail answers and discussions.
Monday, February 17, 2014
Friday, February 14, 2014
From last few years, Software code quality and security has went from being a “nice to have” to a necessity, and many organizations, including investment banks are making it mandatory to pass static code analysis test, penetration testing and security testing before you deploy your code in production. Static analysis tools like findbugs and fortify are getting popular every passing day and more and more companies are making fortify scan mandatory for all new development. For those unaware of what static code analysis is, static code analysis is about analysing your source code without executing them to find potential vulnerabilities, bugs and security threats. Static code analyser looks for patterns, defined to them as rules, which can cause those security vulnerability or other code quality problems, necessary for production quality code. But like every other technology, static analysis has it’s set of advantages and disadvantages, which is also best way to judge any technology. Static code analyser are not a new thing, and they are here from long time, but as a senior Java developer or Team lead, you have responsibility to set-up process like automated code analysis, continuous integration, automation testing to keep your project in healthy state and promote best development practices in your team. In my opinion, unit testing, code review and static code analysis makes a nice combo, along with continuous integration. In this article, we will learn some pros and cons of static code analysis, to let you decide, whether static analysis is important or not. I am already convinced with pros, and we are using fortify scanning in all our projects, and have seen benefits of that, but its not all good, its also time consuming. When your tool alert you with false positive, you start taking them lightly and then it become habit to treat everything as false positive, which eventually take away all benefits of static code analysis. You need to be discipline enough, not to fall on that trap.
Tuesday, February 11, 2014
Friday, February 7, 2014
Java allows you to sort your object in natural order by implementing Comparable interface. It's one of the fundamental interface of Java API and defined in java.lang package, which means you don't need to implement this unlike its counterpart Comparator, which is defined in java.util package. Comparable is used to provide natural order of sorting to objects e.g. numeric order is natural order for numbers, alphabetic order is natural order for String and chronological order is natural for dates. Similarly when you define your own objects e.g. Person, sorting it on name sounds natural. Similarly for teams, ranking seems their natural orders. It all depends how object is looked in their domain. By the way, you are not limited to just one order, you can sort objects in any order by using java.util.Comparator, as we have seen in our last article custom sorting in Java. Comparable interface defines abstract method compareTo(), you need to override this method to implement natural order sorting of objects in Java. This method returns positive if the object, on which you are calling this method is greater than other object, return negative, if this object is less than other and returns zero if both object are equal. Several or other classes from Java API relies on this interface for their behaviour, for example Arrays.sort(), Collections.sort() uses this method to sort objects contained in Array and Collection in their natural order. Similarly SortedSet and SortedMap implementation e.g. TreeSet and TreeMap also uses compareTo() method to keep their elements sorted. I have earlier shared some tips to override compareTo() method, which is also worth looking if you are implementing Comparable interface. In this article, we will see a simple example of Java Comparable interface, to sort objects in their natural order.
Wednesday, February 5, 2014
Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming
In Object-oriented programming, one object is related to other to use functionality and service provided by that object. This relationship between two object is known as association in object oriented general software design, and depicted by an arrow in Unified Modelling language or UML. Both Composition and Aggregation are form of association between two objects, but there is subtle difference between composition and aggregation, which is also reflected by their UML notation. We refer association between two objects as composition, when one class owns other class and other class can not meaningfully exist, when it's owner destroyed, for example Human class is composition of several body parts including Hand, Leg and Heart. When human object dies, all it's body part ceased to exist meaningfully, this is one example of Composition. Programmers often confuse between Association, Composition and Aggregation in Object oriented design discussions, this confusion also makes difference between Association, Composition and Aggregation one of the popular questions in Java Interviews, only after difference between abstract class and interface . Another example of Composition is Car and it's part e.g. engines, wheels etc. Individual parts of car can not function, when car is destroyed. While in case of Aggregation, including object can exists without being part of main object e.g. a Player which is part of a Team, can exists without team and can become part of other teams as well. Another example of Aggregation is Student in School class, when School closed, Student still exist and then can join another School or so. In UML notation, composition is denoted by a filled diamond, while aggregation is denoted by an empty diamond, which shows their obvious difference in terms of strength of relationship. Composition is more stronger than Aggregation. In Short, relationship between two objects is referred as association, and an association is known as composition when one object owns other, while an association is known as aggregation when one object uses other object. In this OOPS tutorial, we will see couple of more examples to understand difference between Association, Composition and Aggregation better.
Saturday, February 1, 2014
StringTokenizer is a legacy class for splitting strings into tokens. In order to break String into tokens, you need to create a StringTokenizer object and provide a delimiter for splitting string into tokens. You can pass multiple delimiter e.g. you can break String into tokens by , and : at same time. If you don't provide any delimiter then by default it will use white-space. It's inferior to split() as it doesn't support regular expression, also it is not every efficient. Since it’s an obsolete class, don't expect any performance improvement either. On the hand split() has gone some major performance boost on Java 7, see here to learn more about splitting String with regular expression. StringTokenizer looks easier to use but you should avoid it, except for trivial task. Always Prefer String's split() method for splitting String and for repeated split use Pattern.split() method. Coming back to StringTokenizer, we will see three examples of StringTokenizer in this article, simple example to break String based on white-space, second example will show how to use multiple delimiter and third example will show you how to count number of tokens. In order to get tokens, you basically follow Enumeration style model, i.e. checking for more tokens using hasMoreTokens() and then getting tokens using nextToken().