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.

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.

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.

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.

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.

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.

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.

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.

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 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.

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.

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 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.

2 Websites to Learn Coding in Java Online for FREE

Here, I often receive questions like how to improve my coding skills?,  or how do I learn programming?, or I am having difficultly 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 program, and that's where many of these programmers fails. 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. To be frank, it's not easy to solve problems from those site, until you have really done programming for year or two, or even more.  A good way to improve coding is to solve basic data structures, algorithms and object oriented design problems by yourself.  If you are absolutely new in programming world then investing some money in buying a book on data structure and algorithm e.g. Introduction to Algorithm , though it will not teach you coding but it will give knowledge of data structure and algorithms, which is very important for any programmer. You can also purchase a book to learn how to program e.g. Head First Programming, which teaches you how to code and write program using Python language. These books can supplement your practice with solid knowledge .

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.

Difference between Inheritance and Composition in Java OOPS

Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Another difference which comes from this fact is that by using Composition you can reuse code for even final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition you can reuse code from many classes as they are declared as just a member variable, but with Inheritance you can reuse code form just one class because in Java you can only extend one class, because multiple Inheritance is not supported in Java. You can do this in C++ though because there one class can extend more than one class. BTW, You should always prefer Composition over Inheritance in Java, its not just me but even Joshua Bloch has suggested in his book Effective Java, which is a great resource to learn how to do things in right way in Java. I have listed my argument in favor of Composition over Inheritance in my earlier post, which you can check now or later.