Skip to main content

Posts

Showing posts with the label Java8

Java : How to convert String to Date?

 Introduction In this post, we will learn how to convert Java String to Date  Example: import java.util.Date; public class DateConversion { public static void main(String[] args) {      SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");      try { Date date = sdf.parse("19-09-2020"); System.out.println(date);      } catch (Exception ex) { ex.printStackTrace();      } } } In Java 8 and onward versions, we can use the LocalDate and DateTimeFormatter class to convert a String to a LocalDate object. We will use the parse method of the LocalDate class to perform this conversion Example (using Java 8+ versions) import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateConversion { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); try { LocalDate date = LocalDate.parse("19-09-2020",formatter); System.out.println(da

Java : How to convert java.util.Date to Gregorian Calendar Date Format?

Introduction Below example demonstrates how to convert java.util.Date to Gregorian Calendar  Example import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateToGregorianCalendar { public static void main(String[] args) { Date date = Calendar.getInstance().getTime(); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(date); } }

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

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

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() {

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

Jersey Java Framework - How to add HTTP Basic Authentication to RESTful web services?

Overview I have shown you in the following post how to develop the RESTful web services using the Jersey Java Framework Jersey JAX-RS Framework - Step by Step Guide for Developing RESTful web services There are different security levels that we can add to web services a) Authentication b) Authorization c) Encryption The scope of this post is for Authentication. If we look at the available options then we have a) OpenID b) OAuth c) HTTP Basic Authentication  HTTP Basic level authentication is the weakest among the above three available options but it is still preferable over no Authentication :) Let's start how to implement  the Basic HTTP Authentication. Requirements for this tutorial  Eclipse  Maven Jersey Framework Tomcat STEP 1 First, we will code our filter to process the request before redirecting it to the respective resource. We will achieve it by implementing the  ContainerRequestFilter. We will add the following dependency to the

Best way to convert float to int in Java 8?

Most of the time, Java developers have to do type conversion. In this example, I will cover the conversion of  float datatype to int . There are several ways to achieve this. Solution 1 public class FloatToIntCasting {               public static void main( String[] args ) {                  float value = 0.9f;                  System.out.println( "0.9f converted to int : " +  (int) value );                  value = 1.1f;                  System.out.println( "1.1f converted to int : " + (int) value );              } } Output  0.9 f converted to int : 0 1.1 f converted to  int  : 1 As we can see in the above example, casting a float to int results in downcasting. It simply removes the fraction part and returns the value. Solution 2 public class FloatToIntUsingMathRound {     public static void main( String[] args ) {         float value = 0.9f;                    System.out.println( "0.9f rounded to int  : " +