Saturday, May 31, 2014
Wednesday, May 28, 2014
Law of Demeter also known as principle of least knowledge is a coding principle, which says that a module should not know about the inner details of the objects it manipulates. If a code depends upon internal details of a particular object, there is good chance that it will break as soon as internal of that object changes. Since Encapsulation is all about hiding internal details of object and exposing only operations, it also assert Law of Demeter. One mistake many Java programmer makes it exposing internal detail of object using getter methods and this is where principle of least knowledge alerts you. I first come to know about this principle, while reading one of the must read programming book, Robert C. Martin's Clean code. Apart from many good thing the book teaches you, "principle of least knowledge" is one principle, which I still remember. Like many bad things, you will tempt to violate Law of Demeter, because of beautiful chaining of methods written in fluent style. On surface it looks pretty good, but as soon as you think about principle of least knowledge, you start seeing the real picture. In this article, we will see formal definition of Law of Demeter and explore code snippet which violates this principle.
Monday, May 26, 2014
Singleton class is quite common among Java developers, but it poses many challenges to junior developers. One of the key challenge they face is how to keep Singleton class as Singleton? i.e. how to prevent multiple instances of a Singleton due to whatever reasons. Double checked locking of Singleton is a way to ensure only one instance of Singleton class is created through application life cycle. As name suggests, in double checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created. By the way, it was broken before Java fixed its memory models issues in JDK 1.5. In this article, we will see how to write code for double checked locking of Singleton in Java, why double checked locking was broken before Java 5 and How that was fixed. By the way this is also important from interview point of view, I have heard it’s been asked to code double checked locking of Singleton by hand on companies in both financial and service sector, and believe me it’s tricky, until you have clear understanding of what you are doing. You can also see my full list of Singleton design pattern questions to prepare well.
Thursday, May 22, 2014
Serialization and SerialVersionUID is always remains a puzzle for many Java developers. I often see questions like what is this SerialVersionUID, or what will happen if I don't declare SerialVersionUID in my Serializable class? Apart from complexity involved and rare use, one more reason of these questions is Eclipse IDE's warning against absence of SerialVersionUID e.g. "The Serializable class Customer does not declare a static final SerialVersionUID field of type long". In this article, you will not only learn basics of Java SerialVersionUID but also it's effect during serialization and de-serialization process. When you declare a class as Serializable by implementing marker interface java.io.Serializable, Java runtime persist instance of that class into disk by using default Serialization mechanism, provided you have not customized the process using Externalizable interface. During serialization, Java runtime creates a version number for a class, so that it can de-serialize it later. This version number is known as SerialVersionUID in Java. If during de-serialization, SerialVersionUID doesn't match than process will fail with InvalidClassException as Exception in thread "main" java.io.InvalidClassException, also printing class-name and respective SerialVersionUID. Quick solution to fix this problem is copying SerialVersionUID and declaring them as private static final long constant in your class. In this article, we will learn about why we should use SerialVersionUID in Java and How to use serialver JDK tool for generating this ID. If you are new to serialization, you can also see Top 10 Java Serialization Interview question to gauge your knowledge and find gap in your understanding for further reading. Similar to Concurrency and Multi-threading, Serialization is another topic, which deserve couple of reading.
Monday, May 19, 2014
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 - Solving Array IndexOutOfBoundsException in Java
If you are coming from C background than there is pleasant surprise for you, Java programming language provides implicit bound checks on Array, which means an invalid array index access is not allowed in Java and it will result in java.lang.ArrayIndexOutOfBoundsException. Array is one of the most used data structure across all programming language and it’s no different in Java. In fact Java API has used array to build several useful data structures e.g. HashMap and ArrayList. These classes also throws IndexOutOfBoundsException if invalid index is supplied to their get(int index) methods. One of the common mistakes Java programmer makes is invalid end condition on classical index based for loops. Since more often than not, you write code to loop over array or list in Java, a wrong end condition can result in Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException, as shown in next section. Along with java.lang.NullPointerException, this exception is biggest problem for new-comers, but, easiest to solve, once you know the basics. As name suggests, ArrayIndexOutOfBoundsException comes, when you try to access an invalid bound i.e. index. Array is fixed length data structure, once created and initialized, you cannot change its size. If an array is created with size 5 means it has five slots to hold items depending upon type of array, and it's index is zero based, which means first item exits in index 0, second at index 1, and last element at index 4 [length-1], this is where most mistakes are made. For getting a refresher in array, please see Java Array 101.
Friday, May 16, 2014
One of the common homework/task in programming courses is about Prime Factorization. You are asked to write a program to find prime factors of given integer number. The prime factors of a number are all of the prime numbers that will exactly divide the given number. For example prime factors of 35 are 7 and 5, both are prime in itself and exactly divides 35. Last time I did this exercise when I was in college, and it was something like, writing a program that asks the user for an integer input and then display that number's prime factorization in command line. There are variants of this program as well e.g. look at this exercise, Write a program that prompts the user to enter a positive integer and displays all its smallest factors in decreasing order. It's more or less same as earlier mentioned version of prime factorization problem, but with a catch of displaying them in decreasing order. Displaying is not a problem at all, you can display it in command prompt or a GUI easily, main thing is to write logic to find prime factors, and this is what you will learn in this programming tutorial. Remember, we can not use an API method, which directly solves the problem e.g. you are not allowed to use reverse method of StringBuffer, in order to reverse a String in Java. You need to write the core logic of prime factorization by using primitive programming constructs e.g. control statements, loops, arithmetic operator etc.
Tuesday, May 13, 2014
Being a Java programmer and Software developer, I have learned a lot from articles titled as What Every Programmer Should Know about ..... , they tend to give a lot of useful and in-depth information about a particular topic, which otherwise is very hard to discover. In my quest of learning I have come across some very useful articles, which I have bookmarked for reference and multiple reading. I personally think that all programmer can benefit by reading these articles, which makes me write this post and share all of these "What Every Programmer Should Know" articles with you guys. These are from my personal bookmarks. In this article, you will see classic what every programmer should know article from topics like memory, Unicode, floating point arithmetic, networking, object oriented design, time, URL Encoding, String and many more. This list is very important for beginner and newcomers, as they are the ones, who lacks practical knowledge. Since most of these post are actually driven by practical knowledge, beginner and intermediate programmers can take a lot from it. Also gaining knowledge of fundamentals early in career helps to avoid mistakes, which has done by other programmers and software developers on their course of learning. Though it’s not easy to grasp all knowledge given in these articles in just one reading. You probably won't understand some details about floating point number or get confused with subtle details of memory, but it’s important to keep these list handy and refer them time to time with a context. So Good luck and Enjoy reading these wonderful articles. By the way, don't forget to share any What Every Programmer Should know article, if it’s not already in this list.
Saturday, May 10, 2014
Can't load IA 32-bit .dll on a AMD 64-bit platform is a generic error, which comes when a 64-bit process tries to load a 32-bit dll, but when it comes its not that easy to resolve. One of my reader was getting this error tibrvnative.dll : Can't load IA 32-bit .dll on a AMD 64-bit when he was trying to install Tibco Rendezvous 8.2 on his Windows 8 HP Laptop. He was working on Java application which was dependent upon Tibco Rendezvous for inter process communication. After installing Tibco on his machine he was having hard time to run his Java application, first he was getting errors like java.lang.UnsatisfiedLinkError: no tibrvnative in java.library.path and after resolving that he was getting a new error tibrvnative.dll: Can't find dependent libraries. After lot of research and trial and error, he found that the version he was trying e.g. Tibco Rendezvous 8.2 was not supported for Windows 8 operating system. That installer was working find on Windows 7 and XP but not working on Windows 8. At last, when he upgraded to latest Tibco Rendezvous version 8.4.1, which supposed to work on windows 8, he started getting a new error Can't load IA 32-bit .dll on a AMD 64-bit platform. Frustrated with all these errors, he was about to give up, when he emailed me. I suggested to try running his Java application, which was using Tibco Rendezvous, with 32-bit JVM rather than 64-bit JVM, which he was initially running because of 64-bit configuration of his notebook. I also suggested him to execute sample programs from Tibco installation, before running your Java application, it's not only quick but also isolate the issue. Thankfully running on 32-bit JVM did work for him, which motivates me to post the solution here.
Wednesday, May 7, 2014
PDF format is a popular format for sending receipt, email confirmation and other documentation and we often has requirement to create PDF documents using Java, mostly in JSP pages. Since most of official documentation uses PDF format now days, it becomes imperative to support PDF files. Recently I received couple of question regarding suggestion of open source Java PDF libraries, like which is the best open source PDF library in Java or should I use iText or Apache FOP in my Java application for PDF processing. These questions motivates me to write this post. In this article, I will share couple of Java based open source PDF libraries, both FREE and with some licensing fees, which you can use to generate PDF documents in Java projects. Many of you would have definitely heard about iText, it's the standard Java library for creating PDF files, but iText 5.0+ is not free any more, you need to pay small licensing fess for using it. Unlike previous version of iText, iText 4.2, which was released under MPL/LGPL licenses, latest version of iText requires you to purchase a license as soon as you develop a commercial application and distributing the iText library inside your project or deploying it on a network, without disclosing source code of your own applications under AGPL license. This includes serving PDF using JSP pages in Java web application or distributing iText with a closed source product. If your project is already using iText then paying this license fee seems to be better option than migrating your PDF processing code to another Java library, but if you are starting a new project, there are couple of open source Java PDF libraries e.g. Apache FOP (Formatting Objects processor), which you can explore. This is definitely not as feature rich as iText, but can be useful as to generate PDF files and support common functionalities, which is what most of the Java projects needs.
Monday, May 5, 2014
Ever Since Java allows using String variable in switch and case statements, there are many programmers using this feature in code, which can be better written using integer and enum pattern. This was one of the popular features of JDK 7 release, including automatic resource management and multi exception catch blocks. Though I upfront didn't like this feature because of better alternative available in terms of using enumeration type, I am not totally against this feature. One reason of this is convenience and given usage of String in Java program, it's quite handy as well, but I prefer to learn more before using any new feature in production code. When I first come to know about this feature, I had an idea that String in Switch can be implemented using equals() and hashCode() method, I was more interested on how String in Switch works in Java 7. One more reason I was curious to know about internal working of this feature because I wanted to ask this during Java interviews, having one of such question makes interviews little more interesting. Testing was simple, you just need to write code using String variables in switch block, and then decompile the code to see, how compiler has translated them. So what are we waiting for, Let's see how String in switch block actually works?
Friday, May 2, 2014
Cloud computing is Hot, it's the biggest IT trend of last few years and will continue to grow strong in coming future. Cloud computing provides several not-so-easy-to-ignore advantages, especially to public and small enterprises, which cannot afford to own and maintain expensive data centres. Since most of online business now days need high avaibility, scalability, and resiliency, with-in quick time, it's not possible to achieve all these by your own, and cloud computing becomes a best alternative here. Cloud service providers like Amazon Web Services (AWS) has helped several firms to remain focus on their business, without worrying for IT and infrastructure too much, this has yield big result for them. Not to forget cost effectiveness of cloud computing compared to your own hardware, software and data centres, and with increased competition and awareness of this business, cost is only going to south to make it even more appealing for public and small companies. There are lots of cloud service providers coming up, with increased focused on leveraging expensive data centres to full, many big companies who owns cloud infrastructure are making foray into cloud computing business. In this list, we will see learn 5 Cloud computing companies, which are either market leader or has potential to be a dominant market player. This list includes companies like Amazon, Google etc. If you are a programmer and think that there is no point knowing about cloud computing or not at-least about these cloud computing companies, you are wrong. As an IT professional, one should know about latest technologies and what is going around, when you grow in your career or forms a start-up, your general knowledge of cloud computing and IT platform, infrastructure will help a lot.