Iterative Binary Tree PreOrder Traversal in Java - Without Recursion

This is the second article on binary tree pre-order traversal in Java. In the first part, I have shown you how to traverse a binary tree with pre-order traversal using recursion, and in this article, you will learn how to implement pre-order traversal without using recursion. Just to revise, pre-order is a depth-first algorithm, where the depth of the tree is first explored before traversing sibling. In preOrder traversal, first, node or root is visited, then left subtree, and right subtree, hence it is also known as NLR (Node-Left-Right) algorithm. You might know that when you use recursion, methods calls are stored in an internal Stack which unwinds itself when algorithm reaches the base case. When recursion is not allowed, you can use the Stack data structure to create the same effect, in fact, this is also a common technique to convert a recursive algorithm into an iterative one.

Top 5 Object Oriented Design Interview Questions for Programmers, Software Engineers

Testing the design skill of a candidate is quite common on programming job interviews. Questions like, how do you design a vending machine or a traffic control system is very popular in object-oriented programming language interviews e.g. Java and C++. Designing a software System requires good experience and knowledge of tools of object-oriented design and analysis. You should not only be good at OOP fundamentals like Abstraction, Inheritance, Polymorphism, Encapsulation, Coupling, Cohesion, Association, Aggregation, or Composition but also on several important object-oriented design principles like SOLID Principles of Object Oriented Design. A good knowledge of when to use a class over an interface is also important for designing a maintainable software or Java application. Now, questions are how do you develop such skills? You need to practice and practice hard. This is why I am sharing some frequently asked object oriented design questions from Java programming interviews here.

How to sort array in descending order - Java Example

It's easy to sort an object array in decreasing or reverse order, just provide the Comparator with opposite order. You can even use Collections.reverseOrder() if you want to sort array in the decreasing order, which returns a reverse Comparator to sort objects in the order opposite of their natural ordering defined by the compareTo() method. Unfortunately, for a primitive array, there is no direct way to sort in descending order. The Arrays.sort() method which is used to sort a primitive array in Java doesn't accept a boolean to sort the primitive array in reverse order. You might have seen the error "no suitable method found for sort(int[],comparator<object>)" which occurs when programmers try to call the Arrays.sort() method by passing reverse Comparator defined by Collection.reverseOrder(). That will work fine with Integer array but will not work with an int array. The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place as shown here. This is also true for two-dimensional primitive arrays.

Common reasons of java.lang.ArrayIndexOutOfBoundsException in Java

The ArrayIndexOutOfBoundsException, also known as java.lang.ArrayIndexOutOfBoundsExcepiton is one of the most common errors in Java program. It occurs when Java program tries to access an invalid index e.g. an index which is not positive or greater than the length of an array. For example, if you have an array of String e.g. String[] name = {"abc"} then trying to access name[1] will give java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 error because index 1 is invalid here. Why? because index in Java array starts with zero rather than 1, hence in an array of just one element the only valid index is index zero.  This was one of the most common scenarios which cause several million of ArrayIndexOutOfBoundsException daily. Sometimes it just a plain programming error but sometimes if an array is populated outside and if there is an error on feed than also you get java.lang.ArrayIndexOutOfBoundsException in Java.

Top 5 OCPJP7 books for 1Z0-804 and 1Z0-805 Exam - Java SE 7 II Certification

You may know that from Java SE 7 onwards, you need to pass two exams to become a certified Java developer e.g. OCAJP and OCPJP. The first one is an associate level exam and it's rather easy to pass, but the second one OCPJP is a professional level exam and it's much harder than OCAJP. If you are giving the Oracle Java certification then you should know that you need to pass OCAJP before taking OCPJP exam. This is also the second part of an article about books to prepare Java SE 7 certifications. In the first part, I have shared best books for OCAJP7 and in this part, I am going to share best books for the OCPJP7 exam. You might know that there are two professional level exam, 1Z0-804, and 1Z0-805, the first one is known as OCPJP7 while the second one is known as an upgrade to Java SE 7 certification, which you can give to become certified Java SE 7 developer if you already passed SCJP 5 or OCJP 6 exam. The books recommended in this article is applicable to both OCJPJP7 (1Z0-804) and upgrade to Java SE 7 (1Z0-805) exams.

How to implement PreOrder traversal of Binary Tree in Java - Example Tutorial

The easiest way to implement the preOrder traversal of a binary tree in Java is by using recursion. The recursive solution is hardly 3 to 4 lines of code and exactly mimic the steps, but before that, let's revise some basics about a binary tree and preorder traversal. Unlike array and linked list which have just one way to traversed i.e. linearly, binary tree has several ways to traverse all nodes e.g. preorder, postorder and in order. But, tree traversal algorithms are mainly divided into two categories, the depth-first algorithms, and breadth-first algorithms. In depth-first, you go deeper into a tree before visiting the sibling node, for example, you go deep following left node before you come back and traverse the right node. On breadth-first traversal, you visit the tree on its breadth i.e. all nodes of one level is visited before you start with another level top to bottom. The PreOrder, InOrder, and PostOrder traversals are all examples of depth-first traversal algorithms.

How to join two ArrayList in Java - Example

You can use the addAll() method from java.util.Collection interface to join two ArrayLists in Java. Since ArrayList implements List interface which actually extends the Collection interface, this method is available to all List implementation including ArrayList e.g. Vector, LinkedList. The Collection.addAll(Collection src) method takes a collection and adds all elements from it to the collection which calls this method e.g. target.addAll(source). After this call, the target will have all elements from both source and target ArrayList, which is like joining two ArrayList in Java. The second ArrayList will remain as it is but the first ArrayList on which you have added elements will have more elements. Its size will be equal to the sum of the size of first and second ArrayList.

How to reverse a singly linked list in Java? Example

In this article, I'll show you how to reverse a singly linked list in Java without recursion. A singly linked list, also known as just linked list is a collection of nodes which can only be traversed in one direction e.g. forward. Each node in the linked list contains two things, a data and a pointer to next node in the list. In order to reverse the linked list, we need to iterate through the list and at each step we need to reverse the link e.g. after first iteration head will point to null and next element will point to head. At the end of traversal when you reach the tail of linked list, the tail will point to the second last element and it will become a new head because you can traverse through all elements from this node.

How to read a text file into ArrayList in Java

Prior to Java 7, reading a text file into an ArrayList involves lot of boiler plate coding, as you need to read the file line by line and insert each line into an ArrayList, but from Java 7 onward, you can use the utility method Files.readAllLines() to read all lines of a text file into a List. This method return a List of String which contains all lines of files. Later you can convert this List to ArrayList, LinkedList, or whatever list you want to. Btw, this the fourth article in the series of reading a text file in Java. In the earlier parts, you have learned how to read a file using Scanner and BufferedReader(1). Then, reading the whole file as String (2) and finally reading a text file into array (3). This program is not very different from those in terms of fundamentals. We are still going to use read() method for Java 6 solution and will read all text until this method return -1 which signals the end of file.

3 Best books to prepare OCAJP 7 (1Z0- 803) Exam - Java SE 7 Certification

Even though the latest OCAJP exam is OCAJP8, the OCAJP7 still the most popular one, at least from the email I receive, I can say that more readers ask for OCAJP7 recommendations and preparation tips than OCAJP8. I have always said the three golden rules of success in OCAJP exam is selecting a good book, writing programs, and doing mock exams e.g. Whizlabs or Enthuware practice tests. In this article, you will find some good OCAJP7 books to deal with the first part. For those, who are new to the structure of Java SE 7 certification, it's now divided into two parts, the OCAJP and OCPJP. The OCAJP stands for Oracle Certified Associate Java Programmer and it's an associate level exam. The OCPJP stands for Oracle Certified Professional Java Programmer and it's a professional level exam. The difference between them is both on exam topic and toughness. The OCPJP is tougher and advanced than OCAJP. Topics like JDBC and Concurrency are included only in OCPJP, you don't need to read them in order to clear the OCAJP exam.

What is the difference between byte and char in Java?

The byte and char are two numeric data types in Java and both can represent integral numbers in a range but there are very different from each other. The main difference between a byte and char data type is that byte is used to store raw binary data while other is used to store characters or text data. You can store character literal into a char variable e.g. char a = 'a'; A character literal is enclosed in single quotes. In terms of range, a byte variable can hold any value from -128 to 127 but a char variable can hold any value between 0 and 255. Another difference between byte and char in Java is that the size of the byte variable is 8 bit while the size of the char variable is 16 bit. One more difference between char and byte is that byte can represent negative values as well but char can only represent positive values as its range is from -128 to 127. In other words, a byte is a signed data type where the first byte represent the sign of number i.e. 0 for positive and 1 for a negative number, but char data type is unsigned. Let's see some more differences between byte and char in Java.

How to fix "variable might not have been initialized" error in Java

This error occurs when you are trying to use a local variable without initializing it. You won't get this error if you use a uninitialized class or instance variable because they are initialized with their default value e.g. Reference types are initialized with null and integer types are initialized with zero, but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.

How to find length/size of ArrayList in Java? Example

You can use the size() method of java.util.ArrayList to find the length or size of ArrayList in Java. The size() method returns an integer equal to a number of elements present in the array list. It's different than the length of the array which is backing the ArrayList, that is called the capacity of ArrayList. When you create an object of ArrayList in Java without specifying a capacity, it is created with a default capacity which is 10. Since ArrayList is a growable array, it automatically resizes when the size (number of elements in array list) grows beyond a threshold. Also, when an ArrayList is first created it is called empty ArrayList and size() will return zero. If you add elements then size grows one by one. You can also remove all elements from ArrayList by using a clear() method which will then again make the ArrayList empty as shown in our examples.

How to remove all elements of ArrayList in Java - Example

There are two ways to remove all elements of an ArrayList in Java, either by using clear() or  by using the removeAll() method. Both methods are defined in the java.util.List and java.util.Collection interface, hence they are available not just to ArrayList but also to Vector or LinkedList etc. Both elements removes all objects from ArrayList but there is a subtle difference in how they do. The clear() method is straightforward, it traverse through the ArrayList and sets all indices to null, which means the ArrayList becomes empty and all elements become eligible to Garbage collection, provided there is no more references to them. The time taken by clear() method is in O(n), which means the bigger the arraylist the longer it will take to empty it.