Friday, June 30, 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 the 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.

How to create Custom Exception in Java - Tutorial Example

Sometimes we need to create custom Exception in Java, i.e. Exceptions which are not defined in JDK or any third party library your application is using. Though it’s widely recommended on several Exception best practices article, even Joshua Bloch has recommended in Effective Java to prefer standard exception over custom exception, sometimes you really need it. There are certain guidelines to help to find whether you really need a custom exception or not. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.
  •     Do you need an exception type that isn't represented by those in the Java platform?
  •     Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  •     Does your code throw more than one related exception?
  •     If you use someone else's exceptions, will users have access to those exceptions? The similar question is, should your package be independent and self-contained?

Thursday, June 29, 2017

Builder Design pattern in Java - Example Tutorial

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well said necessity is mother on invention. learning design pattern without facing problem is not that effective, Instead if you have already faced issues than its much easier to understand design pattern and learn how its solve the issue. In this Java design pattern tutorial we will first see what problem Builder design pattern solves which will give some insight on when to use builder design pattern in Java, which is also a popular design pattern interview question and then we will see example of Builder design pattern and pros and cons of using Builder pattern in Java. 

Is Joshua Bloch's Effective Java Still Valid in the Era of Java 8?

Effective Java is probably one of the most read books on Java technology and has been regarded by many programmers as the best book for Java developers. Though, recently many Java programmers have asked me whether Effective Java is still relevant in the era of Java 8? Or is there any better book on the same topic. The question is logical because It's been more than 9 years since the 2nd edition of Effective Java released in 2008 and also the most recent Java 8 has changed how you code Java. Many idioms and design patterns of good old days now become redundant and can be done easily with the new Java 8 syntax and feature, but does that mean "Effective Java" is not relevant now? Well, No, not at all. Effective Java is still relevant and a must-read for Java programmers due to several reasons, which you will see in this article.

Wednesday, June 28, 2017

10 xargs command example in Linux - Unix tutorial

xargs command in UNIX or Linux is a powerful command used in conjunction with find and grep command in UNIX to divide a big list of arguments into small list received from standard input. find and grep command produces a long list of file names and we often want to either remove them or do some operation on them but many UNIX operating system doesn't accept such a long list of argument. UNIX xargs command divide that list into sub-list with acceptable length and made it work. This Unix tutorial is in continuation of my earlier post on Unix like 10 examples of chmod command in Unix and How to update soft link in Linux. If you haven’t read those unit tutorials than check them out.

Tuesday, June 27, 2017

2 Ways to check If String is Palindrome in Java? Recursion and Loop

A String is said to be Palindrome if it is equal to itself in reverse order. You can use this logic to check if String is Palindrome or not. There are two common ways to find if a given String is Palindrome or not in Java, first by using for loop, also known as iterative algorithm and second by using recursion, also known as recursive algorithm. The crux of this problem lies in how do you reverse String in Java? because once you have the String in reverse order, problem reduced to just comparing itself with the reversed String. If both are equal then given String is Palindrome otherwise it's not. Also whether your solution is iterative or recursive will also determine by implementing this logic.

10 Java Exception and Error Interview Questions Answers

You will always see some interview questions from Exception and Error handling in core Java Interviews. Exception handling is an important aspect of Java application development and its key to writing robust, stable Java programs, which makes it natural favorites on interviews. Questions from Error and Exception in Java mostly based on the concept of Exception and Error in Java, How to handle Exception , best practices to follow during Exception handling etc. Though multithreading, garbage collection, JVM concepts and questions from object oriented design rules these interviews, you should always expect and prepare some questions on effective error handling.

Monday, June 26, 2017

java.lang.ClassNotFoundException: org.postgresql.Driver - Cause and Solution

java.lang.ClassNotFoundException: org.postgresql.Driver error comes when you are trying to connect to a PostgreSQL database from Java program but Java ClassLoader is not able to find the Driver class "org.postgresql.Driver" required to make the connection. Usually, this class is found in PostgreSQL JDBC driver JAR like postgresql-9.4-1201.jdbc41.jar, which is required to connect the PostgreSQL server version greater than 9.3 from JDK 1.7 or JDK 1.8, the exact JAR depends upon your PostgreSQL server version, the Java version you are running and JDBC version you are using.

How to use CopyOnWriteArraySet in Java with Example

CopyOnWriteArraySet is little brother of CopyOnWriteArrayList class. These are special purpose collection classes which was added on JDK 1.5, along with their most popular cousin ConcurrentHashMap. They are part of concurrent collection framework and reside in java.util.concurrent package. CopyOnWriteArraySet is best suited as read-only collection whose size is small enough to copy if some mutative operation happens, for example you can use CopyOnWriteArraySet to store object at start-up of application and let multiple application thread access them during application life time. If an new condition or object comes up during that time, it can also be added into this Set, with incurring cost of creating a new array.

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, June 25, 2017

List of special bash parameter used in Unix or Linux script

Meaning of bash parameter used in Unix script
Many of us use a bash script for doing housekeeping and other stuff but occasionally and not much aware of special bash parameters. When I was new to the bash shell and Linux and looking for some already written bash script I used to get baffled with special bash symbols like $@, $_, $1, etc. I did know that they are bash parameter and has special meaning but I don't have all meanings of special bash parameter on top of my head and I always go to Google and search endlessly for those special bash parameter, sometimes I got and found the meaning of those special bash script parameters quickly but sometimes I need to spend some time to get what I am actually looking for, so I thought to document meanings and expansion of those special bash parameters or bash script parameters.

Saturday, June 24, 2017

What is -XX:+UseCompressedOops in 64 bit JVM

-XX:+UseCompressedOops JVM command-line option is one of the most talked options of 64 bit JVM. Though 64 bit JVM allows you to specify larger Java heap sizes it comes with a performance penalty by using 64 bit OOPS. Ordinary object pointers also are known as OOPS which is used to represent Java objects in Virtual Machine has an increased width of 64 bit than smaller 32 bit from earlier 32 bit JVM. because of the increased size of OOPS, fewer OOPS can be stored in CPU cache registers which effectively reduced CPU cache efficiency. -XX:+UseCompressedOops enables the use of compressed 32 bit OOPS in 64 bit JVM which effectively compensates the performance penalty imposed by 64 bit JVM without scarifying heap size advantage offered by them.

Friday, June 23, 2017

HashSet in Java – 10 Examples Programs Tutorial

HashSet in Java is a collection that implements Set interface and backed by an HashMap. Since HashSet uses HashMap internally it provides constant time performance for operations like add, remove, contains and size give HashMap has distributed elements properly among the buckets. Java HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don't care about insertion order. Iterator of HashSet is fail-fast and throws ConcurrentModificationException if HashSet instance is modified concurrently during iteration by using any method other than remove() method of iterator class.

How to create HTTP Server in Java - ServerSocket Example

Java has a very good networking support, allows you to write client server application by using TCP Sockets. In this tutorial, we will learn how to create a simple HTTP Server in Java, which can listen HTTP request on a port let's say 80 and can send response to client. Being an HTTP Server, you can connect to it using your browser e.g. Chrome, Firefox or Internet Explorer. Though HTTP is ubiquitous and present everywhere, Java doesn't have a dedicated API to create and parse HTTP request, there is no in built HTTP client library in JDK. Though there is no short of good open source library e.g. you can use Jsoup to parse HTML and can use Apache HttpClient library for sending GET and POST request right from your Java program. By the way, for those who wants to master network programming in Java, I suggest to read Java Network Programming, 4th Addition by Harold, Elliotte Rusty, its very comprehensive and not only covers both TCP/IP and UDP protocols, which are backbone of internet but also dive deep into the HTTP protocol, including REST, HTTP headers, and cookies. Book is very focused on practical and you will find lot of interesting example related to common networking task e.g. writing multi-threaded servers, using non blocking IO and using low level socket classes.

3 Exampls to Convert an Array to ArrayList in Java

How to convert an Array to ArrayList in Java
Have you encountered any situation where you quickly wanted to convert your array to ArrayList or ArrayList to array in Java? I have faced many such situations that motivate me to write these quick Java tips about converting an array to ArrayList and ArrayList to array in Java. Both array and ArrayList are quite common and every Java developer is familiar with this. Former is used to store objects and primitive types while later can only hold objects. The array is part of standard Java fundamental data structure while ArrayList is part of the collection framework in Java.

Thursday, June 22, 2017

JUnit4 Annotations : Test Examples and Tutorial

JUnit4 Annotations are a single big change from JUnit 3 to JUnit 4 which is introduced in Java 5. With annotations creating and running a JUnit test becomes easier and more readable, but you can only take full advantage of JUnit4 if you know the correct meaning of annotations used on this version and how to use them while writing tests. In this
Junit tutorial we will not only understand the meaning of those annotations but also we will see examples of JUnit4 annotations. By the way, this is my first post in unit testing but if you are new here than you may like post 10 tips to write better code comments and 10 Object-oriented design principles for Programmer as well.

2 Ways to Parse CSV Files in Java - BufferedReader vs Apache

In last tutorial, you have learned how to parse Excel file in Java and in this Java tutorial, you will learn how to parse CSV file in Java. You can directly parse CSV file in Java without using any third party library, because ultimately its a text file and you can use BufferedReader to read it, but you can also take advantage of good open source library like Apache commons CSV to parse comma separated values. These library makes developer's life easy and provides rich functionality to parse various CSV formats. In real programming world, CSV or comma separated files are used for variety of purpose, including for transporting data from one system to another e.g. FX rates, importing and exporting records from database etc. In CSV files entries are separated by comma, and it may or may not contain header. There are many ways to parse or read CSV files in Java, and if you need to do it on your project, its better not to reinvent the wheel and choose commons csv, but for learning purpose, it's good to know how to do it without using third party library.

Wednesday, June 21, 2017

3 Ways to Find Duplicate Elements in an Array - Java

There are multiple ways to find duplicate elements in an array in Java and we will see three of them in this program. The solution and logic shown in this article are generic and apply to an array of any type e.g. String array or integer array or array of any object. One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes. You shouldn't be using this solution in the real world.

Tuesday, June 20, 2017

10 example of using Vim or VI editor in UNIX and Linux

Vim or VI editor tutorial in UNIX 
VI Editor is like notepad in UNIX but it’s extremely powerful and has a sophisticated feature to work as complete IDE. No matter which version of UNIX you are working or which flavor you are using you always find either VI editors or VIM there. VI is a very large topic and I am not covering every aspect of it what I am sharing here is some examples of using VI editor in UNIX or Linux. most of the time we use only 10% of VI editor and never know 90% of it, to be frank, I also don't know many of VI features by heart but I always search for it, see people working in VI and learn from their experience as well.

Monday, June 19, 2017

Java Lock and Condition Example using Producer Consumer Solution

You can also solve the producer-consumer problem by using a new lock interface and condition variable instead of using the synchronized keyword and wait and notify methods.  The lock provides an alternate way to achieve mutual exclusion and synchronization in Java. Advantage of Lock over synchronized keyword is well known, explicit locking is much more granular and powerful than synchronized keyword, for example, the scope of lock can range from one method to another but the scope of synchronized keyword cannot go beyond one method. Condition variables are instance of java.util.concurrent.locks.Condition class, which provides inter-thread communication methods similar to wait, notify and notifyAll e.g. await(), signal(), and signalAll().

3 ways to solve java.lang.NoClassDefFoundError in Java J2EE

I know how frustrating is to see Exception in thread "main" java.lang.NoClassDefFoundError,  which is a manifestation of NoClassDefFoundError in Java. I have seen it a couple of times and spent quite a lot time initially to figure out what is wrong, which class is missing etc. The first mistake I did was mingling java.lang.ClassNotfoundException and NoClassDefFoundError, in reality, they are totally different, and my second mistake was using trial and error method to solve this java.lang.NoClassDefFoundError instead of understanding why NoClassDefFoundError is coming, what is the real reason behind NoClassDefFoundError and how to resolve this. In this Java tutorial, I have tried to rectify that mistakes and uncover some secrets of NoClassDefFoundError in Java and will share my experience around it. NoClassDefFoundError is not something which cannot be resolved or hard to resolve it’s just its manifestation which puzzles most of Java developer. This is the most common error in Java development along with java.lang.OutOfMemoroyError: Java heap space and java.lang.OutOfMemoryError: PermGen space  Anyway lets’s see Why NoClassDefFoundError comes in Java and what to do to resolve NoClassDefFoundError in Java.

Sunday, June 18, 2017

How to Add Two Integer Numbers without using Plus + or ++ Arithmetic Operator in Java - Recursion example

In this article, we will take a look at another interview question about adding two numbers, but without using + or ++ operator. The interview starts with a simple statement, Can you write a function to add two numbers (integers) without using + or plus arithmetic operator in Java? If you are good at maths, it wouldn’t take more than a second to say that, we can use subtraction or - operator to add two numbers because a-(-b)== a+b. Well, that’s correct, but real question starts when the interviewer quickly points out that, you can not use any arithmetic operator including +,-,*,/++ or --. Programming and Coding questions are an integral part of any Java interview. You should always expect a couple of questions like this, e.g. swapping two numbers without using a temp variable. If you have been giving interviews, then you know that it will eventually come downs to the bitwise operator in Java. 

How to Close Java Program or Swing Application with Example

In order to close the Java program, we need to consider which kind of Java application it is?, because termination of Java application varies between normal core java program to swing GUI application. In general, all Java program terminates automatically once all user threads created by program finishes its execution, including main thread. JVM doesn't wait for daemon thread so as soon as the last user thread finished, Java program will terminate. If you want to close or terminate your java application before this your only option is to use System.exit(int status) or Runtime.getRuntime().exit().

Saturday, June 17, 2017

How to use Comparator and Comparable in Java? With example

Comparator and Comparable in Java Examples
Difference between Comparator and Comparable in Java is very popular Java interview question mostly asked in telephonic round and writing code to sort object using Comparable or Comparator is popular on  written test round of interview.The question was this “How you will sort Employee object based on his EmployeeID and his name” and this involves the use of both Comparable as well as Comparator interface in Java. This post is my revision on Java fundamentals similar to I did about equals method in Java and  some tips to override hashCode in Java. All of these methods are fundamentals in Java programming language and correct understanding is must for any Java developer. Comparators and comparable in Java are two interfaces which is used to implement sorting in Java. It’s often required to sort objects stored in any collection classes like ArrayList, HashSet or in Array and that time we need to use either  compare() or  compareTo() method defined in java.util.Comparator and java.lang.Comparable. In this Java tutorial we will see example of  Comparator and Comparable to sort object in Java and discuss some best practices around when to use Comparator interface etc. Any way before moving ahead Let’s see some important differences between Comparable and Comparator in Java.

How to use Callable and Future in Java? Example

A callable interface was added in Java 5 to complement the existing Runnable interface, which is used to wrap a task and pass it to a Thread or thread pool for asynchronous execution. Callable actually represent an asynchronous computation, whose value is available via Future object. All the code which needs to be executed asynchronously goes into the call() method. Callable is also a single abstract method type (SAM type), so it can be used along with lambda expression on Java 8. Both Callable and Future are parametric types and can be used to wrap classes like Integer, String, or anything else.

How to Count number of Set bits or 1's of Integer in Java?

There are multiple ways to count the number of 1's or set bits in a integer number in Java. You can use a bitwise and bit shift operator by your own, or, you can use Java API to count number of set bits. Java 1.5 added two utility method called bitCount(int i) which returns number of 1's in your integer number, java.lang.Long class has similar bitCount(long number) for long primitives. As I have said earlier, Coding questions are an important part of any Java interview, and from that recursion and bitwise operations are most popular. Questions like, How to Swap two numbers without temp variable or How to find if a number is positive or negative are some of such questions, which you see now and then in various Java interviews.

Thursday, June 15, 2017

JDBC Database Connection Pool in Spring Framework – How to Setup Example

Setting up JDBC Database Connection Pool in Spring framework is easy for any Java application, just matter of changing a few configurations in the spring configuration file. If you are writing core java application and not running on any web or application server like Tomcat or  Weblogic,  Managing Database connection pool using Apache Commons DBCP and Commons Pool along-with Spring framework is a nice choice but if you have the luxury of having web server and managed J2EE Container, consider using Connection pool managed by J2EE server those are a better option in terms of maintenance, flexibility and also help to prevent java.lang.OutofMemroyError: PermGen Space in tomcat by avoiding loading of JDBC driver in web-app class-loader.

How to Connect to MySQL database in Java with Example

In this tutorial, You will learn how to connect to MySQL database from Java program and running SELECT and INSERT queries to retrieve and update data with step by step guide. In order to connect and access the MySQL database from Java, you can use JDBC (Java Database Connectivity) API, which is bundled in JDK itself. JDBC allows you to connect to any database like Oracle, SQL Server, or MySQL, provided you have the vendor's implementation of the JDBC driver interface, which is required to connect the database. You can connect to MySQL from Java by using MySQL's Type 4 JDBC driver which is bundled in mysql-connector-java-5.1.23-bin.jar. It's type 4, pure Java driver, which means you don't need any native library or JDBC ODBC bridge, all you need is to put this JAR in your classpath.

Monday, June 12, 2017

How to converts Java Object to XML - JAXB Example

JAXB, stands for Java API for XML Binding or sometimes Java Architecture for XML Binding is a decade old technology to directly convert a Java object into XML document (marshaling) and back to XML file into Java object(unmarshalling). It uses a combination of annotations and getters and setters to marshal Java object into XML. JAXB actually defines the behavior of a standard set of tools and interfaces that automatically generate Java class files from XML schema, remember JAXB is actually a framework and architecture, not an implementation. The package java.xml.bind provides a runtime binding framework for clients to marshal, unmarshal and validate XML file in Java.

Sunday, June 11, 2017

Is Java Compiled or Interpreted Programming language?

One of the first question a graduate C or C++ programmer, who has just started learning Java ask is, whether Java is a compiled language or an interpreted one? On academic courses or during college, students learn a lot of languages e.g. VB, C, C++ and they happily categories them as either compiled or interpreted, but with Java it's tricky. It's not clear whether Java is compiled or interpreted, because it neither generate machine language code after compiling source file,  neither interpreted source file to execute instruction line by line. In order to answer this question you need to fist know that Java is a platform independent language? Which means you can run a Java program to any platform, which includes hardware + operating system, without any modification. Knowing how Java achieves platform independence is key to answer this question.

How to Generate MD5 checksum for Files in Java

MD5 checksums are good to verify the integrity of files and It's easy to generate MD5 checksum in Java. Java provides a couple of ways to generate the MD5 checksum for any file, you can either use java.security.MessageDigest or any open source library like Apache commons codec or Spring. All 3 ways we have seen in our earlier article about generating the MD5 hash for String is also applicable to generate the MD5  checksum for any file. Since most of the md5() or md5Hex() method takes byte[], you can simply read bytes from InputStream or pass to these md5 methods. Apache commons codec from version 1.4 also provides an overloaded method for accepting InputStream, which makes generating checksum very easy in Java. For those who are not familiar with checksum, it's a fixed-size datum generated from a block of data to detect any accidental change in data. 

Jersey Web Service Hello World Example in Java

After Restlet, Jersey is another popular open-source framework to create RESTful web services in Java. Jersey conforms JAX-RS specification and actually it is the reference implementation of JAX-RS (JSR 311)(http://jsr311.java.net/nonav/releases/1.1/index.html) specification. In the last article, we have seen the Restlet HelloWorld Example and today we'll see the Jersey HelloWorld Example. Typically, when a developer thinks of creating a RESTful web service using Java, they assume that using a Java EE application server is the only way to create this type of application.

Saturday, June 10, 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.

How to Read Write Excel file in Java - POI Example

In this Java Excel tutorial, you will learn how to read and write from Excel file in Java . You will learn steps to read/write both XLS and XLSX file format by using Apache POI library. In this example, we will particularly focus on reading and writing String and Date values into Excel file as writing dates are little bit tricky. In our earlier Java Excel tutorial, you have already learned how to read/write Numeric types from Excel in Java, but we haven't touched date values, which are also stored as numeric types, we will learn that in this tutorial. There are two parts of this tutorial, in first part we will write date and String values into XLS file and in second part we will read them from XLS file. You might aware that Excel file now comes with two formats, XLS file which is an OLE format and XLSX format, which is also known as OpenXML format. Apache POI supports both format but you would need different JAR files to read/write XLS and XLSX files. You need poi-3.12.jar to read XLS file and poi-ooxml-3.12.jar to read XLSX file in Java.

Top 30 Programming questions asked in Interview - Java C C++ Answers

Top 30 Programming interview questions
Programming questions are an integral part of any Java or C++ programmer or software analyst interview. No matter which language you have the expertise it’s expected that you are familiar with the fundamentals of programming and can solve problems without taking the help of API. Programming questions like reversing String using recursion or How to find if Array contains duplicates are some popular examples of programming question in Java. Programming questions present a lot of challenges Especially to Java developers as compared to C++ programmer and I think, One reason for this is powerful Java API; Which has a method for almost every need and you rarely need to write by your own or there are lots of third-party library from Apache, Spring, Google and other open sources.

Friday, June 9, 2017

10 Interview Questions on Java Generics for Programmer and Developers

Generic interview questions in Java interviews are getting more and more common with Java 5 around there for a considerable time and many applications either moving to Java 5 and almost all new Java development happening on Tiger(code name of Java 5).  Importance of Generics and Java 5 features like Enum,  Autoboxing, varargs and Collection utilities like CountDownLatch, CyclicBarrier and BlockingQueue are getting more and more popular on Java interviews. Generic interview question can get real tricky if you are not familiar with bounded and unbounded generic wildcards, How generics works internally, type erasure and familiarity with writing parametrized generics classes and methods in Java.

SynchronousQueue Example in Java - Produer Consumer Solution

SynchronousQueue is a special kind of BlockingQueue in which each insert operation must wait for a corresponding remove operation by another thread and vice versa. When you call to put() method on SynchronousQueue it blocks until another thread is there to take that element out of the Queue. Similarly, if a thread tries to remove an element and no element is currently present, that thread is blocked until another thread puts an element into the queue. You can correlate SynchronousQueue with athletes (threads) running with Olympic torch, they run with a torch (object need to be passed) and passes it to other athlete waiting at another end.

java.lang.NullPointerException - Common Cause of NullPointerException in Java Example

The java.lang.NullPointerException or NullPointerException in Java is probably the first Exception you will face in Java. It is true nightmare for beginners in Java but pretty easy to solve once you get familiar with Exception handling in Java. What makes NullPointerException little tricky is its name which has pointer in itself and Java does not support pointers like multiple inheritance in Java . In this article we will see What is NullPointerException in Java, How to solve Exception in thread "main" java.lang.NullPointerException, finding possible cause of Java NullPointerException and how to troubleshoot NPE in Java.

Thursday, June 8, 2017

Top 30 Array Interview Questions and Answers for Programmers

The array is one of the most important topics for programming interviews. It doesn't matter if you are going to Google, Microsoft, Amazon or investment banks like Goldman Sachs, Barclays, Citi or even service-based companies like IBM, Accenture, TCS, or Infosys, if you are going to interview for the developer position, you must prepare array very well. In fact, it is the second most topic after String and if you look closely, may of String coding problems can be solved by treating them like character array. The array is also ubiquitous, no matter which programming language you choose, you will find array there, it's available in C, C++, Java and even on Python, Perl, and Ruby.

Wednesday, June 7, 2017

10 Examples of Date Command in Linux and UNIX

Date command in UNIX or Linux is one of the important commands to learn and master because we always need date information. no matter you want to know the current date in UNIX or your bash script needs a current date in UNIX for archiving purposes you need to use date command. In its simplest format date command shows the current date and time in UNIX while with a sophisticated option we can extract much useful information from UNIX date command. In this Unix command tutorial, we will see some useful tips on using date command in UNIX and learn more around the date in UNIX and Linux.

Tuesday, June 6, 2017

Exception in thread "main" java.lang.ExceptionInInitializerError in Java Program

JVM throws java.lang.ExceptionInInitializerError, when there is an Exception inside static initializer block. If you know about static variable in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException. Java developers often confused with this error because, they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in source file.

How to get current URL, parameters and Hash tag using JQuery and JavaScript

While dealing with the current URL, many times you want to know what is the current URL path, What are the parameters, and what is the hashtag on the URL. The hashtag is pretty important if you are implementing a tab structure using HTML and JQuery. To avoid confusion, let's take an example of a URL: http://javarevisited.blogspot.com/2013/01/top-5-java-programming-books-best-good.html#ixzz2PGmDFlPd , in this example ixzz2PGmDFlPd, is a hashtag. Now, both JavaScript and JQuery provides a convenient way to retrieve the current URL in the form of window.location object. You can use various properties of the window.location JavaScript object like the window.location.href to get complete URL, window.location.pathname to get the current path, and window.location.hash to get a hashtag from current URL.

Monday, June 5, 2017

How to get JAR files of Jackson Libary for JSON Processing

If you are using Jackson to parse a JSON String in Java first time and wondering where can you get the Jackson related JARs, or which JAR files are really need then you have come to the right place. It can be really confusing for a new user to set up or include Jackson library in their Java projects sometimes, especially, if you are not very familiar with the structure of Jackson projects, various JAR files and in particular Maven. Since Jackson is the most popular open source library for processing JSON responses e.g. generating Java objects from JSON received from RESTful Web services or generating JSON String from Plain Old Java Objects (POJO). It is the go-to library for any JSON need because it offers a lot of features without compromising on performance.

Sunday, June 4, 2017

5 Reasons to Use Composition over Inheritance in Java and OOP

Favor composition over inheritance is a one of the popular object-oriented design principles, which helps to create flexible and maintainable code in Java and other object-oriented languages. Many times I have seen people suggesting use composition instead of inheritance, in fact, my favorite books like Head first Design Patterns also advocates this design principle. Head first books have its own way of explaining, why composition is better than inheritance and though its long its quite interesting and informative. It was the first chapter of this book, which helped me a lot on understanding this key OOP concept. 

Saturday, June 3, 2017

What is the cost of Spring Framework Certification and Training in India and USA?

One of the frequently asked questions about Spring certifications and training e.g. Spring Core and Spring Web Application Developer Certification is their cost e.g. what is the cost of Spring certification in India? or how much it cost for Spring framework certification in the USA etc. Earlier, Spring certification used to cost around 3000 USD in the USA and other North American countries and around 50,000 INR in India due to mandatory training you needed to take before you can appear in the exam. The cost of the Spring framework training was more than 90% of the total cost of the Spring certification. But gone are those days. Since 10th May 2017, you can take the exam without mandatory training, see here. Due to this reason, the cost of Spring certification has come down heavily and it's just now the cost of the exam voucher which is just 200 USD globally.

How Volatile in Java works? Example of volatile keyword in Java

How to use Volatile keyword in Java
What is a volatile variable in Java and when to use the volatile variable in Java is a famous multi-threading interview question in Java interviews? Though many programmers know what is a volatile variable they fail on the second part i.e. were to use volatile variables in Java as it's not common to have a clear understanding and hands-on on volatile variables in Java. In this tutorial, we will address this gap by providing a simple example of the volatile variable in Java and discussing some when to use the volatile variable in Java. Anyway,  the volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache the value of this variable and always read it from the main memory.

Google Protocol Buffers (ProtoBuf) - Java Serialization Alternative

If you have done some serialization works in Java, then you know that it's not that easy. Since the default serialization mechanism is not efficient and has a host of problems, see Effective Java Item 74 to 78, it's really not a good choice to persist Java object in production. Though many of the efficiency shortcomings of default Serialization can be mitigated by using a custom serialized format, they have their own encoding and parsing overhead. Google protocol buffers, popularly known as protobuf is an alternate and faster way to serialize Java objects. It's a good alternative to Java serialization and useful for both data storage and data transfer over the network.

2 Examples to read Zip Files in Java, ZipFile vs ZipInputStream

ZIP format is one of the most popular compression mechanism in computer world. A Zip file may contains multiples files or folder in compressed format.  Java API provides extensive support to read Zip files, all classes related to zip file processing are located in java.util.zip package. One of the  most common task related to zip archive is to read a Zip file and display what entries it contains, and then extract them in a folder. In this tutorial we will learn how to do this task in Java. There are two ways you can iterate over all items in a given zip archive, you can use either java.util.zip.ZipFile or java.util.zip.ZipInputStream. Since a Zip file contains several items, each of them has header field containing size of items in number of bytes. Which means you can iterate all entries without actually decompressing the zip file.

How to find CPU and Memory used by Java process in Solaris – prstat command example

We often need to find CPU and memory utilization of a particular Java process in order to get some performance stats, capacity planning or just to understand the current load on the system. Performance monitoring and testing is an integral part of any Java application development, especially if you are working in high-frequency trading space. In order to fix a performance problem, you have to find them first and knowledge of the right tools and commands helps there. One of the primary cause of poor application performance is it Java or any other process is the exhaustion of important resources like CPU and memory.

20 Design Patterns and Software Design Interview Questions for Programmers

Design patterns and software design questions are an essential part of any programming interview, no matter whether you are going for Java interview or C#  interview. In fact, programming and design skills complement each other quite well, people who are good programmers are often good designers as well as they know how to break a problem in to piece of code or software design but these skills just don’t come. You need to keep designing, programming both small scale and large scale systems, and keep learning from mistakes. Learning about Object-oriented design principles is a good starting point. Anyway, this article is about some design questions which have been repeatedly asked in various interviews.

Thursday, June 1, 2017

Difference between Inheritance and Composition in Java OOPS

Though both Inheritance and Composition provide 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.