Skip to main content

Posts

Showing posts from 2019

JDBC – PreparedStatement– How to Set Null value?

Introduction Java Database Connection (JDBC) API allows the Java programmers to access different relational and NoSQL databases like Oracle, MySQL, SQL Server, etc. It helps to store, access and manipulate the data stored in these databases. In this post, we will explore how to set the NULL values in PreparedStatement. Null String data type For String data type, it does not matter if the value to be set as a parameter in the SQL query is NULL.   Other data types like Integer, Float, Double, Date, etc. For data types like Integer , Float , Double , Date we have to explicitly call the setNull method. Example String name = null ; Long id = null ; PreparedStatement ps = connection.prepareStatement("select * from person where first_name = ? and id = ?");  ps.setString(1,name); The above line will execute without throwing any exception ps.setLong(2, id); In the above line of code, since id is null, it will throw java.lang.NullPoi

Apache Maven - How to set network proxy settings?

In the following post, we learned how to install Apache Maven on Windows 10 How to install Apache Maven on Windows? If your development PC is behind a proxy network, you will not be able to add Java dependencies through Maven. Luckily Maven provides us with proxy settings. Add your network proxy to Maven's proxy settings STEP 1:  Navigate to your maven's directory and open conf folder E:\apache-maven-3.6.2\conf STEP 2:  Open settings.xml in your favorite text editor STEP 3: Uncomment the proxy tag inside proxies tag and add the values according to your network's proxy settings. <proxy>       <active>true</active>       <protocol>http</protocol>       <username>proxyuser</username>       <password>proxypass</password>       <host>proxy.host.net</host>       <port>80</port>       <nonProxyHosts>local.net|some.host.com</nonProxyHosts>     </proxy>

How to install Apache Maven on Windows 10?

Apache Maven is a Java tool that helps in building and managing the Java project. It is based on the concept of Project Object Modle(POM). It helps the Java developers to manage the project's JAR files in a central repository and those JAR files can be shared across the project. Maven project has the following objectives makes the build process easy provides a uniform build system  and many more In this post, we will learn how to install the Apache Maven on Windows (10). STEP 1: Download and install Java Download Java from  https://www.java.com/en/download/ . and install it. STEP 2: Download Apache Maven Download Apache Maven from  https://maven.apache.org/download.cgi  and extract it on your local machine like I have unzipped it to  E:\apache-maven-3.6.2 STEP 3: Set the JAVA_HOME environmental variable Right Click This PC ->  Properties -> Advanced system settings -> Environmental Variables Open Environmental Variables Click on N

How to convert a String to int in Java?

Introduction In this post, we will learn to convert String to int primitive data type. Java provides the Integer wrapper class to convert a String to int. Integer.parseInt(String) String numberString = "134"; int number = Integer.parseInt(numberString ); System.out.println(number); Output : 134 Integer.valueOf(String) String numberString = "134"; int number = Integer.valueOf(numberString ); System.out.println(number); Output : 134 The following code will throw NumberFormatException //134a cannot be converted to Integer String numberString = "134a"; int number = Integer.valueOf(numberString ); System.out.println(number); Exception in thread "main" java.lang.NumberFormatException: For input string: "134a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.valueOf(Unknown Source) at StringExample.main(StringExample

Top 10 mostly asked Java String Interview Questions

Introduction String is the most widely used class in any language. In this post, we will explore String in Java context. This post will help you to understand the String in-depth and to answer String related questions in a Job interview. 1. What is String? String is a final class in Java and not a primitive data type like int, float, etc. It is defined in java.lang package and therefore available by default. 2. How to create objects of String? There are two ways to create String a. String literals String str = "abc"; b. Using new operator String str = new String("abc"); 3. Where is String stored in memory? String literals are stored in the String constant pool. A string is called immutable or constant i.e. once created then it can not be changed. Whenever we create a String using double quotes (String literal), Java looks into the String constant pool if an object with the same value is present, it returns the reference to that object

Prime Anagrams - Comparing Anagrams using Prime Numbers

Introduction In this post, we will use prime numbers to compare anagrams. We will assign the prime number to each character in a string and then multiply them. Two strings will be equal if their product is the same. Implementation in Java public class PrimeAnagram { static int [] alphaPrime = {5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107}; static String alphabets = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { System.out.println(isPrimeAnagram("parse", "spare")); } private static boolean isPrimeAnagram(String value1,String value2) { return getPrime(value1) == getPrime(value2); } private static int getPrime(String value) { value = value.toLowerCase(); int productValue = 1; for(int index = 0; index < value.length(); index++) { productValue *= alphaPrime[ alphabets.indexOf(value.charAt(index)) ]; } return productValue; } } Conclusion We

Often asked interview question to write code of Singleton Pattern?

Introduction I have been often asked this question in an interview to write a code of Singleton pattern. I have noticed that developers have the knowledge of what is Singleton pattern but often they forget the key points regarding its implementation. In this post, I will highlight the key points to remember for your upcoming interview. Implementation public class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } } Key Points to remember a) instance is declared as private and static  b) The constructor is declared as private c) getInstance method is static and synchronized to make it thread free Conclusion In this post, we learned how to implement the Singleton pattern using Java language. We have also noted down the key points to remember.Please leave your comments in the comments box.

Solution of popular FizzBuzz coding puzzle in Java language

Introduction FizzBuzz is one of the popular coding puzzles asked in a programming interview. In this post, we will learn its implementation using Java 8. Problem We have 1 to n Integers. Write a program that iterates over these integers, print Fizz if Integer is multiple of 3, print Buzz if Integer is multiple of 5, print FizzBuzz if Integer is multiple of both 3 and 5 else print the Integer.  Solution import java.util.stream.IntStream; public class FizzBuzz { public static void main(String[] args) { int n = 100; IntStream.range(1, n).forEach( i -> { /* if( i % 3 == 0 && i % 5 == 0 ) is equivalent to i % 15 == 0 * and will reduce lines of code */ if( i % 15 == 0) { System.out.println("FizzBuzz"); }else if ( i % 3 == 0) { System.out.println("Fizz"); }else if ( i % 5 == 0) { System.out.println("Buzz"); }else { System.out.println(i); } }); } } Note that multiple of 15 is mult

How to sort collections in Java 8?

Introduction In this post, we will explore different ways to sort Java collections in a certain order. Java platform provides a  Collections framework that represents a group of objects. All the Java classes those implement the Collection interface have by default implemented the sort method i.e. Collections.sort(list/set/Array) Java classes like String, Date, Integer, Double, Float, Long, Integer etc implements the Comparable interface by default. Java provides us with the following two interfaces to compare and sort the custom objects Comparable Interface  public interface Comparable<T> { public int compareTo(T o); } Java 8 also provides the built in Comparator.comparing method that returns an instance of Comparable. Comparator Interface public interface Comparator<T> { int compare(T o1, T o2); } In this post we will use the following student class for practice. public class Student{ public String name; public Integer age; public St

Java - How to sort String in alphabetical order?

Introduction In this post, we will learn the following two examples a) Sort single String in alphabetical order b) Sort array of Strings Sort single String in alphabetical order import java.util.Arrays; public class SortStringAlphabetical { private static String inputString = "The quick brown fox jumps over the lazy dog"; public static void main(String[] args) { System.out.println("Input String : " + inputString); char [] characters = inputString.toCharArray(); Arrays.sort(characters); System.out.println("Alphabetical sorted String : " + new String(characters)); } } Output Input String : The quick brown fox jumps over the lazy dog Alphabetical sorted String :         Tabcdeeefghhijklmnoooopqrrstuuvwxyz Sort array of Strings import java.util.Arrays; public class SortStringArrayAlphabetical { private static String inputStrings[] = {"efg","xyz","abc"}; public static void ma

Hibernate 5.4.4 - How to fix hibernate depreciation warnings?

Problem Recently we migrated Hibernate to the latest version i.e. 5.4.4. Multiple depreciation warnings appeared in our code i.e. The type Query<R> is deprecated The method setString(String, String) from the type Query is deprecated The method uniqueResult() from the type Query is deprecated The method setBoolean(String, boolean) from the type Query is deprecated The method setLong(String, long) from the type Query is deprecated Solution Existing Change To import org.hibernate.Query; import org.hibernate. query .Query; query . setLong ( "serviceId" , serviceId ) ; query . setParameter ( "serviceId" , serviceId ); query . setBoolean ( "isDelete" ,Boolean. FALSE ) ; query . setParameter ( "isDelete" ,Boolean. FALSE ) ; query . setString ( "serviceNo" , serviceNo ) ; query . setParameter ( "serviceNo"

Scala language implementation of Selection Sort

Introduction Selection sort is the simplest sorting algorithm in terms of implementation. Let's consider we have a list of elements i.e. {3, 9, 0, 5, 4 } a) Selection sort maintains two sublists, one sorted and initially empty and second unsorted sublist i.e. [ {}, {3, 9 , 0, 5 ,4 }] b) It searches for the minimum element (for ascending sort) OR for a maximum element( for descending sort) in the unsorted list in each step. Step 1 [ {0 }, {9,3,5,4}] Minimum element = 0 , swapped with 3 Step 2 Minimum element = 3 , swapped with 9 [{0,3) , {9,5,4} ] Step 3 Minimum element = 4 , swapped with 9 [{0,3,4} , {5,9}] Step 4 Minimum element = 5 , swapped with itself [{0,3,4,5}, {9}] Step 5 Minimum element = 9 , swapped with itself [{0,3,4,5,9}, {}] Worst Complexity: O(n*n) Best Complexity   : O(n * n) Implementation package main.scala object SelectionSort { val array = Array(0, 5, 2, 6, 3, 1) def main(args: Array[String]) { print(&quo

Java Example of Selection Sort

Introduction Selection sort is the simplest sorting algorithm in terms of implementation. Let's consider we have a list of elements i.e. {3, 9, 0, 5, 4 } a) Selection sort maintains two sublists, one sorted and initially empty and second unsorted sublist i.e. [ {}, {3, 9 , 0, 5 ,4 }] b) It searches for the minimum element (for ascending sort) OR for a maximum element( for descending sort) in the unsorted list in each step. Step 1 [ {0 }, {9,3,5,4}] Minimum element = 0 , swapped with 3 Step 2 Minimum element = 3 , swapped with 9 [{0,3) , {9,5,4} ] Step 3 Minimum element = 4 , swapped with 9 [{0,3,4} , {5,9}] Step 4 Minimum element = 5 , swapped with itself [{0,3,4,5}, {9}] Step 5 Minimum element = 9 , swapped with itself [{0,3,4,5,9}, {}] Worst Complexity: O(n*n) Best Complexity   : O(n * n) Imperative style implementation using Java 7 public class SelectionSortExample { private static int array[] = {3,9,0,5,4}; public static void mai

Scala Implementation of Insertion Sort

Introduction Insertion sort is the best sorting algorithm for small-sized list of elements as compared to selection sort and  bubble sort . This sorting algorithm always maintains a sorted sublist within an iteration i.e. it finds the correct position of a single element at a time and inserts it in its correct position within the currently sorted sublist. Worst Complexity     : O(n*n) Best Complexity        : O(n) Average Complexity : O(n*n) Implementation package main.scala object InsertionSort {   val array = Array(0, 5, 2, 6, 3, 1)   def main(args: Array[String]) {     print("Unsorted List ")     println(array.toList)     print("Asceding sorted List ")     insertionSortAscending;     println(array.toList)     insertionSortDescending     print("Desceding sorted List ")     println(array.toList)   }   def insertionSortAscending { //first element is considered as sorted sublist     for (outer <- 1 until array.length) {

Java code of Insertion sort

Introduction Insertion sort is the best sorting algorithm for small-sized list of elements as compared to selection sort and bubble sort . This sorting algorithm always maintains a sorted sublist within an iteration i.e. it finds the correct position of a single element at a time and inserts it in its correct position within the currently sorted sublist. Worst Complexity    : O(n*n) Best Complexity        : O(n) Average Complexity : O(n*n) Imperative style using Java 7 public class InsertionSortExample { private static int array[] = {0,5,2,6,3,1,-9}; public static void main(String[] args) { insertionSortAscending(); System.out.println("Ascending Sorted List"); for(int value : array) { System.out.print(value + " "); } insertionSortDescending(); System.out.println("\nDescending Sorted List"); for(int value : array) { System.out.print(value + " "); } } private static void insertionSortAscending() {

Scala language implementation of Bubble Sort

Introduction Bubble sort is the simplest sorting algorithm. It has the following steps a) Iterates through the list b) Compares the adjacent elements c) Swap the adjacent elements if they are in not in proper sorting order d) The list is traversed repeatedly unless the list is sorted Worst Complexity : O(n*n) Best Complexity    : O(n) Alternate name      : Sinking Sort Implementation package main.scala object BubbleSort { val array = Array(0,5,2,6,3,1) def main (args : Array[String] ) { print("Unsorted List ") println(array.toList) print("Ascending sorted List ") bubbleSortAscending; println(array.toList) bubbleSortDescending print("Descending sorted List ") println(array.toList) } def bubbleSortAscending { //in scala you can combine inner and outer loops, until does not include the last number for( i <- 0 until array.length; j <- 1 until array.le

Create New Scala sbt project for Eclipse

Introduction In this post, we will learn how to create a new Scala sbt project and convert it into the eclipse project. We will then import the project into eclipse Step 1 Open your user's home directory, on windows, it will be user directory\.sbt\1.0\ Step 2 Create a new directory by the name of plugins if one does not exist Step 3 Create a new file  plugins.sbt ( if one does not exist)   inside the plugins folder Step 4 Open the newly created file  plugins.sbt and add the following line addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.2.4") Step 5 Open a Command prompt and create a new directory for your Scala project i.e. > mkdir FirstScalaEclipseProject Step 6 Move to the new directory > cd FirstScalaEclipseProject Step 7 Enter the following command > sbt reload (if the shell is not restarted) > sbt eclipse Step 8 Open the eclipse, Go to File -> Import -> Import Existing Proj

Java Bubble Sort Example

Introduction Bubble sort is the simplest sorting algorithm. It has the following steps a) Iterates through the list b) Compares the adjacent elements c) Swap the adjacent elements if they are in not in proper sorting order d) The list is traversed repeatedly unless the list is sorted Worst Complexity : O(n*n) Best Complexity    : O(n) Alternate name      : Sinking Sort Implementation using Simple Loops public class BubbleSortExample { private static int array[] = {0,5,2,6,3,1}; static int temp = 0; public static void main(String[] args) { bubbleSortAscending(); System.out.println("Ascending Sorted List"); for(int value : array) { System.out.print(value + " "); } bubbleSortDescending(); System.out.println("Descending Sorted List"); for(int value : array) { System.out.print(value + " "); } } private static void bubbleSortAscending() { for(int outer=0; outer<array.length; outer++) {

WARN orm.deprecation - HHH90000014: Found use of deprecated [org.hibernate.id.SequenceGenerator] sequence-based id generator

Introduction  I upgraded Hibernate from version 4 to 5.4.4. Following warning was thrown by Hibernate WARN  orm.deprecation - HHH90000014: Found use of deprecated [org.hibernate.id.SequenceGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead.  See Hibernate Domain Model Mapping Guide for details. http-nio-8080-exec-10 WARN  orm.deprecation - HHH90000014: Found use of deprecated [org.hibernate.id.SequenceHiLoGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead.  See Hibernate Domain Model Mapping Guide for details. Old Code     @Id     @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_PERSON")     @SequenceGenerator(name = "SEQ_PERSON", sequenceName = "SEQ_PERSON_ID",allocationSize=1)     private Long id; SequenceGenerator is deprecated by Hibernate and we have to use either SequenceStyleGenerator or GenericGenerator instea

Default Port numbers used by different software/protocols

The following table lists the default port numbers used by different software/protocols Software/Protocol Default Port Number http 80 https 443 Apache Server 80 IIS Server 80 Apache Tomcat 8080 MySQL server 3306 SQL Server 1433  MongoDB   27017 PostgreSQL 5432 Java No default port DynamoDB 8000 Cassandra 7000 neo4j http port 7474 neo4j https port 7473 Oracle SQL*Net Listener 1521 Oracle Data Guard 1521 Oracle Connection Manager 1630 Oracle Management Agent 3938 Oracle Enterprise Manager Database Console 1158 Oracle SQL*Plus RMI Port 5580 Oracle SQL*Plus JMS Port 5600

Hibernate - Could not instantiate id generator [entity-name=domainObject]

Exception Could not instantiate id generator [entity-name=Your DomainObject] Solution  <generator> or @GeneratedValue specifies the Java class that is used to generate a unique identifier to the mapped persistent class. Using increment  hbm.xml example <id name="id" type="java.lang.Long" column="id">        <generator class="increment" /> </id> Annotation example @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="ID") private Long id; Using database sequence hbm.xml example <id name="id" type="java.lang.Long" column="id">   <generator class="sequence">     <param name="sequence">SEQ_PERSON_ID</param>  </generator> </id> Annotation example @Id @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="PERSON_SEQ") @SequenceGenerator(name="PERSON_SEQ&qu

Hibernate 5.4.4 - select hibernate_sequence.nextval from dual

Exception http-nio-8080-exec-1 DEBUG hibernate.SQL - select hibernate_sequence.nextval from dual http-nio-8080-exec-1 WARN  spi.SqlExceptionHelper - SQL Error: 2289, SQLState: 42000 http-nio-8080-exec-1 ERROR spi.SqlExceptionHelper - ORA-02289: sequence does not exist org.hibernate.exception.SQLGrammarException: could not extract ResultSet at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) Solution Default value for hibernate.id.new_generator_mappings setting changed to true for 5.0, in previous versions it was set to false by default Add the following property to hibernate.cfg.xml <property name="hibernate.id.new_generator_mappings"> false </property> OR Add the following property to the configuration properties.put("hibernate.id.new_generator_mappings", " false &

Hibernate 5.4.4 - Instantiate an instance of SessionFactory

Introduction We will learn how to create an instance of SessionFactory using Hibernate 5.4.4 Code private static final SessionFactory sessionFactory; public static final String cfgFileLocation = "/hibernate.cfg.xml";  try {          StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()                                            .configure( cfgFileLocation ).build();           Metadata metadata = new MetadataSources( standardRegistry )             .getMetadataBuilder()             .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )             .build();     sessionFactory = metadata.getSessionFactoryBuilder()           .build();     } catch (Throwable ex) {                  System.out.println( "exception" );         throw new ExceptionInInitializerError(ex);     } Following exceptions are resolved through the above code java.lang.IllegalArgumentException: org.hibernate.hql.intern

hibernate-release-5.4.4.Final - Required Jars

Introduction Hibernate (Object Relational Mapping framework) is an implementation of Java Persistence API (JPA) specification.   Required Jars for Hibernate 5.4.4 Following Jars resided inside the required folder are the mandatory jars required for Hibernate 5.4.4 antlr-2.7.7.jar byte-buddy-1.9.11.jar classmate-1.3.4.jar dom4j-2.1.1.jar FastInfoset-1.2.15.jar hibernate-commons-annotations-5.1.0.Final.jar hibernate-core-5.4.4.Final.jar istack-commons-runtime-3.0.7.jar jandex-2.0.5.Final.jar javassist-3.24.0-GA.jar javax.activation-api-1.2.0.jar javax.persistence-api-2.2.jar jaxb-api-2.3.1.jar jaxb-runtime-2.3.1.jar jboss-logging-3.3.2.Final.jar jboss-transaction-api_1.2_spec-1.1.1.Final.jar stax-ex-1.8.jar txw2-2.3.1.jar Hibernate 5.4.4 release is compatible with  Java 8 or 11  JPA 2.2 References https://hibernate.org/orm/releases/5.4/

Jersey Framework Client - How to add HTTP Basic Authentication Header to HTTP Request?

Introduction In this tutorial, we will learn how to add HTTP basic authorization token to the HTTP request header. We will use Jersey Framework to consume RESTful web services. Read the following post if you want to learn how to secure web services using HTTP Basic Authentication Jersey Java Framework - How to add HTTP Basic Authentication to RESTful web services? Maven Dependencies <dependency>     <groupId>org.glassfish.jersey.core</groupId>     <artifactId>jersey-client</artifactId>     <version>2.29</version>  </dependency>  <dependency>     <groupId>org.glassfish.jersey.inject</groupId>     <artifactId>jersey-hk2</artifactId>     <version>2.29</version> </dependency> Basic Authentication is the most simple way to secure HTTP requests. It has the following format Authorization: Basic base64-encoding of username:password Jersey Client Jersy is the refe

Eclipse - Server Tomcat v8.5 Server at localhost failed to start.

When I try to launch the tomcat from Eclipse, I encountered the following error Server Tomcat v8.5 Server at localhost failed to start. Solution Step 1  Delete the .snap file located at the following location     eclipse workspace Path\ .metadata\.plugins\org.eclipse.core.resources Step 2 Delete the  tmp0  folder from the following path      eclipse workspace Path \.metadata\.plugins\org.eclipse.wst.server.core Step 3  Delete the server from servers list Step 4  Remove already added Tomcat Server      i)  Click on Define a new Server     ii)  Select Server Runtime Environments     iii) Select the Tomcat Server and remove it as follows Remove Selected Server Step 5 Make sure that correct version of Server is configured in Project Properties Step 6 Restart the Eclipse IDE.