Posts

Showing posts from March, 2019

How to reverse a List in Java

In this blog post, I will be explaining how you can reverse a Set or 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 ReverseDemo {public static void main(String[] args) {List<Integer>inputList = new ArrayList<Integer>();inputList.add(5);inputList.add(15);inputList.add(20);inputList.add(25);List<Integer>reverserdList1 = reverseList1(inputList);List<Integer>reverserdList2 = reverseList2(inputList);System.out.println("Input List is "+inputList);System.out.println("reverserdList using method1 "+reverserdList1);System.out.println("reverserdList using method2 "+reverserdList2);}private static List<Integer> reverseList2(List<Integer>inputList ){List<Integer> reverserdList = new ArrayList<Integer>();for(int i =inputList.size()-1;i >=0;i--){reverserdList.add(inputList.get(i));}return reverse

Collection Factory Methods in Java 9 with Code Samples

One of the new features of Java 9 is the Java 9 Collection factory methods . These allow you to directly create a Collection object with a list of values. In this blog post, I will be explaining this feature in detail. Before Java 9 Suppose you want to create a List of String values. Prior to Java 9, you had to write code like the following: List<String> inputList = new ArrayList<String>(); inputList.add("One"); inputList.add("Five"); inputList.add("Ten"); inputList.add("Twenty");   The above code snippet involves invoking the List.add method several times and does not look very clean. Java 9 introduced a new method that allows directly adding a list of elements into a Collection without having to invoke the add method several times. Java 9 way Java 9 introduced a factory method called of on the Collection interfaces . This method is present on all the Collection interfaces i.e. List, Set and Map . It returns a Collection co

Hibernate save vs saveOrUpdate

Hibernate provides several methods to save or modify the data into a database table. Two such methods are save and saveOrUpdate . In this blog post, I will be providing a detail comparison between the two. What is save? Hibernate provides the save method on the session interface to save a record into the database. So the session.save inserts a record into the database.  It returns the id , that is the primary key that will be assigned to the database record. What is saveOrUpdate? In addition to the save method, Hibernate also provides a method called saveOrUpdate on the session interface. Just as the name suggests, this method either performs a save operation or an update operation . If there is no record in the database corresponding to the object passed in, it inserts a record, but if there is a record corresponding to the object passed in, it just updates the existing record. This is generally useful in applications where a UI is involved. In such cases the back end might not

Java 8 Consumer Interface example

In this blog post, I will be explaining how the Java 8 functional interface Consumer works. To know more about functional interfaces, you can refer this blog post. Edit The Consumer interface provides a method called accept. It accepts a single parameter of any data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in. Consumer example with Integer parameter Consider the following code snippet: public class ConsumerDemo {public static void main(String args[]){Consumer<Integer> squareGenerator = (input) -> System.out.println("Square of "+input +" is "+(input*input));squareGenerator.accept(6);}}} Here, we have implemented the Consumer.accept method using a lambda expression.  This accept method accepts an Integer argument. It squares it and prints the result to the console. So when this code is executed, it will print the following output: Square of 6 is 36 Consumer example with

How to check if a number is even or odd

This blog post demonstrates how you can check if a number is even or odd via Java.   Consider the following code snippet: public class EvenOddDemo {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("Enter your input:");int num = scanner.nextInt();if(num % 2 == 0)System.out.println("The input number "+num+" is even");elseSystem.out.println("The input number "+num+" is odd");scanner.close();}}   This code first reads an input number using the Scanner class. It then uses the % operator. The % operator returns the remainder of division. So the code checks if the remainder obtained after dividing by 2 is 0. If so, the number is odd, otherwise the number is even. So if you run the code with input as 4, the following output is printed: Enter your input:4The input number 4 is even   If you run the code with input as 7, the following output is printed: Enter your input:7The input number 7 is odd

Java 8 Functional Interface explained with code samples

Java 8 introduced the concept of functional interfaces. In this blog post, I will be explaining what a Java 8 functional interface is. Edit What is a functional interface? A functional interface is nothing but an interface that has only one abstract method. It can have more than one static and default methods, but it should have only one abstract method in order to qualify as a functional interface. Consider the following code snippet: package learnjava.java8;@FunctionalInterfacepublic interface MyFunctionalInterface {public void method1();public default void defaultMethod(){System.out.println("Default method");}public default void staticMethod(){System.out.println("Static method");}} Here, we have defined an interface called  MyFunctionalInterface . This has only one abstract method called method1 and so this is a functional interface. It also has a default and a static method. Note that we have specified the @FunctionalInterface annotation. This annotati

Java 8 Static Interface methods with code samples

Just like default methods , Java 8 also supports static methods in interfaces. In this blog post, I will be explaining Java 8 static interface methods in detail. I will be covering what static methods are, how they work and why they were added. Edit What are static interface methods? Static interface methods are methods with the static keyword are with a method body. How do static interface methods work? Consider the following code snippet: </pre>public interface MyInterface {static public void staticMethod(){System.out.println("In staticMethod of interface");}}<pre> So in the code above, the staticMethod is a static interface method.  So we have defined a method with a method body within the interface. It has the static keyword specified. Prior to Java 8, the above code would have caused an error due to two reasons: There is a method with a method body within the interface There is a static method with in the interface How are they similar to default method

Java Autoboxing explained

In this blog post, I will be explaining Java’s autoboxing feature in detail   What is Auto boxing? Java provides class equivalents for all the primitive datatypes. So for example, there is an Integer class which corresponds to the int datatype, a Float class that corresponds to the float data type and so on. Not only that, Java can automatically convert between the class and the corresponding primitive type. So if there is an Integer type, Java can automatically convert it to int and if there is an int type, Java can automatically convert it to Integer. This is known as autoboxing. Consider the following code snippet: public static void main(String[] args) {int i = 5;Integer integer = i;System.out.println("The value of integer is "+integer);} Here, we have defined an int variable called “i” and assigned it the value 5. After that we have defined an Integer variable called integer and assigned it the value “i” . So note that this does not cause any compilation error. Java

Java 8 Default Interface methods explained

One of the new features provided by Java 8 is the support for default methods in interfaces. In this blog post, I will be explaining Java 8 default interface methods in detail. I will be covering what default methods are, how they work and why they were added. Edit What are default interface methods? Default methods are methods in an interface that have method bodies, They are specified with the  keyword “ default “. How do default interface methods work? Prior to Java 8, interfaces could not have method bodies.  So consider the following code snippet: public interface MyInterface {public void methodA();public void methodB(){System.out.println("In methodB");}}   This code causes a compilation error. This is because methodB has a method body.  However, if you are using Java 8, you can change the code as follows: public interface MyInterface {public void methodA();default public void methodB(){System.out.println("In methodB");}} So now, the default keyword is

Nested Classes explained

Quite often, we come across the term “Nested Class” in Java. It is a very common interview topic as well. So in this blog post, I will be explaining what a nested class is in Java. What is a Nested Class? As the word suggests, a nested Java class is a class which lies within another Java class.  Consider the following code snippet: class OuterClass{class NestedClass{}}   The class NestedClass is like any other member of the OuterClass . It has access to other members that is methods and variables of the OuterClass even if a member is a private member. On compiling this code snippet, the compiler creates two class files. One will be the OuterClass.class and the other will be the OuterClass$NestedClass.class .  If you have more than one nested class, the compiler creates a separate class file for each one. However, each of them will be prefixed with the name of the enclosing class and the $ sign. Why do we need nested classes? The following are some reasons where you will need Nested

How to convert a Java list to an array

In this blog post, I will be explaining how you can convert a Java list to an array. To see how to convert an Array to a List, click here .   There are a couple of ways to do this. Consider the following code snippet: public class ListToArrayDemo {public static void main(String[] args) {//Method 1List<Integer> list = Arrays.asList(5,3,11,15,9);Object[] objects = list.toArray();//Method 2Integer[] integers = new Integer[list.size()];integers = list.toArray(integers);//Method 3Integer[] integers2 = new Integer[list.size()];for(int i = 0; i < list.size();i++){integers2[0] = list.get(0);}}} This code shows 3 ways to convert a List having integers to an array. Though I’ve used an Integer List here, you can use a List that stores any type of data. Method 1  The toArray method available on the list interface is used in this approach. This method returns an Object array. The downside to this approach is that the resultant array is an Object array. So you loose the type of data presen