Monday, July 31, 2017

JQuery Selectors Examples to find elements in DOM - ID, Class, Element, Descendent, Child, Multiple and Pseudo Selector

jQuery selectors are like CSS Selectors, which allows you to find or select an element from DOM tree. When an HTML pages loaded in a browser like Chrome, Firefox or Internet Explorer, the browser creates a tree-like structure is known as Document Object Model or DOM. JavaScript and jQuery allow you to play with this DOM i.e. selecting elements from DOM, traversing through DOM, going from one element to another, selecting a list of elements from DOM, adding or removing elements from DOM etc. In order to apply most of the jQuery function, available in the jQuery object, we first need to select HTML elements or tags, on which we want to apply those function, jQuery selector allows you to choose those elements. There are many JQuery selectors e.g. ID selector, class selector or element selector, which provides the capability to choose only elements you need. In this JQuery tutorial, we will take a look at these jQuery selectors, and simple example to learn how to use them. 

How to Create Read Only List, Map and Set in Java – UnModifiable Collection Example

Read only List, Map and Set in Java
A read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for a certain requirement where parameters are final and can not be changed. In Java, you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read-only Map in Java, as shown in below example. Any modification in read only List will result in java.lang.UnSupportedOperationException in Java.  This read-only List example is based on Java 5 generics but also applicable  to other Java versions like JDK 1.4 or JDK 1.3, just remove Generics code i.e. angle bracket which is not supported prior to Java 5. One common mistake programmer makes is that assuming fixed size List and read only List as same. 

Sunday, July 30, 2017

How to Load Resources from Classpath in Java with Example

Classpath in Java is not only used to load .class files, but also can be used to load resources e.g. properties file, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL. Suppose, you have a properties file inside config folder of your project, and you want to load that properties file, how do you do that? Similarly, you have icons and thumbnails for your web applications on icons directory of your project, how do you load them? Answer is by using java.lang.Class' getResource() and getResourceAsStream() method. These method accepts path of resource as String and returns URL and InputStream respectively. You can obtain a reference of Class by calling either getClass() method or by using class literal. If you have an object, then you can call getClass() because its a non-static method, on the other hand, if you don't have any object, you can simply use .class with name of any class e.g. Sample.class will give you reference of java.lang.Class. These methods are available from JDK 1.1 and you can even use them anywhere you have access to core Java library. If you are creating J2ME games or application, you can use these method to load icons and tiles for your game, and all other resource for your application as well.

Saturday, July 29, 2017

Top 5 Data Structure and Algorithm Books - Must Read, Best of Lot

Data Structure and Algorithms books are often taught as textbooks in various universities, colleges, and Computer Science degree courses, yet, when you put programmers in a situation, where they need to find and decide, which data structures and algorithms to use to solve a problem, they struggle. I have seen this, and I think one reason for this is perspective. When you read something as a textbook and your perspective is just to do well in the exam, you might not be thinking about learning and applying that knowledge to real-world problems. Since data structures and algorithms are the core of any programming problem, it becomes extremely important for programmers to master them even if you have learned well during academics.

How to sort a Map by keys in Java 8 - Example Tutorial

In the last article, I have shown you how to sort a Map by values in Java 8 and in this tutorial, you will learn how to sort a Map by keys e.g. an HashMap, ConcurrentHashMap, LinkedHashmap, or even Hashtable. Theoretically, you cannot sort a Map because it doesn't provide any ordering guarantee. For example, when you iterate over a HashMap, you don't know in which order entries will be traversed because HashMap doesn't provide any ordering. Then, how can you sort a Map which doesn't support order? Well, you can't and that's why you only sort entries of HashMap but you don't store the result back into HasMap or any other Map which doesn't support ordering. If you do so, then sorting will be lost.

Friday, July 28, 2017

What is CountDownLatch in Java - Concurrency Example Tutorial

What is CountDownLatch in Java
CountDownLatch in Java is a kind of synchronizer which allows one Thread  to wait for one or more Threads before starts processing. This is very crucial requirement and often needed in server side core Java application and having this functionality built-in as CountDownLatch greatly simplifies the development. CountDownLatch in Java is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap and BlockingQueue in java.util.concurrent package. In this Java concurrency tutorial we will  what is CountDownLatch in Java, How CountDownLatch works in Java, an example of CountDownLatch in Java and finally some worth noting points about this concurrent utility. You can also implement same functionality using  wait and notify mechanism in Java but it requires lot of code and getting it write in first attempt is tricky,  With CountDownLatch it can  be done in just few lines. CountDownLatch also allows flexibility on number of thread for which main thread should wait, It can wait for one thread or n number of thread, there is not much change on code.  Key point is that you need to figure out where to use CountDownLatch in Java application which is not difficult if you understand What is CountDownLatch in Java, What does CountDownLatch do and How CountDownLatch works in Java.

Default, Defender or Extension Method of Java 8 with Example

Java 8 now allows you to add non-abstract method implementations to interfaces by utilizing the default and static keyword. Methods with default keyword are known as default methods or defender methods in Java. Before Java 8, it was virtually impossible to change an interface once published. Any change e.g. addition of a new method would have broken all clients. That's why when Java 8 decided to switch to internal iterator implementation using forEach() method, they face a daunting challenge of breaking all implementation of Iterable interface. Since backward compatibility is top priority for Java engineers, and it wasn't practical to break all clients, they came up with idea of default method.

What is CyclicBarrier Example in Java 5 – Concurrency Tutorial

What is CyclicBarrier in Java
CyclicBarrier in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with other concurrent utility like Counting Semaphore, BlockingQueue, ConcurrentHashMap etc. CyclicBarrier is similar to CountDownLatch which we have seen in the last article  What is CountDownLatch in Java and allows multiple threads to wait for each other (barrier) before proceeding. The difference between CountDownLatch and CyclicBarrier is an also very popular multi-threading interview question in Java. CyclicBarrier is a natural requirement for a concurrent program because it can be used to perform final part of the task once individual tasks  are completed. All threads which wait for each other to reach barrier are called parties, CyclicBarrier is initialized with a number of parties to wait and threads wait for each other by calling CyclicBarrier.await() method which is a blocking method in Java and  blocks until all Thread or parties call await(). In general calling await() is shout out that Thread is waiting on the barrier. await() is a blocking call but can be timed out or Interrupted by other thread. In this Java concurrency tutorial, we will see What is CyclicBarrier in Java  and  an example of CyclicBarrier on which three Threads will wait for each other before proceeding further.

Thursday, July 27, 2017

How to Calculate Difference between two Dates in Java (In Days)

If you are not running on Java 8, then there are two ways to calculate the difference between two dates in Java in days, either by using standard JDK classes e.g. java.util.Date and java.util.Calendar or by using the joda-time library. Unfortunately, Java's old Date and Calendar API is buggy and not intuitive, so many of us by default use Joda for all date and time arithmetic. In this example, you will learn how to find  the number of days between today and any date entered by a user using Joda, as well as without using any third party library. When I first time face this problem, I thought what's a big deal about finding the difference between dates? If you can convert Date to milliseconds then finding a number of days, months or years are just a matter of simple arithmetic, but I was WRONG. I was not thinking about real world date and time nuisance like leap seconds, leap years, and daylight saving time.

Tuesday, July 25, 2017

When a class is loaded and initialized in JVM - Java

Classloading and initialization in Java
Understanding of when a class is loaded and initialized in JVM is one of the fundamental concept of Java programming language. Thanks to Java language specification we have everything clearly documented and explained, but many Java programmer still doesn't know when a class is loaded or when a class is initialized in Java. Class loading and initialization seems confusing and complex to many beginners and its true until having some experience in belt its not always easy to get into subtle details of How JVM works in Java. In this Java tutorial we will see when class loading occurs in Java and when and how class and interface are initialized in Java. I will not go into detail of ClasLoader or How ClassLoader works in  Java, that is subject of another post I am planning. just to keep this article focused and concise. There are several articles on Java fundamentals in Javarevisited like How HashMap works in Java and How Garbage collection works in Java. If you are interested you can also check those.

java.sql.SQLException: No suitable driver found for jdbc:jtds:sqlserver - Cause and Solution

java.sql.SQLException: No suitable driver found for 
There are two ways to connect Microsoft SQL Server from Java program, either by using Microsoft's official JDBC driver (sqljdbc4.jar), or by using jTDS driver (jtds.jar). This error comes when your supplied database URL didn't match with the JDBC driver present in the CLASSPATH. Many programmers who usually use jtds.jar, makes a mistake while using sqljdbc4.jar by adding "microsoft" in JDBC URL. That makes URL invalid and JDBC API throws "java.sql.SQLException: No suitable driver : sqljdbc4.jar" error.

Monday, July 24, 2017

File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial

Uploading File to the server using Servlet and JSP is a common task in Java web application. Before coding your Servlet or JSP to handle file upload request, you need to know a little bit about File upload support in HTML and HTTP protocol. If you want your user to choose files from the file system and upload to the server then you need to use <input type="file"/>. This will enable to choose any file from the file system and upload to a server. Next thing is that form method should be HTTP POST with enctype as multipart/form-data, which makes file data available in parts inside request body. Now in order to read those file parts and create a File inside Servlet can be done by using ServletOutputStream. It's better to use Apache commons FileUpload, an open source library. Apache FileUpload handles all low details of parsing HTTP request which conform to RFC 1867 or "Form-based File upload in HTML” when you set form method post and content type as "multipart/form-data".

Sunday, July 23, 2017

3 Ways to Read File line by line in Java 8? Examples

Java 8 has added a new method called lines() in Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed. So, if you have a huge file and you only read first 100 lines then rest of the lines will not be loaded into memory, which results in better performance. This is slightly different than Files.readAllLines() method (which reads all lines into a List) because this method reads the file lazily, only when a terminal operation is called on Stream e.g. forEach(), count() etc. By using count() method you can actually count a number of lines in files or number of empty lines by filtering empty lines.

How to read file line by line in Java - BufferedReader Scanner Example Tutorial

Line by Line reading in Java using BufferedReader and Scanner
There are multiple ways to read file line by line in Java. Most simple example of reading file line by line is using BufferedReader which provides method readLine() for reading file. Apart from generics, enum and varargs Java 1.5  has also introduced several new class in Java API one of the  utility class is Scanner, which can also be used to read any file line by line in Java. Though BufferedReader is available in Java from JDK 1.1,  java.util.Scanner provides more utility methods compared to BufferedReader. Scanner has method like hasNextLine() and nextLine() to facilitate line by line reading of file's contents. nextLine() returns String similar to  readLine() but scanner has more utility methods like nextInt(), nextLong() which can be used to directly read numbers from file instead of converting String to Integer or other Number classes. By the way Scanner is rather new approach for reading file and BufferedReader is the standard one. This is my 6th tutorial on Java IO,  In last couple of post we have seen creating file and directory in Java, parsing XML files using DOM and how to read properties file in Java. In this post we will focus on reading file line by line in Java using both BufferedReader and Scanner.

Java ArrayList and HashMap Performance Improvement in JDK 7

From long time one reason for me to update to newer Java version was always bug fix and performance improvement. Apart from major changes like Generics in Java 1.5 and Lambdas in Java 8, there are so many small improvements, performance optimization which just goes under radar, one of such change is creating empty ArrayList and HashMap with size zero in JDK 1.7.0_40 update. Many Java developer doesn't even know about these changes, part of the blame lies on Java developers like me, as I hardly read release notes of minor Java updates. Some times these changes are done as part of bug fixes and other time as minor optimization, but given popularity of ArrayList and HashMap in Java application impact of this simple Java optimization is huge.

How to create Thread Pools using Java 1.5 Executor Framework - Example Tutorial

Java 1.5 introduced Thread pool in Java in the form of Executor framework, which allows Java programmer to decouple submission of a task to execution of the task. If you are doing server side programming in Java than Thread pool is an important concept to maintain scalability, robustness, and stability of the system. For those, who are not familiar with thread pool in Java or concept of thread pool here is one liner, Thread pool in Java is a pool of worker threads, which is ready to perform any task given to them, mostly in the form of implementation of Runnable or Callable interface. Since Java supports multithreading in programming language itself, it allows multiple threads to run concurrently and perform parallel processing of the task. In this article, we will learn following things about thread pool in Java :
  1. What is Thread pool in Java?
  2. Why do we need Thread pool in Java ?
  3. What is Executor framework in Java 5?
  4. How to create fixed size thread pool using Executor framework in Java?
  5. Benefits of using Thread Pool in Java?

Saturday, July 22, 2017

Top 50 Java Programs from Coding Interviews

Coding is an integral part of any programming job interviews, and Java development interviews are no exception. I would even suggest you should never hire anyone without testing their coding skill, coding is also an art, and more often than a good code is an excellent developer as well. If you look at tech giants like Amazon, Facebook, and Google they thoroughly test the coding skill of any developer they hire, notably Amazon who first send online coding exercises to filter Java programmers who can code. This online test usually gives you requirements and ask you to write a program in a limited time, usually 2 to 3 hours. The application should meet the output provided by the exercise itself. These type of tasks are very tough to crack if you don't have excellent coding skill.

How to use Java 1. 7 Multiple Catch Block with example - JDK 7 tutorial

As the release of JDK 7 approaching General Availability (GA) on 2011/07/28, I thought to have a look on language enhancement as part of project coin, also called as Small language enhancements or JSR 334. Though there are not any major changes like Enum or Generics of Java 1.5,  but they are still very useful, in terms of simplifying your day to day programming task. Some of the interesting changes are allowing String in Switch cases, inclusion of fork-join framework in JDK itself , type inference using a diamond operator, automatic resource management using  try with resource feature, and ability to catch multiple Exception in the single catch block . In this Java 7 tutorial, we will learn how multi catch block of JDK 1.7 makes Exception handling code simpler and elegant. Multiple catch block will allow you to catch multiple exceptions in one block but it’s only available in JDK7 and you need to compile your code with source 1.7. 

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

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

Friday, July 21, 2017

How to Read XML File as String in Java? 3 Examples

Suppose you have an XML file and you just want to read and display the whole file as String in Java, may be for debugging purpose. If you are wondering how to do that in Java, well there are many ways to read XML as String in Java. You can do it in one line if you are fine with using an open source library or you can do it in a couple of lines of code in core Java as well. Since an XML file is also a file, you can use BufferedReader or FileInputStream to read the content of an XML file as String by using the techniques, I have discussed in my earlier post 3 ways to convert InputStream to String in Java. But this post is about a new library called jcabi-xml which makes working with XML file really easy. You can parse the XML file using XPath expression, you can do XSL transformation, XSD schema validation and you can even parse whole XML file as String in just a couple of lines of code.

Difference between get and load in Hibernate

get vs load in Hibernate
Difference between get and load method in Hibernate is a one of the most popular question asked in Hibernate and spring interviews. Hibernate Session  class provides two method to access object e.g. session.get() and session.load() both looked quite similar to each other but there are subtle difference between load and get method which can affect performance of application. Main difference between get() vs load method is that get() involves database hit if object doesn't exists in Session Cache and returns a fully initialized object which may involve several database call while load method can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object. This lazy initialization can save couple of database round-trip which result in better performance.

By the way there are many articles on interview questions in Java, you can use search button on top left to find them. Some of them like 20 design pattern interview questions and 10 Singleton pattern questions are my favorites, you may also like. Coming back to article, you can find more difference between load and get in rest of this article in point format but this is the one which really makes difference while comparing both of them. If you look at how get and load gets called its pretty identical.

Wednesday, July 19, 2017

How to convert String or char to ASCII values in Java

You can convert a character e.g. 'A' to its corresponding ASCII value 65 by just storing it into a numeric data type e.g. byte, int or long as shown below :

int asciiOfA = (int) 'A';

Here casting is not necessary, simply assigning a character to integer is enough to store ASCII value of character into an int variable, but casting improves readability. Since ASCII is 7-bit character encoding, you don't even need an integer variable to store ASCII values, byte data type in Java, which is 8 bits wide is enough to store ASCII value of any character.  So you can also do like this :
byte asciiOfB = 'B'; // assign 66 to variable

Tuesday, July 18, 2017

How to Configure HTTPS (SSL) in Tomcat 6 and 7 Java Web Server

Setting SSL (Secure Socket Layer) in Tomcat is often a requirement, especially while developing  secure web application, which requires access over https protocol. Since Tomcat web server doesn't provide SSL settings by default, you need to know how to configure SSL in tomcat, and even worse it varies between different tomcat versions. for Example SSL setup which works on tomcat 6, doesn't work as it is in tomcat 7. In this article we will see, how to configure tomcat for https in both tomcat 6 and 7. For those programmers who are not very familiar with SSL and https here is a quick overview of SSL, certificates and https, and I suggest reading that article to get better understanding of How SSL works and How websites are accessed security over internet.

What is Autoboxing and Unboxing in Java – Example Tutorial and Corner cases

What is Autoboxing in Java
Autoboxing and unboxing are introduced in Java 1.5 to automatically convert the primitive type into boxed primitive( Object or Wrapper class). autoboxing allows you to use primitive and object type interchangeably in Java in many places like an assignment, method invocation etc. If you have been using Collections like HashMap or ArrayList before Java 1.5 then you are familiar with the issues like you can not directly put primitives into Collections, instead, you first need to convert them into Object only then only you can put them into Collections. Wrapper class like Integer, Double and Boolean helps for converting primitive to Object but that clutter the code. With the introduction of autoboxing and unboxing in Java, this primitive to object conversion happens automatically by Java compiler which makes the code more readable.

Monday, July 17, 2017

9 Difference between TCP and UDP Protocol - Java Network Interview Question

TCP and UDP are two transport layer protocols, which are extensively used on the internet for transmitting data from one host to another. Good knowledge of how TCP and UDP works is essential for any programmer. That's why the difference between TCP and UDP is one of the most popular programming interview questions. I have seen this question many times on various Java interviews, especially for server-side Java developer positions. Since FIX (Financial Information Exchange) protocol is also a TCP based protocol, several investment banks, hedge funds, and exchange solution provider looks for Java developer with good knowledge of TCP and UDP. Writing fix engines and server side components for high-speed electronic trading platforms needs capable developers with a solid understanding of fundamentals including data structure, algorithms, and networking.

10 Things Every Java Programmer Should Know about String

String in Java is very special class and most frequently used class as well. There are lot many things to learn about String in Java than any other class, and having a good knowledge of different String functionalities makes you to use it properly. Given heavy use of Java String in almost any kind of project, it become even more important to know subtle detail about String. Though I have shared lot of String related article already here in Javarevisited, this is an effort to bring some of String feature together. In this tutorial we will see some important points about Java String, which is worth remembering. You can also refer my earlier post 10 advanced Java String questions to know more about String

Though I tried to cover lot of things, there are definitely few things, which I might have missed; please let me know if you have any question or doubt on java.lang.String functionality and I will try to address them here.

Sunday, July 16, 2017

How to reload/refresh a page using JavaScript and jQuery

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

Difference between ClassNotFoundException vs NoClassDefFoundError in Java

ClassNotFoundException vs NoClassDefFoundError
Though both of these errors are related to missing classes in the classpath, the main difference between them is their root cause. ClassNotFoundExcpetion comes when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath for example when you try to load MySQL or Oracle driver class and their JAR is not available, while in case of NoClassDefFoundError requested class was present at compile time but not available at runtime. Sometimes due to an exception during class initialization e.g. exception from static block causes NoClassDefFoundError when a failed-to-load class was later referenced by the runtime. 

Saturday, July 15, 2017

How to find duplicate words in Java String? [Solution]

Problem :  Write a Java program to print the duplicate words from a given statement e.g. if given String is "Java and JavaScript are totally different, JavaScript follows Java" then your program should print "Java" and "JavaScript" because those two are 2 duplicate words from given String. You need to consider all cases e.g. given String can be null, empty, may or may not contain any duplicate words, but for simplicity, you can assume that sentence will always in English and only use ASCII characters, alphabets, and numerals, no special character.  It's better to get the requirement right of the problem in the beginning even if the interviewer doesn't tell you everything. Directly jumping into solution without asking a couple of questions may not go well with many interviewers who looks for detail oriented candidates.

Difference Between Linked List and Array Data Structure in Java Programming

Array and linked list are two fundamental data structure in programming world. Almost all programs use Array in some form or other, which makes it increasingly important to learn array and linked list. Difference between linked list and array data structure is also a popular data structure question, frequently asked in various programming job interview. This makes it even more important to learn and understand difference between an array and a linked list. Well there are lot of difference between these two starting from how they store data, to how you retrieve data from them. Main difference comes from the fact that array elements are stored in contiguous memory location, which makes it easy to retrieve them in quick time, while linked list elements are scattered through out memory, where one element knows address of other, it makes it hard to retrieve element from linked list in quick time. Some of the differences which we saw in ArrayList vs LinkedList also applicable at data structure level, because ArrayList is backed by array and LinkedList is internally backed by double linked list in Java. 

Is it possible to have an abstract method in a final class?

This is one of the interesting core Java questions which was asked to one of my readers recently during a telephonic interview for Java developer job interview. Even though he knows that you cannot make an abstract class final in Java, he got confused by the wording of the methods. The answer is simple, No, it's not possible to have an abstract method in a final class in Java. Why? because as soon as you declare an abstract method in a Java class, the class automatically becomes an abstract class and you cannot make an abstract class final in Java as discussed before, hence it's not possible to have an abstract method in a final class in Java.

Friday, July 14, 2017

How to Find Largest of Three Integers in Java - Algorithm, Logic Example

One of the classical program to build programming logic is, write a program to find largest of three numbers. I am sure many of you have already done this exercise in variety of languages including C, C++, C#, JavaScript, Perl, Ruby, PHP etc. This time we will do it in Java. We will first learn the logic by understanding flowchart of largest of three numbers and then we will implement solution using ternary operator in Java. I love this program for its sheer simplicity and how it can help beginners to build logic. As always, you are not allowed to use any library function which can solve this problem directly, your main task is to build logic using primitive language tools e.g. operators. In Java, this problem is also used to teach how ternary operator works, as one of the popular version of this require you to find largest of three numbers using ternary operator.

Thursday, July 13, 2017

Why Enum Singleton are better in Java

Enum Singletons are new way to implement Singleton pattern in Java by using Enum with just one instance. Though Singleton pattern in Java exists from long time Enum Singletons are relatively new concept and in practice from Java 5 onwards after introduction of Enum as keyword and feature. This article is somewhat related to my earlier post on Singleton, 10 interview questions on Singleton pattern in Java where we have discussed common questions asked on interviews about Singleton pattern and 10 Java enum examples, where we have seen how versatile enum can be. This post is about why should we use Enum as Singleton in Java, What benefit it offers compared to conventional singleton methods etc.

Why multiple inheritances are not supported in Java

Why multiple inheritence is not supported implemented in javaRecently one of my friend appeared for an interview and after few so called easy questions he was asked "Why multiple inheritance is not supported in Java" , though he has a brief idea that in Java we can support multiple inheritance in java via interface but interviewer was keep pressing on why part , may be he was just read any blog post about it :). So after the interview my friend comes to me and in usual talk he told me about this questions and ask me the answer. Well this is very classical question like Why String is immutable in Java; similarity between these two questions is they are mainly driven by design decision taken by java's creator or designer. Though following two reason make sense to me on Why Java doesn't support multiple inheritances:

How to do GROUP BY in Java 8? Collectors.groupingBy() Example

Java 8 now directly allows you to do GROUP BY in Java by using Collectors.groupingBy() method. GROUP BY is a very useful aggregate operation from SQL. It allows you to group records on certain criteria. How do you group by in Java? For example, suppose you have a list of Persons, How do you group persons by their city e.g. London, Paris or Tokyo? Well, we can do that by using a for loop, checking each person and putting them on a list of HashMap with the same city, but in Java 8, you don't need to hack your way like that, you have a much cleaner solution. You can use Stream and Collector which provides groupingBy() method to do this. Since its one of the most common way to aggregate data, it has a real benefit, coupled that with the various overloaded version of groupingBy() method which also allow you to perform grouping objects concurrently by using concurrent Collectors.

Tuesday, July 11, 2017

How to solve java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver in Java 8

java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver exception comes in Java 8 because it has removed the JDBC ODBC bridge driver class "sun.jdbc.odbc.jdbcodbcdriver" from JDK and JRE. This class is required to connect any database using Object database connectivity driver e.g. Microsoft Access, but unfortunately you cannot use it from JDK 8 onward. In order to solve this error, just use Jackcess library or a commercial driver like HXTT. Normally, in pre Java 8 world, java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver error comes when you try to connect to Microsoft Access database from Java using JDBC and JDBC ODBC bridge driver is not available in classpath. If you remember, In order to open SQL connection to database, first step is to load and register the driver. In order to load driver, we use Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  and this method throws java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver, if ClassLoader is not able to find the requested class (sun.jdbc.odbc.JdbcOdbcDriver) in CLASSPATH. In order to connect to MS Access, we need type 1 JDBC driver, also known as JDBC ODBC bridge driver and the class in question, JdbcOdbcDriver is driver implementation to connect to Open database connectivity driver installed in machine.

Monday, July 10, 2017

Write a Program to Find all Armstrong number in the range of 0 and 9999 - Example

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number, since 1**3 + 5**3 + 3**3 = 153, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371. Along with usual beginner exercises e.g. calculating factorial, reversing string or calculating prime numbers, this is a good exercise to build programming logic. It teaches you basic programming technique of how to use operator for something which is not obvious, for example, to solve this programming challenge, we first need to check if a number is Armstrong or  not, and to do this we need individual digits of the number. how do we do that? well there is a programming technique, which you might have learned while doing number palindrome exercise.

Top 10 Java ArrayList Interview Questions Answers for 2 to 3 years Experience

Most of the Java interview questions on ArrayList asked to freshers or Java developers with 1 to 2 years experience is just simply how to do task e.g. how to sort arraylist, how to serach element, how to remove an element using iterator etc. Since, I have written lots of Java tutorials on ArrayList, covering many general purpose tasks e.g. how to create an object of ArrayList and initialize to how to sort ArrayList in ascending and descending order etc. On request of my readers, I am creating this mega list of ArrayList tutorials, which will help you to learn everything about ArrayList class. These tutorials are great for beginners and even experienced Java developers can learn a trick or two.

When to Make a Method Static in Java

Making a method static in Java is an important decision . Though, static keyword is one of the fundamental concepts, many times programmers gets confused to make a particular method static or not. In Java programming, main motivation for making a method static is convenience. You can call a static method without creating any object, just by using it's class name. So if you need a method, which you want to call directly by class name, make that method static. Utility classes e.g. java.lang.Math or StringUtils, are good examples of classes, which uses static methods. Before making a method static, you should look into limitation of static methods as well, as you can not override static method in Java

Sunday, July 9, 2017

String vs StringBuffer vs StringBuilder in Java

Difference between String, StringBuffer, and StringBuilder
The String is one of the most important classes in Java and anyone who starts with Java programming uses String to print something on the console by using famous System.out.println() statements. Many Java beginners not aware that String is immutable and final in Java and every modification in String creates a new String object. For example, when you get the substring, you get a new String, when you convert uppercase String to lowercase, a new String is created. Even when you remove space by calling the trim() method, a new String is returned. So, now the big question is how do you manipulate String in Java without creating String garbage? StringBuilder and StringBuffer are the answer to this question. StringBuffer is old class but StringBuilder is newly added in Java 5 along with major improvements in Enum, Generics, varargs methods and Autoboxing in Java.

Strategy Design Pattern and Open Closed Principle in Java - Example

Strategy design pattern is based upon open closed design principle, the 'O' of famous SOLID design principles. It's one of the popular pattern in the field of object-oriented analysis and design along with Decorator, Observer and Factory patterns. Strategy pattern allows you to encapsulate possible changes in a process and encapsulate that in a Strategy class. By doing that your process (mainly a method) depends upon a strategy, higher level of abstraction than implementation. This makes your process open for extension by providing new Strategy implementation, but closed for modification, because the introduction of a new strategy doesn't require a change in a tested method. That's how it confirms open closed design principle.

Saturday, July 8, 2017

Top 5 JQuery books for Beginners and Web developers - Best of lot

jQuery is a open source JavaScript library, which has completely changed the way, client side web development was done using HTML, CSS and JavaScript. With growing popularity of jQuery, it become imperative for web developers to learn and take advantage of jQuery and books are one of the best way to learn jQuery. In this article, I am going to share you top 5 jQuery books from my personal collection, which I have looked and researched before purchasing my first book on jQuery, Head First JQuery. Since I like to follow one book at a time, I didn't bother to look into another must read book, JQuery in Action, until I have finished former. After finishing my first book on jQuery, I am quite comfortable with jQuery magic, which means doing things like DOM Selection, traversal, DOM manipulation based on CSS selector, animation and cool effects, and responding to use actions (event handling) in couple of lines. 

OCAJP 8 FAQ - Oracle Certified Associate Java Programmer I Certification (1Z0–808) Frequently asked Questions

The Oracle Certifications is one of the most repeated, industry-recognized certifications. It also provides Java certifications like Oracle Certified Associate Java Programmer, also known as OCAJP and Oracle Certified Professional Java Programmer, also known as OCPJP. These two are most popular Java certification and there are many benefits of passing them e.g. better chance to get a Java development job, improved performance on Java interviews, better salary rise, and promotions, and better opportunity for moving abroad.

Friday, July 7, 2017

SubQuery Example in SQL – Correlated vs Noncorrelated

SubQuery in SQL is a query inside another query. Some time to get a particular information from database you may need to fire two separate sql queries, subQuery is a way to combine or join them in single query. SQL query which is on inner part of main query is called inner query while outer part of main query is called outer query. for example in below sql query

SELECT name FROM City WHERE pincode IN (SELECT pincode FROM pin WHERE zone='west')

section not highlighted is OUTER query while section highlighted with grey is INNER query. In this SQL tutorial we will see both Correlated and non correlated sub-query and there examples, some differences between correlated and noncorrelated subqueries and finally subquery vs join which is classic debatable topic in SQL. By the way this SQL tutorial is next in series of SQL and database articles in Javarevisited like truncate vs delete and 10 examples of  SELECT queries. If you are new here then you may find those examples interesting.

Thursday, July 6, 2017

10 Tips to Debug Java Program in Eclipse

How to debug java program in Eclipse

Debugging is a must have skill for any java developer. Having ability to debug java program enables to find you any subtle bug which is not visible during code review or comes when a particular condition offer, This becomes even more important if you are working in high frequency trading or electronic trading system project where time to fix a bug is very less and bug usually comes on production environment and doesn't appear in your Windows XP machine. in my experience debugging java application also helps you understand flow of java program. In this java tutorial we will see how to debug a java program, setting up remote debugging in java and some java debugging tips on Eclipse and Netbeans IDE. It’s also good to know various java debug tool available and how java debugger or jdb works but it’s not mandatory for doing debugging in Java. To start java debugging you just needs your project to be configured in a modern IDE like eclipse and Netbeans and you are ready to debug java program.

Fibonacci Series in Java Without Recursion - Programming Exercises for Beginners

Fibonacci series is a great example of Recursion and how the use of recursion can result in a clear and concise solution. That's why whenever asked about writing a Java program to get a Fibonacci numbers or print the Fibonacci series of certain numbers, it's quite natural for programmers to resort to recursion. Interviewer often challenged this practice by asking candidates to implement Fibonacci series without using recursion. Yes, you read it right, you can't use recursion and this is what you will learn in this article. If you have attended your programming classes regularly then you may know that many recursive algorithms also has their iterative counterpart which uses loops instead of recursion or calling itself . We will take advantage of that concept to devise a solution of this problem.

Wednesday, July 5, 2017

java.lang.ClassNotFoundException: [Solution]

This error comes when you try to connect to Microsoft SQL Server database from Java program but the required JDBC driver is not available in Classpath or driver is available in CLASSPATH but the class loader is not able to find it due classpath intricacies. Depending upon your situation, a solution could be as simple as downloading any of sqljdbc.jar, sqljdbc4.jar or sqljdbc41.jar, based upon the Java version you are using and adding them into CLASSPATH as set CLASSPATH = %CLASSPATH%; (path to Microsoft JDBC driver) in Windows. BTW, in most of the cases "java.lang.ClassNotFoundException:" comes because of classpath intricacies. For example, if your Java program is using -cp or -classpath option but you added the JAR into CLASSPATH environment variable or vice-versa.

Tuesday, July 4, 2017

Top 5 Books to learn UML (Unified Modeling Language) for Java Developers - Best of Lot, Must Read

The UML stands for Unified Modelling language and it is one of the great tools for Object-oriented design. It allows you to create several diagrams e.g. class diagram, sequence diagram, object diagram etc, which helps you to understand your system better.   The UML also helps you to convey your thoughts and design to peer and team members before implementation. Since a picture is worth a thousand word, those interactions often help you to find shortcomings and loopholes in your software design very early. That's actually the reason I use UML in our projects. Btw, I didn't know about UML or UML diagrams when I first started Java development. Maybe, I might have heard about it but it just like many more things which I heard but don't pay enough attention. It was my first year in work when I was first asked to prepare both class and sequence diagrams for one of the modules I was developing.

How SSL, HTTPS and Certificates Works in Java web Applications

Basic knowledge of SSL, HTTPS and Certificates are must for any Java programmer, especially who is working in financial and security sensitive applications, which are accessed over internet. In this article, I am giving you an overview of these three key concept and How SSL, HTTPS and certificates work together, to provide secure communication between client and server. Security is major concern while developing web application, which is accessible using HTTP protocol. Since HTTP protocol transfer data in plain text format, its not safe for transferring sensitive information like username, password, social security number (SSN) or credit card details for online shopping. HTTP protocol, also doesn't guarantee that a website, you are communicating is the one who claims i.e. if URL redirection is enable than instead of genuine website you may be routed to malicious websites and HTTP can't prevent or alert you.

Monday, July 3, 2017

How to Convert Fahrenheit to Celsius in Java with Example

In this Java tutorial, you will learn how to write a program to convert Fahrenheit to Celsius in Java. Fahrenheit is a thermodynamic temperature scale, where the freezing point of water is 32 degrees Fahrenheit (°F) and the boiling point of water is 212°F (at standard atmospheric pressure). This puts the boiling and freezing points of water exactly 180 degrees apart. Therefore, a degree on the Fahrenheit scale is 1/180 of the interval between the freezing point and the boiling point of water. Absolute zero is defined as -459.67°F. If you know, in Celsius scale, the freezing point of water is at 0ºC and the boiling point of water is at 100ºC. By using these facts, you can easily deduce a formula to convert Fahrenheit temperature into Celsius.

Sunday, July 2, 2017

Role based Access control using Spring Security and MVC, Mapping LDAP Groups to Authorities for Authorization

Authentication and Authorization is integral part of any Java enterprise or web application. Since most of the company uses LDAP Active directory for authentication, authorization and Role based access control (RBAC), it's good to know How to implement Role based access control using Spring MVC and Spring Security. This is the second part of my articles on using Spring Security for authentication and authorization in Spring MVC based Java application. In last part, we have learned about doing LDAP authentication against Windows active directory, and in this Spring Security tutorial, we will learn How to map LDAP groups to authorities for implementing Role based access control or authorization. If you are developing an application, whose access is controled by adding user to a particular LDAP group, then you need a mechanism to load those LDAP group after successful authentication. Spring Secuirty uses GrantedAuthority class for holding all roles for a particular user. 

How to solve java.lang.UnsatisfiedLinkError: no ocijdbc11 in Java

"java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path" error comes when you try to connect to Oracle 11g database using OCI (thick) driver by using tns name, but the ocijdbc11.dll file is not available in PATH or java.library.path environment variable. ocijdbc11.dll is a native library and if you know Java searches native library in PATH or a location specified by java.library.path system property, if it doesn't find the dll, then it throws java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path error. This dll is usually found in C:\Programs\Oracle\ora11g\bin\ocijdbc11.dll, but it could vary depending upon your Oracle installation.

Top 30 Linked List Algorithm Questions from Programming/Coding Interviews

The linked list is one of the most common and essential data structure and that's why you would frequently find linked list based coding questions on interviews. The range of questions can be from simple questions like finding the length of linked list to very difficult e.g. merging two sorted linked list. Nevertheless, point is that you should be familiar with linked list data structure and must know how to perform basics task in linked list e.g. adding or removing nodes from linked list, traversing order linked list and implementing linked list in your choice of programming language e.g. Java, C++, C, or Python. These linked list problems are not only good for coding interviews point of view but also very useful in learning programming. You should try to solve this problem yourselves, before looking at the solution to get the full benefit of them.

Saturday, July 1, 2017

How to resolve java.lang.UnsupportedClassVersionError with example

java.lang.UnsupportedClassVersionError  is a quite common error after NoClassDefFoundError or ClassNotFoundException they all seems to related to class files but they all are different and there cause and resolution are different. In this java tutorial we will see what is UnsupportedClassVersionError in Java? Why UnsupportedClassVersionError comes in Java? What is class file format and version numbers associated with it and finally how to resolve UnsupportedClassVersionError in Java. 

This article is in continuation of debugging tutorials like How to remote debug Java program in Eclipse and 10 Java debugging tips in Eclipse. If you have not read those article you may find them useful.


How to resolve UnsupportedClassVersionError in Java

What is UnSupportedClassVersionError in Java?

UnSupportedClassVersionError, java.lang.UnsupportedClassVersionErrorJava.lang.UnsupportedClassVersionError is a subclass of java.lang.ClassFormatError. This is a kind of linking error which occurs during linking phase accordingly java.lang.ClassFormatError has also derived from java.lang.LinkageError. As the name suggests "UnSupportedClassVersionError" so it’s related to unsupported class version, now questions comes what is class version in Java? Well every source file is compiled into class file and each class file has two versions associated with it, major version and minor version. 

The Version of class file is represented as major_version.minor_version. This version is used to determine format of class file in Java.

According to Java Virtual Machine specification, “A JVM implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a JVM implementation conforming to a certain release level of the Java platform may support.” For example: JDK 1.2 supports class file formats from version 45.0 to version 46.0 inclusive. So if a class file has version 48.0 it means that major version of class file is "48" and minor version is "0", which tells us that JDK 1.4 has been used to compile and generate that class file.

When UnSupportedClassVersionError in Java comes:

So now we got the theory behind class file format and major and minor version of class file in Java. Now a million dollar question is when UnSupportedClassVersionError in Java does occur?  precise answer of this is "When JVM tries to load a class and found that class file version is not supported it throws UnSupportedClassVersionError and it generally occurs if a higher JDK version  is used to compile the source file and  a lower JDK version is used to run the program. for example if you compile your java source file in JDK 1.5 and you will try to run it on JDK 1.4 you will get error "java.lang.UnsupportedClassVersionError: Bad version number in .class file [at java.lang.ClassLoader.defineClass1(Native Method)]".

But its important to note is that vice-versa is not true "you can compile your program in J2SE 1.4 and run on J2SE 1.5 and you will not get any UnSupportedClassVersionError". When a higher JDK is used for compilation it creates class file with higher version and when a lower JDK is used to run the program it found that higher version of class file not supported at JVM level and results in java.lang.UnsupportedClassVersionError.

How to fix UnSupportedClassVersionError

Now we know the root cause of UnSupportedClassVersionError that we are using a lower JVM for running the program. But major problem is that stack trace of UnSupportedClassVersionError will not tell you for which class it’s coming. So if you are using multiple third party jars in your application you find that it comes at a particular part when JVM tries to load a class from a particular jar. anyway we all know that latest version of JDK is 1.6 so maximum version of class file could be generated by JDK 6, so by using JDK 6 we can solve UnSupportedClassVersionError, but many times its not easy to just move to higher JDK version. So I would suggest:

1) Find out due to which jar or class file this UnSupportedClassVersionError is coming?
2) Try to compile source code of that jar with the JDK version you are using to run your program, if source is available.
3) If you don't have source try to find the compatible version of that library.
4) Increase the JRE version you are using to run your program.

You can go by any approach to resolve UnSupportedClassVersionError based upon your need. Generally a higher JVM version is ok and does not cause any problem unless the class file format is quite old and no more supported by Sun in higher JVMs. The best way to deal with UnSupportedClassVersionError in Java is to use same version or JDK and JRE for compiling and running your program.

Example of UnSupportedClassVersionError in Java

You can easily reproduce UnSupportedClassVersionError by using javac of higher JDK and "java" from lower Java version. Let’s see some of examples of UnSupportedClassVersionError in Java:

1) java.lang.UnsupportedClassVersionError: EquityTradingManager (Unsupported major.minor version 49.0)
      at java.lang.ClassLoader.defineClass0(Native Method)
      at java.lang.ClassLoader.defineClass(
==>Since we know that major version 49 is supported by JDK 1.5, so these will "java.lang.UnsupportedClassVersionError” will come if JVM used to run this program is lower than Java 1.5.

2) Java.lang.UnsupportedClassVersionError: Bad version number in .class file

3) java.lang.unsupportedclassversionerror unsupported classversion 50.0
==> Compile in JDK 1.6 and running on lower version than Java 6.

4) java.lang.unsupportedclassversionerror unsupported classversion 49.0
==> compiled in Java 5 and running on lower JVM than JDK 5.

5) java.lang.unsupportedclassversionerror bad version number in eclipse.
java.lang.unsupportedclassversionerror unsupported classversion 49.0 or 50.0
==> Most of us use eclipse for building and running project some of us also use ant for building project. In eclipse there is some setting related to java source version which if you got incorrect can result in "java.lang.unsupportedclassversionerror bad version number". so make sure you have correct configuration. For example if you compile with source compatible 1.6 you need JRE 6 to execute the program. To check the compiler setting in eclipse go to project  ==>Properties==>Java Compiler as shown in image

Important point about UnSupportedClassVersionError in Java:

1) If you encounter UnSupportedClassVersionError, check the JRE version you are using to run program and switch to higher version for quick solution.
2) java.lang.UnsupportedClassVersionError is derived from java.lang.LinkageError, so it will not be detected in compile time and it will only come on runtime, precisely when JVM tries to load a class.
3) Class file format which is identified using major version and minor version. Class file format is assigned when you compile source file and its depends on JDK version used to compile.
4) Its always best practice to use same version of java for compilation and execution to avoid any chance of UnSupportedClassVersionError.
5) UnSupportedClassVersionError is not related to java classpath , so don't confuse this with NoClassDefFoundError or ClassNotFoundException.

Major Class Versions of Various JDK

Following are the major version of class file format in standard JDK environment.

JDK 1.1 = 45
JDK 1.2 = 46
JDK 1.3 = 47
JDK 1.4 = 48
JDK 1.5 = 49
JDK 1.6 = 50

You can also get version of "javac" (used for compilation) and version of "java" (used for execution) as below
C:\equity trading\stocks>javac -version
javac 1.6.0-beta2

C:\equity trading\stocks>java -version
java version "1.6.0-beta2"
Java(TM) SE Runtime Environment (build 1.6.0-beta2-b86)
Java HotSpot(TM) Client VM (build 1.6.0-beta2-b86, mixed mode, sharing)

Now you can identify your JDK version based on class file format version whenever you see java.lang.UnsupportedClassVersionError :)

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

So next time when you see UnsupportedClassVersionError don't be afraid and follow the best approach based upon your need.

If you like this post you may find my other tutorial how java hashmap works, why String is immutable in java, why wait and notify needs to call from synchronized context  interesting.