Monday, 20 November 2017

What is array data structure in Java? Properties, Example and Tutorial

Without any doubt, an array is one of the most used data structure in all programming language, including Java. Pick up any programming language be it functional, object-oriented, imperative or even scripting languages like Python, Bash, and Perl, you will always find array. That's why it's important for any programmer to have a good understanding of  array data structure. The array is used to store elements in the contiguous memory location and many C, C++ programmer can take advantage of a pointer to work with an array. In Java, there are no pointers and arrays are also a little bit different. They are the object, they have length field which denotes how many elements array can store. Arrays are created in the special memory area called heap memory in JVM, which is also created when you start the JVM. What remains same is that you can access the array element in constant time using their index, this works almost similarly in both C, C++ and Java, they start with 0 and ends at length -1, but Java array has an extra caveat that arrays index access are subject to bound check in Java.

Friday, 17 November 2017

How to Compare Two Arrays in Java - String, Integer Array Example

Our task is to compare two arrays in Java and see if they are equal to each other or not. Of-course we can't compare an String array to an int array, which means two arrays are said to be equal if they are of same type, has same length, contains same elements and in same order. Now, you can write your own method for checking array equality or take advantage of Java's rich Collection API. Similar to what we have seen while printing array values in Java, java.util.Arrays class provides convenient methods for comparing array values. They take care of all four condition, I have mentioned above. In fact, Arrays class also provide deepEquals() method to compare two-dimensional array in Java. By the way it's not restricted to just two-dimensional and also valid for any multi-dimensional array.

Tuesday, 14 November 2017

2 Ways to Remove Numbers from Integer Array in Java?

I have showed you how to reverse an array in place in Java and now I have come back with another array based coding interview question. It's also one of the frequently asked coding questions, not as popular as the previous one but still has been asked lot of times. Let's see the problem statement first.

Problem: Given an array and a value, write a function to remove all instances of that value from the array in Java (in place) and return the new length, or simply print out the array before and after removing the number. The order of elements can be changed. It doesn't matter what you leave beyond the new length. For example, if the given array is {12, 122, 12, 13, 14, 23, 14}, and number to be removed is 12 then the result array should be {122, 13, 34, 23,14}, and the length of the new array is 5.

Monday, 13 November 2017

How to convert list to array in Java and vice-versa

There is no easy way to convert an array to list in Java, but you can easily convert a list into array by calling toArray() method, which List inherit from Collection interface. If you solely rely on core JDK, then only way to convert an array to list is looping over array and populating list one element at a time. But if you can use open source libraries like Google Guava or Apache Commons lang then there is many utility classes to convert list to array and vice-versa. If you are working on Java application, you will often need to convert between list and array. A list is nothing but a dynamic array which knows how to re-size itself when it gets full or get close to full. List uses load factor to decide when to re-size, default value of its is 0.75. When they re-size, list usually double their slots e.g. goes from 16 to 32 etc. You can find these nifty details in their implementation classes e.g. ArrayList is one of the popular list in Java which provides order and random access. BTW, if you want to truly master Java Collection framework, then you must read Java Generics and Collection book, written by Maurice Naftaline and one of the must read book to become expert on Java Collections framework.

Friday, 10 November 2017

How to declare and Initialize two dimensional Array in Java with Example

An array of more than one dimension is known as multi-dimensional array. Two of the most common examples of multi-dimensional arrays are two and three dimensional array, known as 2D and 3D array, anything above is rare. I have never seen 4 dimensional arrays, even 3D arrays are not that common. Now question comes, when do use multi-dimensional array? Any real life example? Well, 2D arrays are very common on platform games like Super Mario Bros to represent screen or terrain; 2D arrays can also be used to represent structures like spreadsheet, or to draw board games like Chess, which requires 8x8 board, Checkers and  Tic-Tac-Toe, which requires 3 rows and 3 columns. Another popular application of multi-dimensional arrays are in matrix manipulation. For example to represent a 3x3 matrix you need a two dimensional array of 3 one dimensional array each containing 3 elements.

Wednesday, 8 November 2017

4 Examples to Sort Array in Java

You can use Arrays.sort() method to sort both primitive and object array in Java. This method sorts given array into ascending order, which is the numeric order for primitives and defined by compareTo() or compare() method for objects. For primitive arrays e.g. int,  short, character, float, double or long this method uses  dual-pivot Quicksort sorting algorithm implemented by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch (author of Effective Java) . This algorithm offers O(n log(n)) performance on many data sets that cause other quicksort algorithms to degrade into their worst quadratic performance e.g. O(n^2) and is typically faster than traditional (one-pivot) Quicksort implementations. That's why I always said that prefer library method your own, you can get it right but the amount of exposure library method gets, you will never get for your implementations.

Monday, 6 November 2017

JDOM Example : Reading and Parsing XML with SAX parser in Java

XML parsing with JDOM parser


JDOM is an open source library which allow XML parsing and reading in Java program. JDOM is designed by using Java programming technique and customized for Java programmers, so that Java programmer with  very little knowledge of XML documents can use JDOM to read XML files. Unlike DOM Parser of Java API , which uses Factory design pattern to create instance of parser e.g DocumentBuilderFactory and DocumentBuilder, JDOM uses new() operator to create its parser instances. In fact JDOM is very easy to understand and most of the time its self explanatory. While trying this Java program to parse XML file, you can explore JDOM API. JDOM API also allows to use XPATH expression to query XML documents with package org.jdom2.xpath. In next section we will see complete code example of How to read an XML file using JDOM parser in Java program.

Friday, 3 November 2017

What is array data structure in Java? Properties, Example and Tutorial

Without any doubt, an array is one of the most used data structure in all programming language, including Java. Pick up any programming language be it functional, object-oriented, imperative or even scripting languages like Python, Bash, and Perl, you will always find array. That's why it's important for any programmer to have a good understanding of  array data structure. The array is used to store elements in the contiguous memory location and many C, C++ programmer can take advantage of a pointer to work with an array. In Java, there are no pointers and arrays are also a little bit different. They are the object, they have length field which denotes how many elements array can store. Arrays are created in the special memory area called heap memory in JVM, which is also created when you start the JVM. What remains same is that you can access the array element in constant time using their index, this works almost similarly in both C, C++ and Java, they start with 0 and ends at length -1, but Java array has an extra caveat that arrays index access are subject to bound check in Java.

Thursday, 2 November 2017

How to Search Element in Java Array with Example

Find an index of the object in Array


While programming in Java, many times we need to check if a String array contains a particular String or an int array contains a number or not. Though array is an object in Java but it does not provide any convenient method to perform these kinds of operation. Sometimes you even need an index of an item stored in Array, unfortunately, Java API does not provide any direct method. Thanks to open Source Apache Commons provides a utility class called ArrayUtils which allows you to check for an Item in Array, find its index in the array, find its lastIndex in Array and perform several other common operations. In fact, ArrayUtils has overloaded methods for different kind of Array e.g. String, int, float, double, Object etc, which makes this kind of programming task trivial. In this article, we will see an Apache commons example of How to use ArrayUtils class to search an item in Array and find its index.

Wednesday, 1 November 2017

6 Difference between include directive and include action in JSP

Difference between include directive and include action


Even though both include directive and include action allows you to include response of one JSP into another, they are quite different from each other e.g. include directive is processed at translation time and used to include the static resources e.g. HTML files, images and CSS etc, while the <jsp:include> action is processed at request time and used to include more dynamic resources e.g. JSP or Servlet. What is the difference between include directive and include action is also one of the most popular JSP interview questions, mostly asked either at telephonic round or first few round of Java web developer interviews? Let's see a couple of more difference between these two to answer this question in more detail. Btw, if you are new in JSP and just learning and preparing for interviews at the same time, then you should also look at Head First Servlet and JSP, one of the best books to learn and prepare for Servlet JSP interviews and certification at the same time.

Tuesday, 31 October 2017

4 ways to concatenate Strings in Java - Best Performance

When we think about String Concatenation in Java, what comes to our mind is the + operator, one of the easiest way to join two String, or a String and a numeric in Java. Since Java doesn't support operator overloading, it's pretty special for String to have behavior. But in truth, it is the worst way of concatenating String in Java. When you concatenate two String using + operator e.g. "" + 101, one of the popular ways to convert int to String, compiler internally translates that to StringBuilder append call, which results in the allocation of temporary objects. You can see the real difference in performance of our example program, in which we have concatenated 100,000 String using + operator. Anyway, this article is not just about + operator but also about other ways to concatenate multiple Strings. There are four ways to do this, apart from the + operator, we can use StringBuffer, StringBuilder, and concat() method from java.lang.String class for the same purpose.

Sunday, 29 October 2017

Right way to check if String is empty in Java

What do you most of us do while using String in Java? checking whether String is null or empty right? I am sure you know a couple of ways to test whether String is empty or not, but do you know the right way to do it? When we talk about Strings in Java, we can imagine them as arrays of characters, and they are, but in Java, they also object. An empty Java String is considered as the not null String that contains zero characters, meaning its length is 0. However, a Java String that might only contain the white-space character is not considered as empty, it is considered to contain one character and its length is equal to 1. One of the most popular way of checking whether String is empty or not is String class' isEmpty() method, this looks perfect right, it's readable and returns boolean if String is empty otherwise returns false, but the problem is you can not call this method without checking whether String is null or not. In another word, this is not null safe and it will throw NullPointerException if String is null.

Saturday, 28 October 2017

Right way to Compare String in Java

The String is a special class in Java, so is String comparison. When I say comparing String variables, it can be either to compare two String object to check if they are same, i.e. contains same characters or compare them alphabetically to check which comes first or second. In this article, we are going to talk about the right way of comparing String variables, but what is the wrong way? The wrong way is to compare String using == operator. It is one area in which almost every Java programmer  has made mistakes sometimes by comparing two String variable using == operator. Many Java developers are exposed to string comparison very early in their Java journey,  It's often required in their first few programming assignments e.g. write a program to print hello if the user enters "John".  When you first start with String in Java, you create an object using String literal syntax e.g. name = "John" and then compare using == operator, you will get the right answer, but if you take same String as user input, you will not get the correct answer.  Why? because equality operator compares references i.e. if two reference variable points to the same object in the heap then it returns true, otherwise, it returns false.

Friday, 27 October 2017

How to Convert Byte array to String in Java with Example

There are multiple ways to convert a byte array to String in Java but the most straightforward way is to use the String constructor which accepts a byte array i.e. new String(byte []) , but the key thing to remember is character encoding. Since bytes are binary data but String is character data, it's very important to know the original character encoding of the text from which byte array has created. If you use a different character encoding, you will not get the original String back. For example, if you have read that byte array from a file which was encoded in "ISO-8859-1" and you have not provided any character encoding while converting byte array to String using new String() constructor then it's not guaranteed that you will get the same text back? Why? because new String() by default uses platform's default encoding (e.g. Linux machine where your JVM is running), which could be different than "ISO-8859-1".

Thursday, 26 October 2017

Java 9 – First baby steps with Modules and jlink

In this article, I will use that environment to take few small steps with Java 9 – in particular with modules. Note:this story does not end well. I wanted to conclude with using jlink to create a stand alone runtime that contained both the required JDK modules and my own module – and demonstrate how small that runtime was. Unfortunately, the Link step failed for me. More news on that in a later article.

Wednesday, 25 October 2017

Can You Declare Constructor inside Servlet Class?

Yes, Servlet can have Constructor, it's perfectly legal but it's not the right way to initialize your Servlet. You should use the init() method provided by the Servlet interface to initialize the Servlet. If you remember, Servlet's are special in a sense that they are instantiated by the container and managed by the container. A servlet container like Tomcat creates a pool of multiple Servlets to serve multiple clients at the same time. They instantiate Servlet by calling the default no-argument constructor and suppose you have declared another constructor which takes a parameter e.g. HelloServlet(String name) than Java compiler will not add the default no-argument constructor and Servlet container will not able to initialize the Servlet. That's why it's important not to provide a constructor in Servlet, but if you do, make sure you also add a default constructor there for Servlet container.

Monday, 23 October 2017

Experimenting with Java9 HTTP Client and Process API in JShell

Here we are experimenting with Java9 HTTP/2 Client and Process API in JShell


HTTP/2 Client


The HTTP/2 Client is an incubator project in Java9. This means the API isn’t finalized, so has some scope for change in future versions. The most obvious changes from Java9 to Java10 will be moving it from the jdk.incubator.httpclient module to “http.client” module, plus associated package name changes. Its worth keeping this in mind when using the API.

Difference between first level and second level cache in Hibernate

The main difference between first level and second level cache in Hibernate is that the first level is maintained at the Session level and accessible only to the Session, while the second level cache is maintained at the SessionFactory level and available to all Sessions. This means, you can use the first level cache to store local data i.e. the data which is needed by the Session and you can use the second level cache to store global data i.e. something which can be shared across sessions. This is also one of the frequently asked Hibernate Interview questions and popular in both telephonic rounds as well as on face to face interview, in both fresher and experienced level interviews.

Tuesday, 17 October 2017

10 Points about Enum in Java

Apart from Class and Interface, Enumeration type or Enum is another popular type in Java programming language. Enum allows you to represent fixed number of things in a type-safe manner e.g. days of the week, days of the month, planets in solar system, buttons on remote control, keys on keyboard and suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to represent fixed number of things, known as enum int pattern and enum string pattern. Though they serve the purpose, they had some major drawbacks, one of them was type-safety i.e. you cannot restrict them to represent fixed number of values  e.g. an integer constant, which is representing days of the week can have value as 100, which is incorrect, given we have only 7 days in a week.

Monday, 16 October 2017

Oracle Java Variables

Variables


The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. These elements are examined next.

Friday, 13 October 2017

Best way to convert java.util.Date to java.time.LocalDate in Java 8 - Examples

There seem to be a couple of ways to convert a java.util.Date to java.time.LocalDate in Java 8, but which one is the best way? We'll figure it out in this article, but first, let's explore these different ways to convert a java.util.Date object to LocalDate in Java 8. Btw, even though both Date and LocalDate is used to represent dates in Java they are not quite same, they don't contain even similar information. For example, the old Date class contains both date and time components but LocalDate is a just date, it doesn't have any time part in it e.g. "05-10-2017".

Wednesday, 11 October 2017

2 Ways to Print Custom String Value of Java Enum

We all know that how powerful enumeration type in Java is, and one of the main strength of enum is that they can implement an interface, they can have an instance variable and you can also override any method inside enum instance. In Java programs, we often need to convert Enum to String type, sometimes just to print values in log file and other time for storing log into database.  By default, when you print an enum constant, it print its literal value e.g. if name of enum instance is RED, then it will print RED. This is also the value which is returned by name() method of java.lang.Enum class.

Tuesday, 10 October 2017

Java Program to print prime numbers from 1 to 100

In this article, I'll share you a simple problem about writing a Java program to print prime numbers up to a given number e.g. say prime numbers from 1 to 100. It's one of the most common coding exercises for programmers learning in Java, as it gives you an opportunity to learn more about essential operator in Java Programming. The key here is that you cannot use a library function which can simply your job, you need to devise the algorithm for checking prime number by yourself. One of the most popular algorithm for generating prime is Sieve of Eratosthenes, which we have discussed earlier, but in this post, we will take a simpler approach. We'll first write a function to check whether a number is prime or not and then we loop through first 100 numbers i.e. from 1 to 100 and print only those which passed the prime test. Btw, if you are looking for some serious programming coding question for the interview, then you can also take a look at Cracking the coding interview, which contains more than 150 coding question with solutions.

Monday, 9 October 2017

Counting Sort in Java - Example

The Counting sort algorithm, like Radix sort and bucket sort, is an integer based algorithm (i.e. the values of the input array are assumed to be integers). Hence counting sort is among the fastest sorting algorithms around, in theory. It is also one of the few linear sorting algorithm or O(n) sorting algorithm. It's quite common in Java interviews nowadays to ask, whether do you know any O(n) sorting algorithm or not. If you face this question in future, you can mention Radix sort, bucket sort, or counting sort algorithms.  How does counting sort algorithm works? Well, counting sort creates a bucket for each value and keep a counter in each bucket. Then each time a value is encountered in the input collection,  the appropriate counter is incremented.

Friday, 6 October 2017

5 Difference between an array and linked list in Java

The difference between an array and linked list is one of the frequently asked data structure and algorithm interview question and you might have seen it before on your telephonic or face-to-face interview. It is also very popular question during practical exams on Computer Science degree courses e.g. B.E. and B.Tech. It's very simple and easy to answer but you just can't afford to miss this question on an interview. Both array and linked list are two of the most popular and fundamental data structure in Computer Science and Programming, and Java supports both of them. One of the traits of a good programmer is extensive knowledge of data structure and algorithm and that's why it's very important for you to learn the difference between array and linked list data structure and understand when to use an array over linked list and vice-versa. Though this discussion is valid from C/C++ and other programming language perspective, I'll give you examples and explanation in Java.

Thursday, 5 October 2017

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.

Wednesday, 4 October 2017

Insertion Sort in Java with Example

Insertion sort is next simple sorting algorithm after Bubble Sort. You may not have realized but you must have used insertion sort in a lot of places in your life. One of the best examples of insertion sort is, how you sort your hand in playing cards. We pick one card from the deck, we assume it's sorted, and then we insert subsequent card in their proper position. For example, if our first card is Jack, and our next card Queen then we put that after Jack. Now if next card is King, we put it after the queen, and if we get 9, we put it before jack. So if you look closely, insertion sort is perfect sorting algorithm to insert a new value into the already sorted list. That's why best case complexity of insertion sort is O(n), in which case you insert a new number in the already sorted list of integers. Another thing to keep in mind is the size of the list, insertion sort is very good for small list or array, but not so for a large list, where QuickSort, MergeSort, and HeapSort rules.

Tuesday, 3 October 2017

How to swap two Integers without using temporary variable in Java?

One of the oldest trick question from programming interview is, How do you swap two integers without using temp variable? This was first asked to me on a C, C++ interview and then several times on various Java interviews. Beauty of this question lies both on trick to think about how you can swap two numbers with out third variable, but also problems associated with each approach. If a programmer can think about integer overflow and consider that in its solution then it creates a very good impression in the eye of interviewers. Ok, so let's come to the point, suppose you have tow integers i = 10 and j = 20, how will you swap them without using any variable so that j = 10 and i = 20? Though this is journal problem and solution work more or less in every other programming language, you need to do this using Java programming constructs. You can swap numbers by performing some mathematical operations e.g. addition and subtraction and multiplication and division, but they face problem of integer overflow.

Friday, 29 September 2017

How to convert primitive int value to a Long object in Java?

Suppose you have an int variable but the part of the application is expecting a Long object, how do you convert a primitive int to a Long object in Java? It shouldn't be a problem, right? after all long is a bigger data type than int, so all int values are acceptable as long, but we also need a Long object, not just the long primitive value. Now, the problem is reduced to converting a long primitive to Long object, which is not really a problem if you are running on JRE version higher than Java 5. But, sometimes autoboxing is not efficient e.g. when you have to convert multiple long values into the Long object in a loop. A better way to convert your long primitive to the Long object is by using static factory methods like Long.valueOf(long l), which was originally meant to convert long primitive values to a Long object, prior to Java 5, but, also works fine with int primitive.

Tuesday, 26 September 2017

How to Remove Duplicates from ArrayList in Java

ArrayList is the most popular implementation of List interface from Java's Collection framework, but it allows duplicates. Though there is another collection called Set which is primarily designed to store unique elements, there are situations when you receive a List e.g. ArrayList in your code and you need to ensure that it doesn't contain any duplicate before processing. Since with ArrayList you cannot guarantee uniqueness, there is no other choice but to remove repeated elements from ArrayList. There are multiple ways to do this, you can follow the approach we used for removing duplicates from array in Java, where we loop through array and inserting each element in a Set, which ensures that we discard duplicate because Set doesn't allow them to insert, or you can also use remove method of ArrayList to get rid of them, once you found that those are duplicates.

Difference between Correlated and Non-Correlated Subquery in SQL

The correlated subquery is one of the tricky concepts of SQL. It's similar to recursion in programming which many programmers struggle to understand, but like recursion, it also offers the unique capability to solve many SQL query based problems e.g. second highest salary problem where you need to compare one row of the table to another row. It gives you a different kind of power. The main difference between a regular, non-correlated and correlated subquery in SQL is in their working, a regular subquery just run once and return a value or a set of values which is used by outer query, but correlated subquery runs for each row returned by the outer query because the output of the whole query is based upon comparing the data returned by one row to the all other rows of the table. That's why it is also very slow and generally avoided until you don't know any other way to solve the problem.

Monday, 25 September 2017

What is Thread and Runnable in Java

What is Thread in Java


Thread in Java is an independent path of execution which is used to run two task in parallel. When two Threads run in parallel that is called multi-threading in Java. Java is multithreaded from the start and excellent support of Thread at language level e.g. java.lang.Thread class, synchronized keyword, volatile and final keyword makes writing concurrent programs easier in Java than any other programming language e.g. C++. Being multi-threaded is also a reason of Java's popularity and being number one programming language. On the other hand if your program divides a task between two threads it also brings lot of programming challenges and issues related to synchronization, deadlock, thread-safety and race conditions. In short answer of question What is Thread in Java can be given like "Thread is a class in Java but also a way to execute something in parallel independently in Java". Thread in Java requires a task which is executed by this thread independently and that task can be either Runnable or Callable which we will see in next section along with an example of  How to use multiple Thread in Java.

Thursday, 21 September 2017

Producer Consumer Solution using BlockingQueue in Java

Producer Consumer problem is one of the classic multi-threading problems in computer science and the multi-threading world. It's tricky because it involves inter-thread communication, but it's important because most of the multi-threading problems fits into this category. There are many ways to solve producer consumer problem in Java e.g. you can solve this by using wait() and notify() method, as discussed here, or you can use the Semaphore to solve this problem. In this article, you will learn a third way to solve the producer-consumer problem by using the BlockingQueue in Java. It is arguably the simplest way to solve this problem in any programming language because blocking queue data structure not only provides storage but also provides flow control and thread-safety, which makes the code really simple. Brian Goetz has also explained this key class and pattern in his classic Java Concurrency in Practice book, a must read for serious Java developers.

Tuesday, 19 September 2017

Java 9, Jigsaw, JPMS, and Modules: A Personal Exploration

Java 9 delayed so many times because of Project Jigsaw, and you may be heard a lot of thing about modules, modularity, and other stuff, so, what it’s all about? What the heck is modularization and what do we mean by modularized platform? Java Platform Module System (JPMS)? Is it going to be a revolution in Java ecosystem?

This post is my exploration of the most important thing that happened to the JDK, the Module System. I will explain what modularization is, why you need it, and how you can create your modularized project.

Monday, 18 September 2017

Java Application Performance Monitoring: End-to-end performance of complex distributed applications

Monitor Java application performance — focused on business transactions — end-to-end in the most complex and distributed environments. Auto-discovered business transactions, dynamic baselining, code-level diagnostics, and Virtual War Room collaboration ensure rapid issue identification and resolution to maintain an ideal user experience for any Java application, running on-premises or in cloud. Get real-time visibility into how your applications perform inside many of the industry-leading Java application servers, including Weblogic, WebSphere, JBoss, Tomcat, Glassfish and more.

Tuesday, 12 September 2017

How to find highest repeating word from a text File in Java - Word Count Problem

How to find the word and their count from a text file is another frequently asked coding question from Java interviews. The logic to solve this problem is similar to what we have seen in how to find duplicate words in a String. In the first step you need to build a word Map by reading contents of a text File. This Map should contain word as a key and their count as value. Once you have this Map ready, you can simply sort the Map based upon values. If you don't know how to sort a Map on values, see this tutorial first. It will teach you by sorting HashMap on values. Now getting key and value in sorted should be easy, but remember HashMap doesn't maintain order, so you need to use a List to keep the entry in sorted order. Once you got this list, you can simply loop over the list and print each key and value from the entry. This way, you can also create a table of words and their count in decreasing order.  This problem is sometimes also asked as to print all word and their count in tabular format.

Monday, 11 September 2017

How to enable/disable an element using jQuery and JavaScript?

Sometimes we need to enable and disable input elements e.g. text box, radio buttons or checkbox, how can we do it dynamically without loading the page? Well, we can use JavaScript, particularly jQuery to do this. An element can be disabled in HTML by setting disable property to true and enabled again by setting disabled=false. By using jQuery, we can grab the element we want to enable or disable and change this property by using prop() or attr() function, depending upon which version of jQuery you are using. prop() function was added in jQuery 1.6 and its the standard way to deal with properties but attr() function does the same job for jQuery 1.5 and lower version so you can use attr() for the same purpose in jQuery version lower than 1.6.

Friday, 8 September 2017

What does the InternalResourceViewResolver do in Spring MVC?

The InternalResourceViewResolver is an implementation of ViewResolver in Spring MVC framework which resolves logical view name e.g. "hello" to internal physical resources e.g. Servlet and JSP files e.g. jsp files placed under WEB-INF folder. It is a subclass of UrlBasedViewResolver, which uses "prefix" and "suffix" to convert a logical view name returned from Spring controller to map to actual, physical views. For example, if a user tries to access /home URL and HomeController returns "home" then DispatcherServlet will consult InternalResourceViewResolver and it will use prefix and suffix to find the actual physical view which is integral to a web application. For example, if prefix is "/WEB-INF/views/" and suffix is ".jsp" then "home" will be resolved to "/WEB-INF/home.jsp" by InternalResourceViewResolver.

What is Static and Dynamic binding in Java with Example

Static and dynamic binding  in Java are two important concept which Java programmer should be aware of. this is directly related to execution of code. If you have more than one method of same name (method overriding) or two variable of same name in same class hierarchy it gets tricky to find out which one is used during runtime as a result of there reference in code. This problem is resolved using static and dynamic binding in Java. For those who are not familiar with binding operation, its process used to link which method or variable to be called as result of there reference in code. Most of the references is resolved during compile time but some references which depends upon Object and polymorphism in Java is resolved during runtime when actual object is available. In this Java tutorial we will see some examples of static and dynamic binding and differences between static binding and dynamic binding in Java.

Thursday, 7 September 2017

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.

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.

Monday, 31 July 2017

Monitoring DataSources on Weblogic

As an Oracle SOA developer, I've often heard the phrase; 'BPEL doesn't work!'. Almost always the cause can be found in backend systems which do not function as expected. This error becomes visible when executing a service which uses a specific resource. When people start complaining about BPEL, usually this is an indication you should work on process feedback and error handling so the responsible party can quickly be identified. A trial and error mechanism is however often not what you want. A dashboard or script to monitor backend databases can help prevent such issues.

Saturday, 29 July 2017

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.

Friday, 28 July 2017

Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming

In Object-oriented programming, one object is related to other to use functionality and service provided by that object. This relationship between two objects is known as the association in  object oriented general software design and depicted by an arrow in Unified Modelling language or UML. Both Composition and Aggregation are the form of association between two objects, but there is a subtle difference between composition and aggregation, which is also reflected by their UML notation. We refer association between two objects as Composition, when one class owns other class and other class can not meaningfully exist, when it's owner destroyed, for example, Human class is a composition of several body parts including Hand, Leg and Heart. When human object dies, all it's body part ceased to exist meaningfully, this is one example of Composition.

Thursday, 27 July 2017

Difference between PriorityQueue and TreeSet in Java?

The PriorityQueue and TreeSet collection classes has a lot of similarities e.g. both provide O(log(N)) time complexity for adding, removing, and searching elements, both are non-synchronized and you can get element from both PriorityQueue and TreeSet in sorted order, but there is fundamental difference between them, TreeSet is a Set and doesn't allow a duplicate element, while PriorityQueue is a queue and doesn't have such restriction. It can contain multiple elements with equal values and in that case head of the queue will be arbitrarily chosen from them. Another key difference between TreeSet and PriorityQueue is iteration order, though you can access elements from the head in a sorted order e.g. head always give you lowest or highest priority element depending upon your Comparable or Comparator implementation but iterator returned by PriorityQueue doesn't provide any ordering guarantee.

Wednesday, 26 July 2017

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, 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.

Tuesday, 25 July 2017

Introducing Application Cache Client Java SDK for Oracle Cloud

The Oracle Application Container Cloud (ACCS)'s Application Cache provides (as the name implies) caching for applications! you simply specify the amount of memory you want to cache and whether you just need basic non-HA cache for dev/test or reliable caching for production and the appropriate infrastructure is automatically provisioned.

Monday, 24 July 2017

Arithmetic overflow error converting numeric to data type numeric in SQL Server

This error comes when you try to store an out-of-range floating point value into a numeric variable. For example, if your NUMERIC or DECIMAL variable is defined as NUMERIC(5,2) than the maximum value it can hold is 999.99, if you try to store something like 1000.00 then it will throw "Arithmetic overflow error converting numeric to data type numeric". One of the common reason of this error is the ignorance and misunderstanding of the NUMERIC data type. For example, many SQL Server DBAs and developers think that a NUMERIC(5,2) variable can hold a 7 digit floating point number where 5 digit is before decimal and 2 digits are after the decimal. This is wrong. A NUMERIC(5,2) means, the total number of digits in the value cannot exceed 5 and decimal precision is 2 digits i.e. the maximum possible value is 999.99.

Saturday, 22 July 2017

How to reload/refresh a page using JavaScript and jQuery

JavaScript provides several ways to reload or refresh an HTML page but the standard way to do this job is by using window.location object. This object provides a reload() method which instructs the browser to reload the page. The browser can do it from its cache or from the server, which depends upon optional parameter i.e. reload(true) will reload the page from the server but reload(false) will only reload the page from browser's cache, which may or may not represent the current version at the server.

Friday, 21 July 2017

Difference between Stack and Queue Data Structure in Java

Stack and Queue are two of important data structures in the programming world and have a variety of usage. As opposed to the array and linked list, which are considered as a primary data structure, they are a secondary data structure which can build using an array or linked list. You can use Stack to solve recursive problems and Queue can be used for ordered processing. The difference between Stack and Queue Data structure is also one of the common questions not only in Java interviews but also on C, C++, and other programming job interviews. Well, main difference comes the way these data structures are used, Stack is LIFO (last In First Out) data structure, which means the item which is inserted last is retrieved first, similar to a stack of plates in a dinner party, where every guest pick up the plate from the top of stack.

Thursday, 20 July 2017

Can you make an abstract class/method final in Java?

No, you cannot make an abstract class or method final in Java because abstract and final are the mutual exclusive concept. An abstract class is incomplete and can only be instantiated by extending a concrete class and implementing all abstract methods, while a final class is considered as complete and cannot be extended further. This means when you make an abstract class final, it cannot be extended hence it cannot be used and that's why Java compiler throws a compile time error when you try to make an abstract class final in Java. In short, an abstract class cannot be final in Java, using both abstract and final modifier with a class is illegal in Java.

Wednesday, 19 July 2017

How to count a number of words in given String in Java?

Can you write a method in Java which accepts a String argument and returns a number of words in it? A word is a sequence of one or more non-space character i.e. any character other than '' (empty String). This should be your method signature:

public int count(String word);

Monday, 17 July 2017

Instrumenting Java Web Applications without Modifying their Source Code

Most Java Web applications use standard Java interfaces when interacting with other systems. HTTP-based services like Web-pages or REST servers are implemented using the interface javax.servlet.Servlet. Database interaction is implemented using the JDBC interfaces java.sql.Statement and java.sql.Connection. These standards are almost universally in use, independent of the underlying framework (Spring or Java EE) and the Servlet container (Tomcat, Wildfly, etc.).

Saturday, 15 July 2017

3 Key difference between multi-threading and multitasking?

In the programming world, there are two main ways to improve the throughput of a program,  by using multi-threading and by using multitasking. Both take advantage of parallelism to efficiently utilize immense power of CPU and improve the throughput of your program. Actually, multi-threading is nothing but a thread based multi-tasking. Since the difference between multi-threading and multi-tasking is an important freshers programming interview question and also often ask in viva or oral exams on computer science graduation courses, I thought to jot down a couple of important points together. This article is the result of those points and can be handy when you quickly wants to know the key difference between multi-threading and multi-tasking in concurrent programming.

Friday, 14 July 2017

The real difference between Process and Thread in Java

One of the common question from programming interviews is, what is the difference between a Thread and a Process? Well, the main difference between them  is that a Process is a program which is executing some code and a thread is an independent path of execution in the process. A process can have more than one thread for doing independent task e.g. a thread for reading data from disk, a thread for processing that data and another thread for sending that data over the network. This technique to improve throughput and better utilize CPU power is also known as multi-threading. Technically, most significant difference between thread is address space and context switching. All thread from a process share same address space but a process has their own address space. Similarly, context switching between process is more expensive than context switching between threads.

Thursday, 13 July 2017

Why we use Threads in Java?

In one word, we use Threads to make Java application faster by doing multiple things at same time. In technical terms, Thread helps you to achieve parallelism in Java program. Since CPU is very fast and nowadays it even contains multiple cores, just one thread is not able to take advantage of all the cores, which means your costly hardware will remain idle for most of the time. By using multiple threads, you can take full advantage of multiple cores by serving more clients and serving them faster. Since, in today's fast-paced world, response time matters a lot and that's why you have multi-core CPUs, but if your application doesn't make full use of all resources then there is no point adding them, multi-threading is one way to exploiting huge computing power of CPU in Java application.

Wednesday, 12 July 2017

Difference between Inheritance and Composition in Java OOPS

Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Another difference which comes from this fact is that by using Composition you can reuse code for even final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition you can reuse code from many classes as they are declared as just a member variable, but with Inheritance you can reuse code form just one class because in Java you can only extend one class, because multiple Inheritance is not supported in Java. You can do this in C++ though because there one class can extend more than one class. BTW, You should always prefer Composition over Inheritance in Java, its not just me but even Joshua Bloch has suggested in his book Effective Java, which is a great resource to learn how to do things in right way in Java.

Tuesday, 11 July 2017

Testing Java EE 7 Applications in Docker with Arquillian-Cube

Arquillian is a powerful and flexible testing framework that allows you to test your applications or frameworks with your target application server. The tests that you write can run standalone (client mode) or inside the container (in-container mode). This capability allows you to run your tests in an environment that is closer to your production than is possible using unit tests and mocks alone.

Monday, 10 July 2017

How to Convert JSON array to String array in Java - GSon example

JSON array is an ordered collection of values, which are enclosed within brackets e.g. [] and separated by a comma. In this Java tutorial, we will convert JSON Array to String array in Java and subsequently create JSON from Java String Array, here we will convert JSON array to String array or List in Java. As I said earlier, there are lot's of open source library out there which can help to parse JSON data format and we have already seen Jackson library in our last example. In this tutorial, we will use GSON to parse JSON data format and create Java String array or List from JSON array representation. Given the popularity of JSON as a lightweight alternative to XML to transfer data from Server to client in web applications, it's becoming imperative to know about JSON data format and parsing JSON string, much like parsing XML documents and knowing about different XML parsers e.g. DOM or SAX.

Saturday, 8 July 2017

Difference between Abstraction and Encapsulation in Java - OOP

Both Abstraction and Encapsulation are two of the four basic OOP concepts which allow you to model real-world things into objects so that you can implement them in your program and code. Many beginners get confused between Abstraction and Encapsulation because they both look very similar. If you ask someone what is Abstraction, he will tell that it's an OOP concept which focuses on relevant information by hiding unnecessary detail, and when you ask about Encapsulation, many will tell that it's another OOP concept which hides data from outside world. The definitions are not wrong as both Abstraction and Encapsulation does hide something, but the key difference is on intent.

Friday, 7 July 2017

Can You Run Java Program Without Main Method?

First thing Java programmers learns is that they need a main method to run, but when they go to any Interview or college viva and asked can you run a Java program without a main method, they surprised like hell. Well, there are actually different types of execution model available in Java, for example, Applets which run on browser doesn't have main method, instead they have life-cycle methods like init(), start() and stop(), which controls their execution. Since Applet is a Java program, you can answer this question in Yes. Similarly, we have Servlet, which runs in a Servlet container, comes as bundled in a web server like Tomcat, or Jetty. Servlet also works on callback mechanism, it has methods like init(), service() and destroy(). Container calls init() if Servlet is first time loaded into memory, calls service() if there is a request to process and calls destroy() before removing it from memory.

Thursday, 6 July 2017

How to sort an ArrayList of Objects using Comparator in Java 8 - Ascending and Descending Order

There are a lot of examples of Sorting ArrayList in Java on the internet, but most of them use either String or Integer objects to explain sorting, which is not enough, because in real world you may have to sort a list of custom objects e.g. your domain or business objects like Employee, Book, Order, Trade etc. In order to sort an ArrayList of objects, you need two things, first a class to provider ordering and a method to provide sorting. If you know about ordering and sorting in Java then you know that Comparable and Comparator class is used to provide the ordering for objects. The Comparable interface provides natural order e.g. lexicographic order of String or name for Employees, while Comparator is used to provide custom order. It gives you the flexibility to sort your objects on the parameter you want e.g. you can sort a list of Coupon objects on the percentage discount, expiry dates, or based upon the total cost.

Wednesday, 5 July 2017

JSP - How to check if ArrayList is Empty using JSTL Example

There are multiple ways to check if an ArrayList is empty in JSP or not. For example, you can use the empty operator and the length function of JSTL to check if a list is empty or not. You can also use scriptlet, which allows you to insert Java code into JSP but that is not advisable because it makes it harder to maintain a JSP page. You can also write custom tag but that is not required because JSTL provides you necessary support. In this article, I'll show you two ways to check if a given list or ArrayList is empty or not in JSP page without using the scriptlet. You guessed it right, we will use JSTL, the Java standard tag library to solve this problem.

Tuesday, 4 July 2017

How to compare two lists of values in Microsoft Excel - Java

If you are working in real world application then you may frequently face scenarios where you have to compare data e.g. you get two lists of values and you want to know which values are common between two lists, which values only exists in the first list and which values only exists in the second list. If the list contains just 5 to 10 values you can do it easily with your eyes but what is fun if a programmer doing the task manually. You should be able to leverage all the tools available to you to do this comparison reliably. One of such ubiquitous and omnipresent tool is Microsoft Excel which is much more powerful then you can think of. It's like your brain, most of us just use 5% of Excel and a good knowledge of Excel's little bit advanced functionality e.g. VLOOKUP can be very helpful while comparing the list of values and reconciling data between different worksheet.

Monday, 3 July 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.

Sunday, 2 July 2017

How to Find Missing Number in a Sorted Array in Java

Today's coding problem is not very new, it's age old classic from programming interviews. You have a sorted array containing n - 1 unique numbers starting from 0 to n - 1. There is only one number missing in this range and you need to find that out. I mean you need to write a Java method to find the missing number and print it's value in the console. Some of you might have seen this question before, but if you have not been asked this question before, what is the first approach comes into your mind to solve this question?

Friday, 30 June 2017

Java Command-Line Interfaces (Part 1): Apache Commons CLI

Although I typically use Groovy to write JVM-hosted scripts to be run from the command-line, there are times when I need to parse command-line parameters in Java applications and there is a plethora of libraries available for Java developers to use to parse command-line parameters. In this post, I look at one of the best known of these Java command line parsing libraries: Apache Commons CLI.

Thursday, 29 June 2017

How to shoot yourself in the foot building a Java Agent

Over the years of building Plumbr, we have encountered many challenging problems. Among others, making the Plumbr Java Agent perform reliably without endangering the customers’ applications, is a particularly tricky one. To safely gather all the required telemetry from a live system poses a huge set of problems to tackle. Some of them are quite straightforward while some of them are fiendishly non-obvious.

Wednesday, 28 June 2017

Object-Oriented Declarative Input/Output in Cactoos

Cactoos is a library of object-oriented Java primitives we started to work on just a few weeks ago. The intent was to propose a clean and more declarative alternative to JDK, Guava, Apache Commons, and others. Instead of calling static procedures we want to use objects, the way they are supposed to be used. Let’s see how input/output works in a pure object-oriented fashion.
Let’s say you want to read a file. This is how you would do it with the static method readAllBytes() from the utility class Files in JDK7:

Tuesday, 27 June 2017

Use Precise Java Method Parameters

Learn how to pick the right method parameter types and get more robust and shorter code in your Java applications.

We Java developers generally have a bad habit of using method parameters without thinking of what is actually needed and just picking whatever we are used to, what we have available or whatever first comes into mind. Consider the following representative example:

Thursday, 22 June 2017

How to Convert JSON data from file to ArrayList?

In below example file student_data.txt having collections of students data in JSON form and through these Jacson API’s will convert JSON data to ArrayList java object.

Pre-Requisite 


Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

Wednesday, 21 June 2017

Java 8 New Features : Lambda Expressions, Optional Class, Defender Methods With Examples

Java 8 is already released by Oracle last year. It is the most feature rich update then the previous version 6 and 7 , which both were somehow minor updates .

The major features of the java 8 are as follows :
  1. Introduction of Optional
  2. Defender Methods
  3. Lambda Expressions

Tuesday, 20 June 2017

Threads, Lifecycle Explained With Example

What is Thread ?


Thread is a sequence of code executed independently with other threads of control with   in a single executed program .

for example : Here we are going to calculate the sum of next hundred numbers from the given input number by the user.

Monday, 19 June 2017

6 Difference between forward() and sendRedirect() in Servlet - Java

Servlet in JEE platform provides two methods forward() and sendRedirect() to route an HTTP request to another Servlet for processing. Though, both are used for forwarding HTTP requests for further processing there are many differences between forward() and sendRedirect() method e.g. forward is performed internally by Servlet, but a redirection is a two-step process, where Servlet instruct the web browser (client) to go and fetch another URL, which is different from the original. That's why forward() is also known as a server-side redirect and sendRedirect() is known as the client-side redirect. Becuase of their usefulness, the difference between forward() and sendRedirect is also a frequently asked Servlet interview question.

Thursday, 15 June 2017

How to unzip files from zip file by java?

In Java java.util.zip package provide below classes and api’s to convert files to zip file.

ZipInputStream: This class implements an input stream filter for reading files in the ZIP file format.

ZipEntry: Class is used for zip entry.

In below example will show to unzip files from a zip file  and store in folder

Wednesday, 14 June 2017

Elasticsearch REST Java Connection Client

For Elasticsearch connection, Elasticsearch REST Java API provide RestClient and RestClient.build() to get connection.

Below connection client class covers all the ways of connectivity to elastic search depend of elastic servers configuration and  accessibility accordingly you can uncomment below methods in customize Http Client.  I made this class as Singleton because Elasticsearch client keep connection persistent.

Tuesday, 13 June 2017

How to Convert JSON to Java Object and Java Object to JSON?

In below java codes consider both the cases from JSON to Java Object and Java Object to JSON by ObjectMapper by Jacson API’s

I have given generic method for both the cases as convertJavaObjectToJSON and convertJSONToJavaObject.

Pre-Requisite : Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

Saturday, 10 June 2017

How to enable Spring Security in Java Web application?

Spring Security is one of the most popular frameworks to implement security in Java web application in a declarative way. It provides several essential security features e.g. LDAP authentication, authorization, role-based access control,  remembers the password, URL protection, concurrent active sessions management etc. In order to enable Spring security in Java Web application, you need to do configure three things, declare a delegating proxy filter in web.xml, add the ContextLoaderListener in web.xml and provide actual security constraints on applicationContext-Security.xml file. Since Spring security uses a chain of filters to implement various security constraints, also known as Spring's "security chain filter", it relies on web container for the initialization of delegating filter proxy.

Thursday, 8 June 2017

Difference between Servlet and JSP?

Servlet and JSP are two of the most popular Java web technologies to generate dynamic content in Java web applications there is some key difference between them. For example, Servlet is designed for Java developers as most of the coding is done in Java, while JSP was designed and developed for web GUI developer e.g. guys who write HTML and JavaScript and that's why you see the coding in JSP is tag based. Even though you can use HTML tags as String inside Servlet and Java code as Scriptlet inside JSP, both are considered as bad practice and should be avoided at all cost because they are very hard to maintain. The different nature of Servlet and JSP also allows frontend and backend developers to work in parallel, JSP work is mostly done by frontend developers while Servlet work is done by backend developers.

Monday, 5 June 2017

CRUD Java Application with Couchbase, Java EE and WildFly

Couchbase is an open-source, NoSQL, document database. It allows to access, index, and query JSON documents while taking advantage of integrated distributed caching for high performance data access.

Developers can write applications to Couchbase using different languages (Java, Go, .NET, Node, PHP, Python, C) multiple SDKs. This blog will show how you can easily create a CRUD application using Java SDK for Couchbase.

Friday, 2 June 2017

Efficient Counter in Java

You may often need a counter to understand the frequency of something (e.g., words) from a database or text file. A counter can be easily implemented by using a HashMap in Java. This article compares different approaches to implement a counter. Finally, an efficient one will be concluded.

1. The Naive Counter


Naively, it can be implemented as the following:

String s = "one two three two three three";
String[] sArr = s.split(" ");

Thursday, 1 June 2017

What exactly is null in Java?

Let's start from the following statement:

String x = null;

1. What exactly does this statement do?


Recall what is a variable and what is a value. A common metaphor is that a variable is similar to a box. Just as you can use a box to store something, you can use a variable to store a value. When declaring a variable, we need to set its type.

Wednesday, 31 May 2017

Binary tree post order traversal in Java with example

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.

Unlike in-order traversal which prints all nodes of binary search tree in sorted order, post-order doesn't provide sorting but its useful while deleting nodes from binary tree, see a good book on data structure and algorithms e.g. Introduction to Algorithms by Thomas H. Cormen to learn more about different usage of post-order traversal in Computer Science and programming.

Monday, 29 May 2017

Java: Read Large XML by Using StAX

The following code shows how to read XML file in Java. It uses StAX API which reads xml files sequentially. If you want to read a large xml file, and get outofmemory error, you should be able to solve the problem by using the code below. The solution below read the xml file sequentially, and can process very large xml files, such as 10G or 20G. Therefore, it is a scalable solution!

Friday, 26 May 2017

java.util.ConcurrentModificationException

This post shows show to solve the problem of java.util.ConcurrentModificationException for ArrayList.

The error message looks like the following:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
...
...

Thursday, 25 May 2017

Constructors of Sub and Super Classes in Java?

This post summarizes a commonly asked question about Java constructors.

1. Why creating an object of the sub class invokes also the constructor of the super class?


class Super {
    String s;

    public Super(){
    System.out.println("Super");
    }
}

Thursday, 18 May 2017

Inheritance vs. Composition in Java

This article illustrates the concepts of inheritance vs. composition in Java. It first shows an example of inheritance, and then shows how to improve the inheritance design by using composition. How to choose between them is summarized at the end.
 

1. Inheritance


Let's suppose we have an Insect class. This class contains two methods: 1) move() and 2) attack().

Wednesday, 17 May 2017

JVM Statistics with jstat

I have written about several command-line tools provided with the Oracle and/or OpenJDK Java Development Kits (JDKs) in the past, but I’ve never written exclusively about the jstat tool. The Oracle JDK 9 Documentation Early Access states that jstat is used “to monitor Java Virtual Machine (JVM) statistics.” There is also a warning, “This command is experimental and unsupported.” Although I quoted the JDK 9 documentation, jstat has been a part of the Sun/Oracle JDK in some form (known at one time as jvmstat) in Java SE 8, Java SE 7, Java SE 6, and J2SE 5. Instrumentation for the HotSpot JVM was introduced with Java 1.4.1 (only enabled when -XX:+UsePerfData was set) and has provided “always-on instrumentation” since Java 1.4.2.

Tuesday, 16 May 2017

The Introduction of Java Memory Leaks

One of the most significant advantages of Java is its memory management. You simply create objects and Java Garbage Collector takes care of allocating and freeing memory. However, the situation is not as simple as that, because memory leaks frequently occur in Java applications.

Monday, 15 May 2017

The substring() Method in JDK 6 and JDK 7

The substring(int beginIndex, int endIndex) method in JDK 6 and JDK 7 are different. Knowing the difference can help you better use them. For simplicity reasons, in the following substring() represent the substring(int beginIndex, int endIndex) method.

Thursday, 11 May 2017

Introduction to JDBC

Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. JDBC can also be defined as the platform-independent interface between a relational database and Java programming. It allows java program to execute SQL statement and retrieve result from database.

JVM Architecture in Java

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

JVM Architecture , Java Tutorials

Wednesday, 10 May 2017

Java OOPs Concepts

In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming paradigm where everything is represented as an object, is known as truly object-oriented programming language.

Smalltalk is considered as the first truly object-oriented programming language.

Thursday, 4 May 2017

JDBC from the Oracle Service Bus

There are different ways to do database calls from the Oracle Service Bus. In this blog post I look at several methods.

The methods looked at;
1 using an external webservice (without OSB)
2 using an external webservice proxied by the OSB
3 using the fn-bea:execute-sql function from the OSB
4 using the JCA DbAdapter from the OSB provided by Oracle as part of Oracle SOA Suite

Oracle Java, JDBC, Oracle Java Tutorials and Materials, Oracle Java Guide

Monday, 1 May 2017

Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Sunday, 30 April 2017

Java Force Garbage Collection – Code Example

Garbage collection in java can not be enforced. But still sometimes, we call the System.gc( ) method explicitly. System.gc() method provides just a "hint" to the JVM that garbage collection should run. It is not guaranteed!

The API documentation for System.gc() states that "When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects." The responsibility for a programmer is to make sure no references remain for objects.

Friday, 28 April 2017

What Is Inner Interface in Java?

What is Inner Interface in Java?


Inner interface is also called nested interface, which means declare an interface inside of another interface. For example, the Entry interface is declared in the Map interface.

public interface Map {
interface Entry{
int getKey();
}

void clear();
}

Monday, 24 April 2017

When and how a Java class is loaded and initialized?

In Java, you first write a .java file which is then compiled to .class file during compile time. Java is capable of loading classes at run time. The confusion is what is the difference between "load" and "initialize". When and how is a Java class loaded and initialized? It can be clearly illustrated by using a simple example below.

What does it mean by saying "load a class"?


C/C++ is compiled to native machine code first and then it requires a linking step after compilation. What the linking does is combining source files from different places and form an executable program. Java does not do that. The linking-like step for Java is done when they are loaded into JVM.

Wednesday, 19 April 2017

How does Java handle aliasing?

What is Java aliasing?


Aliasing means there are multiple aliases to a location that can be updated, and these aliases have different types.

In the following example, a and b are two variable names that have two different types A and B. B extends A.

B[] b = new B[10];
A[] a = b;

Friday, 14 April 2017

Java Thread: notify() and wait() examples

This post contains two code examples to demonstrate Java concurrency. They stand for very typical usage. By understanding them, you will have a better understanding about notify() and wait().

1. Some background knowledge

  1. synchronized keyword is used for exclusive accessing.
  2. To make a method synchronized, simply add the synchronized keyword to its declaration. Then no two invocations of synchronized methods on the same object can interleave with each other.
  3. Synchronized statements must specify the object that provides the intrinsic lock. When synchronized(this) is used, you have to avoid to synchronizing invocations of other objects' methods.

Thursday, 13 April 2017

So Java passes object by reference or by value?

This is a classic interview question which confuses novice Java developers. In this post I will use an example and some diagram to demonstrate that: Java is pass-by-value.

1. Some Definitions


Pass by value: make a copy in memory of the actual parameter's value that is passed in.
Pass by reference: pass a copy of the address of the actual parameter.

Wednesday, 12 April 2017

How Static Type Checking Works in Java?

Java uses static type checking to analyze the program during compile-time to prove the absence of type errors. The basic idea is never let bad things happen at runtime. By understanding the following example, you should have a good understanding of how static type checking works in Java.

Oracle Java Tutorials and Materials, Oracle Java Certifications, Oracle Java Guide

Tuesday, 11 April 2017

What do Java objects look like in memory during run-time?

We know functions are implemented in memory as a stack of activation records. And we know Java methods are implemented as a stack of frames in JVM Stack and Java objects are allocated in Heap.

How do Java objects look like in heap? Once an object is laid out in memory, it's just a series of bytes.

Then how do we know where to look to find a particular field? Keep an internal table inside the compiler containing the offsets of each field.

Monday, 10 April 2017

What does a Java array look like in memory?

Arrays in Java store one of two things: either primitive values (int, char, ...) or references (a.k.a pointers).

When an object is creating by using "new", memory is allocated on the heap and a reference is returned. This is also true for arrays, since arrays are objects.

Wednesday, 5 April 2017

Java Web Application sending JSON messages through WebSocket to HTML5 browser application for real time push

This article describes a Java EE 7 web application that exposes a REST service that handles HTTP POST requests with JSON payload. Any message received is sent through a Web Socket to the web socket (server) endpoint that is published by a Java Class deployed as part of the web application. A static HTML page with two associated JavaScript libraries is opened in a web browser and has opened a web socket connection to this same end point. The message sent from the REST service endpoint to the web socket endpoint is pushed through the web socket to the browser and used to instantly update the web page.

Saturday, 1 April 2017

Best Practices for Multithreading in Java

A thread is a path of execution within a process. Multithreading is the ability to improve the overall throughput of an application by providing a way to execute many threads simultaneously. This article presents a discussion on the best practices that should be adopted when working with multi-threading in enterprise applications.

What is multithreading and why is it useful?


Multithreading may be defined as the ability to have multiple threads in memory with one of them in the execution state. Threads share the resources of a process that includes memory resources, process data and open files. This, though it helps to make your application more efficient, might cause issues at runtime due to concurrent access to the same resource.

Tuesday, 21 March 2017

Java Callout from Business Rules

Goal and warning


This blog will show how to invoke java code directly from within a Business Rules component. I didn’t manage to find this in the Oracle product documentation, which is actually a good thing. Invoking java code with business logic directly from within the Business Rules is normally bad design. The proper way to do it would be to first invoke business rules and then – depending on the outcome – invoke the appropriate business logic. Hence, the proper place for business logic is outside of the business rules.
However, for more technical requirements, it may be convenient to do a java callout from within the business rules. The sample situation we have is that a logging line will be generated upon a ‘case start event’. No business logic!

Friday, 3 March 2017

JDBC from the Oracle Service Bus

There are different ways to do database calls from the Oracle Service Bus. In this blog post I look at several methods.

The methods looked at;
1 using an external webservice (without OSB)
2 using an external webservice proxied by the OSB
3 using the fn-bea:execute-sql function from the OSB
4 using the JCA DbAdapter from the OSB provided by Oracle as part of Oracle SOA Suite

Wednesday, 22 February 2017

Implementing the Singleton Design Pattern in Java

The Singleton design pattern is one of the most popular design patterns in use. The Singleton design pattern is one of the Gang of Four's (GOF) design patterns and belongs to the Creational Design Pattern category. This article presents a discussion on the Singleton design pattern, its benefits and how it can be implemented in Java.

What is the Singleton Design Pattern?

The Singleton design pattern is used to restrict instances of a class to just one instance. This design pattern states that there can be one — and only one — instance of a class throughout the application's lifecycle. Essentially, a singleton class is one that can have just one instance throughout the application's life cycle and provides a global point of access to it.