Wednesday, 7 December 2016

I am starting a new series called Java Coding Quiz, in which I'll show you subtle Java concepts hidden in the code. This is an OCAJP or OCPJP style question but focused on teaching subtle details of Java programming language. In today's puzzle, you will learn about one of the key concepts about how floating point and integer arithmetic works in Java. This is a very important concept for any Java developer because Java behaves differently when the same operation is performed by different types of variable but of the same value.

Sunday, 4 December 2016

Spring and Hibernate are two of the hottest and most in-demand web frameworks in Java world and also two of the most essential skill for any Java programmer to get a Job in web development space. The Spring framework is in around from 2004 and established itself as the leading framework to develop Java applications both in core Java and web development area. The Spring framework comes with a lot of modules to support a different kind of developments e.g Spring Security to address the security requirements of most web and enterprise Java applications. It supports single sign-on, LDAP authentication, Role-based access control, and much more such essential features. Spring also supports the development of REST services which is no become standard way to provide web services.

Thursday, 1 December 2016

Java 5 added Executor Framework to provide out-of-box thread pool to Java programmers and Java 7 added ForkJoinPool an implementation of ExecutorService which specifically designed to execute ForkJoinTask. The Executor Framework provides several classes e.g. Executor, ExecutorService, and Executors for execution and creating thread pools. It also provides several built-in, ready to use thread pools like a pool of fixed threads, cached thread pool which can expand itself, spawn new threads if required due to heavy load.

Sunday, 27 November 2016

Apart from books, exam simulators are another essential tool to prepare for Java certifications. They not only give you the opportunity to test you knowledge topic wise but also provide the helpful explanation to clear your doubt and misconception, which means you can learn on the fly. Actually, when I prepared for my SCJP exam, I learned a lot of new concept by just giving mock exams and solving practice question. Since most of the Java certification aspirants are Java developer with some experience i.e. they have done a good amount of coding, they can easily understand the code but they might not be familiar with exam format.

Thursday, 24 November 2016

Some of you might ask, Why software project manager should read books? Isn't they are experienced enough to become a project manager and handle software development? A genuine question but Software management is harder than any other management purely because every software is different than the previous one. Many other streams of engineering e.g. Civil or Mechanical got better in terms of estimation and management with the help of software but software development is still run on experience.

Monday, 24 October 2016

If you remember REST WebServices uses HTTP methods to map CRUD (create, retrieve, update, delete) operations to HTTP requests. Even though both PUT and POST methods can be used to perform create and update operation in REST WebServices, Idempotency is the main difference between PUT and POST. Similar to the GET request, PUT request is also idempotent in HTTP, which means it will produce the same results if executed once more multiple times. Another practical difference PUT and POST method in the context of REST WebService are that POST is often used to create a new entity, and PUT is often used to update an existing entity. If you replace an existing entity using PUT than you should be aware that if only a subset of data elements is passed then the rest will be replaced by empty or null.

Sunday, 23 October 2016

Dealing with SSL issues in Java web application is no fun, especially when you have no debug logs and all you see is an ugly ‘Page Cannot be displayed’ error message in your browser. Thankfully you can easily enable SSL to debug on your Application to start seeing verbose logs that will clearly show what happens during the SSL handshake process. You can enable SSL debugging logs in your Application Server JVM config by adding the following JVM command line parameter and restart the Application Server:

Saturday, 22 October 2016

The Restlet is one of the first open source frameworks to create and deploy RESTful web service in Java. After the release of JAX-RS (Java API for RESTful Web Services) JSR - 317, Restlet also supports JAX-RS annotation and provides a consistent way to create both RESTful Server and Client. HelloWorld program is the traditional way to start with a new technology and continuing to the tradition, we'll write our first Restlet program as HelloWorld. Since Restlet can be used to create on both client and server side, we'll first expose a resource as RESTful web service using Restlet server and then consumer the same RESTful web service by creating a RESTful client. I'll use Maven and Eclipse to create this RESTlet HelloWorld example, if you are not familiar with Maven, it's a build automation tool like ANT for Java projects but also provides dependency management i.e. you don't need to download Restlet JAR manually, Maven will do it for you. To learn more about Maven see here.

Friday, 21 October 2016

Sometimes before processing a file, you want to check it's last modified date to avoid processing an old file. Though some programmers prefer to attach date in the file name itself, I don't find it a cleaner approach. For example, suppose you are downloading closing prices of stocks and processing at the start of the day and loading into the database. In order to accidently process an old file, you can check the last modified date before processing and if it's in the acceptable range, you can process the file. You can get the last modified date of a file in Java by using java.io.File class. This is a class which represents both file and directory in Java. It contains a method called lastModified() which returns the last modified date of the file. This method returns a long millisecond epoch value, which you can convert to more readable dd MM yyyy HH:mm:sss format by using the SimpleDateFormat class of JDK. In this article, I'll tell you how to get the last modified date of file and directory in Java.

Thursday, 20 October 2016

One of the common question on Microsoft SQL Server interview is, what is the difference between GETDATE(), SYSDATETIME(), and GETUTCDATE(). Even though all three SQL Sever function returns the current date time in SQL Server, there are some subtle differences between them. The main difference between GETDATE() and SYSDATETIME() is that GETDATE returns current date and time as DATETIME but SYSDATETIME returns a DATETIME2value, which is more precise. The difference between GETDATE() and GETUTCDATE() is in timezone, the GETDATE() function return current date and time in the local timezone, the timezone where your database server is running, but GETUTCDATE() return current time and date in UTC (Universal Time Coordinate) or GMT timezone.

Wednesday, 19 October 2016

This is the second part of best books for Java 8 certifications. Since you need to pass two exams, OCAJP8 and OCPJP8 to become a Java SE 8 certified developer, I have shared some of the best OCAJP8 books in the last article. In this article, I will tell you more about the second exam OCPJP8 and suggest best books prepare OCPJP8. This exam is known as professional level exam and it's tougher than the associate level exam. The OCPJP8 stands for Oracle Certified Professional Java Programmer. The exam code for this certification is 1Z0-809. This is if you don't have any prior Java certifications but you can still become a Java SE 8 certified developer by giving upgrade exams e.g. 1Z0-810 if you already passed the OCJPJP7 exam and 1z0-813 if you have passed OCPJP6 exams. The books suggested in this article is primarily for the 1Z0-809 exam but it can also be used for upgrade exams e.g. 1Z0-810 (upgrade from Java SE 7 to Java SE 8) and 1Z0-813 (upgrade from Java SE 6 to Java SE 8) certifications.

Tuesday, 18 October 2016

You can find Tomcat and java version running on Linux either by executing the org.apache.catalina.util.ServerInfo class from catalina.jar or by executing version.sh shell script. The first solution will work on any operating system including Windows and UNIX because it's using a Java class from a catalina.jar file, which is platform independent. Though, if you don't know how to run a class from JAR file, you can check the steps here. Alternatively, you also have a version.bat file inside tomcat/bin directory to check the version of Tomcat in Windows. When you run this script in Linux or Windows it prints information about tomcat version, the java version used to run tomcat, Server built date, OS name, OS Version, architecture, JVM version and JVM vendor etc.

Monday, 17 October 2016

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement). This version of the replace() method replaces each substring of this string (on which you call the replace() method) that matches the literal target sequence with the specified literal replacement sequence. For example, if you call "Effective Java".replace("Effective", "Head First") then it will replace "Effective" with "Head First" in the String "Effective Java". Since String is Immutable in Java, this call will produce a new String "Head First Java".

Sunday, 16 October 2016

Until Java 8, there was no standard way to Base64 encode a String in Java or decode a base64 encoded String. Java Programmers either use Apache Commons library and it's Base64 class to encode or decode binary data into base 64 encoding, as shown here, or rely on internal Sun classes e.g. sun.misc.BASE64Encoder and sun.misc.BASE64Decoder(), which were not officially part of JDK and can be removed without notification. Java 8 solves this problem by providing standard support for base64 encoding and decoding by providing a java.util.Base64 class. This class contains methods like getEncoder() and getDecoder() to provide Base64 encoder and decoder to carry out base 64 encoding of String or binary data. In this article, I'll show you some example of how to base64 encode String in Java 8.

Saturday, 15 October 2016

You can print Pyramid pattern of stars or numbers using loops and print methods in Java. There are two print method you need to know, System.out.print() and System.out.println(), the difference between print() and println() is that println adds a new line character at the end i.e. it appends \n automatically. which means next time you write something will begin at the new line. On the other hand, if you use print() then the text is appended to the same line. By using these two methods, you can print any kind of pattern in Java program e.g. pattern involving multiple stars in one line, a pattern involving stars at different lines, pyramid of numbers, a pyramid of stars, inverted pyramid pattern of numbers, stars and alphabets, and so on.

Friday, 14 October 2016

Even though there are a couple of powerful build and deployment tools exists for Java applications e.g. Gradle or ANT, It seems Maven is the king of them. I have used in several Java projects over the years and it was initially ANT, but now they all use Maven with few Scala projects using Gradle. When you work with Maven you know that there are lots of commands to remember, especially if you are working on the command line. The thee Maven build commands which often confuses Java developers are mvn install, mvn release, and mvn deploy. Many Java developers are never sure which one put the artifact on the remote repository, local repository, and tag the source code in SCM like SVN. In this article, I'll explain the purpose of mvn install, mvn release, and mvn deploy command and some key difference between them.

Thursday, 13 October 2016

I often receive emails and queries asking about some good books to learn Java 8. Since Java 8 is very different from any other JDK release, in terms of language and API enhancement you really need a good book to learn fundamentals. In short, based upon my 2 years of learning and reading Java 8 books, I can say that Java SE 8 for Really Impatient is hands down the best book to learn Java 8. It covers all the essential things released in JDK 8, not just lambda expression and streams but also new Date and Time API and several other minor enhancement yet important features, which often goes un-noticed. It doesn't scare you with comprehensive detail as well and tell you what you need to know as an application developer. It's not going to teach you fundamentals of functional programming, but it will teach you how to use the map and flatMap operations.

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accept a String and return starting position of the string if it exists, otherwise it will return -1. For example "fastfood".indexOf("food") will return 4 but "fastfood".indexOf("Pizza") will return -1. This is the easiest way to test if one String contains another substring or not. The second method is lastIndexOf() which is similar to indexOf() but start the search from the tail, but it will also return -1 if substring not found in the String or the last position of the substring, which could be anything between 0 and length -1.

Tuesday, 11 October 2016

Write a program to calculate the square root of a number in Java or C++ is one of the popular coding interview questions from Programming job interviews both on tech companies like Facebook, Amazon, and investment banks like Citibank and Bank Of America etc. The problem may look easy because you might know how to find the square root of a number but it's not. In fact, it's one of the tricky questions you would encounter in programming job interviews. The first hurdle is do you really remember how to calculate square root by hand? Many programmers don't. I know they have learned it past but when you ask them to calculate square root by hand, many won't remember the algorithm they have learned in school or college.

Monday, 10 October 2016

In day-to-day programming, you often need to check if a given String is numeric or not. It's also a good interview question but that's a separate topic of discussion. Even though you can use a Regular expression to check if given String is empty or not, as shown here, they are not full proof to handle all kinds of scenarios, which common third party library like Apache commons lang will handle e.g. hexadecimal and octal String. Hence, In Java application, the simplest way to determine if a String is a number or not is by using Apache Commons lang's isNumber() method, which checks whether the String a valid number in Java or not. Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation and numbers marked with a type qualifier (e.g. 123L). Non-hexadecimal strings beginning with a leading zero are treated as octal values. Thus the string 09 will return false since 9 is not a valid octal value. However, numbers beginning with 0. are treated as decimal.null and empty/blank String will return false.

Sunday, 9 October 2016

The JDBC ResultSet doesn't provide any isEmpty(), length() or size() method to check if its empty or not. Hence, when a Java programmer needs to determine if ResultSet is empty or not, it just calls the next() method and if next() return false it means ResultSet is empty. This is correct but the main problem with this approach is if the ResultSet is not empty then you may miss the first row if you follow the standard idiom to iterate over ResultSet and get the rows which involve calling next() method of ResultSet in a while loop. The key thing, which you need to remember is that initially the ResultSet's cursor points to before the first row when you call the next() method it points to the first row and if you don't get this data and calls the next() method again then you will lose the first row.

Saturday, 8 October 2016

This is the third article on tree traversal. In the last couple of articles, I have shown you how to implement preorder and inorder traversal in Java, both recursively and iteratively and today, you will learn about the post order traversal. Out of these three main tree traversal algorithms, the post-order traversal is most difficult to implement, especially the iterative version. In post order traversal, you first visit left subtree, then right subtree and at last you print the value of root or not. So, the value of root is always printed at last in the post-order traversal. As I told you before, all three preOrder, inOrder, and postOrder are depth-first algorithms so they go down in the binary tree first before visiting nodes of the same level. The implementation of the recursive algorithm is very simple, you just need to adjust the order of recursive call according to the algorithm and you are done, but iterative algorithm requires some effort to get it right, which you will see in this article.

Friday, 7 October 2016

You can split a String by whitespaces or tabs in Java by using the split() method of java.lang.String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces. Though this is not as straightforward as it seems, especially if you are not coding in Java regularly. Input String may contain leading and trailing spaces, it may contain multiple white spaces between words and words may also be separated by tabs. Your solution needs to take care of all these conditions if you just wants words and no empty String. In this article, I am going to show you a couple of examples to demonstrate how you can split String in Java by space. By splitting I mean getting individual words as String array or ArrayList of String, whatever you need.

Thursday, 6 October 2016

If you are running lots of Java projects in Eclipse and it's throwing OutOfMemoryError every now and then it's time to increase the heap memory of Eclipse. Since Eclipse is a Java program, you can increase heap size of Eclipse by using JVM memory options -Xms and -Xmx. There are two ways to provide JVM options to eclipse either updating Eclipse shortcut or adding -vmargs on eclipse.ini file. I prefer the second option because it's clean. I'll tell you the exact steps to increase the java heap space in Eclipse but before that some background why I had to increase heap memory of Eclipse. I was getting "an internal error occurred during repository search . java heap space" while using Maven in Eclipse. Eclipse keep throwing java.lang.OutOfMemory:Java Heap Space while updating the index or searching for maven artifacts.

Wednesday, 5 October 2016

The easiest way to convert a java.util.Date to java.time.LocalDate is via Instant, which is the equivalent class of java.util.Date in JDK 8. You can first convert util Date to Instant and then create a LocalDateTime object from that instant at your default timezone. Once you have an instant of LocalDateTime, you can easily convert that to LocalDate or LocalTime in Java. If you are not living under the rock in last two years that its 2016 and Java 8 has been around for more than 2 years, 18th March 2014 Java SE 8 GA happened. In the third attempt of designing a robust date and time API, JDK 8 has come up with JSR 318 new Date and Time API and many programmers have already started using it.

Tuesday, 4 October 2016

It's tricky to use dates in SQL server query, especially if you don't have good knowledge of how DateTime type works in SQL server. For example, one of the frequently asked SQL queries on the interview is to "select all rows where the date is 20151007?" How would you do that? Does following SQL Query will work correctly

select * from table where date = '20151007'

It may or may not, it entirely depends on upon data in your table. When you only provide date part of a DateTime variable, it uses '00:00:00.000' for time part.

Monday, 3 October 2016

Can you write a Java program to check if two rectangles are overlapping with each other or not? is one of the frequently asked coding questions on tech giants like Facebook, Amazon, Microsoft and others. This is also a kind of problem where it's easy to find opposite or negative conditions e.g. when rectangles are not overlapping and then inverting the result to prove that rectangles are colliding with each other. I first heard about this problem from one of my friend who was on Android game development space. He was asked to write an algorithm to find if given rectangles are intersecting or not. He was given the choice to implement the algorithm in any programming language e.g. Java, C, C++ or even pseudo code was fine, so don't worry about language here, it's more about algorithm and logic. He is a genius so he came successful from that interview, impressing the interviewer, talking about efficiency and accuracy of the algorithm as well.

Sunday, 2 October 2016

Earlier I have talked about how to calculate a number of days between two dates in Java (see here), and now you will learn how to get the number of months and years between dates. Though it may look easy, it's not that easy to calculate months and years between dates, unless you take care of all kinds of nuisances like Daylight saving time and when daylight change occurs, leap seconds, and an extra day added in a leap year. Unfortunately, JDK doesn't have a standard method like Period.between() method of Java 8 before to solve this problem. So, if you have to calculate the number of months and years between given dates, you have three main options, first, use Calendar class to write your method to find a number of months and year between given dates, second, use Joda-time library and the third option is to upgrade to Java 8.

Saturday, 1 October 2016

It's been more than 2 years since Java SE 8 was launched on 17th March 2014 and almost 2 years since we have OCAJP8 live. You might know that in order to become a Java SE 8 certified developer you need to pass two examples, the OCAJP8 (Exam 1Z0-808) and OCPJP8 (Exam 1Z0-809). The first one is called associate level certification and the second one is called professional level certification. When OCAJP8 first comes, there were not enough good books to prepare this exam and many candidates rely heavily on Java 8 books and professional exam simulators like Whizlabs and Enthuware, but if you are going to appear for the OCAJP8 exam now, there are no such problems. In this article, you will find some of the best books to prepare for OCAJP8 exams.

Friday, 30 September 2016

You are an enthusiastic Java programmer who just learned about developing Android apps in Java. To start with you have installed Android Studio, which is the official Integrated Development Environment (IDE) for Android app development, based on IntelliJ IDEA, but as soon as you click on the Android Studio Desktop Icon to start Android Studio you are getting "No JVM installation found. Please install a 64-bit JDK" error? How do you solve this problem? Well, even though the error message is same, every problem is different depending upon your machine, the Java version, whether your desktop or laptop has 32-bit or 64-bit OS e.g. Windows 8.1 or Windows 10. Whether you have installed 32-bit Java or 64-bit JDK e.g. JDK 1.8.0 and what is the value of JAVA_HOME environment variable or whether you have defined it or not.

Thursday, 29 September 2016

Serialization is one of the important but confusing concept in Java. Even experienced Java developer struggle to implement Serialization correctly. The Serialiation mechamism is provided by Java to save and restore state of an object programatically. Java provides two classes Serializable and Externalizable in java.io package to facilitate this process, both are marker interface i.e. an interface without any methods. Serializing an Object in Java means converting into a wire format so that you can either persists its state in a file locally or transfer it to another client via the network, hence it become an extrememly important concept in distributed applications running across several JVMs. There are other features in Java e.g. Remote Method Invocation (RMI) or HttpSession in Servlet API which mandates the participating object should impelment Serializable interface because they may be transffered and saved across the network.

Wednesday, 28 September 2016

The quicksort algorithm is one of the important sorting algorithms. Similar to merge sort, quicksort also uses divide-and-conquer hence it's easy to implement quicksort algorithm using recursion in Java, but it's slightly more difficult to write an iterative version of quicksort. That's why Interviewers are now asking to implement QuickSort without using recursion. The interview will start with something like writing a program to sort an array using quicksort algorithm in Java and most likely you will come up with a recursive implementation of quicksort as shown here. As a follow-up, Interviewer will now ask you to code the same algorithm using Iteration.

Tuesday, 27 September 2016

The JSON format is one of the most popular formats to transfer and exchange data in web. Almost all RESTful web services take JSON input and provide JSON output but unfortunately JDK doesn't have built-in support for one of the most common web standard like JSON. As a Java developer if you want to develop RESTful web service and produce JSON data or if you are developing a client to an existing RESTFul web services and want to consume JSON response, you don't need to be disappointed. Fortunately, there are so many open source libraries and API available for creating, parsing and processing JSON response in Java e.g. Jackson, Google GSon, json-simple etc.

Monday, 26 September 2016

The GETDATE is one of the most popular built-in methods of Microsoft SQL Server, but unlike its name suggest, it doesn't return just date, instead it returns date with time information e.g. 2015-07-31 15:42:54.470 , quite similar to our own java.util.Date from Java world. If you want just date like 2015-07-31, or just time like 15:42:54.470 then you need to either CAST or CONVERT output of GETDATE function into DATE or TIME data type. From SQL Server 2008 onward, apart from DATETIME, which is used to store both date and time, You also have a DATE data type to store date without time e.g. 2015-07-31, and a TIME data type to store time without any date information e.g. 15:42:54.470. Since GETDATE() function return a DATETIME value, You have to use either CAST or CONVERT method to convert a DATETIME value to DATE or TIME in SQL Server.

Sunday, 25 September 2016

If you are working in Java, you might have heard about Scala, Groovy, and Closure. Out of these three Groovy seems to be gaining a place in Java projects more rapidly than others. Groovy is a Scripting language but runs on Java virtual machine. Every Java program can run on Groovy platform. As per official Groovy website, "Apache Groovy is a powerful, optionally typed and dynamic language, with static typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax". I think, they have highlighted the key capabilities of Groovy very well in that sentence. It basically further reduce the burden from Java developer with respect to coding. Now, you can put more focus on business logic and get your work done quickly without wasting time on writing more code.

Saturday, 24 September 2016

I wanted to transfer some files from Windows to Unix using FileZilla, but the problem arises when these files are transferred (Ascii or Binary mode both) and opened using VI we get ^M characters, also known as CTRL-M characters. I searched about this but the solutions were to remove these ^M characters when files are transferred using utilities. Is there any way that these ^M characters do not appear in the first place? Well, my search continues but I will share the solution which worked for me for removing control M characters i.e. CTRL-M or ^M characters. There are several UNIX commands e.g. dos2unix which can be used to convert a Windows or DOS generated files to UNIX one. You can also use sed command (stream editor) to remove CTRL-M characters without opening the file, very useful if you are removing CTRL-M characters from a large file. Alternatively, you can use VI command to open the file and replace ^M characters with nothing.

Friday, 23 September 2016

The final modifier is one of the important keywords in Java. You can use this with a class, method, and variable as well. A good knowledge of final keyword is not only essential for writing good, performant and secure Java programs but also to clear any Java interview. Interviewer pays special attention to final keyword and expects candidates knows how and when to use the final modifier with variables, methods, and classes. In this article, I have collected Java interview questions which are based upon the concept of final modifier. You might have seen many of these questions on both telephonic and face-to-face round. You can use this collection not only to check your knowledge about final keyword but also to prepare for final modifier from Java interview's perspective. If you have come across any interesting final modifier question which is not in this list, please share with us as a comment and I'll add into this list.

Thursday, 22 September 2016

If you are using Maven inside Eclipse IDE via M2Eclipse plugin then following tips can help you a lot.

1) Setup Dependency as Java Project in EclipseIf your POM dependencies is another project in Eclipse then your project will automatically get updated whenever you build the dependent project. For example, let's say you have a project, ABC, which is dependent on two core modules e.g. framework.jar and persistence.jar, if you have checked out these project and has set up them as Maven Eclipse project, M2Eclipse can directly add them as dependency, instead of loading their JAR files from repository, be it local or remote.

Wednesday, 21 September 2016

Binary tree based questions are very common in Java or any other Programming job interviews. One of the frequently asked binary tree questions is "write a program to print all leaf nodes of a binary tree". In order to solve this problem, you must know what is a leaf node? A leaf node in a binary tree is a node whose left and right child is null. They are actually the last nodes of any binary tree. In a typical programming interview, you would be given a binary tree and asked to write a program to print all leaf nodes. Usually, all binary tree related questions can be solved easily using recursion because a tree is a recursive data structure, but you should also know how to solve them without recursion.

Sunday, 11 September 2016

The Spring framework is one of the most popular frameworks for developing Java application. Apart from many goodies, it also provides a DI and IOC container which initialize objects and their dependencies and assemble them together. The Java classes created and maintained by Spring are called Spring bean. At the startup, when Spring framework initializes system by creating objects and their dependencies depending upon @Autowired annotation or spring configuration XML file, it throws "org.springframework.beans.factory.BeanCreationException: Error creating a bean with name X" error if it is not able to instantiate a particular Spring bean. There could be numerous reasons why Spring could not able to create a bean with name X, but clue always lies on the detailed stack trace. This error always has some underlying cause e.g. a ClassNotFoundException or a NoClassDefFoundError, which potentially signal a missing JAR file in the classpath.

Friday, 9 September 2016

In the last 2 decade many Java programmers started programming with C and C++ but the situation is changed now, you have more choices e.g. you can choose Python or you can even start with Java. It seems Academia is preferring Python in USA and Java in India, but there are still many programmers who know C and C++ and wants to learn Java for one or other reasons. I often receive emails from my readers about book recommendation and recently a couple of them asked me to suggest best Java books for C and C++ programmer. I can relate those beginners to myself because I have also gone through the same phase but those days the university text books are our only source to learn new thing. We didn't have broadband and unlimited access to Internet and eBooks was not popular at that time but things have changed. The good thing is now I know a couple of really good books which can help to utilize most of his C and C++ knowledge to learn Java e.g. Core Java Volume 1 - Fundamentals by Cay S. Horstmann which provides comparative analysis with C++ time to time.

Thursday, 8 September 2016

When I started coding in Eclipse, I was not aware that by default Eclipse uses tabs for indentation and tabs can have varied with e.g. 1 tab can be equal to 2 spaces or 4 spaces or even 8 spaces. Sometimes, It's all up to you how you configure tabs in your code editor and other times just the mercy of the tool you don't know how to configure e.g. VI in UNIX. I only realize the problem when I found too many difference in a file while check-in into SVN. Apparently, other people was using different indentation (spaces) and that's why the file was showing so many differences when I reformatted them in Eclipse. This happens to many programmers, some pay attention, some didn't and go ahead with the check-in the code, only to revert it back later. There is no clear guideline upon which one is better and whether a programmer should use tabs or spaces, even the Clean Code doesn't help here.

Tuesday, 6 September 2016

Hello, guys, today I am going to talk about one of the fundamental concepts in Java, defining the natural ordering of the objects e.g. lexicographical order for String and numerical order for Number classes e.g. Integer, Double, Float etc. The compareTo() method is defined in the java.lang.Comparable interface. It is used to define the natural ordering of an object e.g. String class override compareTo() to define the lexicographical order for String objects. Integer class override compareTo() to define the numeric ordering of integer objects. Similarly, you can override compareTo() method by implementing Comparable interface to define the natural order on which you want to order your object. For example, an Order should be ordered by order id hence compareTo() must provide logic for that.

Saturday, 3 September 2016

The error "java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test" occurs when you try to connect MySQL database running on your localhost, listening on port 3306 port from Java program but either you don't have MySQL JDBC driver in your classpath or driver is not registered before calling the getConnection() method. Since JDBC API is part of JDK itself, when you write a Java program to connect any database like MySQL, SQL Server or Oracle, everything compiles fine, as you only use classes from JDK but at runtime, when the JDBC driver which is required to connect to database is not available, JDBC API either throws this error or "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver".

Tuesday, 30 August 2016

Adapter design pattern in Java, also known as the Wrapper pattern is another very useful GOF pattern, which helps to bridge the gap between two classes in Java. As per the list of Gang of Four patterns, Adapter is a structural pattern, much like Proxy, Flyweight, Facade, and Decorator pattern in Java. As the name suggest, Adapter allows two classes of a different interface to work together, without changing any code on either side. You can view Adapter pattern is a central piece of the puzzle, which joins two pieces, which can not be directly joined because of different interfaces. I see a couple of reference of Adapter design pattern in one of my favorite book Clean Code, but the idea is very well explained in Head First Design Pattern, the image which they show to illustrate Adapter design pattern is worth all the talk.

Saturday, 27 August 2016

Hello guys, today I am going to share a list of free OCAJP7 and OCPJP7 mock exams and online practice tests. If you are preparing for Java SE 7 Programmer 1 or 2 certification or upgrading your existing OCJP 6 exam then this will help you to gauge your progress. As per my experience, the three keys to success in any Java certification is a selection of good books, writing small Java programs to understand concepts, and practicing mock exams. You can see that mock exams are very important to do well on the real exam. They give you much-needed practice as well as some idea about what kind of questions you can expect on real exams. Unfortunately, there are not many good quality free mock exams available for OCAJP7 but I have managed to collect some of them. Earlier, I have shared some OCAJP8 mock exams and received a lot of feedback from my readers about a similar list for OCAJP7 and OCPJP7 exams. This is a smaller list as compared to the previous one but I'll keep adding new mock exams if I come across.

The java.lang.NumberFormatException comes when you try to parse a non-numeric String to Number e.g. Short, Integer, Float, Double etc. For example, if you try to convert . "null" to an integer then you will get NumberFormatException. The error "Exception in thread "main" java.lang.NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type e.g. Integer.parseInt() which convert String to int, Double.parseDoble() which convert String to double, and Long.parseLong() which convert String to long throws NumberFormatException to inform that the input String is not numeric.

Saturday, 20 August 2016

The difference between Callable and Runnable is one of the most frequently asked multi-threading and concurrency interview question in Java world. I remember, it was 2007 when I first heard about Callable interface and that too on a telephonic interview. Till then, I was happy using Runnable to implement threads and just started paying attention to Java 1.5, as most of the application by then using Java 1.4. That one interview question encouraged me to learn more about several other useful features introduced in Java 5 concurrency library e.g. CountDownLatch, CyclicBarrier, Semaphore, Atomic variables, and Thread pool. This is one of the reasons I always encourage Java developer to give/take regular interviews, just to update your knowledge.

Wednesday, 17 August 2016

This is the second article about tree traversal algorithms using Java. In the first part, we have seen the pre-order algorithm for visiting all nodes of the binary tree and today we'll learn about the InOrder traversal. As I told you before, unlike array and linked list, binary tree has several ways of traversal. The traversal algorithms are broadly divided into depth first and breadth first traversal algorithms depending upon how algorithm actually works. As the name suggest, depth first explores binary tree towards depth before visiting sibling, while breath first visits all nodes in the same level before going to next level, hence it is also known as level order traversal. Both PreOrder and InOrder tree traversal algorithms are depth first and the only difference between pre-order and in-order algorithm is the order on which root, left node, and right node of the binary tree is visited.

Monday, 15 August 2016

One of the tricky question from Java Interview is, "Can we pass a Timestamp instance to a method expecting java.util.Date?", it's a tricky question because the answer is both Yes and No. You can, of course, pass a Timestamp object to a method with the argument as Date because first, Timestamp is a subclass of java.util.Date and second it contains both date and time values which are missing in either java.sql.Date and java.sql.Time. So there is more reason to pass a Timestamp value to Date but you should not be doing that. Why? because Timestamp is not exactly Date. It's a composite type of java.util.Date and an additional nanosecond value which is fitted there to confirm database DATETIME data type, which supports nanosecond precision. If you look at the implementation of java.sql.Timestamp class, you will find that the long value supplied by Date is stored separately then this nanosecond value.

Monday, 8 August 2016

Suppose you have a ConcurrentHashMapof String and Integer and you want to print all keys and values, how do you that? This is a common, day to day programming task for Java programmer and there are many ways to do it. The Map interface provides several view methods e.g. keySet(), values(), and entrySet() to retrieve all keys, values, and all key and value pairs as entries. You can use respective methods to print all keys, all values, or all key values pairs. For printing, you also have multiple choice e.g. you can either use enhanced for loop or Iterator, though later also provide you the facility to remove key value pairs while printing if needed. Though you should remember that these views are backed by Map, so when you remove a key-value pair from entry set it will also be removed by the ConcurrentHashMap.

Tuesday, 2 August 2016

In the last couple of years, Maven has become the de-facto build tool for Java applications. Though there are challenges exists from tools like Gradle, but I think the dominance of Maven will help it to win the final battle. When I started with Maven, I was happy with just dependency management but then I come to know about maven plugins which let you customize your build up to the level you can do with ANT. These plugins provide true power to Maven to automate most of the build related task e.g. compilation, testing, packaging, deployment, and even committing the source code into the remote source repository. Many Java developers who use Maven daily are usually not aware of these essential Maven plugins mostly because Maven just works, or someone has already done the hard work for them.

Saturday, 30 July 2016

The problem to find the 3rd element from the end in a singly linked list or nth node from the tail is one of the tricky but frequently asked linked list problems in programming job interviews. The challenge here is to solve the problem in just one pass, i.e. you can not traverse the linked list again and you cannot traverse backward because it's a singly linked list. If you have practiced some linked list problems e.g. finding length, inserting elements, or deleting elements then you should be familiar with traversal. Here, we'll use the same algorithm which we have used to find the middle element of linked list in one pass. The algorithm is also known as tortoise and hare algorithm because of the speed of two pointers used by the algorithm to traverse the singly linked list.

Sunday, 24 July 2016

As I told you before that there are multiple ways to read a file in Java e.g. FileReader, BufferedReader, and FileInputStream. You chose the Reader or InputStream depending upon whether you are reading text data or binary data, for example, the BufferedReader class is mostly used to read a text file in Java. The Scanner class is also another way to read a text file in java. Even though Scanner is more popular as a utility to read user input from the command prompt, you will be glad to know that you can also read a file using Scanner. Similar to BufferedReader, it provides buffering but with a smaller buffer size of 1KB and you can also use the Scanner to read a file line by line in Java. Similar to readLine(), Scanner class also have nextLine() method which return the next line of the file. Scanner also provides parsing functionality e.g. you can not only read text but parse it into correct data type e.g. nextInt() can read integer and nextFloat() can read float and so on.

Saturday, 23 July 2016

Though all three are ranking functions in SQL, also known as window function in Microsoft SQL Server, the difference between rank(), dense_rank(), and row_number() comes when you have ties on ranking i.e. duplicate records. For example, if you are ranking employees by their salaries then what would be the rank of two employees of same salaries? It depends on upon which ranking function you are using e.g. row_number, rank, or dense_rank. The row_number() function always generates a unique ranking even with duplicate records i.e. if the ORDER BY clause cannot distinguish between two rows, it will still give them different rankings, though which record will come earlier or later is decided randomly e.g. in our example two employees Shane and Rick have the same salary and has row number 4 and 5, this is random, if you run again, Shane might come 5th.

Monday, 18 July 2016

This week's programming exercise is to write a Java program to calculate GCF and LCM of two numbers. The GCF, stands for Greatest common factor and LCM stands for Lowest common multiplier, both are popular mathematical operation and related to each other. The GCF is the largest number which divides both the number without leaving any remainder e.g. if two numbers are 24 and 40 then their GCF is 8 because 8 is the largest number which divides both 24 and 40 perfectly, without leaving any remainder. Similarly, LCM is the lowest number which is perfectly divisible by the two number, for example, if given number is 40 and 24 then their LCM is 120 because this is the lowest number which is perfectly divisible by both 40 and 24.

Friday, 15 July 2016

String pool in Java is a pool of String literals and interned Strings in JVM for efficient use of String object. Since String is immutable in Java, it makes sense to cache and shares them in JVM. The String pool has gone through an important change in Java 7 release when it was relocated from PermGen space to heap space. Till Java 1.6, interned String and literals are stored in the PermGen space of JVM memory, which was a fixed size area for storing class metadata. The biggest issue of having String pool in PermGen is the small and fixed size of PermGen space. In some JVM it ranges from 32M to 96M, which is quite small for a large program. Since String is extensively used in both small and large Java application, Java designers thought String pool is the best way optimize the use of String object in Java.

Monday, 11 July 2016

Unlike linked list and array which can only be traversed linearly, there are several ways to traverse a binary tree. The tree traversal algorithms are mainly divided into two parts, depth first and breadth first. As their name suggests, in depth first, the tree is traversed downwards (towards the depth) before the next sibling is visited, the PreOrder, InOrder and PostOrder traversal of a binary tree are actually depth-first traversals. On the breadth first, the entire breadth of the tree is traversed before moving to next level, hence it is also known as level order traversal. There are other algorithms to traverse a binary tree as well e.g. Monte Carlo tree search, which concentrates on analyzing the most promising moves, but the pre-order, post-order, and in-order traversal are the most popular ways to traverse a binary tree in Java. They are also the most popular data structure and algorithm questions at beginner and intermediate level.

Saturday, 9 July 2016

There are multiple ways you can add an external JAR into the classpath of a Java project in Eclipse, but all goes via adding them into build path. Many beginner's struggles to add JARs into classpath and we will try to address that problem in this tutorial. You will learn step by step tutorial to add an internal or third party JAR in your application's CLASSPATH in Eclipse Indigo. Since this feature has hardly changed in any Eclipse version, you can follow same steps in Eclipse Kepler, Indigo, and Juno version to add JARs into classpath. Since Eclipse is the most popular Java IDE and used by many companies, it's important for a Java developer to know Eclipse in and out. It will not only help to work better but also to create the better impression among your teammates.

Thursday, 7 July 2016

There are a couple of ways to remove duplicate rows from a table in SQL e.g. you can use a temp tables or a window function like row_number() to generate artificial ranking and remove the duplicates. By using a temp table, you can first copy all unique records into a temp table and then delete all data from the original table and then copy unique records again to the original table. This way, all duplicate rows will be removed, but with large tables, this solution will require additional space of the same magnitude of the original table. The second approach doesn't require extra space as it removes duplicate rows directly from the table. It uses a ranking function like row_number() to assign a row number to each row.

Tuesday, 5 July 2016

The Java IO API provides two kinds of interfaces for reading files, streams and readers. The streams are used to read binary data and readers to read character data. Since a text file is full of characters, you should be using a Reader implementations to read it. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability. You can also use bothBufferedReader and Scannerto read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.

Saturday, 2 July 2016

One of the common programming questions is, how do you find the largest and smallest number in N numbers without using arrays in Java? Can you write a program to solve this problem? Well, it's very similar to the problem we have seen before, find the largest and smallest of 3 integers. You can use the same approach and generalize it for N numbers. All you need to do is start with largest as Integer.MIN_VALUE and smallest number as Integer.MAX_VALUE and loop through N numbers. At each iteration, compare the number with the largest and smallest number, if the current number is larger than largest than its a new largest and if the current number is smaller than smallest than its a new smallest number.

There is no direct way to take array input in Java using Scanner or any other utility, but it's pretty easy to achieve the same by using standard Scanner methods and asking some questions to the user. For example, if you want to take a one-dimensional array of String as input then you can first ask the user about the length of the array and then you can use a for loop to retrieve that many elements from user and store them in an array. You can use the next() to take a String input from the user. Similarly, if you need to take an integer array or double array, you can use nextInt() or nextDouble() method of Scanner class. Some programmer may still stuck and ask, how about taking a two-dimensional array as input? Well isn't that pretty easy by applying some maths?

Wednesday, 29 June 2016

If you are preparing for Programming Job interviews and looking for some of the best books for programming questions then you have come to the right place. In this article, I am going to share a couple of good books to prepare coding, software design, and data structure algorithm questions, which are essential for any coding interviews. Though a programming interview also explores other areas of software development e.g. the programming language you would be mainly using in your project e.g. C++ or Java. The database and SQL based questions, the operating systems and UNIX related questions, some of the software design and object oriented design pattern questions and much more, but coding based questions forms the core of programming interviews.

Monday, 27 June 2016

You often need to convert java.sql.Date to java.util.Date while interacting with databases from Java application. Since JDBC the Java API for database connectivity uses java.sql.Date to represent and most of the java code accepts java.util.Date, you have no choice but to convert SQL date to util date in Java. Though, there is some fundamental difference between them e.g. java.sql.Date only contains date part e.g. day, month, and year, it doesn't contain any time attributes, but java.util.Date contains both date and time attributes e.g. hour, minutes, seconds and milliseconds. So, when you convert a java.sql.Date to java.util.Date, the resultant java.util.Date instance has the time part as zero i.e 00:00:00 to reflect midnight.

Saturday, 25 June 2016

The telnet is one of the most useful networking commands, which is used to check if a server is listening on a particular port on the remote host, but it's a little bit tricky to use, especially, if you are not using it daily. Though I have used telnet before, but when I use it after a long time, I actually forget how to close the telnet terminal and how to get out of it. I tried every possible command I can think of which is used to close, cancel a command, or exit from VIM editor in UNIX, e.g. Ctrl + C, quit, exit, q! and even the escape character '^]', only to realize that nothing is working. I finally managed to come out from telnet command prompt after a bit of struggle, and trial and error but I was surprised how difficult it can be to use one of the top 10 networking commands in UNIX.

Friday, 24 June 2016

I use Eclipse IDE extensively to write Java programs for testing and example purpose, but when I copy those program in any text editors e.g. VIM, Notepad, TextPad or Edit plus, the indentation goes weird. I see a lot of white spaces which makes the program wider than expected. This happens because when you copy Java program from Eclipse to a text editor, tabs are converted to spaces and different editor has the different settings of tabs. UNIX text editors prefer tab is 8 spaces, Windows text editors, and IDEs e.g. Eclipse treat tabs as 4 spaces. If you are like many Java programmer who is more comfortable with space than tabs because they give a true sense of spacing, you can always change the Java editor settings to use space instead of tabs in Eclipse. In this article, I am going to share how to make Eclipse uses spaces instead of tabs for Java editor, which you use while writing Java programs.

Wednesday, 22 June 2016

It's quite common in day to day programming to join Strings e.g. if you have an array or List of String let's say {Sony, Apple, Google} and you want to join them by comma to produce another String "Sony, Apple, Google", there is not an easy way to do it in Java. You need to iterate through array or list and then use a StringBuilderto append a comma after each element and finally to remove the last comma because you don't want a comma after the last element. A JavaScript-like Array.join() method or join() method of Android's TextUtils class is what you need in this situation, but you won't find any of such method on String, StringBuffer, StringBuilder, Arrays, or Collections class until Java 8. Now, you have a class called StringJoiner which allows you to join multiple String by a delimiter.

Monday, 20 June 2016

Printing messages to the console is an integral part of development, testing and debugging a Java program. If you are working on a Server side application, where you can not see what's going on inside the server, your only visibility tool is a log file; without logs, you can not do any debugging or see what's going on inside your application. Though, Java has pretty handy System.out.println() methods to print something on console, which can also be routed to log file but not sufficient for a real-world Java application. If you are running a Java program in Linux or any UNIX based system, Log4j or SLF4j or any other logging framework offers a lot more features, flexibility, and improvement on message quality, which is not possible using the System.out.println() statement.

Sunday, 19 June 2016

There is no difference in installing Maven on Windows7, Windows 8, Windows 8.1 or Windows 10, you can follow the same steps to install Maven in any version Windows operating system. Installing Maven is very easy, just download the Apache Maven ZIP file from Apache Maven Project website (https://maven.apache.org/download.cgi). You can download the apache-maven-3.3.9-bin.zip for using Maven in your 64-bit Windows machine. Remember, Maven 3.3 requires JDK 1.7 or above to run, so make sure you already installed JDK 7 or JDK8. Once you download the binary distribution of Maven, half of the job is down. Now, you only need to extract the binary distribution and add the bin folder in PATH or add a couple of environment variable e.g. M2, M2_HOME into your Windows machine.

Friday, 17 June 2016

If you are like many Java developer who uses Maven and Eclipse to build Java project using M2Eclipse plugin, you might have seen this error before. I ran into it recently when I ran the Maven Install command for one of the Java projects, configured as Maen project, only to realize that Maven builds failed after throwing this error. The main reason for this error is that Maven is not able to find javac (the Java compiler) which is required to compile Java source file. If you remember, the javac command comes in the bin directory of JDK, hence, you need a JDK installation in your local machine to compile Java project. You also need to have that configured in Eclipse as Installed JRE. Most likely, you have only installed and set up JRE and not JDK, at least that was the reason it throws "No compiler is provided in this environment" in my machine.

Wednesday, 15 June 2016

Books are very important to learn something new and despite being in the electronic age, where books have lost some shine to internet and blogs, I still read and recommend them to get a complete and authoritative knowledge on any topic e.g. concurrent programming. In this article, I will share five best books to learn concurrent programming in Java. These books cover basics, starting from how to create and start a thread, parallel programming, concurrency design patterns, an advantage of concurrency and of course pitfalls, issues, and problems introduced due to multithreading. learning concurrent programming is a difficult task, not even in Java but also on other languages like C++ or modern days JVM languages like Groovy, Scala, Closure, and JRuby.

Monday, 13 June 2016

Since a primary key is nothing but a constraint you can use ALTER clause of SQL to add a primary key into existing table. Though it's an SQL and database best practice to always have a primary key in a table, many times you will find tables which don't have a primary key. Sometimes, this is due to lack of a column which is both NOT NULL and UNIQUE (constraint require to be a primary key) but other times purely due to lack of knowledge or lack of energy. If you don't have a column which can serve as primary key you can use identity columns for that purpose. Alternatively, you can also combine multiple columns to create a composite primary keys e.g. you can combine firstname and lastname to create a primary key name etc.

Saturday, 11 June 2016

Oracle launched "Java EE 6 Web Component Developer Certified Expert 1Z0-899 Exam" in 2011 to replace "Java Platform, Enterprise Edition 6 Java Server Pages and Servlet Developer Certified Expert Exam" and the "Oracle Certified Expert, Java Platform, Enterprise Edition 6 Java Server Pages and Servlet Developer" certification. They are equivalent of plain old SCWCD exam of Sun Microsystems era. Frankly speaking, I always found sun naming less confusing and clearer than Oracle's e.g. SCJP was much better than OCAJP and OCPJP. Though this exam is based on your knowledge of Servlet and JSP as per Java EE 6 specification, any book which covers this two technology e.g. "Head First Servlet and JSP" is highly recommended because Servlets and JSP are not changed much except Servlet 3.0 specification, which you can prepare separately. Oracle also provides training and preparation material and you can also take help from commercial mock exam providers like Whizlabs and Enthuware.