Wednesday, 28 December 2016

Prototype of Java Database Class

Can we make a database connection class which allows us just change the configuration file, and then use the database? I did the prototype of this class which is very simple. But the idea is good, always use a very simple jar file to get setup database which can then do SQL query operations.

Monday, 26 December 2016

How to make a method thread-safe in Java?

Is the following method thread-safe? How to make it thread-safe?

class MyCounter {
private static int counter = 0;

public static int getCount() {
return counter++;
}
}

Friday, 23 December 2016

The Interface and Class Hierarchy Diagram of Java Collections

1. Collection vs Collections

First of all, "Collection" and "Collections" are two different concepts. As you will see from the hierarchy diagram below, "Collection" is a root interface in the Collection hierarchy but "Collections" is a class which provide static methods to manipulate on some Collection types.

Thursday, 22 December 2016

What is Inheritance in Java with example - Object Oriented Programming

What is Inheritance in Java 

Inheritance in Java or OOPS (Object oriented programming) is a feature which allows coding reusability.  In other words, Inheritance  self-implies inheriting or we can say acquiring something from others. Along with Abstraction, Encapsulation and Polymorphism, Inheritance forms the backbone of Object oriented programming and Java.  In Java, we use the term inheritance when one object acquires some property from other objects. In Java, inheritance is defined in terms of superclass and subclass. it is normally used when some object wants to use existing feature of some class and also want to provide some special feature, so we can say inheritance has given the advantage of reusability.

Tuesday, 13 December 2016

How to implement Thread pool in Java

A thread is an independent program’s path of execution. In java, each thread extends the java.lang.Thread class or implements java.lang.Runnable.

Multithreading refers to the execution of two or more threads concurrently within a single task.In multithreading, each task can have many threads, and these threads can run concurrently, either asynchronously or synchronously.

Monday, 12 December 2016

Using XML and Jar Utility API to Build a Rule-Based Java EE Auto-Deployer Part-2

Design of the Deployment Tool

For this sample tool, a Factory design pattern is applied to build deployment module, POJOs, from a deployment rule, after that these POJOs are serialized to XML documents by a RuleGenerator using XStream utility library. The class design is shown in Figure 4.

Using XML and Jar Utility API to Build a Rule-Based Java EE Auto-Deployer Part-2
Figure 4. Class diagram of deployment tool

Friday, 9 December 2016

Using XML and Jar Utility API to Build a Rule-Based Java EE Auto-Deployer

Introduction

Today's Java EE application deployment is a common task, but not an easy job. If you have ever been involved in deploying a Java EE application to a large enterprise environment, no doubt you have faced a number of challenges before you click the deploy button. For instance, you have to figure out how to configure JMS, data sources, database schemas, data migrations, third-party products like Documentum for web publishing, dependencies between components and their deployment order, and so on. Although most of today's application servers support application deployment through their administrative interfaces, the deployment task is still far from being a one-button action.

Thursday, 8 December 2016

What is Instance Initializer in Java?

In this post, I will illustrate what are instance variable initializer, instance initializer, static initializer, and how the instance initializer works in Java.

1. Execution Order

Look at the following class, do you know which one gets executed first?

public class Foo {

Tuesday, 6 December 2016

What is the difference between a Class and an Object in Java?

This article is solely for all beginner programmers, who are learning object oriented programming language e.g. Java, C++ or C# and aspire to do well on any programming interview. The difference between class and object is one of the most common questions, you would like to ask a fresher coming out from college or training institute, but you would be surprised how many beginner Java programmers struggle with this question. Class and Object are two pillars of Object Oriented Programming (OOPS) and a good understanding is a must, but when you ask this question apart from the theoretical and bookish answer that "class is a blueprint and objects are actual things created out of that blueprint", you would hardly get anything substantial. Though that answer is correct and works perfectly, it doesn't differentiate between a programmer, who has just mugged the answer, or the one who truly understand the difference between class and object.

Monday, 5 December 2016

4 ways of Session management in Servlet Java

Session tracking or Session management is an important feature of modern web applications which allows the server to remember it's clients. By keeping a session for each user, Server can serve the client better. It also helps in safety, security and personalization and must for certain kind of web applications e.g. e-commerce sites like Amazon or e-bay which stores item selected by the user for purchase in a shopping cart, even after the user is logged out. Since HTTP is a stateless protocol, there are no ways to know that two HTTP requests are related to each other i.e. they are coming from the same client or they are part of the same process.

Friday, 2 December 2016

3 Difference between Web Server vs Application vs Servlet Containers in Java JEE

In the Java EE, or J2EE or JEE world, there are a lot of confusion between terminology, which is quite evident that now we have three words (J2EE, Java EE, and JEE) to describe the same technology platform. You will see Java developers using the terms like Web Server, Application Server, and Web containers interchangeably but they are not exactly same. The main difference between Web server and application server is that web server is meant to serve static pages e.g. HTML and CSS, while Application Server is responsible for generating dynamic content by executing server side code e.g. JSP, Servlet or EJB. One of the most popular web servers is Apache HTTPD which is often used in conjunction with Tomcat to host many Java web application. Now, tomcat is not exactly an application server, it's more of a servlet engine or web container or also known as servlet containers because it provides the runtime environment for Servlet and JSP but doesn't provide the services like EJB and distributed transaction which are a key feature of the application server in Java JEE world.

Thursday, 1 December 2016

Fibonacci Series in Java Using Recursion

Fibonacci series is also a popular topic on various programming exercises in school and colleges. Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number e.g. fn = fn-1 + fn-2. The first two numbers of Fibonacci series is always 1, 1. In this Java program example for Fibonacci series, we create a function to calculate Fibonacci number and then print those numbers on Java console.

Wednesday, 30 November 2016

How to convert Timestamp to Date in Java - JDBC

The JDBC API uses separate Date, Time and Timestamp class to confirm DATE, TIME and DATETIME data type from the database, but most of the Java object oriented code is written in java.util.Date. This means you need to know how to convert the timestamp to date and vice-versa. You can do by using the getTime() method, which return the number of millisecond from Epoch value. This can be used to create both Timestamp and java.util.Date, hence it acts as a bridge between Date class from java.util package and Date, Time and Timestamp class from the java.sql package.

Tuesday, 29 November 2016

Auto-Generate Optimized Java Class Specializations

Background

As you might know, Java has a number of built-in value types. These are bytes, shorts, integers, longs, floats, doubles, booleans and characters. Primitive value types are different from ordinary objects primarily in that they can be allocated directly on the memory stack, reducing the burden on the Garbage Collector. A problem with not inheriting from Object is that they can’t be put into collections or passed as parameters to methods that take object parameters without being wrapped. Typical wrapper classes are therefore “Integer”, “Double”, “Boolean” etc.

Monday, 28 November 2016

Inheriting Javadoc Method Comments

The following interfaces and classes are contrived examples that will be used in this post to illustrate inheritance of Javadoc comments on methods. Some inherited/implementing methods include their own Javadoc comments that override parent’s/interface’s methods comments fully or partially and other simply reuse the parent’s/interface’s methods’ documentation.

Saturday, 26 November 2016

What is Polymorphism in Java? Overriding or Overloading?

Polymorphism vs Overloading vs Overriding

Someone asked me What are the difference between Polymorphism and Overriding in Java and the similar difference between Polymorphism and Overloading. Well, they are not two different things, Polymorphism is an object oriented or OOPS concept like Abstraction, Encapsulation or Inheritance which facilitate the use of the interface and allows Java program to take advantage of dynamic binding in Java. Polymorphism is also a way through which a Type can behave differently than expected based upon which kind of Object it is pointing. Overloading and overriding are two forms of Polymorphism available in Java.

Friday, 25 November 2016

Default Methods in Java 8 and Multiple Inheritance

Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit characteristics and features from more than one parent object or parent class.
Default methods in Java 8 can be viewed as a form of multiple inheritance (except that attribute can not be inherited). Consider the example below, the Button class implements two interfaces - Clickable and Accessible.

Wednesday, 23 November 2016

Difference between include() and forward() methods of RequestDispatcher in Servlert

What is the difference between include and forward methods of RequestDispatcher interface is one of the frequently asked Servlet questions from Java EE interviews and we'll see how you can answer this question on your interview. You get the RequestDispatcher reference either from ServletContext or ServletRequest interface and even though both include() and forward() method allow a Servlet to interact with another servlet, main difference between include() and forward is that include() method is used to load the contents of the specified resource (could be a Servlet, JSP, or static resource e.g. HTML files) directly into the Servlet's response, as if it is part of the calling Servlet. On the other hand, forward() method is used for server side redirection, where an HTTP request for one servlet is routed to another resource (Servlet, JSP file or HTML file) for processing.

Monday, 21 November 2016

Auto-Generate Optimized Java Class Specializations

If you visited JavaOne this year you might have attended my presentation on “How to Generate Customized Java 8 Code from your Database”. In that talk I showcased how the Speedment Open Source toolkit is used to generate all kinds of Java code using a database as the domain model. One thing we didn’t have time to go into though is the fact that Speedment is not only making code generation easier, it is also itself made up by generated code. In this article I will show you have we set up Speedment to generate specialized versions of many classes to reduce the memory footprint of performance critical parts of the system.

Monday, 14 November 2016

Java Annotations Are a Big Mistake

Annotations were introduced in Java 5, and we all got excited. Such a great instrument to make code shorter! No more Hibernate/Spring XML configuration files! Just annotations, right there in the code where we need them. No more marker interfaces, just a runtime-retained reflection-discoverable annotation! I was excited too. Moreover, I’ve made a few open source libraries which use annotations heavily. Take jcabi-aspects, for example. However, I’m not excited any more. Moreover, I believe that annotations are a big mistake in Java design.

Friday, 11 November 2016

Are You Still Debugging?

Debugging is “a process of running a program/method interactively, breaking execution flow after each statement and showing…” In a nutshell, it is a very useful technique … for a bad programmer. Or an old programmer who is still writing procedural code in C. Object-oriented programmers never debug their code—they write unit tests. My point here is that unit testing is a technique that completely replaces debugging. If debugging is required, the design is bad.

Thursday, 10 November 2016

How to solve java.sql.BatchUpdateException: String or binary data would be truncated

Recently I was working in Java application which uses Microsoft SQL Server at its backend. The architecture of Java application was old i.e. even though there was heavy database communication back and forth there was no ORM used e.g. no Hibernate, JPA, or Apache iBatis. The Java application was using old DAO design pattern, where the DB related classes which are responsible for loading and storing data from database was calling stored procedure to do their Job. These stored procedure takes data from Java application and insert into SQL Server tables. One day, one of my collegue called me to troubleshoot "java.sql.BatchUpdateException: String or binary data would be truncated", which it's application was throwing and he has no clue whatsoever that what is wrong with the data he is getting from other system and trying to store.

Resolve method calls in Java code using the JavaSymbolSolver

Why I created the java-symbol-solver?

A few years ago I started using JavaParser and then I started contributing. After a while I realized that many operations we want to do on Java code cannot be done just by using the Abstract Syntax Tree produced by a parser, we need also to resolve types, symbols and method calls. For this reason I have created the JavaSymbolSolver.

One thing that is missing is documentation: people open issues on JavaParser asking how to answer a certain question and the answer is often “for this you need to use JavaSymbolSolver”. Starting from these issues I will show a few examples.

Wednesday, 9 November 2016

5 Things Only Experienced Developers Can Teach You About Java

An overview of everything you need to know before diving deep into developing Java

There are numerous tools, methods, environments and features that change the way you handle your code, that you usually don’t come across during school years. While it offers the first foot through the door in the Java development world, most of the actual learning happens on the job.

In the following post we’ll go over some key elements you only learn about as you get more experienced. These will include the basics and mix in a some philosophy. Get your notebook ready, it’s back to school time.

Tuesday, 8 November 2016

Difference between PUT and POST in REST WebService in Java

If you remember REST WebServices uses HTTP methods to map CRUD (create, retrieve, update, delete) operations to HTTP requests. Even though both PUT and POST methods can be used to perform create and update operation in REST WebServices, Idempotency is the main difference between PUT and POST. Similar to the GET request, PUT request is also idempotent in HTTP, which means it will produce the same results if executed once more multiple times. Another practical difference PUT and POST method in the context of REST WebService are that POST is often used to create a new entity, and PUT is often used to update an existing entity. If you replace an existing entity using PUT than you should be aware that if only a subset of data elements is passed then the rest will be replaced by empty or null.

Monday, 7 November 2016

Explore Polymorphism in Java

Polymorphism is the existence of the same thing in various forms. It is a feature of OOP that enables items to change form based on circumstances. The term polymorphism is derived from two Greek words, namely, "poly" and "morphos." While the term "poly" means many, and "morphos" which implies forms. Hence, polymorphism denotes the existence of the same thing in various forms. The Java Programming Language has been one of the most popular programming languages for decades. It is widely used in enterprise software development and has matured a lot over the last decade. The Java Programming Language provides excellent support for polymorphism.

Saturday, 5 November 2016

How to Add and Subtract Two Matrices in Java

This is the second program in the series of matrices related programming exercises in Java. In the last program, you have learned matrix multiplication and in this program, you will learn how to perform addition and subtraction of two matrices in Java. We'll create methods to calculate both sum and difference of two matrices in Java program. In Mathematics, a matrix is a rectangular array with two dimensions known as rows and columns. In Java, your can use a two-dimensional array to represent a matrix because it also has two dimensions rows and columns. Since a 2D array is nothing but an array of the array in Java, the length of the outer array is equal to the number of rows and length of sub-array is equal to the number of columns.

Friday, 4 November 2016

How to compare String by their length in Java 7 and 8?

The natural way to compare String is the lexicographic way, which is implemented in the compareTo() method of String class, but sometimes you need to compare String by their length. You cannot use the default compareTo() method for that task, you need to write your own custom Comparator, which can compare String by length. Don't worry, It's easy to compare multiple String by their length, all you need to write is a Comparator which calculates their length using the length() method and compare them. Such comparator should return a positive value if first String has a length greater than second String, a negative value if the length of first String is less than the length of second String and zero if both String has the same length.

Wednesday, 26 October 2016

Difference between PUT and POST in REST WebService in Java

If you remember REST WebServices uses HTTP methods to map CRUD (create, retrieve, update, delete) operations to HTTP requests. Even though both PUT and POST methods can be used to perform create and update operation in REST WebServices, Idempotency is the main difference between PUT and POST. Similar to the GET request, PUT request is also idempotent in HTTP, which means it will produce the same results if executed once more multiple times. Another practical difference PUT and POST method in the context of REST WebService are that POST is often used to create a new entity, and PUT is often used to update an existing entity. If you replace an existing entity using PUT than you should be aware that if only a subset of data elements is passed then the rest will be replaced by empty or null.

Tuesday, 25 October 2016

Embed Jython to you java codebase

Jython is a great tool for some quick java scripts using a pretty solid syntax. Actually it works wonderfully when it comes to implement some maintenance or monitoring scripts with jmx for you java apps.

In case you work with other teams with a python background, it makes absolute sense to integrate python to your java applications.

First let’s import the jython interpeter using the standalone version.

Monday, 24 October 2016

How to enable SSL debugging in Java JVM?

Dealing with SSL issues in Java web application is no fun, especially when you have no debug logs and all you see is an ugly ‘Page Cannot be displayed’ error message in your browser. Thankfully you can easily enable SSL to debug on your Application to start seeing verbose logs that will clearly show what happens during the SSL handshake process. You can enable SSL debugging logs in your Application Server JVM config by adding the following JVM command line parameter and restart the Application Server:

Friday, 21 October 2016

Handling Events in JavaServer Faces, Part 2

Handling User Interface Events


When the user clicks a button or a link, chances are good that backend code should be asked to do something, like adding a report entry to the current report when the Add button is clicked in the sample application. Occasionally, though, an event affects only the user interface. For instance, clicking a button or changing the value of an input control may expose additional options or display more information.

As an example of user interface changes triggered either by a button click or a value change, let's add a feature to the sample application, namely an extendable expense types list. Initially, only the most common expense types are listed, but the user can extend the list with more uncommon choices.

Thursday, 20 October 2016

Handling Events in JavaServer Faces, Part 1

Handling Events

When the user clicks a button or link, changes a value in a field, or makes a selection in a list, the application may need to react. JSF user interface components signal user actions by firing an event handled by application code that has registered itself to be notified of the event. It's a model borrowed from traditional GUI frameworks, making it easy to develop and maintain the code for each specific user action in a separate code module. You can even use multiple event handling modules for different aspects of the processing, such as one that logs the action and another that acts on it.

Wednesday, 19 October 2016

How to calculate sum and difference of two complex numbers in Java

From the last couple of articles, I am writing about coding exercises for beginners e.g. yesterday you learned how to write a program from matrix multiplication in Java and a couple of days back, you have learned recursive binary search algorithm. To continue that tradition today I am going to show you how to write a program for calculating sum and difference of two complex numbers in Java. If you remember the complex number from you maths classes, it has two part real and imaginary and to add a complex number we add their real and imaginary part separately, similar to subtract complex number we minus their real and imaginary part separately. For example, if first complex number is A + iB and the second complex number is X + iY then the addition of these two complex number will be equal to (A +X ) + i(B + Y).

Tuesday, 18 October 2016

How to replace a substring in Java?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement). This version of the replace() method replaces each substring of this string (on which you call the replace() method) that matches the literal target sequence with the specified literal replacement sequence. For example, if you call "Effective Java".replace("Effective", "Head First") then it will replace "Effective" with "Head First" in the String "Effective Java". Since String is Immutable in Java, this call will produce a new String "Head First Java".

Monday, 17 October 2016

5 Difference between StringBuffer, StringBuilder and String in Java

Though all three classes StringBuffer, StringBuilder and String are used for representing text data in Java there are some significant differences between them. One of the most notable differences between StringBuilder, StringBuffer, and String in Java is that both StringBuffer and StrinBuilder are Mutable class but String is Immutable in Java. What this means is, you can add, remove or replace characters from StringBuffer and StringBuilder object but any change on String object e.g. converting uppercase to lowercase or appending a new character using String concatenation will always result in a new String object. Another key difference between them is that both StringBuffer and String are thread-safe but StringBuilder is not thread-safe in Java. String achieves its thread-safety from Immutability but StringBuffer achieves it via synchronization, which is also the main difference between the StringBuffer and StringBuilder in Java.

Saturday, 15 October 2016

Binary Search using Recursion in Java

In order to implement a recursive solution, you need a base case because without a base case your program will never terminate and it will eventually die by throwing StackOverFlowError . In the case of recursive binary search implementation, we calculate middle position by taking start and end position and check if the target element is equal to the middle element or not. If target, the number of element you are searching in an array is equal then our search is complete, but if the target is greater than middle we look on second half of array and if the target is less than middle element then we look into the first half of array. This is possible because in the case of binary search the array is always sorted, if it's not, you must sort the array before conducting a binary search.

Sunday, 9 October 2016

10 Essential JVM Options for a Java Production System

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

Saturday, 8 October 2016

How to calculate area of triangle in Java - Program

Writing a Java program to calculate the area of a triangle is one of the basic programming exercises to develop coding sense on beginner programmers. Like many mathematical conceptual programs e.g. square root, factorial, or prime number this also serves a good exercise for beginners. Now, if you remember in maths you might have seen two main ways to calculate the area of a triangle, using vertices and using base and height. In this program, I have created two methods to calculate the area of a triangle using both ways. In the first method area (Point a, Point b, Point c)  we expect coordinates of three vertices of triangle and then we calculate area of triangle using the formula (Ax(By -Cy) + Bx(Cy -Ay) + Cx(Ay - By))/2, while in second method, area(int base, int height) we expect value of base and height and then we calculate are of triangle using formula (base * height) / 2.

Wednesday, 5 October 2016

3 ways to convert String to JSON object in Java?

It's very common nowadays to receive JSON String from a Java web service instead of XML, but unfortunately, JDK doesn't yet support conversion between JSON String to JSON object. Keeping JSON as String always is not a good option because you cannot operate on it easily, you need to convert it into JSON object before you do anything else e.g. retrieve any field or set different values. Fortunately, there are many open source library which allows you to create JSON object from JSON formatted String e.g. Gson from Google, Jackson, and json-simple. In this tutorial, you will learn how to use these 3 main libraries to do this conversion with step by step examples.

Even though you can use a simple or complex JSON String e.g. with lots of attributes and JSON arrays, I'll use following JSON String for example purpose:

Tuesday, 4 October 2016

Difference between Heap and Stack Memory in Java JVM

One of the many traits of a good programmer is how well he understands the fundamental and if you want to check the fundamentals of Java programmer than asking the difference between heap and stack memory is a good choice. Even though both are part of JVM and both consumers memory allocated to the Java process, there are many differences between them e.g. Heap memory is shared by all threads of Java application but Stack memory is local to each thread. Objects are created in heap memory but method frames are stored in Stack memory, and size of heap space is much bigger than the small size of Stack in Java. Even if you know this much information about heap and stack in Java, you are one of the better candidates, but let's see some more details to impress the interviewer.

Monday, 3 October 2016

3 ways to get number of months and year between two dates in Java?

Earlier I have talked about how to calculate a number of days between two dates in Java, and now you will learn how to get the number of months and years between dates. Though it may look easy, it's not that easy to calculate months and years between dates, unless you take care of all kinds of nuisances like Daylight saving time and when daylight change occurs, leap seconds, and an extra day added in a leap year. Unfortunately, JDK doesn't have a standard method like Period.between() method of Java 8 before to solve this problem. So, if you have to calculate the number of months and years between given dates, you have three main options, first, use Calendar class to write your method to find a number of months and year between given dates, second, use Joda-time library and the third option is to upgrade to Java 8.

Saturday, 1 October 2016

3 Ways to Solve "No JVM installation found. Please install a 64-bit JDK" - Android Studio

You are an enthusiastic Java programmer who just learned about developing Android apps in Java. To start with you have installed Android Studio, which is the official Integrated Development Environment (IDE) for Android app development, based on IntelliJ IDEA, but as soon as you click on the Android Studio Desktop Icon to start Android Studio you are getting "No JVM installation found. Please install a 64-bit JDK" error? How do you solve this problem? Well, even though the error message is same, every problem is different depending upon your machine, the Java version, whether your desktop or laptop has 32-bit or 64-bit OS e.g. Windows 8.1 or Windows 10. Whether you have installed 32-bit Java or 64-bit JDK e.g. JDK 1.8.0 and what is the value of JAVA_HOME environment variable or whether you have defined it or not.

Friday, 30 September 2016

How to Serialize Object in Java - Serialization Example

Serialization is one of the important but confusing concept in Java. Even experienced Java developer struggle to implement Serialization correctly. The Serialiation mechamism is provided by Java to save and restore state of an object programatically. Java provides two classes Serializable and Externalizable in java.io package to facilitate this process, both are marker interface i.e. an interface without any methods. Serializing an Object in Java means converting into a wire format so that you can either persists its state in a file locally or transfer it to another client via the network, hence it become an extrememly important concept in distributed applications running across several JVMs. There are other features in Java e.g. Remote Method Invocation (RMI) or HttpSession in Servlet API which mandates the participating object should impelment Serializable interface because they may be transffered and saved across the network.

Thursday, 29 September 2016

Iterative QuickSort Example in Java - without Recursion

The quicksort algorithm is one of the important sorting algorithms. Similar to merge sort, quicksort also uses divide-and-conquer hence it's easy to implement quicksort algorithm using recursion in Java, but it's slightly more difficult to write an iterative version of quicksort. That's why Interviewers are now asking to implement QuickSort without using recursion. The interview will start with something like writing a program to sort an array using quicksort algorithm in Java and most likely you will come up with a recursive implementation of quicksort as shown. As a  follow-up, Interviewer will now ask you to code the same algorithm using Iteration.

Wednesday, 28 September 2016

Top 5 JSON Library Java JEE Developers Should Know

The JSON format is one of the most popular formats to transfer and exchange data in web. Almost all RESTful web services take JSON input and provide JSON output but unfortunately JDK doesn't have built-in support for one of the most common web standard like JSON. As a Java developer if you want to develop RESTful web service and produce JSON data or if you are developing a client to an existing RESTFul web services and want to consume JSON response, you don't need to be disappointed. Fortunately, there are so many open source libraries and API available for creating, parsing and processing JSON response in Java e.g. Jackson, Google GSon, json-simple etc.

Actually, there are numerous JSON libraries exists in Java but you don't need to learn all of them, learning just one of them e.g. Jackson should be enough, but, on the other hand, it's worth knowing what are some of the most popular JSON parsing library exists in your disposal. In this article, I am going to share 5 useful JSON libraries which I believe every Java JEE developer should be aware of.

Friday, 23 September 2016

Java 9 module-info Files in the Eclipse IDE

It’s been a while, but I’m back to experimenting in Java 9 support in the Eclipse IDE.
For testing purposes, I downloaded the most recent Oxygen (4.7) integration build (I20160914-0800) from the Eclipse Project downloads the latest  Java 9 JRE build (135).

I configured the Eclipse IDE to run on the Java 9 JVM. This still requires a minor change in the eclipse.ini file: to launch successfully, you must add --add-modules=java.se.ee to the vmargs section (I expect this to be resolved before Java 9 support is officially released; see Bug 493761 for more information). I used and used the Install new softwar. dialog to pull in updates from the BETA_JAVA9 SDK builds repository.

Thursday, 22 September 2016

BDD and Automated Acceptance Testing for Java Web Apps: Creating a Suite

This final installment demonstrates how to start implementing some automated acceptance criteria. To follow along, you can clone the github repository for the sample project.

Alternatively, if you want to create your own brand new Thucydides test suite and write your own tests, you can use the Maven archetype. From the command line, run mvn archetype:generate -Dfilter=thucydides-jbehave, as illlustrated below:

mvn archetype:generate -Dfilter=thucydides-jbehave

Saturday, 17 September 2016

Java SE 8 Date and Time

Why do we need a new date and time library?

A long-standing bugbear of Java developers has been the inadequate support for the date and time use cases of ordinary developers.

For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe, leading to potential concurrency issues for users—not something the average developer would expect to deal with when writing date-handling code.

Some of the date and time classes also exhibit quite poor API design. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive.

Friday, 16 September 2016

How to Build Java Projects Using Gradle

Overview


Gradle is an automated project building tool that uses the concepts of both Apache Ant and Apache Maven but is based on a domain specific language rather than the traditional XML approach. Gradle is designed to support multi-project builds that are quite large and are difficult to manage via Ant or Maven.

This article will discuss the concepts of Gradle as a project building tool and also show how to configure and build a sample Java project.

Thursday, 15 September 2016

What’s exciting about Java 9 and Application Performance Monitoring

In today’s modern computing age, constant enhancements in software innovations are driving us closer to an era of software revolution. Perhaps in the distant future, that may be how the 21st century is remembered best. Among the popular software languages out there, however, Java continues to have the largest industry footprint, running applications around the globe producing combined annual revenue in trillions. That’s why keeping up on the JDK is a high priority. Despite having a massive API to improve programming productivity, Java has also grown due to its high performance yet scalable JVM runtime, building among the fastest computing modern applications. As Java’s footprint expands, JDK innovations continue to impact billions of lines of code. As AppDynamics continues to grow, our focus towards supporting Java is only furthered by our customer use & industry adoption of the JVM.

Tuesday, 13 September 2016

What is Java Content Repository Part-2

Developing a Blogging Application


With our Apache Jackrabbit installation built and configured, it's time to take the next step and build a sample application. In this section, we will develop a sample blogging application using the JCR-170 API. We need two things for developing this sample application: a backend to add, update, delete, and remove content in the content repository, and a client to provide a UI for performing these operations.

First we create clear-cut separation between these two parts by defining a DAO interface for the backend layer. So, create BlogEntryDAO.java interface like this

Monday, 12 September 2016

What is Java Content Repository

JSR-170 defines itself as "a standard, implementation independent way to access content bi-directionally on a granular level within a content repository," and goes on to define a content repository as "a high-level information management system that is a superset of traditional data repositories, [which] implements 'content services' such as: author based versioning, full textual searching, fine grained access control, content categorization and content event monitoring."

Sunday, 11 September 2016

Scaling Enterprise Java on 64-bit Multi-Core X86-Based Servers

Multi-core and 64-bit CPUs are the hottest commodities in the enterprise server market these days. In recent years, as the cost and power requirement of faster CPU clock speeds has increased, the growth in raw clock speed (usually measured in megahertz) of single CPUs has slowed down. Hardware manufacturers continue to improve X86-based server performance by increasing both the multitasking capability and internal data bandwidth. Both Intel and Advanced Micro Devices are shipping 64-bit processors with two internal CPU cores, and quad core processors are soon to follow. Ninth-generation servers from Dell exploit this new generation of chips. The PowerEdge 1955 blade server, for example, supports up to two 64-bit dual core processors in a blade configuration, with up to ten such blades in a 7-rack unit (12.25") chassis.

Friday, 9 September 2016

The Foundation of Proper Object-Oriented Design: Interfaces

Object-oriented (OO) design has been a staple of modern programming since the 1990s. At its core it is about having "objects" that carry both state (data relevant to this object) and behavior (the operations you can perform on the data). Several programming languages added explicit support to OO style development (most notably C++, which was very popular back then). This was an advancement over the procedural programming practices that were prevalent earlier in which programmers who had "objects" had to manage the connection between their data and behavior.

Wednesday, 7 September 2016

How to Access Relational Data Using JDBC with Spring

Overview


The Spring framework has become an essential part of modern Java-based application development and has effectively managed to take control of every department in the Java development world. The JDBC template for Spring is used in most of the Spring-based JEE applications to communicate with the database. This article will discuss how to access a relational database using the JDBC template in Spring.

Tuesday, 6 September 2016

Java Generics and Collections: Evolution, Not Revolution, Part 2

Legacy Library with Generic Client


It usually makes sense to update the library before the client, but there may be cases when you wish to do it the other way around. For instance, you may be responsible for maintaining the client but not the library; or the library may be large, so you may want to update it gradually rather than all at once; or you may have class files for the library, but no source.

In such cases, it makes sense to update the library to use parameterized types in its method signatures, but not to change the method bodies. There are three ways to do this: by making minimal changes to the source, by creating stub files, or by use of wrappers. We recommend use of minimal changes when you have access to source and use of stubs when you have access only to class files, and we recommend against use of wrappers.

Saturday, 3 September 2016

Java Generics and Collections: Evolution, Not Revolution, Part 1

One motto underpinning the design of generics for Java is evolution, not revolution. It must be possible to migrate a large, existing body of code to use generics gradually (evolution) without requiring a radical, all-at-once change (revolution). The generics design ensures that old code compiles against the new Java libraries, avoiding the unfortunate situation in which half of your code needs old libraries and half of your code needs new libraries.

The requirements for evolution are much stronger than the usual backward compatibility. With simple backward compatibility, one would supply both legacy and generic versions for each application; this is exactly what happens in C#, for example. If you are building on top of code supplied by multiple suppliers, some of whom use legacy collections and some of whom use generic collections, this might rapidly lead to a versioning nightmare.

Friday, 2 September 2016

Introduction to Java Caching System

Introduction 


In most of the web applications, data is retrieved from the database. The database operation is expensive and time consuming. Present-day web applications are data intensive and first response time is the basic criteria for success. If the web application is frequently accessing the database for each request then its performance will be slow. As a result, many web applications are following different design techniques for reducing latency times and scale up.

JCS is a composite distributed caching system that works on JDK 1.4 and higher versions. The performance of JCS is very impressive for low put and high read applications.

Wednesday, 31 August 2016

Functional Features in Java 8

Short History of Java


Java originated in 1995 and it was the language of the Internet and provided some unheard of capabilities in mainstream static typed languages, such as garbage collection, cross-platform out of the box (Write Once Run Anywhere), automatic documentation and the ability to run inside the browser as Java Applet. It quickly became very popular, especially for enterprise systems. About six years later, C# was released. The C# designers had taken a good look at Java and produced a language that was very similar, but addressed many of the issues that came to the front during Java's first years. Ever since, Java has been playing catch-up with C# and other languages in terms of language features.

Monday, 29 August 2016

Programming Basics: The Function Signature

The basic unit of programming is the function. You build your program one function (or method) at a time. The smallest thing you can test in a unit test is a function. A function is also the smallest piece of code you can name and hence create a new abstraction. The whole point of a function is to encapsulate some piece of code and make it available to the rest of your program or other programs in a library.

Tuesday, 23 August 2016

Discovering a Java Application's Security Requirements

Application security is not easy - we know that. But we also know there are steps we can take to mitigate the risk of security failures. If we are network engineers, we invest in knowledge of network partitioning and packet filters. If we program in C, we protect against buffer overflow. If we program in Java, we consider running our application under the protection of a security manager. In each case, we use knowledge of best practices to give ourselves an advantage over inadvertent system failure.

The security provisions for Java applications are well-documented, and form a superset of the discussion in this article. Our discussion focuses on aspects of Java security managers, a topic which is a small subset of the Java security architecture.

Monday, 22 August 2016

Designing Messaging Applications with Temporary Queues

Introduction


Most JMS destinations (queues and topics) are created administratively and are treated as static resources, even though dynamic destinations (temporary queues and temporary topics) are supported in JMS. Using static queues to communicate between tiers of a client/server application creates barriers to scalability and maintainability. In this article, we will look at the benefits and drawbacks of using temporary destinations in an enterprise healthcare system. We will also look at design perspectives for using temporary queues as an alternative to static queues and explore some design strategies using synchronous requests and replies.

Sunday, 21 August 2016

IRC Text to Speech with Java

Internet Relay Chat (IRC) is a network chat system used by millions of people all over the world. It has been around for several years and is used by groups of friends, programmers, universities, and even banks to facilitate discussions, the exchanging of ideas, and collaborative research.

Because IRC is very much a real-time chat system, you will rarely benefit from using it unless you are able to pay close attention to the sequence of dialog as it transpires. Unfortunately, this can lead to a lack of productivity in the workplace, which is why many employers naively frown upon the use of IRC. However, when used properly, IRC can let employees work effectively with remote colleagues, regardless of whether they are on the other side of the planet or just in the next building. Real-time group chat systems like IRC make it easier to organize meetings (and possibly even carry out virtual meetings), ask questions, and to negotiate the less-important things such as where to go for lunch.

Friday, 19 August 2016

Schemaless Java-XML Data Binding with VTD-XML

This article introduces a new Java-XML data binding technique based entirely on VTD-XML and XPath. The new approach differs from traditional Java-XML data binding tools in that it doesn't mandate schema, takes advantage of XML's inherent loose encoding, and avoids needless object creation, resulting in much greater efficiency.


Limitations of Schema-based XML Data Binding


XML data binding APIs are a class of XML processing tools that automatically map XML data into custom, strongly typed objects or data structures, relieving XML developers of the drudgery of DOM or parsing.SAX 

Thursday, 18 August 2016

Real-Time Java: An Introduction Part - 1

I've worked in investment banking for several years and my experience suggests that most problems in financial software arise from the lack of real-time support. Many large financial IT systems use a Java platform, and even an unplanned two-second stop for full garbage collection in an application can cause a loss of tens of thousands of dollars. The situation is worsened by the fact that garbage collections usually occur during a high-application activity, when the app is especially sensitive to any breaks in execution. The same situation occurs in other high-tech and production industries, which is why they are taking a careful look at real-time Java specification and its implementations.

Wednesday, 17 August 2016

Introduction to Amazon S3 with Java and REST

Introduction


Amazon Simple Store Service (S3) is a service from Amazon that allows you to store files into reliable remote storage for a very competitive price; it is becoming very popular. S3 is used by companies to store photos and videos of their customers, back up their own data, and more. S3 provides both SOAP and REST APIs; this article focuses on using the S3 REST API with the Java programming language.

Saturday, 13 August 2016

Guide to time and date in Java

Properly handling dates, time, time zones, daylight saving time, leap years and such has been my pet peeve for a long time. This article is not a comprehensive guide to time domain.It’s still relevant, but doesn’t cover java.time from Java 8. I want to cover the absolute minimum that every junior Java developer should be aware of.

When did an event happen?


Philosophy and quantum physics aside, we may treat time as a one-dimensional metric, a real number value. This value keeps growing when time passes by. If one event appeared after another, we assign greater time to that event. Two events happening simultaneously have the same time value.

Saturday, 6 August 2016

What is Java Content Repository

JSR-170 defines itself as "a standard, implementation independent way to access content bi-directionally on a granular level within a content repository," and goes on to define a content repository as "a high-level information management system that is a superset of traditional data repositories, [which] implements 'content services' such as: author based versioning, full textual searching, fine grained access control, content categorization and content event monitoring."

The Java Content Repository API (JSR-170) is an attempt to standardize an API that can be used for accessing a content repository. If you're not familiar with content management systems (CMS) such as Documentum, Vignette, or FileNet, then you must be wondering what a content repository is.

Thursday, 4 August 2016

Java and Web Services Primer

Web Services are a new technology that could revolutionize the way business-to-business and business-to-consumer services are provided. Web Services use a variety of technologies to allow two applications to communicate. However, none of these are new claims; what makes Web Services different from other similar mechanisms are the technologies which provide the service.

Web Services have at their core XML as a mechanism for communication. Ultimately, Web Services are based on three specific technologies: a mechanism to register a service, a mechanism to find a service, and a mechanism for two parties to communicate. Today, developers can use the Java 2 Enterprise Edition APIs and XML to provide Web Services. Such developments leverage existing Web sites and provide simple methods to extend, interconnect and publish existing J2EE-based applications in new and exciting ways.

Wednesday, 3 August 2016

SQL Database Access with DBTags

In a J2SE or J2EE application, Java Database Connectivity (JDBC) can be used to create a connection with a SQL database, create database tables, retrieve result sets, and update the database. To use a database from a Java Server Page (JSP), one often uses a JSP scriptlet to create a JDBC connection via the getConnection() method.

Jakarta DBTags is a custom tag library that contains tags to perform the same tasks -- creating a database connection, creating tables, retrieving result sets, and updating tables with prepared statements -- all without the use of JSP scriptlets.

Thursday, 28 July 2016

Caching Dynamic Content with JSP 2.0

Content caching is one of the most common optimization techniques used in web applications, and it can be implemented easily. For example, you can use a custom JSP tag--let's call it <jc:cache>--to wrap every page fragment that must be cached between <jc:cache> and </jc:cache>. Any custom tag can control when its body (i.e. the wrapped page fragment) is executed, and the dynamic output can be captured. The <jc:cache> tag lets the JSP container (e.g. Tomcat) generate the content only once, storing each cached fragment as a JSP variable in the application scope. Every time the JSP page is executed, the custom tag inserts the cached page fragment without re-executing the JSP code that generated the output. A tag library developed as part of the Jakarta project uses this technique, and it works fine when the cached content doesn't need to be customized for each user or request.

Wednesday, 27 July 2016

Upload Files with JSF and MyFaces

Web browsers provide an easy way for sending files to web applications, but the current versions of the Java web standards (servlets, JSP, and JSF) do not offer any help. Fortunately, there are third-party frameworks, such as Apache Commons File Upload, Apache MyFaces, and Oracle ADF Faces, that implement this feature, exposing simple APIs and custom tags. The first half of this article explains how file uploading works, walking you through the source code of MyFaces and Commons File Upload (the former uses the latter internally). It is helpful to know what happens inside of these open source frameworks in order to use them efficiently, and to be able to modify them if you have to. In the second half of the article, you'll find a sample application that lets users upload files using their web browsers.

Monday, 25 July 2016

Hibernate for Java SE

By now it's easy to see that Hibernate is quickly becoming a popular (if not the most popular) O/R mapper/data integration framework for J2EE. It offers a developer clear, concise, and powerful tools for working with relational databases in the enterprise. But what if you need outside access to those entities that are wrapped up in your J2EE web application? Do you develop separate, yet identical, entities to access your data? Or do you write additional web components to manage the internal access to your data?

At some point, these questions are bound to come up, and for me, it was when my company needed to upload records into our database from multiple vendors in multiple file formats. I thought about the approach I had always taken before, which was to write shell and SQL scripts (and even stored procedures) to upload the data. But because our data model is quite complex, I decided to leverage what existing entities, Spring DAOs, and services outside of our web app I could and develop a custom J2SE command-line data loader.

Wednesday, 20 July 2016

Beware of Functional Programming in Java!

This isn’t going to be a rant about functional programming, which is awesome. This is a warning about some practices that you are very likely going to apply to your code, which are terribly wrong!.

Higher order functions are essential to functional programming, and thus, talking about them will help you be the center of attention at parties.

If you’re writing JavaScript, you’re doing it all the time. For instance:

setTimeout(function() {
    alert('10 Seconds passed');
}, 10000);

Monday, 18 July 2016

Query DynamoDB Items with Java

On this post we will create Tables on a DynamoDB Database the java way. Before getting started we need to have local dynamodb installed since we want to avoid any costs for dynamodb usage.

In case you use docker you can find a local dynamodb image or you can create one on you own as described here. The dynamodb java sdk gives us the ability to create dynamodb tables using java code.
The most basic action is to create a table with a hash key. In this case the email of the user would be the hash key.

Monday, 11 July 2016

Working with the JDBC API for Large Objects

The JDBC API provides the necessary support to work with Large Objects (LOB), such as storing an image file or a large text document in the database. The requirements of data persistence may vary both by its size and type of data content; a LOB can be of these types: BLOB (Binary Large Object), CLOB (Character Large Object), and NCLOB (National Character Large Object). These are the LOB variations supported by the JDBC API. However, there is a difference on how a RDBMS treats and handles LOB objects internally. They are very vendor specific, but at the application level, specifically from JDBC APIs out treatment assumes it to be BLOB or CLOB, or perhaps NCLOB.

Tuesday, 28 June 2016

Installing Java Application As a Windows Service

It sounds like something you’d never need, but sometimes, when you distribute end-user software, you may need to install a java program as a Windows service. I had to do it because I developed a tool for civil servants to automatically convert and push their Excel files to the opendata portal of my country. The tool has to run periodically, so it’s a prime candidate for a service (which would make the upload possible even if the civil servant forgets about this task altogether, and besides, repetitive manual upload is a waste of time).

Even though there are numerous posts and stackoverflow answers on the topic, it still took me a lot of time because of minor caveats and one important prerequisite that few people seemed to have – having a bundled JRE, so that nobody has to download and install a JRE (would complicate the installation process unnecessarily, and the target audience is not necessarily tech-savvy).

Sunday, 26 June 2016

Functor and monad examples in plain Java

However introduction to monads, albeit very much related to reactive programming, didn’t suit very well. So I decided to take it out and publish separately as a blog post. I am aware that “my very own, half correct and half complete explanation of monads” is the new “Hello, world” on programming blogs. Yet the article looks at functors and monads from a specific angle of Java data structures and libraries. Thus I thought it’s worthwhile sharing.

RxJava was designed and built on top of very fundamental concepts like functors , monoids and monads . Even though Rx was modeled initially for imperative C# language and we are learning about RxJava, working on top of similarly imperative language, the library has its roots in functional programming. You should not be surprised after you realize how compact RxJava API is. There are pretty much just a handful of core classes, typically immutable, and everything is composed using mostly pure functions.

Tuesday, 21 June 2016

Java Arrays Sort decoded

Sorting is one the first algorithm that we learn in computer science. Sorting is such an interesting area that it has around 20+ algorithm and it is always difficult to decided which one is best. Sorting algorithm efficiency is measured in terms of time taken & space required. Some time bubble sort is best because it has no space requirement and for device where space is constraint or random access of element is not possible then it can be good fit .

These days we tend to use library sort functions, most of language library sort function is adaptive and it uses best algorithm depending on size of data.

Friday, 10 June 2016

How to Remove Duplicate Characters from String in Java

Sometimes, a choice is restricted by putting additional constraint put by the interviewer, that's why it's better to know multiple ways to solve a problem. This not only helps in understanding the problem better but also on comparative analysis.

Solution 1 - Replacing duplicate with NULL character

Our first solution is coded in the method removeDuplicates(String word), it takes a String and returns another String without duplicates. This algorithm goes through each character of String to check if it's a duplicate of an already found character. It skips the duplicate character by inserting 0, which is later used to filter those characters and update the non-duplicate characters.

Tuesday, 7 June 2016

How to Master Your Java Memory (and Save Your Programming)

Solve App Problems 10x Faster with AppDynamics – Monitor production apps at code-level depth with minimal overhead.

You spent countless hours working out the bugs in your Java application and getting its performance where you need it. During the testing, you noticed the application getting progressively slower over time, outright crashing or exhibiting poor performance. You go through your code and make sure you haven’t missed anything else that could cause these problems. Ultimately, you admit that you’re dealing with a memory leak. Java’s garbage collector does what it can to help with these leaks, but there’s only so much it can do when you’re running into major issues. You need a way to identify what’s causing your memory leaks, ways to address the issue and understanding of the role Java garbage collection plays in your overall application performance.

Wednesday, 1 June 2016

Java Certification: To Cert or Not to Cert

Professional certification is always a bit of a controversial subject, with benefits vs. cost/time debated by those who are eligible.  With Oracle’s Java certifications, I hold the opinion that there are two primary audiences that stand to benefit:

  • Those who are starting a career in software. Solid work experience with demonstrable code is always going to be a top hiring consideration by potential employers.  However, in the absence of that, Java certifications are an objective way to demonstrate a base level of proficiency in a related skill.  With a junior programming position opportunity, where candidates have a limited work history, a certification could be the difference between staying in the resume pile and getting into the interview chair.  Similarly, if you have a solid work history, but are applying for a job that focuses on an API you haven’t used on a project, a certification could help bridge that gap in your resume.

Tuesday, 31 May 2016

Getting a name for someone to connect back to your server

When doing test automation it is often the case you need to know the name of the current machine in order to prompt another machine to connect to it, particularly if you are running your tests in parallel. This week I was trying to get the server under test to connect back to a WireMock server running on the slave test machine.
The standard response on stack overflow is to use the following pattern to get a network address. In my version here if we can’t resolve the name then we are assuming we are running on a developers laptop on VPN so all the tests are run on the same machine. (Hence localhost)

String hostName = "localhost";
try {
       InetAddress addr = InetAddress.getLocalHost();
       String suggestedName = addr.getCanonicalHostName();
       // Rough test for IP address, if IP address assume a local lookup
       // on VPN
       if (!suggestedName.matches("(\\d{1,3}\\.?){4}") && !suggestedName.contains(":"))           
       hostName = suggestedName;
       }

} catch (UnknownHostException ex) {

}
System.out.println(hostName);

Friday, 15 April 2016

JLBH – Introducing Java Latency Benchmarking Harness

What is JLBH?

JLBH is a tool that can be used to measure latency in Java programs. It has these features:
  • Aimed at running code that would be larger than a micro benchmark.
  • Suitable for programs that use asynchronous activity like the producer consumer pattern.
  • Ability to benchmark individual points within the program
  • Ability to adjust the throughput into the benchmark
  • Adjusts for coordinated omission i.e. end to end latencies of iterations impact each other if they back up
  • Reports and runs its own jitter thread

Thursday, 18 February 2016

Object-Oriented approach to Code Generation

Code Generation is  a common way to reduce the unhealthy load of boring tasks often put on us eager code grunts. Many code generation frameworks I have seen use a template-replace-repeat approach where you write a template for how the generated code file should look and then replace certain keywords and repeat other sections to produce the specific file you want.

A problem with this approach that annoys me is that it is really difficult to know if the generated code will work or not until you compile it. You might have changed the name of one class and suddenly the generated code won’t build. To handle this issue I started a project called CodeGen that aim to be completely object-oriented so that you can benefit from type-safety all the way from template to executable code. The main user case for the generator is the Speedment software, but it can be used in a variety of projects.

Thursday, 11 February 2016

Decrease your Java IDE lagging by fine tuning JVM Garbage Collector

Ever wondered why Eclipse/Netbeans keeps pausing for a while every now an then? Especially right at the time when you want to show something in the code to your dear colleages? It feelt embarrassing and awkward, didn’t it?

I found out that most of the time the IDE pauses because of Garbage Collector execution. The subtle little element in design of JVM, which usually does great job in relieving us developers from worrying about memory consumption, and most people are just happy that it does its job well and ignore it most of the time. However, the consequences of running Garbage Collector may surprise us if we simply ignore it.

Friday, 29 January 2016

Java Dynamic Proxy

Proxy is a design pattern. We create and use proxy objects when we want to add or modify some functionality of an already existing class. The proxy object is used instead of the original one. Usually the proxy objects have the same methods as the original one and in Java proxy classes usually extend the original class. The proxy has a handle to the original object and can call the method on that.

This way proxy classes can implement many things in a convenient way:
  • logging when a method starts and stops
  • perform extra checks on arguments
  • mocking the behavior of the original class
  • implement lazy access to costly resources

Tuesday, 12 January 2016

Reading/Writing to/from Files using FileChannel and ByteBuffer in Java

In the past, I have talked about RandomAccessFile and how it can be used for doing faster IO in Java, and in this Java NIO tutorial, we are going to see how to use read/write data from using FileChannel and ByteBuffer.

Channel provides an alternate way to read data from a file, it provides better performance than InputStream or OutputStream. It can also be opened in blocking and non-blocking mode. Though, FileChannles are read/write channels and they are always blocking, they cannot be put into non-blocking mode. The RandomAccessFile class treats a file as an array of Bytes.

You can write your data in any position of the Array and you can read from any position. To do that, it uses a pointer that holds the current position and provides several methods like seek() to move that pointer. Once you are at the right position, you can get the FileChannel from RandomAccessFile and starting reading data from a file. By the way, JDK 7 also introduced NIO 2, which makes dealing with files and directory even easier.