HTML

Difference between early (static) binding vs late (dynamic) binding in Java

In order to understand the difference between static and dynamic binding in Java, it's important to first learn what is binding? Binding means the link between reference and actual code e.g. when you refer a variable it's bonded to the code where it is defined, similarly when you call a method, it's linked to the code where a method is defined. There are two types of method binding in Java, static binding and dynamic binding. When a method is called in Java it's bonded to the actual code either at compile time or runtime, when the program is actually started and objects are created. As the name suggest, static binding is more of static nature hence it occurs at compile time i.e. your code knows which method to call once you compiled your Java source file into a class file. Since it happens early in program's life cycle it is also known as early binding in Java.

Java 8 - String.join() Example

I have been writing about new features of Java SE 8 since it's release in March 2014. Initially, my focus areas on much talked about lambda expressions and streams, but slowly I realize that Java 8 is not just about them. It has many more new features which will help Java developers in their day-to-day job as much lambdas and streams. One of them is the ability to join the String with any delimiter. It has added a class called StringJoiner in java.util package which we have seen earlier, but it has also added a new method on String class, the join() method, which finally allows you to join Strings in Java. You might have faced scenarios in past where you have a list of String or an array of String and you want to join them by a comma. Unfortunately, Java didn't have anything like Android's TextUtils.join() or JavaScript's Array.join() method which can join String on a delimiter.

How to fix "illegal start of expression" error in Java

The "illegal start of expression" error is a compile time error when the compiler finds an inappropriate statement in the code. The java compiler, javac, compiles your source code from top to bottom, left to right and when it sees something inappropriate at the start of an expression, it throws "illegal start of expression" error. The most common reason of this is a missing semi-colon. You might know that every statement in Java ends with a semicolon, but if you forget one, you won't get an error that there is a missing semi-colon at the end of statement because the compiler doesn't know the end. When compiler checks the next statement it sees illegal start because an earlier statement was not terminated. The bad part is that you can get tens of "illegal start of expression" error by just omitting a single semi-colon or missing braces, as shown in the following example.

Binary tree InOrder traversal in Java using Recursion

The InOrder traversal is one of the three popular ways to traverse a binary tree in Java, other two being preOrder and postOrder. During the inOrder traversal algorithm, left subtree is explored first, followed by root, and finally right subtree. You start traversal from root then goes to left node, then again goes to left node until you reach a leaf node. At that point of time, you print the value of the node or mark it visited and moved to right subtree. Continuing the same algorithm until all nodes of the binary tree are visited. The InOrder traversal is also known as left-node-right traversal or LNR traversal algorithm. Similar to the preOrder algorithm, it is also a depth-first algorithm because it explores the depth of binary tree before exploring siblings.   Since it is one of the fundamental binary tree algorithms it's quite popular in programming interviews. They are also the basis to learn more advanced binary tree algorithm, hence every programmer should learn, understand and know how to implement in-order and other traversal algorithms.

How to fix "class, interface, or enum expected" error in Java

If you have ever written Java programs using Notepad or inside DOS editor, then you know that how a single curly brace can blow your program and throw 100s of error during compilation. I was one of those lucky people who started their programming on DOS editor, the blue window editor which allow you to write Java program. I didn't know about PATH, CLASSPATH, JDK, JVM, or JRE at that point. It's our lab computer where everything is supposed to work as much our instructor wants. Since we don't have the internet at that point of time, we either wait for the instructor to come and rescue us and we surprise how he solve the error by just putting one curly brace and all errors mysteriously go away.  Today, I am going to tell you about one such error,  "class, interface, or enum expected".   This is another compile time error in Java which arises due to curly braces. Typically this error occurs when there is an additional curly brace at the end of the program.

How to read a text file as String in Java

There was no easy way to read a text file as String in Java until JDK 7, which released NIO 2. This API now provides a couple of utility methods which you can use to read entire file as String e.g. Files.readAllBytes() returns a byte array of the entire text file. You can convert that byte array to String to have a whole text file as String inside your Java program. If you need all lines of files as List of String e.g. into an ArrayList, you can use Files.readAllLines() method. This return a List of String, where each String represents a single line of the file. Prior to these API changes, I used to use the BufferedReader and StringBuilder to read the entire text file as String. You iterate through the file, reading one line at a time using readLine() method and appending them into a StringBuilder until you reach the end of the file. You can still use this method if you are running on Java SE 6 or lower version.

Difference between a class and an interface in Java

It is one of the frequently asked Java questions from beginners which struggles to get the concept behind an interface. The main difference between a class and an interface lies in their usage and capabilities. An interface is the purest form of abstraction available in Java where you just define the API or contract e.g. you define run() method on the Runnable interface without worrying about how something will run, that is left to the implementor which will use a class to define how exactly to run. So an interface gives you method name but how the behavior of that method is come from the class which implements it. That's your general difference between an interface and class in Java and applicable to all object oriented programming language, not just Java. Even though this question is not exactly the difference between abstract class and interface, it's somewhat related to it because an abstract class is nothing but a class with some abstract method. The points I have discussed there, also applicable here in terms of rules of Java programming related to class and interface.

Difference between HashMap vs IdentityHashMap in Java?

The IdentityHashMap is one of the lesser known Map implementation from JDK. Unlike general purposes Map implementations like HashMap and LinkedHashMap, it is very special and it's internal working is quite different than HashMap. The main difference between IdentityHashMap and HashMap in Java is that former uses equality operator (==) instead of equals() method to compare keys. Which means you need the same key object to retrieve the value from IdentityHashMap, you cannot retrieve values by using another key which is logically equal to previous key. Another important difference between HashMap and IdentityHashMap is that IdentityHashMap doesn't use hashCode() method instead it uses System.identityHashCode() method. This is a significant difference because now you can use mutable objects as key in Map whose hash code are likely to change when the mapping is stored inside IdentityHashMap.

How to read a text file in Java - BufferedReader Example

There are multiple ways to read a file in Java e.g. you can use a Scanner as we have seen in the last example, or you can use the BufferedReader class. The advantage of using a BufferedReader to read a text file is speed. It allows faster reading because of internal buffering provided by BufferedReader. Other Reader classes e.g. FileReader access the file or disk everytime you call the read() method but BufferedReader keeps 8KB worth of data in its internal buffer which you can read it without accessing file multiple times. It's loaded when you access the file first time for a subsequent read. The BufferedReader class is also a good example of Decorator design pattern because it decorates existing readers e.g. FileReader to provide buffering, remember, the reading from file functionality still comes from the FileReader class.

Java 8 StringJoiner Example - How to join multiple Strings

The Java 8 has added a new class StringJoiner to join Strings. The java.util.StringJoiner can be used to join any number of arbitrary String, a list of String, or an array of String in Java. You can choose any delimiter to join String e.g. command, pipe, colon or semi-colon. The StringJoiner class also allow you to specify a prefix and suffix while joining two or more String in Java. In order to join Strings, you first create an instance of StringJoiner class. While creating, you provide the delimiter, a String or character, which will be used between Strings while joining them e.g. you can pass comma as a delimiter to create a comma separated String or pipe to create a pipe delimited String. In this article, you will see some examples of StringJoiner to learn how to join String in Java 8.

10 Essential JVM Options for a Java Production System

This is a brief guide of important JVM options which you will often see with production Java systems. As a Java developer, you should know what these JVM options means and their importance. You will find that most of the JVM options are related to heap memory settings, garbage collection and to log some details e.g. heap dump, necessary for troubleshooting any issue e.g. memory leak or excessive memory consumption. It's ok if you don't know them yet but you should know them and that's the objective of this article. How do you find the JVM options your application is using? Well, you can see the startup scripts through which your application is started. Alternatively, if your application is running on Linux you can do ps -ef | grep java to find the Java process and see the JVM options printed as process arguments. If more than one Java process is running on the system then you may need to search with a keyword which is unique to your Java application.

How to replace an element of ArrayList in Java?

You can use the set() method of java.util.ArrayList class to replace an existing element of ArrayList in Java. The set(int index, E element) method takes two parameters, first is the index of an element you want to replace and second is the new value you want to insert. You can use this method as long as your ArrayList is not immutable e.g. not created using Collections.unmodifiableList(), in such case the set() method throws java.lang.UnsupportedOperationExcepiton. Though, you can also use the set() method with the List returned by Arrays.asList() method as oppose to add() and remove() which is not supported there. You just need to be careful with the index of elements. For example, if you want to replace the first element then you need to call set(0, newValue) because similar to an array, ArrayList index is also zero based.

Java 8 - Stream.filter() method Example

In the last couple of Java 8 tutorials, you have learned how to use map(), flatMap(), and other stream examples to get an understanding of how Java 8 makes it easy to perform the bulk data operation on Collection classes. In this example, I am going to share how to use the filter() method in Java 8, another key method of Stream class. The filter() method as it name suggests is used to perform filtering e.g. if you have a stream of numbers you can create another stream of even numbers by using the filter() method. Though, filter() method is little bit of counter intuitive i.e. in order to create a stream of even number you call filter( i -> i%2 == 0) which means you do filter(isEven()) but, you are actually filtering odd numbers to create a new stream of even numbers, but that's how it works. The key benefit of using filter() method is lazy evaluation i.e. no data comparison is performed unless you call a terminal operation on stream e.g. findFirst() or forEach(). The filter() method just set up some pointers when you first call them on stream and only performs real filtering when you call the terminal method.