Wednesday, July 30, 2014

How to Load Resources from Classpath in Java with Example

Classpath in Java is not only used to load .class files, but also can be used to load resources e.g. properties file, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL. Suppose, you have a properties file inside config folder of your project, and you want to load that properties file, how do you do that? Similarly, you have icons and thumbnails for your web applications on icons directory of your project, how do you load them? Answer is by using java.lang.Class' getResource() and getResourceAsStream() method. These method accepts path of resource as String and returns URL and InputStream respectively. You can obtain a reference of Class by calling either getClass() method or by using class literal. If you have an object, then you can call getClass() because its a non-static method, on the other hand, if you don't have any object, you can simply use .class with name of any class e.g. Sample.class will give you reference of java.lang.Class. These methods are available from JDK 1.1 and you can even use them anywhere you have access to core Java library. If you are creating J2ME games or application, you can use these method to load icons and tiles for your game, and all other resource for your application as well.

Monday, July 28, 2014

Default, Defender or Extension Method of Java 8 with Example

Java 8 now allows you to add non-abstract method implementations to interfaces by utilizing the default and static keyword. Methods with default keyword are known as default methods or defender methods in Java. Before Java 8, it was virtually impossible to change an interface once published. Any change e.g. addition of a new method would have broken all clients. That's why when Java 8 decided to switch to internal iterator implementation using forEach() method, they face a daunting challenge of breaking all implementation of Iterable interface. Since backward compatibility is top priority for Java engineers, and it wasn't practical to break all clients, they came up with idea of default method. This is an amazing and very powerful change, because now you can evolve your existing interface with all the knowledge you have gained after using them. JDK itself is utilizing default methods in big way, java.util.Map interface is extended with several new default methods e.g. replaceAll(), putIfAbsent(Key k, Value v) and others. By the way, Since default method allows extension of existing interface, it’s also known as Extension method. You are also free to define any number of default method in your interface. I think after this change, you unlikely need an abstract class to provide skeletal implementation as described in Effective Java e.g. List comes with AbstractList, Collection comes with AbstractCollection, Set comes with AbstractSet and Map comes with AbstractMap. Instead of creating a new abstract class with default implementation, you can define them as default method inside interface itself. Similarly, introduction of static methods inside interface will make pattern of an interface utility class redundant e.g. Collections for Collection interface, Paths for Path and so on. You can directly define static utility method on interface itself.

Wednesday, July 23, 2014

Java ArrayList and HashMap Performance Improvement in JDK 1.7| Empty List and Map will Cost Less Memory

From long time one reason for me to update to newer Java version was always bug fix and performance improvement. Apart from major changes like Generics in Java 1.5 and Lambdas in Java 8, there are so many small improvements, performance optimization which just goes under radar, one of such change is creating empty ArrayList and HashMap with size zero in JDK 1.7.0_40 update. Many Java developer doesn't even know about these changes, part of the blame lies on Java developers like me, as I hardly read release notes of minor Java updates. Some times these changes are done as part of bug fixes and other time as minor optimization, but given popularity of ArrayList and HashMap in Java application impact of this simple Java optimization is huge. If you are running on Java 1.6 or earlier version of Java 1.7, you can open code of java.util.ArrayList and check that, currently empty ArrayList is initialized with Object array of size 10. If you create several temporary list in your program, which remains uninitialized, due to any reason then you are not only losing memory but also losing performance by giving your garbage collector more work. Same is true for empty HashMap, which was initialized by default initial capacity of 16. This changes are result of observation made by Nathan Reynolds, and Architect at Oracle, which apparently analysed 670 Java heap dumps from different Java programs to find out memory hogs.

Thursday, July 17, 2014

9 Difference between TCP and UDP Protocol - Java Network Interview Question

TCP and UDP are two transport layer protocols, which are extensively used in internet for transmitting data between one host to another. Good knowledge of how TCP and UDP works is essential for any programmer. That's why difference between TCP and UDP is one of the most popular programming interview question. I have seen this question many times on various Java interviews , especially for server side Java developer positions. Since FIX (Financial Information Exchange) protocol is also a TCP based protocol, several investment banks, hedge funds, and exchange solution provider looks for Java developer with good knowledge of TCP and UDP. Writing fix engines and server side components for high speed electronic trading platforms needs capable developers with solid understanding of fundamentals including data structure, algorithms and networking. By the way, use of TCP and UDP is not limited to one area, its at the heart of internet. The protocol which is core of internet, HTTP is based on TCP. One more reason, why Java developer should understand these two protocol in detail is that Java is extensively used to write multi-threaded, concurrent and scalable servers. Java also provides rich Socket programming API for both TCP and UDP based communication. In this article, we will learn key differences between TCP and UDP protocol, which is useful to every Java programmers. To start with, TCP stands for Transmission Control Protocol and UDP stands for User Datagram Protocol, and both are used extensively to build Internet applications.

Monday, July 14, 2014

How to Find Largest of Three Integers in Java - Algorithm, Logic Example

One of the classical program to build programming logic is, write a program to find largest of three numbers. I am sure many of you have already done this exercise in variety of languages including C, C++, C#, JavaScript, Perl, Ruby, PHP etc. This time we will do it in Java. We will first learn the logic by understanding flowchart of largest of three numbers and then we will implement solution using ternary operator in Java. I love this program for its sheer simplicity and how it can help beginners to build logic. As always, you are not allowed to use any library function which can solve this problem directly, your main task is to build logic using primitive language tools e.g. operators. In Java, this problem is also used to teach how ternary operator works, as one of the popular version of this require you to find largest of three numbers using ternary operator. This problem is in similar category as how to determine if number is prime. This Java program finds largest of three numbers and then prints it. If the entered numbers are unequal then one version of this program returns Integer.MIN_VALUE, while other return the number itself. By the way, the method used here is not general, and doesn't scale well for many numbers. For example, If you want to find out largest of a list of numbers say 10 integers then using above approach is not easy, instead you can use array data structure, and keep track of largest number while comparing with other numbers. We will also see how we can use ternary operator in Java to find biggest of three integers. I have made both method static, because they are actually utility method and only operates on their arguments, and I can call them from main method directly, without creating object of this class.

Thursday, July 10, 2014

Write a Program to Find all Armstrong number in the range of 0 and 9999 - Example

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number, since 1**3 + 5**3 + 3**3 = 153, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371. Along with usual beginner exercises e.g. calculating factorial, reversing string or calculating prime numbers, this is a good exercise to build programming logic. It teaches you basic programming technique of how to use operator for something which is not obvious, for example, to solve this programming challenge, we first need to check if a number is Armstrong or  not, and to do this we need individual digits of the number. how do we do that? well there is a programming technique, which you might have learned while doing number palindrome exercise. If you modulo an integer number by 10, you will get last digit, for example 656%10 will give you 6, which is last digit of 656. Similarly to reduce the input after each iteration, you can use division operator, as 656/10 will return 65, which is without last digit. If you know this trick, it's very easy to solve any programming problem, which requires examination of individual digits.  This Java program uses same technique and compute all Armstrong numbers in the range of 0 and 999. By the way this program has different variations as well e.g. how do you find Armstrong number of four digit, as this program only calculates three digit Armstrong number. Well, for that you need to remember general definition of Armstrong number which is, An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits. So a four digit Armstrong number will be equal to sum of power four of individual digits of that number. Another interesting challenge is to write  a program which uses recursion to find if number is Armstrong or not.

Tuesday, July 8, 2014

Top 5 Java Performance Tuning Books - Best of Lot, Must read

Why Java developer should read a book on Performance tuning? When I first faced this question long time back, I thought I will do it later, but I never get back to that for a long time. I realize my mistake of having lack of knowledge on performance measurement, tuning and finding bottleneck only when I faced serious performance and scalability issues on our mission critical server side financial application written in Java. It's true that when you really need it you learn most, but those times are not the best time to learn fundamentals, in fact those times are to apply and correct your misunderstanding. This is why I am sharing these Java performance books to all Java programmers and suggesting them to take sometime and go through at-least one book in full. By the way these books are in addition to my 5 must read books for Java programmers. Remember knowledge of Performance tuning is one important aspect of Senior Java developers, and can separate you from crowd. Ever since Java was introduced, almost 20 years back, it has faced criticism on being slow and lacking performance. Today, I don't think Java is anywhere behind in terms of performance to native languages. Given Java's ability to natively compile hot code using JIT (Just in time Compiler), it is almost at par with native applications written in C and C++, but a lot can be done by following best practices, avoiding common performance pitfalls and using latest tools and techniques. In this article, I am going to introduce with five + one good books on Java performance, which will not only teach you what to measure, how to measure but also explains fundamentals and concept behind those issues. You will not only learn about System and JVM on which your Java application run but also how to to writer faster coding using Java API. So what are we waiting for, let's begin our journey to land of great books on Java performance tuning.

Wednesday, July 2, 2014

Top 50 Java Thread Interview Questions Answers for Freshers, Experienced Programmers

You go to any Java interview, senior or junior, experience or freshers,  you are bound to see couple of questions from thread, concurrency and multi-threading. In fact this built-in concurrency support is one of the strongest point of Java programming language and helped it to gain popularity among enterprise world and programmers equally. Most of lucrative Java developer position demands excellent core Java multi-threading skills and experience on developing, debugging and tuning high performance low latency concurrent Java applications. This is the reason, it is one of the most sought after skill on interviews. In a typical Java interview, Interviewer slowly starts from basic concepts of Thread by asking questions like, why you need threads, how to create threads, which one is better way to create threads e.g. by extending thread class or implementing Runnable and then slowly goes into Concurrency issues, challenges faced during development of concurrent Java applications, Java memory model, higher order concurrency utilities introduced in JDK 1.5, principles and design patterns of concurrent Java applications, classical multi-threading problems e.g. producer consumer, dining philosopher, reader writer or simply bounded buffer problems. Since its not enough just to know basics of threading, you must know how to deal with concurrency problems e.g. deadlockrace conditions, memory inconsistency and various thread safety related issues. These skills are thoroughly get tested by presenting various multi-threading and concurrency problems. Many Java developers are used to only look and read interview questions before going for interview, which is not bad but you should not be too far away. Also collecting questions and going through same exercise is too much time consuming, that's why I have created this list of top 50 Java multi-threading and concurrency related questions, collected from various interviews. I am only going to add new and recent interview questions as and when I am going to discover them. By the way, I have not provided answers of this questions here, Why? because I expect most of Java developer to know the answers of this question and if not, also answers are widely available by using Google. If you don't find answer of any particular question, you can always ask me in comments section. You can even find answers of few questions on the link provided or my earlier post Top 12 Java Thread Questions with Answers.