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.

Tuesday, 21 February 2017

Working with Files and I/O in Java

The java.nio package contains the types required to perform input output operations in Java. The introduction of the java.nio package has simplified input — output operations. This article presents a discussion on how to perform input — output operations in Java with special focus on the java.nio package.

When you work with files for I/O, you basically work with streams. A stream may be defined as a sequence of bytes. There are two types of streams. These include: input stream and output stream. While the former is used to read data from a source, the latter is used to write data to a destination.

Wednesday, 11 January 2017

Extracting JavaDoc documentation from source files using JavaParser

A lot of people are using JavaParser for the most different goals. One of these is extracting documentation. In this short post we will see how you can print all the JavaDoc comments associated to classes or interfaces.

Code is available on GitHub: https://github.com/ftomassetti/javadoc-extractor

Getting all the Javadoc comments for classes

Tuesday, 10 January 2017

HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap

Map is one of the most important data structures in Java. In this post, I will illustrate how to use different types of maps, such as HashMap, TreeMap, HashTable and LinkedHashMap.

1. Map Overview


HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap

Monday, 9 January 2017

Java read a file line by line – How Many Ways?

The number of total classes of Java I/O is large, and it is easy to get confused when to use which. The following are two methods for reading a file line by line.

Method 1:

private static void readFile1(File fin) throws IOException {
FileInputStream fis = new FileInputStream(fin);

Friday, 6 January 2017

Monitors – The Basic Idea of Java Synchronization

If you took operating system course in college, you might remember that monitor is an important concept of synchronization in operating systems. It is also used in Java synchronization. This post uses an analogy to explain the basic idea of "monitor".

1. What is a Monitor?

A monitor can be considered as a building which contains a special room. The special room can be occupied by only one customer(thread) at a time. The room usually contains some data and code.

Thursday, 5 January 2017

Why do we need Generic Types in Java?

Generic types are extensively used in Java collections. Why do we need Generic types in Java? Understanding this question can help us better understand a lot of related concepts. In this article, I will use a very short example to illustrate why Generic is useful.

Wednesday, 4 January 2017

Working with Abstract Classes and Interfaces in Java

There are three important constructs in Java — concrete classes, abstract classes and interfaces. An abstract class is a special type of a class that is marked with the abstract keyword to indicate that the class cannot be instantiated but can be inherited if need be. An interface is actually a purely abstract class. We will explore more on both of these as we progress through this article. This article presents a discussion on when and how to use abstract class and interface when working with enterprise applications in Java.

Tuesday, 3 January 2017

Unit testing Java data classes immutability with the Mutability Detector

In all our project, we use data classes which, by definition, contain data (fields) but no (business) logic.

According to the best coding practices, a data class should preferably be immutable because immutability means thread safety.

An immutable class has several interesting properties:

Monday, 2 January 2017

How to create a ZIP File in Java? ZipEntry and ZipOutputStream Compression Example

Since compressing and archiving old log file is an essential housekeeping job in any Java application environment, a Java programmer should know how to compress files in .zip format and then how to read them programmatically if required. The JDK provides full support to create and read ZIP files in Java. There is a separate package java.util.zip to hold all classes related zipping and unzipping files and streams.