Difference between SOAP and RESTful Web Service in Java

Though both SOAP and RESTful web services allow a client to query the server for some information, the way they are implemented and used is quite different. The main difference between SOAP and REST is that former provides a standard of communication between client, server and other parties and has restricted a set of rules and format, while REST leverages the ubiquity of HTTP protocol, in both client and servers, to allow them to communicate with each other regardless of their implementation. In short, getting data from a RESTful web service requires less headache than getting data from a SOAP web service.

How to use string in switch case in Jdk 7 with example

Have you ever feel that String should be used in switch cases like int and char? JDK 7 has made an important enhancement in their support of String, now you can use String in switch and case statement, No doubt String is most widely used type in Java and in my opinion they should have made this enhancement long back when they provided support for enum in java and allowed enum to be used in a switch statement. In this java tutorial, we will see how we can use String inside switch and case statement in JDK 7. This article is in continuation of my earlier post on JDK7 feature improved exception handling using multi-cache block in Java

10 Equals and HashCode Interview Questions in Java

Equals and HashCode methods in Java are two fundamental methods from java.lang.Object class, which is used to compare equality of objects, primarily inside hash-based collections such as Hashtable and HashMap. Both equals() and hashCode() are defined in java.lang.Object class and their default implementation is based upon Object information e.g. default equals() method return true if two objects are exactly the same i.e. they are pointing to the same memory address while default implementation of hashcode method return int and implemented as a native method. The similar default implementation of toString() method, returns type of class, followed by memory address in hex String.

Top 10 JDBC Best Practices for Java Programmer

Java JDBC Best practices
JDBC Best Practices are some coding practices which Java programmer should follow while writing JDBC code. As discussed in how to connect to the Oracle database from Java, JDBC API is used to connect and interact with a Database management System.  We have touched some of the JDBC best practices in our last article 4 JDBC Performance tips, On which we have discussed simple tips to improve the performance of Java application with the database. By using JDBC you can execute DDL, DML, and Stored Procedures. JDBC Best practices are probably the most significant set of coding practices in Java because it significantly affects the performance of Java application.

Quicksort Sorting Algorithm in Java - Example and Explanation

Quicksort algorithm is one of the most used sorting algorithms, especially to sort the large lists, and most of the programming languages, libraries have implemented it in one or another way. In Java, Arrays.sort() method sorts primitive data types using a double-pivot Quicksort algorithm, authored by Joshua Bloch and others. This implementation provides better performance for a lot of data sets, where traditional quicksort algorithms reduced into quadratic performance. This method also uses MergeSort, another good sorting algorithm, to sort objects. QuickSort implementations are also available in the C++ STL library.

Why Java does not support Operator overloading

Unlike C++, Java doesn't support operator overloading. Java doesn't provide freedom to programmer, to overload the standard arithmetic operators e.g. +, -, * and / etc. If you have worked previously in C++, than you know that, Java has left lot of feature supported in C++ e.g.  Java doesn't support multiple inheritance, no pointers in Java, and no pass by reference in Java. Rarely this question asked in Java interviews, to check how programmer thinks about certain features, which is not supported in Java. Another similar questions is regarding Java being pass by reference, which is mostly appear as, whether Java is pass by value or reference.

2 Examples to Convert Byte[] Array to String in Java

Converting a byte array to String seems easy but what is difficult is, doing it correctly. Many programmers make the mistake of ignoring character encoding whenever bytes are converted into a String or char or vice versa. As a programmer, we all know that computer's only understand binary data i.e. 0 and 1. All things we see and use like images, text files, movies, or any other multi-media are stored in form of bytes, but what is more important is the process of encoding or decoding bytes to a character. Data conversion is an important topic on any programming interview, and because of the trickiness of character encoding, this question is one of the most popular String Interview questions on Java Interviews.

How to calculate Large Factorials using BigInteger in Java?

Factorial of numbers greater than or equal to 13 cannot be found using primitive int data type as shown in our earlier factorial solution due to overflow. These factorials are too large to fit in an int variable, whose maximum value is just 2147483647 (2^31 -1). Even if we use the long data type, factorials greater than or equal to 21 will generate an overflow. To find the factorial of anything above 21, you need to use the BigInteger class from the java.math package. As the name suggests, BigInteger class is designed to hold really large integer value, something which is even bigger than the maximum value of long primitive e.g. 2^63 -1 or 9223372036854775807L. You also need to change the way we calculate factorial for a smaller number. You can not use recursion to calculate factorial of a larger number instead we need to use for loop for that.

Difference between HashMap, LinkedHashMap and TreeMap in Java

The java.util.Map is one of the most important interfaces from the Java Collection Framework.  It provides hash table data structure functionality by its implementations like HashMap, Hashtable, LinkedHashMap, and a little bit of sorting with the TreeMap. So if you are looking to store key-value pairs in Java program,  you have a wide range of choices available depending upon your requirement. The main difference between LinkedHashMap, TreeMap, and HashMap comes in their internal implementation and specific features, which makes them useful in certain scenarios. For example, the HashMap is a general-purpose Map (hash table data structure), which should be used whenever you need a hashing-based data structure for storing your mappings (key-value pairs).

How to Convert Collection to String in Java - Spring Framework Example

How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma-separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through the loop and create a big String where individual String are separated by a delimiter, you still need to handle cases like the last element should not have delimiter or at a bare minimum, you need to test that code.

3 CDN URL to load jQuery into Web Page from Google, Microsoft

jQuery is one of the most popular and powerful JavaScript libraries, but in order to use it, you need to load into your web page using standard HTML <script> tag. Based on whether your web page is publicly accessible or for an organization, you can either choose to load the jQuery library from the local file system, bundled inside your web application or you can directly download using one of the content delivery networks (CDN) e.g. Google or Microsoft CDN. Choosing CDN to download jQuery can offer a performance benefit because their servers are spread across the globe.

5 Entertaining Posts from StackOverFlow - Must Read

StackOverFlow is great place to look for help, learn and participate, but it's also a great place to taste some real entertainment, contributed by programmers from all over the world. Though, due to strict policies of stackoverflow.com, most of entertaining post either are either gets closed or deleted, some of them remained to entertain programming community. Being a regular reader of StackOverFlow from long time, I have found couple of threads which are truly amazing, and has lot's of funny and entertaining content. Here I am going to share 5 of my favorite StackOverFlow posts, which I suggest you to read, if you get bored or you have some time to kill. By the way, don't forget to leave comments and let us know which is your favorite funny and entertaining threads in StackOverFlow.

Why use SLF4J over Log4J for logging in Java

Every Java programmers know that logging is critical for any Java application, especially server-side application, and many of them are already familiar with various logging libraries e.g. java.util.logging, Apache log4j, logback, but if you don't know about SLF4J, Simple logging facade for Java,  then it's time to learn and use SLF4J in your project. In this Java article, we will learn why using SLF4J is better than using log4j or java.util.logging. It’s been a long time, since I wrote 10 logging tips for Java programmer,I don’t remember anything I have writing about logging.

10 Best Practices to Follow While Writing Code Comments

Comments are an important part of writing code not only in Java but whatever programming or scripting language you use. At the same time, this is one of the most abused things as well. Both writing no comment and writing too much comment is bad and this has been highlighted by many software gurus e.g. Robert C. Martin in his classic book Clean code. There is a whole chapter dedicated to How to write comments and finding the pros and cons of a comment. This article is my learning in the same direction, here I am going to share with you guys some 0f the rule and best practices I follow while writing comments.

15 Java NIO, Socket, and Networking Interview Questions Answers

Networking and Socket Programming is one of the important area of Java programming language, especially for those programmers, who are working in client server based applications. Knowledge of important protocols e.g. TCP and UDP in detail is very important, especially if you are in business of writing high frequency trading application, which communicate via FIX Protocol or native exchange protocol. In this article, we will some of the frequently asked questions on networking and socket programming, mostly based around TCP IP protocol. This article is kinda light on NIO though, as it doesn't include questions from multiplexing, selectors, ByteBuffer and FileChannel but it does include classical questions like difference between IO and NIO.

What is polymorphism in Java? Method overloading or overriding?

What is Polymorphism in Java
Polymorphism is an important Object oriented concept and widely used in Java and other programming languages.  Polymorphism in java is supported along with other concepts like Abstraction, Encapsulation, and Inheritance. Few words on the historical side; Polymorphism word comes from ancient Greek where poly means much so polymorphic are something which can take many forms. In this Java Polymorphism tutorial we will see what is Polymorphism in Java , How Polymorphism has implemented in Java e.g method overloading and overriding, why should we use Polymorphism and how can we take advantage of polymorphism while writing code in Java. Along the way we will also see a real world example of using Polymorphism in Java

How to write parametrized Generic class and method in Java Example

Parameterized Generic class and method in Java
Writing Generic parametrized class and method in Java is easy and should be used as much as possible. Generic in Java was introduced in version 1.5  along with Autoboxing, Enum, varargs and static import. Most of the new code development in Java uses type-safe Generic collection i.e. HashSet in place of HashSet but still Generic is underused in terms of writing own parametrized classes and method. I agree that most Java programmers has started using Generic while working with the Java collection framework but they are still not sure how Generic can allow you to write Template kind of classes which can work with any Type just like the parametrized ArrayList in Java which can store any Type of element.

How to Sort List in reverse Order in Java Collection Framework with Example

Java Collection Framework provides a convenient reverse comparator, to sort List of objects in reverse order.  You can obtain reverse Comparator, by calling Collections.reverseOrder(), which by default sort List of Integer in reverse numeric order and List of String in reverse alphabetic order. It actually reverse natural ordering of objects imposed by Comparable interface. Apart from this method, Collections class also provides an overloaded method Collections.reverseOrder(Comparator cmp), which takes a Comparator, and sort List on reverse order of that Comparator.

10 tips to quickly become productive with new Project/Codebase

One of the main drawback of changing job or changing project it that you lost all subject matter expertise you have learned by working the last couple of years in that project or domain. It doesn't matter whether you are an expert in a programming language, once you change job, you lost your hard earned experience on projects or domain you are working on. When starting a new job or on to a new project you will rarely be working on a complete greenfield environment. Understanding and mastering an unfamiliar code is a difficult process and it can sometimes feel overwhelming due to the amount of new information you need to take on.

How to Find All Permutations of String in Java using Recursion

How to find all permutation of a String using recursion is one of the tricky coding questions from programming job interviews. I have first seen this question in my college exam when we were asked to code the solution using C or C++ language. Since then I have seen this question many times at various written tests and Java interviews for a junior developer position. It does not only serve as a good question to check whether the candidate understands recursion but also its one of the better Java programming exercise for beginners.

Bubble Sort Algorithm in Java with Example

Bubble Sort is the first sorting algorithm I learned during my college day, and after so many years it's the one I remember by heart. It's kind of weird that one of the most popular sorting algorithms is also one of the worst-performing sorting algorithms. Bubble sort's average-case performance is in O(n^2), which means as the size array grows, the time it takes to sort that array increases quadratically. Due to this reason, bubble sort is not used in production code, instead of quick sort and merge sort are preferred over it. In fact, Java's own Arrays.sort() method, which is the easiest way to sort an array in Java also uses two pivot quicksort to sort primitive array and stable mergesort algorithm to sort object arrays.

SQL Query to Find All Table Names on a Database With MySQL and SQL Server Examples

How do you find names of all tables in a database is a recent  SQL interview questions asked to one of my friends. There are many ways to find all table names form any database like MySQL and SQL Server. You can get table names either from INFORMATION_SCHEMA or sys.tables based upon whether you are using MySQL or SQL Server database. This is not a popular question like when to use truncate and delete or correlated vs noncorrelated subquery which you can expect almost all candidates prepare well but this is quite common if you are working on any database like MySQL.

Java Enum Tutorial: 10 Examples of Enum in Java

What is Enum in Java
Enum in Java is a keyword, a feature which is used to represent fixed number of well-known values in Java, For example, Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. One of the common use of Enum which emerged in recent years is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety and Serialization automatically. By the way, Java Enum as a type is more suitable to represent well known fixed set of things and state,  for example representing the state of Order as NEW, PARTIAL FILL, FILL or CLOSED.

How to Find all Pairs in Array of Integers Whose sum is Equal to a Given Number - Java Solution

Practicing coding problems are very important to do well in any programming interview. You should at your best on data-structures like an array, linked list, and string to clear any programming interview, and believe me, you can not do this in one day or one week. It's rather a long process of learning through coding, and that's where these small coding problems help. Today, we are going to look at another interesting programming question from the array; write a program to find all pairs of integers whose sum is equal to a given number. For example, if the input integer array is {2, 6, 3, 9, 11} and given sum is 9, the output should be {6,3}.

Java 8 - Journey of for loop in Java, for(index) to forEach()

for loop has come a long way in Java 8 with a new forEach() method in java.util.stream.Stream class. In this article, we will take a look at the journey of for loop in different versions of Java programming language. for loop is there from the very beginning of Java i.e. JDK 1.0. Almost all Java programmers have used the classical for() loop, as it is also an essential programming construct, I guess just next to if-else, but when the foreach loop or as some people call it enhanced for loop was introduced in JDK 1.5, everything changed from looping over Collection and array perspective.

How to Parse String to Float in Java | Convert Float to String in Java - 3 Examples

float and double are two data type which is used to store floating-point values in Java and we often need to convert String to float in Java and sometimes even a Float object or float primitive to String. One thing, which is worth remembering about floating-point numbers in Java is that they are approximate values, a float value 100.1f may hold actual value as 100.099998, which will be clear when we have seen examples of converting float to String and vice-versa. By the way, It's easy to parse String to float and vice-versa, as rich Java API provides several ways of doing it.

Difference between getPath(), getCanonicalPath() and getAbsolutePath() of File in Java

File API is very important one in Java, it gives access of File system to Java programs. Though Java's file API is rich, there are lot of subtleties to know when you use them. One of the common query programmer's has about file path is difference between getPath(), getCanonicalPath() and getAbsolutePath() methods, why there are three methods to get file path and what happens if you call getPath() in place of getCanonicalPath(). By the way, before understanding difference between getPath(), getAbsolutePath() and getCanonicalPath() let's understand the concept behind this methods, i.e. difference between path, absolute path, and canonical path.

How to format String in Java – String format Example

String format and printf Example
How to format String in Java is most common problem developer encounter because of classic System.out.println() doesn’t support formatting of String while printing on console. For those who doesn’t  know What is formatted String? here is a simple definition,  Formatted String is a String which not only displays contents but also displays it in a format which is widely accepted like including comma while displaying large numbers e.g. 100,000,000 etc. Displaying formatted String is one of the needs for modern GUI application and thankfully Java has good support for formatting String and all other types like Integers, Double, and Date. How to format a String in Java is never as easy as it has been since Java 1.5 which along with front line features like Generics, Enum, Autoboxing and Varargs also introduce several utility methods to support rich formatting of String in Java

How to format/parse dates with LocalDateTime in Java 8 - Example Tutorial

One of the common tasks in Java project is formatting or parsing date to String and vice-versa. Parsing date means you have a String which represents a date e.g. "2017-08-3" and you want to convert it into an object which represents the date in Java e.g. java.util.Date in pre-Java 8 world and LocalDate or LocalDatetime in Java 8 world. Similarly, formatting a date means converting a date instance into String, for example, you have a Date object or LocalDatetime object and you want a String in dd-MM-yyyy format. Java 8 API provides good support for formatting and parsing dates.

How to Convert String to Integer to String in Java with Example

Converting String to integer and Integer to String is one of the basic tasks of Java and most people learned about it when they learn Java programming. Even though String to integer and Integer to String conversion is basic stuff but same time its most useful also because of its frequent need given that String and Integer are two most widely used types in all sorts of programs and you often gets data between any of these formats. One of the common tasks of programming is converting one data type another e.g. Converting Enum to String or Converting Double to String, Which is similar to converting String to Integer. Some programmers asked a question that why not Autoboxing can be used to convert String to int primitive or Integer Object? 

Difference between SubStr vs SubString method in JavaScript - Tutorial Example

JavaScript provides two similar-looking String manipulation function, substr and substring, though both are used to get a substring from a String, there is a subtle difference between substring and substr method in JavaScript. If you look at there signature, both substr(to, length) and substring(to, from) both take two parameters, but substr takes length of substring to be returned, while substring takes end index (excluding) for substring. This main difference will be more clear when we will see a couple of examples of using substr and substring in JavaScript code.

How to get Environment Variables in Java- Example Tutorial

Environment variables in Java
There are two ways to get the environment variable in Java, by using System properties or by using System.getEnv(). System properties provide an only a limited set of predefined environment variables like java.classpath, for retrieving Java Classpath or java.username  to get User Id which is used to run Java program etc but a more robust and platform-independent way of getting environment variable in Java program on the other hand System.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if the program relies on a particular environment variable.

Difference between Clustered Index and Non Clustered Index in SQL Server - Database Interview Question

In the SQL Server database, there are mainly two types of indexes, Clustered index, and Non-Clustered index and the difference between Clustered and Non Clustered index is very important from an SQL performance perspective. It is also one of the most common SQL Interview questions, similar to the difference between truncate and delete,  primary key or unique key or correlated vs non-correlated subquery. For those, who are not aware of the benefits of Index or why we use an index in the database, they help in making your SELECT query faster.

Difference between Direct, Non Direct and Mapped ByteBuffer in Java

ByteBuffer is one of the important class of Java NIO API. It was introduced in java.nio package on JDK 1.4, it not only allows you to operate on heap byte arrays but also with direct memory, which resides outside the JVM. There are mainly three types f ByteBuffer, Direct, Non-Direct and mapped byte buffers. You can create both direct and non-direct buffers using java.nio.ByteBuffer class, while MappedByteBuffer is a subclass of ByteBuffer, which is created by FileChannel.map() method, to operate on memory mapped file. The main difference between direct and non-direct byte buffers are there memory location, non-direct byte buffers are just a wrapper around byte array and they reside in Java Heap memory while direct byte buffer is outside of JVM and memory is not allocated from the heap.

How to Send Email from Java Program with Example

Sending Email from Java program is a common requirement. It doesn't matter whether you are working on core Java application, web application or enterprise Java EE application, you may need to send email to alert support personal with errors, or just send email to users on registration, password reset or asking them to confirm their email after registration. There are many such scenarios, where you need ability to send emails from Java program. In mature applications, you already have a module or library dealing with all king of email functionality and issues e.g. ability to send attachments, images, including signatures and other rich text formatting on emails, but if you have to code something from scratch then Java's Mail API is perfect place.

5 ways to convert InputStream to String in Java

InputStream to String Conversion Example
Converting InputStream to String in Java has become very easy after the introduction of Scanner class in Java 5 and due to the development of several open-source libraries like Apache commons IOUtils and Google Open source guava-libraries which provides excellent support to convert InputStream to String in Java program. we often need to convert InputStream to String while working in Java for example if you are reading XML files from InputStream and later performing XSLT transformation on it or if InputStream is reading data from text file or text input Source and we either want to log  Strings in a log file or want to operate on whole String.

How to increase java heap space on Maven and ANT

Many times we get java.lang.OutOfMemoryError: Java heap space while building our project either by using maven or ANT just because heap size is not enough to build the project. At this point we just want to increase the heap size used by ANT or MAVEN and this java tip will let you do this:

2 Example to Merge or Join Multiple List in Java - Tutorial

Sometimes, we need to merge multiple lists into one before performing any operation, say Iteration or transformation. It's quite common to merge two lists, or combine them into a bigger list and there are multiple ways to do it. In this article, we will take a look at two simple way to join two lists in Java, you can further extend that idea to join any number of List or it's implementation e.g. ArrayList or LinkedList in Java. One way to merge multiple lists is by using addAll() method of java.util.Collection class, which allows you to add content of one List into another List. By using addAll() method you can add contents from as many List as you want, it's best way to combine multiple List.

How to fix Chrome, Firefox Blurry, Over bright, fading after Windows 10 Update

Today morning, I updated My HP Laptop to Windows 10. The first impression was great, crystal clear images, better wallpaper, better themes, better welcome screen and improved start menu and task bar at the right-hand corner. But when I open Chrome and Firefox the text look faded, more bright and contrast was not perfect. Since I had not changed anything, I suspect this is the Windows 10 default settings which are causing the problem. I knew it before because I had also faced similar issues when I was moved from Windows XP to Windows 8 and then Windows 8.1 update. If you are facing the same problem where your Chrome, Firefox are not looking clear, instead looking blurry and faded then you need to adjust your Laptop's screen brightness, contrast, and gamma.

Difference between WHERE vs HAVING clause in SQL - GROUP BY Comparison with Example

What is difference between WHERE and  HAVING clause in SQL is one of the most popular question asked on SQL and database interviews, especially to beginners. Since programming jobs, required more than one skill, it’s quite common to see couple of SQL Interview questions in Java and .NET interviews. By the way unlike any other question, not many Java programmers or dot net developers, who is supposed to have knowledge of basic SQL, fail to answer this question. Though almost half of the programmer says that WHERE is used in any SELECT query, while HAVING clause is only used in SELECT queries, which contains aggregate function or group by clause, which is correct.