Monday, 28 August 2017

Create Java String Using ” ” or Constructor?

In Java, a string can be created in two ways:

String x = "abc";
String y = new String("abc");

What is the difference between using the double quotes and using the constructor?

Friday, 25 August 2017

Java Program to convert String ArrayList to String Array

Converting String ArrayList into String array is very common programming task in Java. you often need to convert Array to Array List in Java  and vice-versa. In this Java program, we will How to convert String ArrayList to String array. This is also a common programming exercise which is asked too many Java programmers in various Java related courses. It’s also worth noting that ArrayList in Java is internally backed by array and Array in Java are objects much like String which is also an Object in Java. In this Java program, we first create an ArrayList which stores name of months as String e.g. Jan, Feb, and Mar. Later we use ArrayList  toArray() method to convert ArrayList into an array.

Thursday, 24 August 2017

5 Examples of substring() in Java

SubString in Java is a useful method from java.lang.String class, which is used to create smaller String from bigger ones. The way Substring works prior to Java 1.7 can create a subtle memory leak because both String and their substring shares same character array. Which means, if you have a big String of 200MB and created a substring of 2MB from that, that could prevent 200MB String from being garbage collected. I agree this doesn't look normal and indeed was a bug, but it was like that till Java 1.6 and it's various update. One reason, which I could think, why Java designer initially thought like that, maybe to save memory by sharing char array and to make, creating substring faster by just copying pointers, instead of data. Nevertheless, this was reported as bug and Oracle have fixed it, so no more substring memory leak issue in Java 7.

Wednesday, 23 August 2017

How to Convert Array to String in Java with Example

Array and String are very closely related, not with anything else but with popularity. Many times we need to convert an array to String or create an array from String, but unfortunately, there is no direct way of doing this in Java. Though you can convert an array to String by simply calling their toString() method, you will not get any meaningful value.  If you convert an integer array to String, you will get something like I@4fee225 due to the default implementation of toString() method from java.lang.Object class. First, I show the type of the array and content after @ is hash code value in hexadecimal. How valuable is that? This is not what I want to see, I was interested in contents rather than hashcode. Fortunately, Java provides a utility class called java.util.Arrays, which provides several utility methods for arrays in Java.

Tuesday, 22 August 2017

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

ConcurrentHashMap vs Hashtable vs Synchronized Map


Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is a significant difference between them, which arise from the fact that how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1 itself, which uses synchronized methods to achieve thread-safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. The only difference between Hashtable and Synchronized Map is that later is not a legacy and you can wrap any Map to create it's synchronized version by using Collections.synchronizedMap() method.

Monday, 21 August 2017

Default Methods in Interface, Multiple Inheritance and Diamond Problem in Java 8

Ever since Java 8 introduced default and static methods in JDK 8, it's become possible to define non-abstract methods in interfaces and since in Java one class can implement multiple interfaces and because there can be concrete methods in interfaces, the diamond problem surfaced again. What will happen if two interface has methods o the same name and a Java class inherit from it? Many Java programmer also asks me the question that, is Java 8 is also supporting multiple inheritances of classes, as it seems because interface with methods is similar to abstract class or in that any class. Well, it’s not.

Saturday, 19 August 2017

New Regex Features in Java 9

In this article I will focus on the regular expression features that are specific to Java 9 and were not available in earlier version of the JDK. There is not many, though.

Java 9 Regular Expression Module


The JDK in Java 9 is split up into modules. One could rightfully expect that there is a new module for the regular expression handling packages and classes. Actually there is none. The module java.base is the default module on which all other modules depend on by default and thus the classes of the exported packages are always available in Java applications. The regular expression package java.util.regex is exported by this module. This makes the development a bit simpler: there is no need to explicitly ‘require’ a module if we want to use regular expressions in our code. It seems that regular expressions are so essential to Java that it got included in the base module.

Thursday, 17 August 2017

Java 8 Optionals

While programming, we have all faced the most (in)famous NullPointerException. And I believe we all would agree that encountering NullPointerException is also a pain. Just to keep the readers informed, the famous computer scientist Tony Hoare introduced null references and he thinks this as A million-dollar mistake. We all know, it’s very easy to implement but it’s quite unpredictable as well. And that’s why developers need to be very cautious.

Wednesday, 16 August 2017

Java 8 Default Methods On Interface : What, Why and Example

Whenever someone talks about Java 8, the first thing he speaks about is lambda expression and How lambda expression will change the way you use Collections API today. In truth, lambda expression would not be that useful had language not been enhanced to support default methods on Java Interface. Also known as a virtual extension or defender methods, they allow you to declare a non-abstract method inside Java interface. Which means, finally you can add new methods without breaking all classes, which implements a certain interface. This opens a new path for enhancing and evolving existing Collection API to take advantage of lambda expressions. For example, now you can iterate over all elements of Collection in just one line, as opposed to four lines it requires you to do prior to Java 8.

Friday, 11 August 2017

How to create a thread-safe ConcurrentHashSet in Java 8?

Until JDK 8, there was no way to create a large, thread-safe, ConcurrentHashSet in Java. The java.util.concurrent package doesn't even have a class called ConcurrentHashSet, but from JDK 8 onwards, you can use newly added keySet(default value) and newKeySet() method to create a ConcurrentHashSet backed by ConcurrentHashMap. Unlike tactical solutions like using concurrent hash map with dummy value or using the set view of the map, where you cannot add new elements. The Set returned by keySet(defaultValue) and newKeySet() method of JDK 8 is a proper set, where you can also add new elements along with performing other set operations e.g. contains(), remove() etc. Though you need to be careful that these methods are only available in ConcurrentHashMap class and not in ConcurrentMap interface, so you need to use a ConcurrentHashMap variable to hold the reference, or you need to use type casting to cast a ConcurrentHashMap object stored in ConcurrentMAp variable.

Thursday, 10 August 2017

How to determine if a string has all unique characters in Java?

This is one of the common string based coding problem from programming job interviews. You need to write a program to determine if a given string has all unique characters or not. For example input= "Java" then your function should return false because all characters are not unique, and if the input is "Python" then your program should return true because all characters in Python are unique. For the purpose of this problem, you can assume the given String only contains ASCII printable characters, though you should always verify that with the interviewer. You can also assume that your solution needs to case-sensitive i.e. "P" and "p" will be considered two different characters and a string containing a letter in both capital and the small case will be considered unique. You are also free to solve the problem in place of using any additional data structure.

Tuesday, 8 August 2017

Process Handling in Java 9

Managing operating system processes in Java was a daunting task all times. The reason for that is the poor tooling and poor API that are available. To be honest that is not without reason: Java was not meant for the purpose. If you wanted to manage OS processes, you had the shell, perl script whatever you wanted. For larger applications that faced tasks that are more complex, you were supposed to program the issue in C or C++.

Friday, 4 August 2017

5 ways to redirect a web page using JavaScript and jQuery

When an HTTP request for one page automatically goes to another page then it is called a redirection. The redirection of a web page is used for different reasons e.g. redirecting to a different domain e.g. when you move your website from one URL to another URL or redirecting to a more recent version of a page you are looking at it. There are many ways to redirect a web page and different web technologies provide different ways e.g. Java provides sendRedirect() and forward() method for redirection. The redirection can also be divided into two categories, client side and server side. In client side, redirection client is responsible for routing request to another URL but in server side redirection, its server's job to redirect to a new page.

Thursday, 3 August 2017

HashSet vs TreeSet in Java? Similarities and Differences

HashSet and TreeSet both implement same interface i.e  java.util.Set interface and they possess the quality of Set interface means duplicate elements are not allowed. Both HashSet and TreeSet are used for to store unique elements, but HashSet doesn't care about any order and TreeSet keeps a thing in order. Ordering or sorting on TreeSet can be customized by using Comparator interface, by default TreeSet uses elements natural order for sorting, which is defined by compareTo() method of java.lang.Comparable interface. What is the difference between HashSet and TreeSet is is also one the frequently asked Java interview question, So you should know about similarities and difference between them? It also helps you to understand when to use both TreeSet and HashSet and what are the scenario when we should use this sets. Let's go through the similarities and difference between HashSet and TreeSet in Java.

Wednesday, 2 August 2017

Difference between String literal and New String object in Java

String is a special class in Java API and has so many special behaviours which is not obvious to many programmers. In order to master Java, first step is to master String class, and one way to explore is checking what kind of String related questions are asked on Java interviews. Apart from usual questions like why String is final, or  equals vs == operator, one of the most frequently asked question is what is difference between String literal and String object in Java. For example, what is the difference between String object created in following two expression :

Tuesday, 1 August 2017

How to Escape JSON String in Java- Eclipse IDE Tips

While working or JSON parsing in Java application it's quite common to just copy paste a JSON String from some resources e.g. a RESTful web service and then use the Jackson library to parse the JSON. This is the quickest way to test and learn parsing JSON string in Java, but the main problem with this approach is that the JSON String also includes double quotes "" which is also used for enclosing String literals in Java. Since JSON String itself contains double quotes, when you just copy paste them in your IDE or Java source file, the didn't work as expected. If you remember, if your String contains double quotes then those need to be escaped when you are pasting them as String literals in your Java code.