Friday, June 30, 2017

JSP - How to check if ArrayList is Empty using JSTL Example

There are multiple ways to check if an ArrayList is empty in JSP or not. For example, you can use the empty operator and the length function of JSTL to check if a list is empty or not. You can also use scriptlet, which allows you to insert Java code into JSP but that is not advisable because it makes it harder to maintain a JSP page. You can also write custom tag but that is not required because JSTL provides you necessary support. In this article, I'll show you two ways to check if a given list or ArrayList is empty or not in JSP page without using the scriptlet. You guessed it right, we will use JSTL, the Java standard tag library to solve this problem.

How to create Custom Exception in Java - Tutorial Example

Sometimes we need to create custom Exception in Java, i.e. Exceptions which are not defined in JDK or any third party library your application is using. Though it’s widely recommended on several Exception best practices article, even Joshua Bloch has recommended in Effective Java to prefer standard exception over custom exception, sometimes you really need it. There are certain guidelines to help to find whether you really need a custom exception or not. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.
  •     Do you need an exception type that isn't represented by those in the Java platform?
  •     Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  •     Does your code throw more than one related exception?
  •     If you use someone else's exceptions, will users have access to those exceptions? The similar question is, should your package be independent and self-contained?

Difference between Dependency Injection and Factory Pattern in Java

TL;DR Main difference between dependency injection and factory pattern is that in the case of former dependency is provided by the third party (framework or container) while in the case of later dependency is acquired by client class itself. Another key difference between them is that use of dependency injection result in loosely coupled design but the use of factory pattern create a tight coupling between factory and classes which are dependent on the product created by the factory. Though both Dependency Injection and Factory pattern look similar in a sense that both creates an instance of a class, and also promotes interface driven programming rather than hard coding implementation class; But, there are some subtle differences between Factory pattern and dependency injection pattern.

Thursday, June 29, 2017

Builder Design pattern in Java - Example Tutorial

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well said necessity is mother on invention. learning design pattern without facing problem is not that effective, Instead if you have already faced issues than its much easier to understand design pattern and learn how its solve the issue. In this Java design pattern tutorial we will first see what problem Builder design pattern solves which will give some insight on when to use builder design pattern in Java, which is also a popular design pattern interview question and then we will see example of Builder design pattern and pros and cons of using Builder pattern in Java. 

Is Joshua Bloch's Effective Java Still Valid in the Era of Java 8?

The Effective Java is probably one of most read book on Java technology and has been regarded by many programmers as the best book for Java developers. Though, recently many Java programmers have asked me whether Effective Java is still relevant in the era of Java 8? Or is there any better book on the same topic. The question is logical because It's been more than 9 years since the 2nd edition of Effective Java released in 2008 and also the most recent Java 8 has changed how you code Java. Many idioms and design patterns of good old days now become redundant and can be done easily with the new Java 8 syntax and feature, but does that mean "Effective Java" is not relevant now? Well, No, not at all. The Effective Java is still relevant and must read for Java programmers due to several reasons, which you will see in this article.

Wednesday, June 28, 2017

10 xargs command example in Linux - Unix tutorial

xargs command in unix or Linux is a powerful command used in conjunction with find and grep command in UNIX to divide a big list of arguments into small list received from standard input. find and grep command produce long list of file names and we often want to either remove them or do some operation on them but many unix operating system doesn't accept such a long list of argument. UNIX xargs command divide that list into sub-list with acceptable length and made it work. This Unix tutorial is in continuation of my earlier post on Unix like 10 examples of chmod command in Unix and How to update soft link in Linux. If you haven’t read those unit tutorial than check them out. By the way In this tutorial we will see different example of unix xargs command to learn how to use xargs command with find and grep and other unix command and make most of it. Though what you can do with xargs in unix can also be done by using options provided in find but believe xargs is much easy and powerful.

Tuesday, June 27, 2017

2 Ways to check If String is Palindrome in Java? Recursion and Loop

A String is said to be Palindrome if it is equal to itself in reverse order. You can use this logic to check if String is Palindrome or not. There are two common ways to find if a given String is Palindrome or not in Java, first by using for loop, also known as iterative algorithm and second by using recursion, also known as recursive algorithm. The crux of this problem lies in how do you reverse String in Java? because once you have the String in reverse order, problem reduced to just comparing itself with the reversed String. If both are equal then given String is Palindrome otherwise it's not. Also whether your solution is iterative or recursive will also determine by implementing this logic. If you reverse String using for loop then it become an iterative solution and if you reverse String using recursion then it become a recursive solution. In general, recursive solution are short, readable and more intuitive but subject to StackOverFlowError and that's why not advised to be used in production system. You should always be using iterative solution in production, unless your programming language supports tail recursion optimization e.g. Scala which eliminates risk of StackOverFlowError by internally converting a recursive solution to an iterative one. If you are doing this exercise as part of your Interview preparation then I suggest you to take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions, as title says it contains 150 good questions based upon different topics e.g. String, array, linked list, binary tree, networking etc. A good book for preparing both Java and C++ interview.

10 Java Exception and Error Interview Questions Answers

You will always see some interview questions from Exception and Error handling in core Java Interviews. Exception handling is an important aspect of Java application development and its key to writing robust, stable Java programs, which makes it natural favorites on interviews. Questions from Error and Exception in Java mostly based on the concept of Exception and Error in Java, How to handle Exception , best practices to follow during Exception handling etc. Though multithreading, garbage collection, JVM concepts and questions from object oriented design rules these interviews, you should always expect and prepare some questions on effective error handling.

Monday, June 26, 2017

java.lang.ClassNotFoundException: org.postgresql.Driver - Cause and Solution

java.lang.ClassNotFoundException: org.postgresql.Driver error comes when you are trying to connect to a PostgreSQL database from Java program but Java ClassLoader is not able to find the Driver class "org.postgresql.Driver" required to make the connection. Usually this class is find in PostgreSQL JDBC driver JAR e.g. postgresql-9.4-1201.jdbc41.jar, which is required to connect PostgreSQL server version greater than 9.3 from JDK 1.7 or JDK 1.8, the exact JAR depends upon your PostgreSQL server version, the Java version you are running and JDBC version your are using. Now your problem could be either you don't have that PostgreSQL JDBC driver JAR in your machine or the JAR is not in your classpath, or you might be battling with some classpath intricacies. If you don't have this JAR, then solution of "java.lang.ClassNotFoundException: org.postgresql.Driver" is simple, just download it from PostgreSQL site. Make sure you download the correct version of JDBC driver based upon the PostgreSQL server you are connecting and JVM version of your machine. Once you download that, just put in the lib directory of your Java application e.g. WEB-INF/lib if you are connecting to PostgreSQL from Java Web Application. If you are running in Tomcat, then you can alternatively also put this in tomcat/lib directory, but beware of the difference in the application dependency in WEB-INF/lib or in tomcat/lib. You can also take a look at Practical database programming with Java book by Ying Bai. This books is a comprehensive guide of how to use JDBC in Java to connect to different databases. You will learn right ways of doing things with respect to Java and database.

How to use CopyOnWriteArraySet in Java with Example

CopyOnWriteArraySet is little brother of CopyOnWriteArrayList class. These are special purpose collection classes which was added on JDK 1.5, along with their most popular cousin ConcurrentHashMap. They are part of concurrent collection framework and reside in java.util.concurrent package. CopyOnWriteArraySet is best suited as read-only collection whose size is small enough to copy if some mutative operation happens, for example you can use CopyOnWriteArraySet to store object at start-up of application and let multiple application thread access them during application life time. If an new condition or object comes up during that time, it can also be added into this Set, with incurring cost of creating a new array.

How to Escape JSON String in Java- Eclipse IDE Tips

While working or JSON parsing in Java application it's quite common to just copy paste a JSON String from some resources e.g. a RESTful web service and then use the Jackson library to parse the JSON. This is the quickest way to test and learn parsing JSON string in Java, but the main problem with this approach is that the JSON String also includes double quotes "" which is also used for enclosing String literals in Java. Since JSON String itself contains double quotes, when you just copy paste them in your IDE or Java source file, the didn't work as expected. If you remember, if your String contains double quotes then those need to be escaped when you are pasting them as String literals in your Java code.

Sunday, June 25, 2017

List of special bash parameter used in Unix or Linux script

Meaning of bash parameter used in Unix script
Many of us use a bash script for doing housekeeping and other stuff but occasionally and not much aware of special bash parameters. When I was new to the bash shell and Linux and looking for some already written bash script I used to get baffled with special bash symbols like $@, $_, $1 etc. I did know that they are bash parameter and has special meaning but I don't have all meanings of special bash parameter on top of my head and I always go to Google and search endlessly for those special bash parameter, sometimes I got and found meaning of those special bash script parameters quickly but sometimes I need to spend some time to get what I am actually looking for, so I thought to document meanings and expansion of those special bash parameters or bash script parameters.

This bash script parameter tutorial is in continuation of my earlier UNIX tutorials find examples in UNIX, grep command examples in UNIX, and UNIX networking commands tutorial if you haven’t read already you may find them interesting and useful.

5 Websites to Learn SQL Online for FREE

SQL is one of the most important skill for any programmer be it a Java, C++, PHP or Ruby developer. Almost 95% of the Java applications uses relational database in their back-end and almost all web applications uses database. In recent years, one of the most common way to learn any programming skill is online, at your comfort of office or home and SQL is no different. Learning SQL online has another advantage of quick head start because you don't need to install database and create tables to write some SELECT queries. Once you start writing queries and seeing result, you feel that confidence needed to go to next level, which involves downloading and installing free copy of popular databases e.g. MySQL, SQL Server or Oracle in your machine. From my experience I can say that SQL is easy to learn but difficult to master. You can start writing SQL queries in about an hour or so, but when it comes to write queries to solve real time requirements or for reporting purpose, its not that easy. Practicing SQL online on sites like SQLZoo or SQLFiddle will help you to keep yourself up-to-date. You can also take help from some good SQL books like Head First SQL if you are beginner, head first way is one of the best way to learn SQL.

5 Books to Learn Object Oriented Programming and Design Patterns - Best of lot

Knowledge of Object oriented design principle and the various design pattern is a must for any Java developer. As I said earlier on 10 OOPS and SOLID design principles, coding without knowing these principles are like trying to learn a language without knowing alphabets. By the way, there are several books written on Object-oriented design principles, design patterns, and best practices, but only a few of them provides what they claim. There are two things here, design principles and design patterns, one is basic and other is best practice built on that basic. One should first learn Object-oriented principles and then learn design patterns to see how those principles are used to solve day to day problems. 

Difference between Stable and Unstable Sorting Algorithm?

Recently in one on the interview, after some initial questions about sorting algorithms e.g. how do you write QuickSort or difference between QuickSort and MergeSort, the interviewer asked about do you understand the difference between stable and unstable sorting algorithm? This question was new to my reader, so he says, Sorry, never heard about that. The story ended there, and Interviewer moved on to next question but like many of us, my reader went on to find more about unanswered  questions and ultimately he asks me what is the meaning of a stable and unstable sorting algorithm? Some of you might be heard about it and many of you might not know about this distinction, I'll try to answer this question in this article.

Saturday, June 24, 2017

What is -XX:+UseCompressedOops in 64 bit JVM

-XX:+UseCompressedOops JVM command line option is one of the most talked options of 64 bit JVM. Though 64 bit JVM allows you to specify larger Java heap sizes it comes with a performance penalty by using 64 bit OOPS. Ordinary object pointers also known as OOPS which is used to represent Java objects in Virtual Machine has an increased width of 64 bit than smaller 32 bit from earlier 32 bit JVM. because of increased size of OOPS, fewer OOPS can be stored in CPU cache registers which effectively reduced CPU cache efficiency. -XX:+UseCompressedOops enables the use of compressed 32 bit OOPS in 64 bit JVM which effectively compensate performance penalty imposed by 64 bit JVM without scarifying heap size advantage offered by them. You should use -XX:+UseCompressedOops if maximum heap size specified by -Xmx is less than 32G. This is my 3rd article on JVM after 10 JVM option Java programmer should know and  how to find 32 bit JVM or 64 bit JVM, I suggest reading those if you want to learn more about JVM.

Friday, June 23, 2017

HashSet in Java – 10 Examples Programs Tutorial

HashSet in Java is a collection which implements Set interface and backed by an HashMap. Since HashSet uses HashMap internally it provides constant time performance for operations like add, remove, contains and size give HashMap has distributed elements properly among the buckets. Java HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don't care about insertion order. Iterator of HashSet is fail-fast and throws ConcurrentModificationException if HashSet instance is modified concurrently during iteration by using any method other than remove() method of iterator class.If you want to keep insertion order by using HashSet than consider using LinkedHashSet. It is also a very important part of any Java collection interview, In short correct understanding of HashSet is must for any Java developer.

Top 5 books to learn Agile and Scrum Methodologies - Best, Must Read

When I started my career, it was all waterfall model. You try, fail, and then with every version you get an improved version of a software. I pretty much used to this model of software development until I was introduced to Agile development methodologies in my next company. I was confused about Agile as some people say its Scrum and Sprint, other ways its XP and Kanban etc. The confusion lasted for a long time because I was afraid of asking questions (afraid of being perceived as dumb and someone who wastes time on meetings) and only getting information in bits and pieces and I wasn't good at searching books at that time. From that experience, I learned that, when you have confusion and want to learn more about a new technology, nothing is better than a book or online training courses to start with.

How to create HTTP Server in Java - ServerSocket Example

Java has a very good networking support, allows you to write client server application by using TCP Sockets. In this tutorial, we will learn how to create a simple HTTP Server in Java, which can listen HTTP request on a port let's say 80 and can send response to client. Being an HTTP Server, you can connect to it using your browser e.g. Chrome, Firefox or Internet Explorer. Though HTTP is ubiquitous and present everywhere, Java doesn't have a dedicated API to create and parse HTTP request, there is no in built HTTP client library in JDK. Though there is no short of good open source library e.g. you can use Jsoup to parse HTML and can use Apache HttpClient library for sending GET and POST request right from your Java program. By the way, for those who wants to master network programming in Java, I suggest to read Java Network Programming, 4th Addition by Harold, Elliotte Rusty, its very comprehensive and not only covers both TCP/IP and UDP protocols, which are backbone of internet but also dive deep into the HTTP protocol, including REST, HTTP headers, and cookies. Book is very focused on practical and you will find lot of interesting example related to common networking task e.g. writing multi-threaded servers, using non blocking IO and using low level socket classes.

3 Exampls to Convert an Array to ArrayList in Java

How to convert an array to ArrayList in Java
Have you encountered any situation where you quickly wanted to convert your array to ArrayList or ArrayList to array in Java? I have faced many such situations which motivate me to write these quick Java tips about converting an array to ArrayList and ArrayList to array in Java. Both array and ArrayList are quite common and every Java developer is familiar with this. Former is used to store object and primitive type while later can only hold objects. The array is part of standard Java fundamental data structure while ArrayList is part of collection framework in Java. Most of the time we store data in the form of an object in either Array or ArrayList or sometimes we find either of them suitable for processing and we want to convert from one array to ArrayList or ArrayList to array in Java.

Thursday, June 22, 2017

JUnit4 Annotations : Test Examples and Tutorial

JUnit4 Annotations are single big change from JUnit 3 to JUnit 4 which is introduced in Java 5. With annotations creating and running a JUnit test becomes more easy and more readable, but you can only take full advantage of JUnit4 if you know the correct meaning of  annotations used on this version and how to use them while writing tests. In this
Junit tutorial we will not only understand meaning of those annotations but also we will see examples of JUnit4 annotations. By the way this is my first post in unit testing but if you are new here than you may like post 10 tips to write better code comments and 10 Object oriented design principles for Programmer as well.

2 Ways to Parse CSV Files in Java - BufferedReader vs Apache

In last tutorial, you have learned how to parse Excel file in Java and in this Java tutorial, you will learn how to parse CSV file in Java. You can directly parse CSV file in Java without using any third party library, because ultimately its a text file and you can use BufferedReader to read it, but you can also take advantage of good open source library like Apache commons CSV to parse comma separated values. These library makes developer's life easy and provides rich functionality to parse various CSV formats. In real programming world, CSV or comma separated files are used for variety of purpose, including for transporting data from one system to another e.g. FX rates, importing and exporting records from database etc. In CSV files entries are separated by comma, and it may or may not contain header. There are many ways to parse or read CSV files in Java, and if you need to do it on your project, its better not to reinvent the wheel and choose commons csv, but for learning purpose, it's good to know how to do it without using third party library.

Wednesday, June 21, 2017

3 Ways to Find Duplicate Elements in an Array - Java

There are multiple ways to find duplicate elements in an array in Java and we will see three of them in this program. Solution and logic shown in this article are generic and applies to an array of any type e.g. String array or integer array or array of any object. One of the most common way to find duplicates is by using brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for the academic purpose. You shouldn't be using this solution in the real world. The standard way to find duplicate elements from an array is by using HashSet data structure. If you remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter duplicate elements. This solution has a time complexity of O(n), as you only need to iterate over array once, but also has space complexity of O(n) as you need to store unique elements in the array.

3 Best Spring Security Online Training Courses for Java Developers

The Spring Security is one of the leading open source, security framework which allows you to implement security in Java based web applications. It provides several security features e.g. authentication, authorization, remember me out-of-the-box, which means you can directly use them without adding code or changing your class. Yes, Spring Security implements security at application level i.e. you can even secure your non-secure resource without modifying them. It is also the leading framework to secure RESTful Web Services. Because of all these, the demand for Java developers with good knowledge of Spring Security is very high. They are also some of the highly paid Java developers. Many Java and Spring developer, particularly those who are involved in enterprise and Java web development are learning Spring Security.

Tuesday, June 20, 2017

10 example of using Vim or VI editor in UNIX and Linux

Vim or VI editor tutorial in UNIX vi editor in unixVI Editor is like notepad in UNIX but it’s extremely powerful and have a sophisticated feature to work as complete IDE. No matter which version of UNIX you are working or which flavor you are using you always find either VI editor or VIM there. VI is a very large topic and I am not covering every aspect of it what I am sharing here is some examples of using VI editor in UNIX or Linux. most of the time we use only 10% of VI editor and never know 90% of it , to be frank, I also don't know many of VI feature by heart but I always search for it , see people working in VI and learn from their experience as well. after working on VI editor what I found that every day we learn something new in VI editor but we  forget something equally important and there I thought lets document whatever VI commands I have learned so far and using regularly. Idea is to keep this VI Editor tutorial updated with every single useful VI commands I learn and I also ask you guys to contribute with something useful. 

Monday, June 19, 2017

Java Lock and Condition Example using Producer Consumer Solution

You can also solve producer consumer problem by using new lock interface and condition variable instead of using synchronized keyword and wait and notify methods.  Lock provides an alternate way to achieve mutual exclusion and synchronization in Java. Advantage of Lock over synchronized keyword is well known, explicit locking is much more granular and powerful than synchronized keyword, for example, scope of lock can range from one method to another but scope of synchronized keyword cannot go beyond one method. Condition variables are instance of java.util.concurrent.locks.Condition class, which provides inter thread communication methods similar to wait, notify and notifyAll e.g. await(), signal() and signalAll(). So if one thread is waiting on a condition by calling condition.await() then once that condition changes, second thread can call condition.signal() or condition.signalAll() method to notify that its time to wake-up, condition has been changed. Though Lock and Condition variables are powerful they are slightly difficult to use for first timers. If you are used to locking using synchronized keyword, you will using Lock painful because now it becomes developer's responsibility to acquire and release lock. Anyway, you can follow code idiom shown here to use Lock to avoid any concurrency issue. In this article, you will learn how to use Lock and Condition variables in Java by solving classic Producer Consumer problem. In order to deeply understand these new concurrency concepts, I also suggest to take a look at Java 7 Concurrency Cookbook, Its one of the best book in Java concurrency with some good non trivial examples.

3 ways to solve java.lang.NoClassDefFoundError in Java J2EE

I know how frustrating is to see Exception in thread "main" java.lang.NoClassDefFoundError,  which is a manifestation of NoClassDefFoundError in Java. I have seen it a couple of times and spent quite a lot time initially to figure out what is wrong, which class is missing etc. The first mistake I did was mingling java.lang.ClassNotfoundException and NoClassDefFoundError, in reality, they are totally different, and my second mistake was using trial and error method to solve this java.lang.NoClassDefFoundError instead of understanding why NoClassDefFoundError is coming, what is the real reason behind NoClassDefFoundError and how to resolve this. In this Java tutorial, I have tried to rectify that mistakes and uncover some secrets of NoClassDefFoundError in Java and will share my experience around it. NoClassDefFoundError is not something which cannot be resolved or hard to resolve it’s just its manifestation which puzzles most of Java developer. This is the most common error in Java development along with java.lang.OutOfMemoroyError: Java heap space and java.lang.OutOfMemoryError: PermGen space  Anyway lets’s see Why NoClassDefFoundError comes in Java and what to do to resolve NoClassDefFoundError in Java.

Sunday, June 18, 2017

How to Add Two Integer Numbers without using Plus + or ++ Arithmetic Operator in Java - Recursion example

In this article, we will take a look at another interview question about adding two numbers, but without using + or ++ operator. Interview starts with a simple statement, Can you write a function to add two numbers (integers) without using + or plus arithmetic operator in Java? If you are good at maths, it wouldn’t take more than a second to say that, we can use subtraction or - operator to add two numbers because a-(-b)== a+b. Well, that’s correct, but real question starts when interviewer quickly points out that, you can not use any arithmetic operator including +,-,*,/++ or --. Programming and Coding questions are an integral part of any Java interview. You should always expect a couple of questions like this, e.g. swapping two numbers without using a temp variable. If you have been giving interviews, then you know that it will eventually come downs to the bitwise operator in Java. 

How to Close Java Program or Swing Application with Example

In order to close Java program we need to consider which kind of Java application it is?, because termination of Java application varies between normal core java program to swing GUI application. In general all Java program terminates automatically once all user threads created by program finishes its execution, including main thread. JVM doesn't wait for daemon thread so as soon as last user thread finished, Java program will terminate. If you want to close or terminate your java application before this your only option is to use System.exit(int status) or Runtime.getRuntime().exit(). This cause JVM to abandon all threads and exit immediately. Shutdown hooks are get called to allow some last minute clearing before JVM actually terminates. System.exit() also accept an int status parameter where a non zero value denote abnormal execute and its the result returned by java command to caller. In this java tutorial we will see example of closing both Java program and Java Swing application. This is also a good swing interview questions which you can ask to any GUI developer and my second article in swing after writing invokeAndWait vs invokeLater

Saturday, June 17, 2017

How to use Comparator and Comparable in Java? With example

Comparator and Comparable in Java Examples
Difference between Comparator and Comparable in Java is very popular Java interview question mostly asked in telephonic round and writing code to sort object using Comparable or Comparator is popular on  written test round of interview.The question was this “How you will sort Employee object based on his EmployeeID and his name” and this involves the use of both Comparable as well as Comparator interface in Java. This post is my revision on Java fundamentals similar to I did about equals method in Java and  some tips to override hashCode in Java. All of these methods are fundamentals in Java programming language and correct understanding is must for any Java developer. Comparators and comparable in Java are two interfaces which is used to implement sorting in Java. It’s often required to sort objects stored in any collection classes like ArrayList, HashSet or in Array and that time we need to use either  compare() or  compareTo() method defined in java.util.Comparator and java.lang.Comparable. In this Java tutorial we will see example of  Comparator and Comparable to sort object in Java and discuss some best practices around when to use Comparator interface etc. Any way before moving ahead Let’s see some important differences between Comparable and Comparator in Java.

Top 5 Java And Android Game Programming Books for Programmers

Many programmers and game developers  think that Java isn't the best language for game design, but you cannot ignore Java for game development. There is always some popular platform which allowed you to develop and sell games in Java e.g. J2ME in past and Android now. Ever since Android used Java as a programming language, the game development in Java has got a new lifeline and seems to be doing quite well. Even games like Minecraft also doing great on the Java platform. It's true that C++ is still the best language to develop games due to their high-performance and many top game development companies e.g. Sony, Nintendo, and Microsoft XBox they prefer C++ over Java when it comes to developing great games. But with the Introduction of Android and iOS has completely changed the game development industry.

How to use Callable and Future in Java? Example

Callable interface was added in Java 5 to complement existing Runnable interface, which is used to wrap a task and pass it to a Thread or thread pool for asynchronous execution. Callable actually represent an asynchronous computation, whose value is available via Future object. All the code which needs to be executed asynchronously goes into call() method. Callable is also a single abstract method type (SAM type), so it can be used along with lambda expression on Java 8. Both Callable and Future are parametric type and can be used to wrap classes like Integer, String or anything else. When you pass a Callable to thread pool, it choose one thread and execute the Callable. It immediately return a Future object which promises to hold result of computation once done. You can then call get() method of Future, which will return result of computation or block if Computation is not complete. If you don't like indefinite blocking then you can also use overloaded get() method with timeout. Future also allows you to cancel the task if its not started or interrupt if its started. We will see, how we can calculate factorial of large number using Callable and Future in Java. BTW, if you are serious about mastering concurrency API of Java, I suggest you to also take a look at one of the best book on the subject, Java Concurrency in Practice by Brian Goetz. It is one of the book I keep refer whenever I have a doubt or want to refresh my knowledge.

How to Count number of Set bits or 1's of Integer in Java?

There are multiple ways to count number of 1's or set bits in a integer number in Java. You can use bitwise and bit shift operator by your own, or, you can use Java API to count number of set bits. Java 1.5 added two utility method called bitCount(int i) which returns number of 1's in your integer number, java.lang.Long class has similar bitCount(long number) for long primitives. As I have said earlier, Coding questions are important part of any Java interview, and from that recursion and bitwise operations are most popular. Questions like, How to Swap two numbers without temp variable or How to find if a number is positive or negative are some of such questions, which you see now and then in various Java interviews.

Friday, June 16, 2017

Top 5 Android Online Training Courses for Java Developers - Best of Lot

Java has been very lucky that Android uses it as a programming language. This opened a big door of opportunities for Java developers in Android app development. Many people ask me why Java Developer should learn Android? My simple answer is that good knowledge of Android OS improves your chances of getting a job and making a difference in people's lives because Android Apps is the direct way to connect billions of people. Android is without a doubt THE biggest mobile platform in the world, with over 80% market share and over billions of devices running Android. By creating apps for such a big platform, you have great opportunity to make a difference. You can also develop for Android on a Windows, Mac or Linux, which means your existing Java development experience will not go wasted.

Thursday, June 15, 2017

JDBC Database Connection Pool in Spring Framework – How to Setup Example

Setting up JDBC Database Connection Pool in Spring framework is easy for any Java application, just matter of changing few configuration in spring configuration file.If you are writing core java application and not running on any web or application server like Tomcat or  Weblogic,  Managing Database connection pool using Apache Commons DBCP and Commons Pool along-with Spring framework is nice choice but if you have luxury of having web server and managed J2EE Container, consider using Connection pool managed by J2EE server those are better option in terms of maintenance, flexibility and also help to prevent java.lang.OutofMemroyError:PermGen Space in tomcat by avoiding loading of JDBC driver in web-app class-loader, Also keeping JDBC connection pool information in Server makes it easy to change or include settings for JDBC over SSL. In this article we will see how to setup Database connection pool in spring framework using Apache commons DBCP and commons pool.jar

This article is in continuation of my tutorials on spring framework and database like LDAP Authentication in J2EE with Spring Security and  manage session using Spring security  If you haven’t read those article than you may find them useful.

Maven - 10 Things Java developer should know

The Apache Maven is an essential tool for Java developers. It makes their life easy by allowing them to create Java project faster by using a standard directory structure. It also helps them to download project dependency automatically. Not only that, Maven also download transitive dependencies which relieve Java developers from the big headache of keep check of different versions of dependent libraries. For example, if your application is dependent on Spring framework but Spring is dependent on Log4j then you also need to download the correct version of Log4j JAR files for Spring MVC framework, Maven does this automatically for you. Maven also allows you to build projects, upload artifacts to the central or local nexus repository and deploy the release in your various test environments automatically.

How to Connect to MySQL database in Java with Example

In this tutorial, You will learn how to connect to MySQL database from Java program and running SELECT and INSERT queries to retrieve and update data with step by step guide. In order to connect and access MySQL database from Java, you can use JDBC (Java Database Connectivity) API, which is bundled in JDK itself. JDBC allow you to connect to any database e.g. Oracle, SQL Server or MySQL, provided you have the vendor's implementation of JDBC driver interface, which is required to connect database. You can connect to MySQL from Java by using MySQL's Type 4 JDBC driver which is bundled in mysql-connector-java-5.1.23-bin.jar. It's type 4, pure Java driver, which means you don't need any native library or JDBC ODBC bridge, all you need is to put this JAR in your classpath. This JAR contains "com.mysql.jdbc.Driver" which is the key for making database connection from Java program to MySQL DB. If this JAR is not present in the classpath, then while running this program you will get java.lang.ClassNotFoundException: com.mysql.jdbc.Driver, so always make sure you have this JAR in the classpath. By the way if you are looking for some good book to master JDBC programming in Java, I suggest you to take a look at Practical Database Programming with Java By Ying Bai. This is one of the relatively latest book on JDBC and cover two of the most popular database SQL Server 2008 and Oracle. This book also teaches you how to work in Netbeans Integrated environment, similar to our example and provides all necessary tools and knowledge to handle database programming in Java. An ideal book for graduate and undergraduate students, as well as database programmers and software engineers.

Tuesday, June 13, 2017

Difference between application/x-www-form-urlencoded and multipart/form-data in HTTP/HTML?

Recently in one of the Java web developer interview, one of my readers asked about the difference between x-www-form-url-encoded and multipart/form-data MIME types. In HTTP, there are two ways to send the HTML form data to the server either by using ContentType application/x-www-form-urlencoded or by using multipart/form-data. Even though both can be used to send both text and binary data to the server there is a subtle difference between them. In the case of x-www-form-urlencoded, the whole form data is sent as a long query string.

Monday, June 12, 2017

How to converts Java Object to XML - JAXB Example

JAXB, stands for Java API for XML Binding or sometimes Java Architecture for XML Binding is a decade old technology to directly convert a Java object into XML document (marshaling) and back to XML file into Java object(unmarshalling). It uses combination of annotations and getters and setters to marshal Java object into XML. JAXB actually defines the behavior of a standard set of tools and interfaces that automatically generate Java class files from XML schema, remember JAXB is actually a framework and architecture, not an implementation. The package java.xml.bind provides a runtime binding framework for clients to marshal, unmarshal and validate XML file in Java. BTW, JAXB is not the only option to parse XML in Java, you can always use SAX or DOM parser or JAXP API to convert XML to Java object and vice-versa. If you want to learn more about XML processing in Java, I suggest to look at chapter 2 of Core Java Volume 2 By Cay S. Horstmann. This book covers not only DOM and SAX but also StAX parser and locating information with XPath.

Sunday, June 11, 2017

Is Java Compiled or Interpreted Programming language?

One of the first question a graduate C or C++ programmer, who has just started learning Java ask is, whether Java is a compiled language or an interpreted one? On academic courses or during college, students learn a lot of languages e.g. VB, C, C++ and they happily categories them as either compiled or interpreted, but with Java it's tricky. It's not clear whether Java is compiled or interpreted, because it neither generate machine language code after compiling source file,  neither interpreted source file to execute instruction line by line. In order to answer this question you need to fist know that Java is a platform independent language? Which means you can run a Java program to any platform, which includes hardware + operating system, without any modification. Knowing how Java achieves platform independence is key to answer this question.

How to Generate MD5 checksum for Files in Java

MD5 checksums are good to verify the integrity of files and It's easy to generate MD5 checksum in Java. Java provides a couple of ways to generate the MD5 checksum for any file, you can either use java.security.MessageDigest or any open source library like Apache commons codec or Spring. All 3 ways we have seen in our earlier article about generating the MD5 hash for String is also applicable to generate the MD5  checksum for any file. Since most of the md5() or md5Hex() method takes byte[], you can simply read bytes from InputStream or pass to these md5 methods. Apache commons codec from version 1.4 also provides an overloaded method for accepting InputStream, which makes generating checksum very easy in Java. For those who are not familiar with checksum, it's a fixed-size datum generated from a block of data to detect any accidental change in data. 

Jersey Web Service Hello World Example in Java

After Restlet, Jersey is another popular open source framework to create RESTful web services in Java. Jersey conforms JAX-RS specification and actually it is the reference implementation of JAX-RS (JSR 311)(http://jsr311.java.net/nonav/releases/1.1/index.html) specification. In the last article, we have seen the Restlet HelloWorld Example and today we'll see the Jersey HelloWorld Example. Typically, when a developer thinks of creating a RESTful web service using Java, they assume that using a Java EE application server is the only way to create this type of application. However, there are simpler, lightweight alternative methods for creating RESTful applications available using Java SE. This tutorial demonstrates one such alternative using the Grizzly Web server along with the Jersey REST framework. Grizzly's main use case is the web server component for the GlassFish application server.

Saturday, June 10, 2017

How to compare two lists of values in Microsoft Excel - Java

If you are working in real world application then you may frequently face scenarios where you have to compare data e.g. you get two lists of values and you want to know which values are common between two lists, which values only exists in the first list and which values only exists in the second list. If the list contains just 5 to 10 values you can do it easily with your eyes but what is fun if a programmer doing the task manually. You should be able to leverage all the tools available to you to do this comparison reliably. One of such ubiquitous and omnipresent tool is Microsoft Excel which is much more powerful then you can think of. It's like your brain, most of us just use 5% of Excel and a good knowledge of Excel's little bit advanced functionality e.g. VLOOKUP can be very helpful while comparing the list of values and reconciling data between different worksheet.

How to Read Write Excel file in Java - POI Example

In this Java Excel tutorial, you will learn how to read and write from Excel file in Java . You will learn steps to read/write both XLS and XLSX file format by using Apache POI library. In this example, we will particularly focus on reading and writing String and Date values into Excel file as writing dates are little bit tricky. In our earlier Java Excel tutorial, you have already learned how to read/write Numeric types from Excel in Java, but we haven't touched date values, which are also stored as numeric types, we will learn that in this tutorial. There are two parts of this tutorial, in first part we will write date and String values into XLS file and in second part we will read them from XLS file. You might aware that Excel file now comes with two formats, XLS file which is an OLE format and XLSX format, which is also known as OpenXML format. Apache POI supports both format but you would need different JAR files to read/write XLS and XLSX files. You need poi-3.12.jar to read XLS file and poi-ooxml-3.12.jar to read XLSX file in Java.

Top 30 Programming questions asked in Interview - Java C C++ Answers

Top 30 Programming interview questions
Programming questions are an integral part of any Java or C++ programmer or software analyst interview. No matter on which language you have expertise it’s expected that you are familiar with fundamental of programming and can solve problems without taking help of API. Programming questions like reversing String using recursion or How to find if Array contains duplicates are some popular examples of programming question in Java. Programming questions present lot of challenges Especially to Java developers as compared to C++ programmer and I think, One reason for this is powerful Java API; Which has method for almost every need and you rarely need to write by your own or there are lots of third party library from Apache, Spring, Google and other open source.

Friday, June 9, 2017

10 Interview Questions on Java Generics for Programmer and Developers

Generic interview questions in Java interviews are getting more and more common with Java 5 around there for considerable time and many application either moving to Java 5 and almost all new Java development happening on Tiger(code name of Java 5).  Importance of Generics and Java 5 features like Enum,  Autoboxing, varargs and Collection utilities like CountDownLatch, CyclicBarrier and BlockingQueue are getting more and more popular on Java interviews. Generic interview question can get real tricky if you are not familiar with bounded and unbounded generic wildcards, How generics works internally, type erasure and familiarity with writing parametrized generics classes and methods in Java. Best way to prepare for Generics interview is to try simple program best on various features of generics. Anyway In this Java interview article we will see some popular Java Generics interview questions and there answer. By the way there are lot of material available in Javarevisited to better preparing for Java and J2EE interviews, you can prepare multi-threading and Collections using 15 thread interview question and Top 10 Java collection interview question along with several other questions answers articles on Spring, Struts, JSP and Servlet. If you are GUI developers and working in Java Swing technology than you can also check interview questions on Java Swing  mostly asked in Investment banks

How Spring MVC Framework works? How HTTP Request is processed?

One of the frequently asked Spring MVC Interview questions is about explaining the flow of web request i.e. how an HTTP request is processed from start to end. In other words, explaining the flow of request in Spring MVC. Since many of my readers ask this question time and again, I thought to summarize the flow of request processing in a short article. It all starts with the client, which sends a request to a specific URL. When that request hit the web container e.g. Tomcat it look into web.xml and find the Servlet or Filter which is mapped to that particular URL. It the delegate that Servlet or Filter to process the request. Since Spring MVC is built on top of Servlet, this is also the initial flow of request in any Spring MVC based Java web application.

SynchronousQueue Example in Java - Produer Consumer Solution

SynchronousQueue is special kind of BlockingQueue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. When you call put() method on SynchronousQueue it blocks until another thread is there to take that element out of the Queue. Similarly, if a thread tries to remove an element and no element is currently present, that thread is blocked until another thread puts an element into the queue. You can correlated SynchronousQueue with athletes (threads) running with Olympic torch, they run with torch (object need to be passed) and passes it to other athlete waiting at other end.

java.lang.NullPointerException - Common Cause of NullPointerException in Java Example

java.lang.NullPointerException or NullPointerException in Java is probably the first Exception you will face in Java. It is true nightmare for beginners in Java but pretty easy to solve once you get familiar with Exception handling in Java. What makes NullPointerException little tricky is its name which has pointer in itself and Java does not support pointers like multiple inheritance in Java . In this article we will see What is NullPointerException in Java, How to solve Exception in thread "main" java.lang.NullPointerException, finding possible cause of Java NullPointerException and how to troubleshoot NPE in Java. Based on my experience once you know little bit about NullPointerException its pretty easy to solve. By the way, as said, "prevention is better than cure", you can avoid != null check and NullPointerException by following some best practices.

Thursday, June 8, 2017

Top 30 Array Interview Questions and Answers for Programmers

The array is one of the most important topics for programming interviews. It doesn't matter if you are going to Google, Microsoft, Amazon or investment banks like Goldman Sachs, Barclays, Citi or even service based companies like IBM, Accenture, TCS, or Infosys, if you are going to interview for the developer position, you must prepare array very well. In fact, it is the second most topic after String and if you look closely, may of String coding problems can be solved by treating them like character array. The array is also ubiquitous, no matter which programming language you choose, you will find array there, it's available in C, C++, Java and even on Python, Perl, and Ruby. In fact, it is one of the building blocks of programming tools along with arithmetic, relational and bit operators. You learn about array in the very first week of your programming course and use that knowledge all your career.

Wednesday, June 7, 2017

How to prepare for Spring Framework Certifications?

Ever since Pivotal, the company behind Spring framework made the mandatory Spring training optional (see here), I have received many queries from experienced Java developers who are interested in doing Spring certifications. This move from Pivotal suddenly makes the Spring certification affordable for many experienced Java and Spring developers who were interested in Spring certification earlier but couldn't progress further due to expensive mandatory training. Since many of them are now preparing for Spring certifications e.g Spring Core or Spring via self-study they are increasingly looking for good resources to prepare for the exam. I have received a lot of questions on preparation, books, mock exams, exam structure, passing marks and useful resources.

10 Examples of Date Command in Linux and UNIX

Date command in unix or Linux is one of important command to learn and master because we always need date information. no matter you want to know current date in unix or your bash script needs current date in unix for archiving purpose you need to use date command. In its simplest format date command shows the current date and time in unix while with sophisticated option we can extract many useful information from unix date command. In this Unix command tutorial  we will see some useful tips on using date command in unix and learn more around date in unix and Linux. One important thing to note is that different implementation of unix date command may not be exactly same e.g. AIX version of date command doesn't support option "-d" or "date". Anyway let's see some example of unix date command:

By the way this is fifth article in my series of covering examples of important and frequently used commands e.g. find examples, grep examples, chmod example and sort command example.

Tuesday, June 6, 2017

Exception in thread "main" java.lang.ExceptionInInitializerError in Java Program

JVM throws java.lang.ExceptionInInitializerError, when there is an Exception inside static initializer block. If you know about static variable in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException. Java developers often confused with this error because, they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in source file.

How to get current URL, parameters and Hash tag using JQuery and JavaScript

While dealing with current URL, many time you want to know what is the current URL path, What are the parameters, and what is the hashtag on URL. The hash tag is pretty important if you are implementing tab structure using HTML and JQuery. To avoid confusion, let's take an example of URL: http://javarevisited.blogspot.com/2013/01/top-5-java-programming-books-best-good.html#ixzz2PGmDFlPd , in this example ixzz2PGmDFlPd, is a hash tag. Now, both JavaScript and JQuery provides a convenient way to retrieve current URL in the form of window.location object. You can use various properties of the window.location JavaScript object e.g. window.location.href to get complete URL, window.location.pathname to get the current path, and window.location.hash to get a hash tag from current URL. If you like to use JQuery then you can get a window.location as JQuery object and retrieve relevant properties using attr() function. 

Monday, June 5, 2017

Top 5 Websites to Learn Java and Coding Online for FREE - Best of lot

Here, I often receive questions like how to improve my coding skills?,  or how do I learn to programme?, or I am having difficulty solving programming problems, please help etc. This is mostly from programmers, who has just started programming or a graduate with programming degree or even some programmers with a year or two in Job. Like many other things in the world, to improve coding you need to code, code, and code - and to improve programming you need to write a program, and that's where many of these programmers fail. In 90% cases, they simply don't write enough program to develop programming logic and code sense and if without too much experience at data structures and algorithms, if they attempt problems given on sites like TopCoder, or Project Euler, they fail miserably.

How to get JAR files of Jackson Libary for JSON Processing

If you are using Jackson to parse a JSON String in Java first time and wondering where can you get the Jackson related JARs, or which JAR files are really need then you have come to the right place. It can be really confusing for a new user to set up or include Jackson library in their Java projects sometimes, especially, if you are not very familiar with the structure of Jackson projects, various JAR files and in particular Maven. Since Jackson is the most popular open source library for processing JSON responses e.g. generating Java objects from JSON received from RESTful Web services or generating JSON String from Plain Old Java Objects (POJO). It is the go-to library for any JSON need because it offers a lot of features without compromising on performance.

Sunday, June 4, 2017

5 Reasons to Use Composition over Inheritance in Java and OOP

Favor composition over inheritance is a one of the popular object-oriented design principles, which helps to create flexible and maintainable code in Java and other object-oriented languages. Many times I have seen people suggesting use composition instead of inheritance, in fact, my favorite books like Head first Design Patterns also advocates this design principle. Head first books have its own way of explaining, why composition is better than inheritance and though its long its quite interesting and informative. It was the first chapter of this book, which helped me a lot on understanding this key OOPS concept. In this Java and OOPS tutorial, I have tried to summarize my experience around composition and inheritance in two main category, first, difference between composition and inheritance and second, when to use Composition over inheritance in Java. 

Saturday, June 3, 2017

What is the cost of Spring Framework Certification and Training in India and USA?

One of the frequently asked question about Spring certifications and training e.g. Spring Core and Spring Web Application Developer Certification is their cost e.g. what is the cost of Spring certification in India? or how much it cost for Spring framework certification in the USA etc. Earlier, Spring certification used to cost around 3000 USD in the USA and other North American countries and around 50,000 INR in India due to mandatory training you needed to take before you can appear in the exam. The cost of the Spring framework training was more than 90% of the total cost of the Spring certification. But gone are those days. Since 10th May 2017, you can take the exam without mandatory training, see here. Due to this reason, the cost of Spring certification has come down heavily and it's just now the cost of the exam voucher which is just 200 USD globally.

How Volatile in Java works? Example of volatile keyword in Java

How to use Volatile keyword in Java
What is volatile variable in Java and when to use  the volatile variable in Java is a famous multi-threading interview question in Java interviews. Though many programmers know what is a volatile variable but they fail on second part i.e. where to use volatile variable in Java as it's not common to have a clear understanding and hands-on on volatile in Java. In this tutorial, we will address this gap by providing a simple example of the volatile variable in Java and discussing some when to use the volatile variable in Java. Anyway,  the volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in an int or a boolean variable then  you can declare them as volatile variable.

Google Protocol Buffers (ProtoBuf) - Java Serialization Alternative

If you have done some serialization works in Java, then you know that it's not that easy. Since default serialization mechanism is not efficient and has host of problems, see Effective Java Item 74 to 78, it's really not a good choice to persist Java object in production. Though many of efficiency shortcomings of default Serialization can be mitigated by using custom serialized format, they have their own encoding and parsing overhead. Google protocol buffers, popularly known as protobuf is an alternate and faster way to serialize Java object. It's a good alternative of Java serialization and useful for both data storage and data transfer over network. It's open source, tested and most importantly widely used in Google itself, which everyone knows put a lot of emphasis on performance. It's also feature rich and defines custom serialization formats for all data types, which means, you don't need to reinvent the wheel. It's also very productive, as a developer you just need to define message formats in a .proto file, and the Google Protocol Buffers takes care of rest of the work. Google also provides a protocol buffer compiler to generate source code from .proto file in Java programming language and an API to read and write messages on protobuf object. You don't need to bother about any encoding, decoding detail, all you have to specify is your data-structure, in a Java like format. There are more reasons to use Google protocol buffer, which we will see in next section.

2 Examples to read Zip Files in Java, ZipFile vs ZipInputStream

ZIP format is one of the most popular compression mechanism in computer world. A Zip file may contains multiples files or folder in compressed format.  Java API provides extensive support to read Zip files, all classes related to zip file processing are located in java.util.zip package. One of the  most common task related to zip archive is to read a Zip file and display what entries it contains, and then extract them in a folder. In this tutorial we will learn how to do this task in Java. There are two ways you can iterate over all items in a given zip archive, you can use either java.util.zip.ZipFile or java.util.zip.ZipInputStream. Since a Zip file contains several items, each of them has header field containing size of items in number of bytes. Which means you can iterate all entries without actually decompressing the zip file.

How to find CPU and Memory used by Java process in Solaris – prstat command example

We often need to find CPU and memory utilization of a particular Java process in order to get some performance stats, capacity planning or just to understand the current load on the system. Performance monitoring and testing is an integral part of any Java application development, especially if you are working in high-frequency trading space. In order to fix a performance problem, you have to find them first and knowledge of right tools and commands helps there. One of the primary cause of poor application performance is it Java or any other process is exhaustion of important resources like CPU and memory. Monitoring CPU and memory utilization of your Java process give you some useful insight like what is the normal memory and CPU utilization, when are you getting spikes in CPU and memory consumption. If  heap memory is constantly increasing over time than it’s an indication that your Java application may have a memory leak. 

In this Java performance tutorial, we will learn about two most common Solaris commands prstat and pmap to find CPU and memory utilization of Java process. prstat is a process monitoring tool easily available in any Solaris systems including SPARC and x86 boxes, which provides useful statics of CPU and memory utilization of a process. 

For other systems e.g. windows you can use windows task manager for CPU monitoring and Linux you can use top command for same purpose. By the way, you can also check out Java performance by Charlie Hunt and Binu John, it is immensely helpful for Java performance monitoring and tuning. This is the book, which gives you right kind of tools and knowledge required to find performance stats for Java application.