Sunday, July 30, 2017

How to Load Resources from Classpath in Java with Example

Classpath in Java is not only used to load .class files, but also can be used to load resources e.g. properties file, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL. Suppose, you have a properties file inside config folder of your project, and you want to load that properties file, how do you do that? Similarly, you have icons and thumbnails for your web applications on icons directory of your project, how do you load them? The answer is by using java.lang.Class' getResource() and getResourceAsStream() method. These method accepts the path of resource as String and returns URL and InputStream respectively.

Saturday, July 29, 2017

How to sort a Map by keys in Java 8 - Example Tutorial

In the last article, I have shown you how to sort a Map by values in Java 8, and in this tutorial, you will learn how to sort a Map by keys lik a HashMap, ConcurrentHashMap, LinkedHashmap, or even Hashtable. Theoretically, you cannot sort a Map because it doesn't provide any ordering guarantee. For example, when you iterate over a HashMap, you don't know in which order entries will be traversed because HashMap doesn't provide any ordering. Then, how can you sort a Map which doesn't support order? Well, you can't and that's why you only sort entries of HashMap but you don't store the result back into HasMap or any other Map which doesn't support ordering. If you do so, then sorting will be lost.

Thursday, July 27, 2017

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

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.

Sunday, July 23, 2017

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 the first 100 lines then the rest of the lines will not be loaded into memory, which results in better performance. This is slightly different from 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.

How to Create Thread Pool in Java using Executor Framework - Example Tutorial

Java 1.5 introduced a Thread pool in Java in the form of an Executor framework, which allows Java programmers to decouple submission of a task to the execution of the task. If you are doing server-side programming in Java than the Thread pool is an important concept to maintain scalability, robustness, and stability of the system. For those, who are not familiar with thread pool in Java or concept of thread pool here is a one-liner, Thread pool in Java is a pool of worker threads, which is ready to perform any task given to them, mostly in the form of implementation of Runnable or Callable interface.

Saturday, July 22, 2017

Top 50 Java Programs from Coding Interviews

Coding is an integral part of any programming job interviews, and Java development interviews are no exception. I would even suggest you should never hire anyone without testing their coding skill, coding is also an art, and more often than a good code is an excellent developer as well. If you look at tech giants like Amazon, Facebook, and Google they thoroughly test the coding skill of any developer they hire, notably Amazon who first send online coding exercises to filter Java programmers who can code. This online test usually gives you requirements and ask you to write a program in a limited time, usually 2 to 3 hours. The application should meet the output provided by the exercise itself. These type of tasks are very tough to crack if you don't have excellent coding skill.

Friday, July 21, 2017

Difference between get and load in Hibernate

get vs load in Hibernate
Difference between get and load method in Hibernate is one of the most popular questions asked in Hibernate and spring interviews. Hibernate Session class provides two methods to access object e.g. session.get() and session.load() both looked quite similar to each other but there are subtle differences between load and get method which can affect the performance of the application. The main difference between get() vs load method is that get() involves database hit if an object doesn't exist in Session Cache and returns a fully initialized object which may involve several database calls while load method can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object.

Tuesday, July 11, 2017

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 the 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 the Microsoft Access database from Java using JDBC and JDBC ODBC bridge driver is not available in the classpath.

Sunday, July 9, 2017

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.

Saturday, July 8, 2017

OCAJP 8 FAQ - Oracle Certified Associate Java Programmer I Certification (1Z0–808) Frequently asked Questions

The Oracle Certifications is one of the most repeated, industry-recognized certifications. It also provides Java certifications like Oracle Certified Associate Java Programmer, also known as OCAJP and Oracle Certified Professional Java Programmer, also known as OCPJP. These two are most popular Java certification and there are many benefits of passing them e.g. better chance to get a Java development job, improved performance on Java interviews, better salary rise, and promotions, and better opportunity for moving abroad.

Sunday, July 2, 2017

Top 30 Linked List Algorithm Questions from Programming/Coding Interviews

The linked list is one of the most common and essential data structure and that's why you would frequently find linked list based coding questions on interviews. The range of questions can be from simple questions like finding the length of a linked list to very difficult e.g. merging two sorted linked lists. Nevertheless, the point is that you should be familiar with linked list data structure and must know how to perform basics task in the linked list e.g. adding or removing nodes from a linked list, traversing order linked list and implementing linked list in your choice of programming language e.g. Java, C++, C, or Python.

Saturday, July 1, 2017

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