Binary tree post order traversal in Java with example

In last couple of articles, we have learned about pre-order and in-order tree traversal in Java and today, you will learn about the post order traversal in binary tree. The post order traversal is also a depth-first algorithm because you go deep before you visit other nodes in same level. In post order traversal, you first visit left subtree, then right subtree and finally you print the value of node or root. That's why the value of root is always printed last on post order traversal. Like many tree algorithms, the easiest way to implement post-order traversal is by using recursion. In fact, if you know how to write pre-order using recursion, you can use the same algorithm with bit of adjustment to implement post order traversal. All you need to do is instead of printing the value of node first, just call the recursive method with left subtree as shown in our example.

How to transpose a matrix in Java? Example Tutorial

Hello guys, continuing the tradition of this week, where I have mostly published articles about coding exercises for Java beginners, today also I am going to share an interesting coding problem, many of you have solved in your college or school days. Yes, it's about writing a Java program to transpose a matrix. In the last couple of tutorials, we have learned to how to add and subtract two matrices in Java (see here) and how to multiply two matrices in Java (see here). In this tutorial, I'll show you how to transpose a matrix in Java. The transpose of a matrix is a new matrix whose rows are the columns of the original. This means when you transpose a matrix the columns of the new matrix becomes the rows of the original matrix and vice-versa. In short, to transpose a matrix, just swap the rows and columns of the matrix. For example, if you have a matrix with 2 rows and 3 columns then transpose of that matrix will contain 3 rows and two columns.

How to Add and Subtract Two Matrices in Java

This is the second program in the series of matrices related programming exercises in Java. In the last program, you have learned matrix multiplication and in this program, you will learn how to perform addition and subtraction of two matrices in Java. We'll create methods to calculate both sum and difference of two matrices in Java program. In Mathematics, a matrix is a rectangular array with two dimensions known as rows and columns. In Java, your can use a two-dimensional array to represent a matrix because it also has two dimensions rows and columns. Since a 2D array is nothing but an array of the array in Java, the length of the outer array is equal to the number of rows and length of sub-array is equal to the number of columns.

How to compare String by their length in Java 7 and 8?

The natural way to compare String is the lexicographic way, which is implemented in the compareTo() method of String class, but sometimes you need to compare String by their length. You cannot use the default compareTo() method for that task, you need to write your own custom Comparator, which can compare String by length. Don't worry, It's easy to compare multiple String by their length, all you need to write is a Comparator which calculates their length using the length() method and compare them. Such comparator should return a positive value if first String has a length greater than second String, a negative value if the length of first String is less than the length of second String and zero if both String has the same length.

How to calculate sum and difference of two complex numbers in Java

From the last couple of articles, I am writing about coding exercises for beginners e.g. yesterday you learned how to write a program from matrix multiplication in Java (see here) and a couple of days back, you have learned recursive binary search algorithm. To continue that tradition today I am going to show you how to write a program for calculating sum and difference of two complex numbers in Java. If you remember the complex number from you maths classes, it has two part real and imaginary and to add a complex number we add their real and imaginary part separately, similar to subtract complex number we minus their real and imaginary part separately. For example, if first complex number is A + iB and the second complex number is X + iY then the addition of these two complex number will be equal to (A +X ) + i(B + Y).

How to Multiply Two Matrices in Java

I first learned about matrix in class 12th and I first wrote the program to multiply two matrices on my first semester of engineering, so, when I thought about this program, It brings a lot of memories from the past. It's actually a beginner exercise to develop coding logic, much like Fibonacci, prime, and palindrome check, but what make this program interesting is the use of the two-dimensional array to represent a matrix in Java.  Since matrix has both rows and columns, two-dimensional array just naturally fits into the requirement. Another important thing to solve this problem is to remember the rule of matrix multiplication in mathematics. If you don't remember the rule, just forget about how to solve this problem, unless you have access to Google. So, first, we'll refresh the rules of multiplication and then we'll look into coding aspect.

java.lang.OutOfMemoryError: unable to create new native thread - Cause and Solution

There are several types of OutOfMemoryError in Java e.g. OutOfMemoryError related to Java heap space and permgen space, and a new one coming in Java 8, Java.lang.OutOfMemoryError: MetaSpace. Each and every OutOfMemoryError has their own unique reason and corresponding unique solution. For example, java.langOutOfMemoryError: Java Heap Space comes when the application has exhausted all heap memory and tries to create an object which requires further memory allocation, that time JVM throws this error to tell the application that it's not possible to create any object. Similarly java.lang.OutOfMemoryError: PermGen Space comes when there is no more memory in permgen space and application tries to load more classes (as class metadata is stored in this area) or tries to create new String (because prior to Java 7 String pool has also existed on permgen space).

5 Difference between StringBuffer, StringBuilder and String in Java

Though all three classes StringBuffer, StringBuilder and String are used for representing text data in Java there are some significant differences between them. One of the most notable differences between StringBuilder, StringBuffer, and String in Java is that both StringBuffer and StrinBuilder are Mutable class but String is Immutable in Java. What this means is, you can add, remove or replace characters from StringBuffer and StringBuilder object but any change on String object e.g. converting uppercase to lowercase or appending a new character using String concatenation will always result in a new String object. Another key difference between them is that both StringBuffer and String are thread-safe but StringBuilder is not thread-safe in Java. String achieves its thread-safety from Immutability but StringBuffer achieves it via synchronization, which is also the main difference between the StringBuffer and StringBuilder in Java.

Binary Search using Recursion in Java

In the last article, we have seen the iterative implementation of binary search in Java and in this article, you will learn how to implement binary search using recursion. In order to implement a recursive solution, you need a base case because without a base case your program will never terminate and it will eventually die by throwing StackOverFlowError . In the case of recursive binary search implementation, we calculate middle position by taking start and end position and check if the target element is equal to the middle element or not. If target, the number of element you are searching in an array is equal then our search is complete, but if the target is greater than middle we look on second half of array and if the target is less than middle element then we look into the first half of array. This is possible because in the case of binary search the array is always sorted, if it's not, you must sort the array before conducting a binary search.

How to solve java.sql.BatchUpdateException: String or binary data would be truncated.

Recently I was working in Java application which uses Microsoft SQL Server at its backend. The architecture of Java application was old i.e. even though there was heavy database communication back and forth there was no ORM used e.g. no Hibernate, JPA, or Apache iBatis. The Java application was using old DAO design pattern, where the DB related classes which are responsible for loading and storing data from database was calling stored procedure to do their Job. These stored procedure takes data from Java application and insert into SQL Server tables. One day, one of my collegue called me to troubleshoot "java.sql.BatchUpdateException: String or binary data would be truncated", which it's application was throwing and he has no clue whatsoever that what is wrong with the data he is getting from other system and trying to store.

How to calculate average of all numbers of array in Java

In the last article, I teach you how to calculate the sum of all numbers in a given array and in this article, we'll go one more step. This time, you need to write a program to calculate the average of all numbers from a given array, for example, you will be passed salaries of Java developers in different states in the USA and you need to calculate the average salary of Java developer in the USA. The example of average salaries of Java developer is more interesting because everybody wants to know how much Java developers make, isn't it? Anyway, coming back to the requirement of the program, The array will contain integers, which can be both positive and negative, so you must handle them. Your program should also be robust e.g. it should not break if you pass empty array or null. In these case either you can throw IllegalArgumentException  as returning any other number will be ambiguous.

How to calculate sum of array elements in Java

In today's coding problem, we'll see how to write a program to calculate the sum of array elements in Java. You need to write a method which will accept an integer array and it should return total sum of all the elements. The array could contain both positive and negative numbers but only decimal numbers are allowed. The array can also be null or empty so make sure your solution handle those as well. In the case of a null or empty array, your program can throw IllegalArgumentException. The empty array means, an array whose length is zero or there is no element inside it. Well, that's enough for the requirement of this simple coding problem. The solution is really simple, just loop through the array and keep adding elements into sum until you process all the elements.

10 Reasons of java.lang.NumberFormatException in Java - Solution

The NumberFormatException is one of the most common errors in Java application along with NullPointerException. This error comes when you try to convert a String into numeric data types e.g. int, float, double, long, short, char or byte. The data type conversion methods like Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), and Long.parseLong() throws NumberFormatException to signal that input String is not valid numeric value. Even though the root cause is always something which cannot be converted into a number, there are many reasons and input due to which NumberFormatException occurs in Java application. Most of the time I have faced this error while converting a String to int or Integer in Java, but there are other scenarios as well when this error occurs. In this article, I am sharing 10 of the most common reasons of java.lang.NumberFormatException in Java programs.

How to implement Linear Search in Java? Example tutorial

In the last article about searching and sorting, we have learned binary search algorithm and today I'll teach you another fundamental searching algorithm called Linear search. Linear search is nothing but iterating over the array and comparing each element with target element to see if they are equal since we search the array sequential from start to end, this is also known as sequential search or linear search. It is very slow as compared to binary search because you have to compare each element with every other element and definitely not suitable for a large array. It's practically useful only in case of the small array up to 10 to 15 numbers. In the worst case, you need to check all elements to confirm if target element exists in an array or not.

How to calculate area of triangle in Java - Program

Writing a Java program to calculate the area of a triangle is one of the basic programming exercises to develop coding sense on beginner programmers. Like many mathematical conceptual programs e.g. square root, factorial, or prime number this also serves a good exercise for beginners. Now, if you remember in maths you might have seen two main ways to calculate the area of a triangle, using vertices and using base and height. In this program, I have created two methods to calculate the area of a triangle using both ways. In the first method area(Point a, Point b, Point c)  we expect coordinates of three vertices of triangle and then we calculate area of triangle using the formula (Ax(By -Cy) + Bx(Cy -Ay) + Cx(Ay - By))/2, while in second method, area(int base, int height) we expect value of base and height and then we calculate are of triangle using formula (base * height) / 2.

Top 5 Design Patterns Books for Java Developers

Design patterns is an important topic for object-oriented programmers e.g. Java and C++ developers. It becomes even more important as your experience grows because everybody starts expecting a lot more from you in terms of writing quality code. I often receive emails from intermediate and senior Java developers about progressing to next level e.g. how to become Tech Lead, Team Lead or a software architect, knowledge of design pattern plays an important role in taking more technical responsibility. While the GoF book is the bible for object-oriented design patterns, in my opinion, it is a bit too dry and academic. Many of you might have already read it but I doubt you have enjoyed it a lot. The first real book I read on design pattern was the head first book. It's full of interesting stories, cartoons, UML diagrams, fireside chats to analyze the pros and cons of each design pattern, fill in the blanks, exercise, and most importantly some non-trivial code examples. Another good thing is that it focuses on a good set of core patterns e.g. Decorator, Observer, Factory, Command, Strategy, and Facade patterns.

How to print leaf nodes of binary tree without recursion

In the last article, you have learned how to print all leaf nodes of a binary tree in Java by using recursion and in this article, we'll solve the same problem without using recursion. Why should we do this? Well, it's a common pattern on programming job interview to solve the same problem using recursion and iteration. Since some problems are easy to solve using recursion e.g. tree based problems, tower of Hanoi, or Fibonacci series but their non-recursive solution is comparatively difficult, interviewer test candidates against this shift in the algorithm. If you have attended your computer science classes and enjoyed there, then you know that we can use Stack to convert a recursive algorithm to an iterative one. I'll use the same technique to print all leaf nodes of a binary tree without recursion.

3 ways to convert String to JSON object in Java?

It's very common nowadays to receive JSON String from a Java web service instead of XML, but unfortunately, JDK doesn't yet support conversion between JSON String to JSON object. Keeping JSON as String always is not a good option because you cannot operate on it easily, you need to convert it into JSON object before you do anything else e.g. retrieve any field or set different values. Fortunately, there are many open source library which allows you to create JSON object from JSON formatted String e.g. Gson from Google, Jackson, and json-simple. In this tutorial, you will learn how to use these 3 main libraries to do this conversion with step by step examples.

Difference between Heap and Stack Memory in Java JVM

One of the many traits of a good programmer is how well he understands the fundamental and if you want to check the fundamentals of Java programmer than asking the difference between heap and stack memory is a good choice. Even though both are part of JVM and both consumers memory allocated to the Java process, there are many differences between them e.g. Heap memory is shared by all threads of Java application but Stack memory is local to each thread. Objects are created in heap memory but method frames are stored in Stack memory, and size of heap space is much bigger than the small size of Stack in Java. Even if you know this much information about heap and stack in Java, you are one of the better candidates, but let's see some more details to impress the interviewer.

How to parse String to LocalDate in Java 8? DateTimeFormatter Example

From Java 8 onward, you are no longer dependent on the buggy and bulky SimpleDateFormat class to parse and format date Strings into real Date object in Java e.g. java.util.Date. You can use the DateTimeFormatter class from java.time package for all your formatting and parsing need. You are also no longer required to use another buggy class java.util.Date if you are doing fresh development, but if you have to support legacy code then you can also easily convert LocalDate and LocalTime to java.util.Date or java.sql.Date. In this tutorial, we will learn about both parsing String to date in Java and formatting Date into String. Remember, parsing is equivalent to converting String to date and formatting means converting a Date to String in Java.

3 Ways to Reverse an Array in Java - Coding Interview Question

One of the common coding questions is, how do you reverse an array in Java? Well, there are multiple ways to solve this problem. You can reverse array by writing your own function, which loops through the array and swaps elements until the array is sorted. That's actually should you be your first approach on interviews. Later you can impress the interviewer by a couple of other tricks, which is specific to Java development world. For example, you can reverse an array by converting array to ArrayList and then use this code to reverse the ArrayList. You can also use Apache Commons ArrayUtils.reverse() method to reverse any array in Java. This method is overloaded to reverse byte, short, long, int, float, double and String array. You can use any of the method depending upon your array type.