OOPS Concept Tutorial in Java - Object Oriented Programming

I have written several OOP (Object Oriented Programming) concepts tutorials in past and I was thinking to bring them together so that anyone who wants to learn OOP basics can benefit from them easily. In this article, I will share you my collection of OOP tutorials and OOP concepts interview questions, which will not only help you to understand four pillars of Object Oriented programming e.g. Abstraction, Encapsulation, Inheritance, and Polymorphism but also powerful design techniques of Aggregation, Association and Composition, along with SOLID design principles, which are key to write flexible, extensible and object-oriented software. Java is also a great language to start with object oriented programming, though it's not a pure object oriented language but it is the best one we have got so far. You cannot write code outside Class, which standardize the code organization.

When to use PUT or POST in RESTful Web Service

One of the most common confusion among web developers is the choice of PUT or POST HTTP method for creating or updating a resource while developing RESTful Web Services. Since both can be used to submit data, you can use either POST or PUT to create or update a resource. Many web developers want to use PUT for creating a resource on the server because it's idempotent. No matter, how many times you call the PUT, the state of the resource will not jeopardize. Since the possibility of re-submission is real on a slow network, using PUT to create resource makes it easy, as you don't need to worry about user clicking the submit button multiple times. But, the key point to remember is that when you use PUT to create a resource, you need to provide the id e.g.

How to print all leaf nodes of binary tree in Java?

This is another interesting coding problem which is based on binary tree and like many other binary tree algorithms, you can use recursion to print all leaf nodes of a binary tree in Java. Since the tree is a recursive data structure, you can apply the same algorithm to the left and right subtree. A leaf node is the one whose left and right child nodes are null. So you can print all leaf nodes by traversing the tree, checking if the left and right nodes are null and then printing that leaf node. The logic is very much similar to post order traversal but instead of just printing node, we first check if both left and right children are null or not. It is also one of the frequently asked coding questions. Since the binary tree is an essential part of Data structures and algorithms, you can expect a couple of questions on binary trees and BST e.g. whether a given tree is binary search tree or not? This one is rather simple but it can be tricky if interviewer also asks you to solve this problem without recursion, as discussed here.

Map Reduce Example in Java 8

The map-reduce concept is one of the powerful concept in computer programming which utilizes the power of distributed and parallel processing to solve a big and heavy problems in quick time. From Java 8 onwards, Java also got this powerful feature from functional programming world. Many of the services provided by internet e.g. Google Search are based on the concept of the map and reduce. In  map reduce a job is usually split into the input data-set into independent chunks which are processed by the map tasks in a completely parallel manner. The framework sorts the outputs of the maps, which are then inputted to the reduce tasks. For example, suppose you want to calculate the average age of all the people in a town, instead of counting sequentially you can first calculate their age using the map and then calculate the average using reduce.

SQL - 5 Best Books to Learn and Master SQL and Database design

The SQL (Structured Query Language) is one of the most important skills of a programmer. I would rate this skill similar to UNIX if you are a professional programmer because it doesn't matter whether you are Java, C++, or a .NET developer, you are bound to write SQL queries. Since a database is an integral part of any modern Java or Web application, Interviewer always preferred candidates with good SQL skills. Now, the big question comes, how a programmer can learn SQL? Does just knowing how to query a table is enough? If you know insert, update, delete, and select then are you a competent SQL programmer? What about indexes, query plans, triggers, views, stored procedures and other advanced SQL concepts? What about writing complex queries involving joins, subqueries, derived tables etc? Well, all those are very important to be a competent full stack developer.

3 ways to solve Eclipse - main class not found error

Like many Java programmers who gets "Error: Could not find or load main class Main" while running Java program in Eclipse, I was also getting the same problem recently. The "Error: Could not find or load main class" was rendered me puzzled even after my 10+ years of experience with Java errors and exceptions. Whenever I run my Java application either by Run configurations or right click and run as Java program, I get an annoying popup complaining about "could not find or load the main class, the program will exit". I checked, the project was compiling fine, I can see the .class file for the main class in the bin directory of Eclipse, and I can even see the project and output folder added on the classpath of Run configuration, but still I am getting the "could not find main class, program will exit error".

10 Example of jQuery Selectors for Web Developers

I am primarily a Java developer but I have done a lot of work with Java web application including Servlet, JSP, and JavaScript on the client side. It was difficult for me to perform client side validation using JavaScript but ever since I come to know about jQuery, I simply love to do more validation and other stuff on the client side. The jQuery gives you immense power to do things with HTML pages and half of that power comes from its CSS-like selector engine, which allows you to select any element or group of elements from HTML page and then do things with them e.g. changes their style or behavior. For example, you can grab the divs and hide them, you can grab the buttons and make them clickable and so on. In order to learn jQuery, you need to learn its selector engine and in this tutorial, I am going to share you 10 good examples of different jQuery selectors e.g. ID selector to select single HTML element, the class selector to select group of an element and * wildcard to select all elements. Since jQuery supports many types of a selector, some of them I didn't even know, it's good to know as much as possible about them.

3 ways to count words in Java String

You can count words in Java String by using the split() method of String. A word is nothing but a non-space character in String, which is separated by one or multiple spaces. By using regular expression to find spaces and split on them will give you an array of all words in given String. This was the easy way to solve this problem as shown here, but if you have been asked to write a program to count a number of words in given String in Java without using any of String utility methods like String.split() or StringTokenizer then it's a little bit challenging for a beginner programmer. It's actually one of the common Java coding questions and I have seen it a couple of times with Java developer interviews of 2 to 4 years of experience. The interviewer put additional constraints like split() is not allowed, you can only use basic methods like charAt(), length(), and substring() along with loop, operators, and other basic programming tools.

Base64 Encoding and Decoding Example in Java 8 and before

Though, there are a couple of ways to Base64 encode a String in Java e.g. by using Java 6's javax.xml.bind.DatatypeConverter#printBase64Binary(byte[]) or by using Apache Commons Codec's Base64.encodeBase64(byte[) and Base64.decodeBase64(byte[])as shown here, or the infamous Sun's internal base64 encoder and decoder, sun.misc.BASE64Encoder().encode() and sun.misc.BASE64Decoder().decode(), there was no standard way in JDK API itself. That was one of the few missing item (another one is about joining string) which is addressed in Java 8. The JDK 8 API contains a Base64 class in java.util package which supports both encoding and decoding text in Base64. You can use Base64.Encoder to encode a byte array or String and Base64.Decoder to decode a base64 encoded byte array or String in Java 8.

How to compare two dates in Java? Examples

There are multiple ways to compare two dates in Java, it also depends on upon what exactly comparison means. If you are looking to compare two dates to find out whether they are equal or not, then you can simply use equals() method of java.util.Date class. This method will return true if both dates are equal, precisely both thave same millisecond value. If you are looking to find out whether a date comes before or after another date then you have 3 choices, you can use compareTo() method of java.util.Date class, or you can use before() and after() method of Date class, or you can use before() and after() method of Calendar class. I suggest leveraging before() and after() method of Date class, they are more readable and easy to use.

5 Difference between Iterator and ListIterator in Java?

The Iterator is the standard way to traverse a collection in Java. You can use Iterator to traverse a List, Set, Map, Stack, Queue or any Collection, but you might not know that there is another way to traverse over List in Java? Yes, it's called the ListIterator. There are many differences between Iterator and ListIterator in Java, but the most significant of them is that Iterator only allows you to traverse in one direction i.e. forward, you have just got a next() method to get the next element, there is no previous() method to get the previous element. On the other hand, ListIterator allows you to traverse the list in both directions i.e. forward and backward. It has got both next() and previous() method to access the next and previous element from List.

Top 5 Apache Maven Free Ebooks for Java Developers

If you are working in Java for a couple of years you surely know about Maven, the most popular tool to build Java application. Recently I had shared 10 Maven Plugins Java developer should know and I receive a lot of good feedback about how useful those plugins and Maven, in general, is for Java developers. This motivated me to write more stuff about Apache Maven and then I thought about sharing some of the free ebooks Java developers can use to learn Maven. Sonatype, the company behind Nexus open source repository manager and creators of Apache Maven project provides a couple of good free ebooks to learn Maven and Nexus repository. Unlike other free ebooks which are mostly outdated, these Maven free eBooks are most accurate, up-to-date and can be used as reference material, particularly Maven: The Complete Reference.

Difference between include() and forward() methods of RequestDispatcher in Servlert

What is the difference between include and forward methods of RequestDispatcher interface is one of the frequently asked Servlet questions from Java EE interviews and we'll see how you can answer this question on your interview. You get the RequestDispatcher reference either from ServletContext or ServletRequest interface and even though both include() and forward() method allow a Servlet to interact with another servlet, main difference between include() and forward is that include() method is used to load the contents of the specified resource (could be a Servlet, JSP, or static resource e.g. HTML files) directly into the Servlet's response, as if it is part of the calling Servlet. On the other hand, forward() method is used for server side redirection, where an HTTP request for one servlet is routed to another resource (Servlet, JSP file or HTML file) for processing.

Difference between IdentityHashMap, WeakHashMap and EnumMap in Java

Apart from popular implementation like HashMap and LinkedHashMap, java.util.Map also has some specialized implementation classes e.g. IdentifyHashMap which uses == instead of equals() method for comparing keys, WeakHashMap which uses WeakReference to wrap the key object and a key/value mapping is removed when the key is no longer referenced from elsewhere, and EnumMap where keys are Enum constants. Many Java developer doesn't know about these special Map implementation classes and failed to take advantage of improved performance and feature offered by them. Their knowledge is also important from core Java interview perspective because Java interviewer put a huge focus on JDK API, particularly Java Collection framework and Java Concurrency framework which includes concurrent collections classes.

How to get current TimeStamp value in Java

Do you know that Java developer Google for even simplest of things? Yes, that's true and I can say it because even I do that :-). The current timestamp value is one of them. In UNIX you can just use the date command to get the current date and time but how do you get that in your Java program? Well, you can get the current timestamp in Java by using Date and Timestamp class of JDK. Note, there is "s" instead of "S" in Timestamp. Since Date in Java contains both date and time, it can be used as Timestamp value as well but when you print Date, it shows time in the local timezone. If you need just the timestamp, then you need to convert the java.util.Date to java.sql.Timestamp. You can convert a Date to Timestamp by using the getTime() method which returns the number of millisecond from the Epoch.

InOrder traversal in binary tree without recursion in Java

This is the second part of implementing inorder traversal of a binary tree in Java, in the first part, I have shown you how to solve this problem using recursion and in this part, we'll implement inorder traversal algorithm without recursion. Now, some of you might argue, why use iteration if the recursive solution is so easy to implement? Well, that's true, but the iterative solution is often regarded better as they are not prone to StackOverFlowError. Another reason why we are discussing iterative solution here is because of technical interviews. If you to go to a programmer job interview, you will find that Interviewer will often ask you to solve the same problem using iteration and recursion e.g. Fibonacci series or String reversal algorithm. It's also good for your learning and developing algorithm skill, which is very important for becoming a better programmer.

Java 8 Stream.peek() Example to debug Stream

I have been writing about some important methods from Java SE 8  e.g. map(), flatMap() etc from quite some time and today I'll share my experience about another useful method peek() from java.utill.stream.Stream class. The peek() method of Stream class can be a very useful to debug and understand streams in Java 8. You can use the peek() method to see the elements as they flow from one step to another e.g. when you use the filter() method for filtering, you can actually see how filtering is working e.g. lazy evaluation as well as which elements are filtered. the peek() method returns a stream consisting of the elements of this stream and performs the action requested by the client. The peek() method expect a Consumer instance to perform a non-interfering action on the elements of this stream, usually printing them using forEach() method.

Difference between TCP and UDP in Java

What is the difference between TCP and UDP is a popular networking question from Java interviews? Though TCP or UDP is Java independent concept and very likely to be asked in other programming language interviews as well, many programmers not really understand them clearly. They sure have heard them because TCP and UDP are two of the most important transport protocol of internet, but when it comes to list down the difference between them, they fail to mention key differences in terms of ordering, guaranteed delivery, speed, and usage. In this article, I'll tell you the difference between TCP and UDP protocol from Java interview perspective.

What is instanceof operator in Java with example

The Java programming language and JVM are full of hidden gems and even though I am using Java for more than a decade I still get surprised of features which I didn't know for quite some time e.g. shutdown hook, covariant method overriding, and JVM option to refresh DNS cache.  The instanceof operator is also one of the rarely known features of Java, It is used to check if an object is the instance of a particular Class or not. It returns true if the object is an instance of the class, otherwise, returns false. You might have seen usages of instanceof operator in Java while overriding equals() method. Since for checking equality of two instances, the first step is to verify whether they are the instance of the same object or not, you can use the instanceof operator there.

3 ways to Copy a File From One Directory to Another in Java

Even though Java is considered one of the best feature-rich programming language, until Java 7, It didn't have any method to copy a file from one directory to another directory. It did have the java.io.File class, which provides a method to check if a file exists or not and methods for several other file operations but it lacks support for copying file from one folder to another. It was easy to write your own routine to copy a file using FileInputStream or FileChannel, most developers prefer to use Apache Commons IO library; which is not a bad idea at all. Even Joshua Bloch (author of several Java classes in JDK, including Java Collection Framework) advise using libraries instead of reinventing wheels in must read Effective Java book. The Apache Commons IO library provides a class called FileUtils, which contains several file utility methods including one for copying file from one directory to another.