Posts

Showing posts from February, 2019

JPA vs Hibernate - An In-depth comparison

Often, we come across the terms JPA and Hibernate. Quite often, they are used interchangeably as well. Also, if you try to read up some tutorial to JPA, there will be a reference to Hibernate in it. So also, when you are studying Hibernate, you will come across references to JPA too. So it is often confusing for developers. In this post, I will attempt to clear this confusion. What is Hibernate? Hibernate is an ORM tool. ORM is nothing but a programming technique that allows you to map Java objects to database tables and vice versa. In addition to Hibernate, there are several other ORM tools. Before Hibernate came into existence, JDBC was widely used to access a relational database from Java code. The downside of JDBC is that it is not very object oriented.  It is very hard to map database tables to the code. Hibernate allows you to directly map your database tables to Java classes. So compared to JDBC, Hibernate provides a much cleaner approach. However, there is a disadvantage to usi

How to find if two lists are exactly the same

In this blog post, I will be explaining how you can check if 2 lists are exactly the same. Consider the following code snippet: public class CompareLists {public static void main(String[] args) {List<Integer> list1 = Arrays.asList(3,9,5,15,11);List<Integer> list2 = Arrays.asList(3,9,5,15,11);boolean matches = false;if(list1.size() == list2.size()){matches = list1.containsAll(list2);}if(matches)System.out.println("List1 and List2 are the same");elseSystem.out.println("List1 and List2 are different");}}   Here, we have 2 lists, list1 and list2 . First, we are comparing the size of the lists.  If they are different, then it means that the two lists are different. However, if the sizes are the same, then the code invokes the list.containsAll method. This method returns true if the list on which it is invoked contains all the elements in the list passed in. So when you run this code, it will print the following output: List1 and List2 are the same Now lets

How to check if an input character is a vowel

In this blog post, I will be demonstrating how you can check if an input character is a vowel. I will be using Enum for this. If you’d like to study enums in detail, you can refer to this blog post.   Consider the following code snippet: public enum Vowels {a,e,i,o,u;}public class CheckIfVowel {public static void main(String[] args) {System.out.println("Enter a character:");Scanner scanner = new Scanner(System.in);String input = scanner.nextLine();boolean found = false;for(Vowels vowel:Vowels.values()){if (vowel.name().equalsIgnoreCase(input)){found = true;break;}}if(!found) System.out.println("Input "+input +" is NOT a vowel");else System.out.println("Input "+input +" is a vowel");scanner.close();}} Code explanation First, the code declares an Enum called Vowels . It is assigned the vowels i.e. a,e,i,o,u .  We are using the CheckIfVowel class to check if the input character is a vowel. The input character is read using the Scanne

What is Hibernate Criteria API

In this blog post, I will be explaining what is the Hibernate Criteria API. There are 3 ways in which you can query a database via Hibernate: Methods like load/get HQL (Hibernate Query Language) Criteria API Approach 1 – Methods like load/get Hibernate provides methods like load and get . You can use these to load a specific record from the database. The downside is that you can use these methods to only load a single record corresponding to an id. So if you want to retrieve all records that have a certain value, you cannot use these methods Approach 2 – Using HQL HQL stands for Hibernate Query Language . It has syntax similar to SQL.So whenever you need to query the database, you can write HQL queries in Hibernate. Instead of the database table and column names, you need to specify the class and field names in an HQL query. Based on the underlying database being used, Hibernate automatically converts HQL into equivalent SQLs statements. The downside to using HQL is that it is not a v

Statement vs PreparedStatement

In JDBC programming, you might have come across the Statement and PreparedStatement interfaces. In this blog post, I will provide a comparison between the two. You can use both  Statement and PreparedStatement  to execute a query on a database table via JDBC. However, there are several differences between the two. Difference 1  – PreparedStatement is more efficient as compared to Statement A Statement object directly executes the SQL statement. In contrast, a PreparedStatement  is a pre-compiled SQL statement. It parses and compiles the underlying query only once. After that, the query can be executed with different parameters. So if you need to run a particular query several times but with different parameters, a PreparedStatement  is more efficient. Consider the following code snippet ( Code Listing 1 )   Class.forName(&quot;com.mysql.jdbc.Driver&quot;);// Open a connectionconn = DriverManager.getConnection(&quot;url&quot;, &quot;username&quot;, &quot;p

NullPointerException explained

How many times has a NullPointerException in your code caused the code to break? In this blog post, I will be explaining what a NullPointerException is and what you can do to prevent it.   What is a NullPointerException? A NullPointerException is a RuntimeException . It is an unchecked exception and so does not need to be handled by the code. It occurs when you try to manipulate an object that has a null value.   When does it occur ? A NullPointerException can occur in several scenarios. Scenario 1 – Invoking a method on an object that has a null value. The most common scenarios where a NullPointerException  occurs is when you invoke a method on an object that has a null value. Consider the following code snippet:   String str = "Hello World";System.out.println("Length of the String is "+str.length());str = null;System.out.println("Length of the String is "+str.length());   A variable called “ str ” is initialized to the value “ Hello World “. Its length

How to create a list with data without using list.add multiple times

In this blog post, I will be explaining how you can easily create a List of elements with some data. Consider the following code snippet: public static void main(String[] args) {List<Integer> input = new ArrayList<Integer>();input.add(3);input.add(9);input.add(5);input.add(15);input.add(11);}   The code above creates a new ArrayList called input. It invokes the add method multiple times in order to add data to this list. This code does not look very clean. The above code can be re-written as follows: List<Integer> input = Arrays.asList(3,9,5,15,11); Here, the Arrays.asList method is invoked.  The Arrays class has methods for manipulating arrays. It also has the asList method. This returns a List which is backed by the specified array.So in this case, the  Arrays.asList returns an ArrayList  that has the elements specified.

How to calculate the sum of the numbers in an array

In this blog post, I will be explaining how you can calculate the sum of numbers in an array. Consider the following code snippet: package demo;public class SumDemo {public static void main(String[] args) {int numbers[] = {5,4,7,9,12};int sum = 0;for(int number:numbers){sum += number;}System.out.println("sum="+sum);}}   A variable called sum is used to store the sum of numbers. It is initialized to 0. There is a for loop used. This iterates through the input list. It adds each number in the list to the sum variable. This code will print the following output: sum=37

How to sort a List via Java

In this blog post, I will be explaining how you can sort a list via Java.  Consider the following code snippet: package learnjava.collections;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class SortDemo {public static void main(String[] args) {List<Integer> input = new ArrayList<Integer>();input.add(3);input.add(9);input.add(5);input.add(15);input.add(11);System.out.println("Before sorting:"+input);Collections.sort(input);System.out.println("Before sorting:"+input);}}   This code uses the Collections.sort method. The Collections class contains static utility methods that operate on collections like List, Set etc.  When the Collections.sort method is invoked, it sorts the input list in ascending order. The return type of this method is void, so the input list is modified for sort. This code will print the following output: Before sorting:[3, 9, 5, 15, 11]Before sorting:[3, 5, 9, 11, 15]

How to query a database table via JDBC

Image
In this blog post, I will be explaining how you can query a database table via JDBC. JDBC as you might probably know stands for Java Database Connectivity .It is an API which can be used to access a relational database from Java code. Using JDBC, you can execute SQL queries directly from Java code. JDBC has been around for a very long time now.  Although nowadays ORM frameworks like Hibernate, SpringDAO, JPA etc are used to access a database, there is still a lot of legacy code around that uses JDBC. So in this blog post, I will be covering how you use JDBC to query a table.   Database Setup Step 1  – Install MySQL. This step is optional, you need to follow this step only if you want to use a MySQL database. You can download it from here . You can download the version that is appropriate for your operating system. This will download the MySQL Installer. Once the download is complete, you can follow the onscreen instructions to proceed with the installation.I recommend going with the de

How to reverse a sentence via Java

In this blog post, I will be demonstrating how you can reverse a sentence via Java. So if the input String is “Hello World”, the program will print “World Hello”.   Consider the following code snippet: package learnjava.strings;public class ReverseASentenceDemo {public static void main(String[] args) {String inputStr = "This is a test program";System.out.println("Input String is "+inputStr);String[] words = inputStr.split(" ");StringBuffer reversedString = new StringBuffer("");for(int i = words.length-1; i >= 0; i --){reversedString.append(words[i]);if(i != 0)reversedString.append(" ");}System.out.println("Reversed String is "+reversedString.toString());}}   In this code, the input String is first split using the String.split method. It is split based on spaces, so it returns an array of words. This array is then traversed in the reverse direction. Each word in the array is appended to a new StringBuffer object. If the cu

ArrayList Vs LinkedList

In this blog post, I will be comparing the ArrayList and LinkedList classes. I will be explaining how they are similar, how they are different and when you should use which.   Similarities: Both are Collections and implement the List interface Both are used to store a dynamic number of elements (Primitive or Object type) Differences ArrayList uses an array data structure internally to store the data. A LinkedList on the other hand, uses a doubly linked list internally as the data structure to store data. If you are not familiar with what a Linked List data structure is, you can refer this link . When you need to insert or delete data from the bottom of the List, an ArrayList is faster. If you need to insert or delete an element from the middle of the list,  a LinkedList is faster. An ArrayList  uses an array to store the data internally. So when you insert or delete an element from the bottom of the list, this does not affect the array. However if you insert or delete an element fro