Wednesday, July 29, 2015

Top 5 Data Structure and Algorithm Books - Must Read, Best of Lot

Data Structure and Algorithms books are often taught as textbooks in various universities, colleges and Computer Science degree courses, yet, when you put programmers in a situation, where they need to find and decide, which data structures and algorithms to use to solve a problem, they struggle. I have seen this, and I think one reason of this is perspective. When you read something as a textbook and your perspective is just to do well in the exam, you might not be thinking about learning and applying that knowledge to real-world problems. Since data structures and algorithms are the core of any programming problem, it becomes extremely important for programmers to master them even if you have learned well during academics.

Monday, July 27, 2015

How to Calculate Difference between two Dates in Java (In Days)

If you are not running on Java 8, then there are two ways to calculate the difference between two dates in Java in days, either by using standard JDK classes e.g. java.util.Date and java.util.Calendar or by using the joda-time library. Unfortunately, Java's old Date and Calendar API is buggy and not intuitive, so many of us by default use Joda for all date and time arithmetic. In this example, you will learn how to find  the number of days between today and any date entered by a user using Joda, as well as without using any third party library. When I first time face this problem, I thought what's a big deal about finding the difference between dates? If you can convert Date to milliseconds then finding a number of days, months or years are just a matter of simple arithmetic, but I was WRONG. I was not thinking about real world date and time nuisance like leap seconds, leap years, and daylight saving time.

Saturday, July 25, 2015

java.sql.SQLException: No suitable driver found for jdbc:jtds:sqlserver - Cause and Solution

java.sql.SQLException: No suitable driver found for 
There are two ways to connect Microsoft SQL Server from Java program, either by using Microsoft's official JDBC driver (sqljdbc4.jar), or by using jTDS driver (jtds.jar). This error comes when your supplied database URL didn't match with the JDBC driver present in the CLASSPATH. Many programmers who usually use jtds.jar, makes a mistake while using sqljdbc4.jar by adding "microsoft" in JDBC URL. That makes URL invalid and JDBC API throws "java.sql.SQLException: No suitable driver : sqljdbc4.jar" error.

Thursday, July 23, 2015

3 Ways to Read File line by line in Java 8? Examples

Java 8 has added a new method called lines() in Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed. So, if you have a huge file and you only read first 100 lines then rest of the lines will not be loaded into memory, which results in better performance. This is slightly different than Files.readAllLines() method (which reads all lines into a List) because this method reads the file lazily, only when a terminal operation is called on Stream e.g. forEach(), count() etc. By using count() method you can actually count a number of lines in files or number of empty lines by filtering empty lines.

Tuesday, July 21, 2015

How to Read XML File as String in Java? 3 Examples

Suppose you have an XML file and you just want to read and display the whole file as String in Java, may be for debugging purpose. If you are wondering how to do that in Java, well there are many ways to read XML as String in Java. You can do it in one line if you are fine with using an open source library or you can do it in a couple of lines of code in core Java as well. Since an XML file is also a file, you can use BufferedReader or FileInputStream to read the content of an XML file as String by using the techniques, I have discussed in my earlier post 3 ways to convert InputStream to String in Java. But this post is about a new library called jcabi-xml which makes working with XML file really easy. You can parse the XML file using XPath expression, you can do XSL transformation, XSD schema validation and you can even parse whole XML file as String in just a couple of lines of code.

Sunday, July 19, 2015

How to convert String or char to ASCII values in Java

You can convert a character e.g. 'A' to its corresponding ASCII value 65 by just storing it into a numeric data type e.g. byte, int or long as shown below :

int asciiOfA = (int) 'A';

Here casting is not necessary, simply assigning a character to integer is enough to store ASCII value of character into an int variable, but casting improves readability. Since ASCII is 7-bit character encoding, you don't even need an integer variable to store ASCII values, byte data type in Java, which is 8 bits wide is enough to store ASCII value of any character.  So you can also do like this :
byte asciiOfB = 'B'; // assign 66 to variable

Friday, July 17, 2015

Good time to become Java Certified Programmer - 20% discount on ALL Exams

In a nice gesture, Oracle has announced 20% discount on any Java certification to celebrate 20 years of Java. Which means now you can get your Java SE certification at 20% discount, this is almost a saving of almost 50 USD. This is really exciting to all Java developers who are preparing for Java SE 8 certification, 1Z0-808 (Oracle Certified Associate, Java SE 8 Programmer) or certified Java developers who are looking to upgrade their certification for Java SE 8. This discount is available to ANY Java certification, including OCPJP 6, OCAPJP 7, OCPJP 7 and OCAJP 8. Now, the big question, how do you get this discount?  Not much, just choose the exam you want to take and register for it as shown below, but don't get late. This offer is only valid till 31st December 2015.

Wednesday, July 15, 2015

How to find duplicate words in Java String? [Solution]

Problem :  Write a Java program to print the duplicate words from a given statement e.g. if given String is "Java and JavaScript are totally different, JavaScript follows Java" then your program should print "Java" and "JavaScript" because those two are 2 duplicate words from given String. You need to consider all cases e.g. given String can be null, empty, may or may not contain any duplicate words, but for simplicity, you can assume that sentence will always in English and only use ASCII characters, alphabets, and numerals, no special character.  It's better to get the requirement right of the problem in the beginning even if the interviewer doesn't tell you everything. Directly jumping into solution without asking a couple of questions may not go well with many interviewers who looks for detail oriented candidates.

Monday, July 13, 2015

How to do GROUP BY in Java 8? Collectors.groupingBy() Example

Java 8 now directly allows you to do GROUP BY in Java by using Collectors.groupingBy() method. GROUP BY is a very useful aggregate operation from SQL. It allows you to group records on certain criteria. How do you group by in Java? For example, suppose you have a list of Persons, How do you group persons by their city e.g. London, Paris or Tokyo? Well, we can do that by using a for loop, checking each person and putting them on a list of HashMap with the same city, but in Java 8, you don't need to hack your way like that, you have a much cleaner solution. You can use Stream and Collector which provides groupingBy() method to do this. Since its one of the most common way to aggregate data, it has a real benefit, coupled that with the various overloaded version of groupingBy() method which also allow you to perform grouping objects concurrently by using concurrent Collectors.

Saturday, July 11, 2015

How to solve java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver in Java 8

java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver exception comes in Java 8 because it has removed the JDBC ODBC bridge driver class "sun.jdbc.odbc.jdbcodbcdriver" from JDK and JRE. This class is required to connect any database using Object database connectivity driver e.g. Microsoft Access, but unfortunately you cannot use it from JDK 8 onward. In order to solve this error, just use Jackcess library or a commercial driver like HXTT. Normally, in pre Java 8 world, java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver error comes when you try to connect to Microsoft Access database from Java using JDBC and JDBC ODBC bridge driver is not available in classpath. If you remember, In order to open SQL connection to database, first step is to load and register the driver. In order to load driver, we use Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  and this method throws java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver, if ClassLoader is not able to find the requested class (sun.jdbc.odbc.JdbcOdbcDriver) in CLASSPATH. In order to connect to MS Access, we need type 1 JDBC driver, also known as JDBC ODBC bridge driver and the class in question, JdbcOdbcDriver is driver implementation to connect to Open database connectivity driver installed in machine.

Friday, July 10, 2015

Top 10 Java ArrayList Interview Questions Answers for 1 to 2 years Experience

Most of the Java interview questions on ArrayList asked to freshers or Java developers with 1 to 2 years experience is just simply how to do task e.g. how to sort arraylist, how to serach element, how to remove an element using iterator etc. Since, I have written lots of Java tutorials on ArrayList, covering many general purpose tasks e.g. how to create an object of ArrayList and initialize to how to sort ArrayList in ascending and descending order etc. On request of my readers, I am creating this mega list of ArrayList tutorials, which will help you to learn everything about ArrayList class. These tutorials are great for beginners and even experienced Java developers can learn a trick or two.

Thursday, July 9, 2015

Strategy Design Pattern and Open Closed Principle in Java - Example

Strategy design pattern is based upon open closed design principle, the 'O' of famous SOLID design principles. It's one of the popular pattern in the field of object-oriented analysis and design along with Decorator, Observer and Factory patterns. Strategy pattern allows you to encapsulate possible changes in a process and encapsulate that in a Strategy class. By doing that your process (mainly a method) depends upon a strategy, higher level of abstraction than implementation. This makes your process open for extension by providing new Strategy implementation, but closed for modification, because the introduction of a new strategy doesn't require a change in a tested method. That's how it confirms open closed design principle.

Wednesday, July 8, 2015

5 Programming Languages Every Programmer Should Learn

I have read somewhere that programmer should learn a new programming language every year ( I think it's code complete, not sure, though), but if you cannot do so, I suggest to at least learn following five programming language to do well in your career. Everybody loves polyglot programmer and an all rounder who is versatile enough to write a quick script and can also write complex Java programs. In fact, it's almost mandatory for a senior developer to learn more than one language. Interviewers are giving more attention to a programmer who has good experience with multiple languages e.g. C++ and Java goes quite well, so is Python and Java. I personally like programmers who have strong experience on either C++ or Java and can write scripts in groovy, Perl or Python.

Monday, July 6, 2015

Fibonacci series in Java without using Recursion

Fibonacci series is a great example of Recursion and how the use of recursion can result in a clear and concise solution. That's why whenever asked about writing a Java program to get a Fibonacci numbers or print the Fibonacci series of certain numbers, it's quite natural for programmers to resort to recursion. Interviewer often challenged this practice by asking candidates to implement Fibonacci series without using recursion. Yes, you read it right, you can't use recursion and this is what you will learn in this article. If you have attended your programming classes regularly then you may know that many recursive algorithms also has their iterative counterpart which uses loops instead of recursion or calling itself . We will take advantage of that concept to devise a solution of this problem.

Sunday, July 5, 2015

java.lang.ClassNotFoundException: [Solution]

This error comes when you try to connect to Microsoft SQL Server database from Java program but the required JDBC driver is not available in Classpath or driver is available in CLASSPATH but the class loader is not able to find it due classpath intricacies. Depending upon your situation, a solution could be as simple as downloading any of sqljdbc.jar, sqljdbc4.jar or sqljdbc41.jar, based upon the Java version you are using and adding them into CLASSPATH as set CLASSPATH = %CLASSPATH%; (path to Microsoft JDBC driver) in Windows. BTW, in most of the cases "java.lang.ClassNotFoundException:" comes because of classpath intricacies. For example, if your Java program is using -cp or -classpath option but you added the JAR into CLASSPATH environment variable or vice-versa.

Friday, July 3, 2015

How to Convert Fahrenheit to Celsius in Java with Example

In this Java tutorial, you will learn how to write a program to convert Fahrenheit to Celsius in Java. Fahrenheit is a thermodynamic temperature scale, where the freezing point of water is 32 degrees Fahrenheit (°F) and the boiling point of water is 212°F (at standard atmospheric pressure). This puts the boiling and freezing points of water exactly 180 degrees apart. Therefore, a degree on the Fahrenheit scale is 1/180 of the interval between the freezing point and the boiling point of water. Absolute zero is defined as -459.67°F. If you know, in Celsius scale, the freezing point of water is at 0ºC and the boiling point of water is at 100ºC. By using these facts, you can easily deduce a formula to convert Fahrenheit temperature into Celsius.

Thursday, July 2, 2015

How to solve java.lang.UnsatisfiedLinkError: no ocijdbc11 in Java

"java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path" error comes when you try to connect to Oracle 11g database using OCI (thick) driver by using tns name, but the ocijdbc11.dll file is not available in PATH or java.library.path environment variable. ocijdbc11.dll is a native library and if you know Java searches native library in PATH or a location specified by java.library.path system property, if it doesn't find the dll, then it throws java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path error. This dll is usually found in C:\Programs\Oracle\ora11g\bin\ocijdbc11.dll, but it could vary depending upon your Oracle installation.

Wednesday, July 1, 2015

How to use wait, notify and notifyAll in Java - Producer Consumer Example

You can use wait, notify and notifyAll methods to communicate between threads in Java. For example, if you have two threads running in your program e.g.Producer and Consumer then producer thread can communicate to the consumer that it can start consuming now because there are items to consume in the queue. Similarly, a consumer thread can tell the producer that it can also start putting items now because there is some space in the queue, which is created as a result of consumption. A thread can use wait() method to pause and do nothing depending upon some condition. For example, in the producer-consumer problem, producer thread should wait if the queue is full and consumer thread should wait if the queue is empty.