Friday, October 29, 2021

How to Split String in SQL Server and Sybase? Example Tutorial

Sometimes we need to split a long comma-separated String in a Stored procedure e.g. Sybase or SQL Server stored procedures. It's quite common to pass comma delimited or delimiter separated String as an input parameter to Stored procedure and then later split comma separated String into multiple values inside stored proc. This is not just the case of the input parameter but you can also have a comma-separated string in any table data. Unfortunately, there is no split() function in Sybase or SQL Server 2005 or 2008 which can directly split a string based on delimiter just like in the Java string split method

How to Count Number of Leaf Nodes in a Binary Tree in Java ? [ Iterative and Recursive Solution]

Hello guys, today I am going to talk about an interesting binary tree-based coding problem from Programming Job interviews. If you have attended a couple of technical interviews then there is a good chance that you already have seen this question about counting the number of leaf nodes in a binary tree. If you know how to solve this problem then it's well and good but if you haven't don't worry, you will learn in this article. If you follow this blog then you might know that I have discussed a lot of data structure and algorithms problems here, including array, linked list, hash table, binary tree, and binary search tree. 

Thursday, October 28, 2021

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 files, 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 the 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 the icons directory of your project, how do you load them? The answer is by using java.lang.Class' getResource() and getResourceAsStream() method. These methods accept the path of resource as String and return URL and InputStream respectively.

Wednesday, October 27, 2021

6 ways to declare and initialize a two-dimensional (2D) String and Integer Array in Java - Example Tutorial

Declaring a two-dimensional array is very interesting in Java as the Java programming language provides many ways to declare a 2D array and each one of them has some special things to learn about. For example, It's possible to create a two-dimensional array in Java without specifying the second dimension, sounds crazy right? but it's possible because a two-dimensional array in Java is nothing but an array of array. You can even create a two-dimensional array where each subarray has a different length or different type, also known as a heterogeneous array in Java. This means it's possible to create a two-dimensional array with variable column length in Java.

Tuesday, October 26, 2021

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

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 the real-world date and time nuisance like leap seconds, leap years, and daylight saving time.

Friday, October 22, 2021

How to implement Bucket Sort in Java? [Solved] - Example Tutorial

In recent years, one of the questions I have increasingly seen in programming job interviews is about constant time sorting algorithms like do you know any O(n) sorting algorithm? how do they work? When I first encountered this question, I had no idea whether we can sort in constant time because even some of the fastest sorting algorithms like QuickSort or MergeSort take O(N log N) time for sorting on their average case. After some research, mainly by going through the classic CLRS book and this DS and Algorithms course by Tim Buchalka and Goran Lochert on Udemy, I come to know that there indeed are some constant time or linear time sorting algorithms like bucket sort, counting sort, and radix sort, which can sort an array in O(n) time but they work with only a special set of input.

2 Best Open source Java Libraries to Create PDF documents - iText vs Apache FOP

PDF format is a popular format for sending receipts, email confirmation, and other documentation and we often have a requirement to create PDF documents using Java, mostly in JSP pages. Since most of the official documentation uses PDF format nowadays, it becomes imperative to support PDF files. Recently I received a couple of questions regarding the suggestion of open-source Java PDF libraries, like which is the best open source PDF library in Java or should I use iText or Apache FOP in my Java application for PDF processing. These questions motivates me to write this post. In this article, I will share a couple of Java based open source PDF libraries, both FREE and with some licensing fees, which you can use to generate PDF documents in Java projects.

What is difference between ArrayList and ArrayList<?> in Java?- Raw Type vs Wildcard Example Tutorial

One of my readers asked me about the difference between ArrayList vs ArrayList< in Java?>, which was actually asked to him in a recent Java development interview. The key difference between them is that ArrayList is not using Generics while ArrayList is a generic ArrayList but they look very similar. If a method accepts ArrayList or ArrayList<?> as a parameter then it can accept any type of ArrayList like ArrayList of String, Integer, Date, or Object, but if you look closely you will find that one is raw type while the other is using an unbounded wildcard. What difference that could make? Well, that makes a significant difference because ArrayList with raw type is not type-safe but ArrayList<?> with the unbounded wildcard is type-safe.

Wednesday, October 20, 2021

Difference between Abstraction and Encapsulation in Java? OOP Question Answer

Both Abstraction and Encapsulation are two of the four basic OOP concepts which allow you to model real-world things into objects so that you can implement them in your program and code. Many beginners get confused between Abstraction and Encapsulation because they both look very similar. If you ask someone what is Abstraction, he will tell that it's an OOP concept which focuses on relevant information by hiding unnecessary detail, and when you ask about Encapsulation, many will tell that it's another OOP concept which hides data from the outside world. The definitions are not wrong as both Abstraction and Encapsulation do hide something, but the key difference is on intent.

Recursive Binary Search Algorithm in Java - Example Tutorial

The binary search algorithm is one of the most famous search algorithms in computer science. It allows you to search a value in logarithmic time i.e. O(logN), which makes it ideal to search a number on a huge list. For example, in order to search a number in a list of 1 million numbers will take around 210 comparisons compared to 1 million comparisons required by the linear search algorithm. The only thing is that the list must be sorted before you can use a binary search algorithm and it must support index-based search. That's why binary search is often implemented using an array because doing a binary search with a linked list will not be fast because it doesn't provide index-based access i.e. O(1) access. You have to traverse to that element to read its value in the linked list which is O(n), effectively reducing the performance of binary search to a sequential search algorithm.

Tuesday, October 19, 2021

3 Ways to Prevent Method Overriding in Java - Private, Static and Final Method Example Tutorial

Every Java programmer knows that final modifier can be used to prevent method overriding in Java because there is no way someone can override final methods; but, apart from final modifier, is there any other way to prevent method overriding in Java? This was the exact question, asked to one of my friend in a recent Java interview at one of the leading Investment bank. I guess, he was lucky to get this question because he already knows those tricks and was able to answer it quickly. When he told me about his experience,  I didn't understand why someone ask this question? What is the purpose? What they were trying to find out? I can understand if they have asked what's the best way to prevent method overriding in Java, or what is the risk of overriding? 

Monday, October 18, 2021

Java 8 Date Time - 20 Examples of LocalDate, LocalTime, LocalDateTime

Along with lambda expressions, streams, and several minor goodies, Java 8 has also introduced brand new Date and Time API, and in this tutorial, we will learn how to use Java 8 Date Time API with simple how-to-do task examples. Java's handling of Date, Calendar, and Time is long been criticized by the community, which is not helped by Java's decision of making java.util.Date mutable and SimpleDateFormat not thread-safe. It seems, Java has realized a need for better Date and time support, which is good for a community which already used to of Joda Date and Time API.

Difference between Stack and Queue Data Structure in Java? Example

Stack and Queue are two of the important data structures in the programming world and have a variety of usage. As opposed to the array and linked list, which are considered primary data structures, they are secondary data structures that can build using an array or linked list. You can use Stack to solve recursive problems and Queue can be used for ordered processing. The difference between Stack and Queue Data structure is also one of the common questions not only in Java interviews but also in C, C++, and other programming job interviews.

10 Examples of Converting a List to Map in Java 8

Hello guys, suppose you have a list of objects, List and you want to convert that to a Map, where a key is obtained from the object and value is the object itself, how do you do it by using Java 8 stream and lambda expression? Prior to Java 8, you can do this by iterating through the List and populating the map by keys and values. Since it's an iterative approach and if you are looking for a functional solution then you need to use the stream and lambda expression, along with some utility classes like Collectors, which provides several useful methods to convert Stream to List, Set, or Map.

Tuesday, October 12, 2021

How to Remove all Unused imports in a Java file - Eclipse Shortcut Example

How to remove all unused imports in Eclipse
Eclipse IDE gives a warning "The import XXX is never used" whenever it detects unused import in a Java source file and shows a yellow underline. Though unused import in Java file does not create any harm, it's unnecessary to increase the length and size of Java source file and if you have too many unused imports in your Java source file, those yellow underline and Eclipse warning affect readability and working. In my last post on Eclipse, we have seen some Java debugging tips on Eclipse and in this post, we will see Eclipse shortcut to remove all unused imports in Eclipse. 

Friday, October 8, 2021

How to get just DATE or TIME from GETDATE() in SQL Sever - Example Tutorial

The GETDATE is one of the most popular built-in methods of  Microsoft SQL Server, but unlike its name suggests, it doesn't return just date, instead, it returns date with time information e.g. 2015-07-31 15:42:54.470, quite similar to our own java.util.Date from Java world. If you want just a date like 2015-07-31, or just a time like 15:42:54.470 then you need to either CAST or CONVERT output of GETDATE function into DATE or TIME data type. From SQL Server 2008 onward, apart from DATETIME, which is used to store both date and time, You also have a DATE data type to store data without time e.g. 2015-07-31, and a TIME data type to store time without any date information like 15:42:54.470.

Wednesday, October 6, 2021

5 ways to Convert Java 8 Stream to List - Example, Tutorial

One of the common problems while working with Stream API in Java 8 is how to convert a Stream to List in Java because there is no toList() method present in the Stream class. When you are processing a List using Stream's map and filter method, you ideally want your result in some collection so that you can pass it to other parts of the program. Though java.util.stream.Stream class has toArray() method to convert Stream to Array, but there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion methods between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.io.File, they provided a toPath() method to File class.

How to distinguish logging per Client or Request in Java? Use MDC or Mapped Diagnostic Context in Log4j Example

The MDC or Mapped Diagnostic Context is a concept or feature of the Log4j logging library which can be used to group related log messages together. For example, by using MDC you can stamp a unique identification String like clientId or orderId on each log message, and then by using grep command in Linux, you can extract all log messages for a particular client or order to understand exactly what happened to a particular order. This is especially very useful in multi-threaded, concurrent Java applications where multiple threads are simultaneously processing multiple orders from multiple clients.  In such applications, searching for relevant log messages in a big log file where log messages for multiple orders or clients are overlapping is a big task.

Sunday, October 3, 2021

How to find all Checked checkboxes in jQuery? Example Tutorial

Hello guys, suppose you have multiple checkboxes in your HTML page and you want to retrieve all checkboxes which are checked? How will you do that in jQuery? Well, you can use the pseudo selector like :checked to get all checked checkboxes. This selector checks for the checked property of the checkbox and returns only those checkboxes which have this property. For example, the following jQuery selector will return all the checkboxes which are checked:

$('input[type=checkbox]:checked')

In this, we are first selecting all input elements where type is a checkbox and then adding: checked to filter only those which are checked.

What is 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 keywords. Methods with default keywords 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 like the addition of a new method would have broken all clients. That's why when Java 8 decided to switch to internal iterator implementation using the forEach() method, they face the daunting challenge of breaking all implementation of the Iterable interface. Since backward compatibility is a top priority for Java engineers, and it wasn't practical to break all clients, they came up with the idea of the default method.

Friday, October 1, 2021

How to convert float to long or int data type in Java? Example

Yesterday one of the new joiner Java Trainee Engineers from our team came to me and asked about how do you convert a float variable into a long or int data type? He was storing some values coming from another system in the database and only wanted to store values before the decimal point e.g. he was getting "3.144" and he wants to convert it to "3" to store into the database. The good thing was that API was returning a float primitive value and you don't need to convert a String to float etc. I asked him whether he needs routing or not, which he wasn't sure but it turns out that he didn't need that. I explained to him how to do that and that's what you will find in this article as well. In short, there are 3 ways to convert a float value into long or int in Java, but we will only focus on the long data type part.