Posts

Showing posts from April, 2019

Compile time polymorphism vs Runtime polymorphism

Polymorphism is the process where the same action can be performed in a number of different ways. Java supports 2 types of polymorphism – Compile time and runtime. Compile time polymorphism Java supports compile-time polymorphism via method overloading.Method overloading allows us to define two or more methods with the same name within a class but with different parameter declarations. Consider the following code snippet: public class AdditionService {int add() {return 3+5;}int add(int i) {return i+i;}int add(int i,int j) {return i+j;}double add(double i,double j) {return i+j;}} This class has 4 methods with the name add. All four add methods differ in the parameters, so there is no compilation error. 1 st add method does not have any parameters, the 2 nd add method takes two integer parameters, the 3 rd add method takes one integer parameter and the 4 th add method takes two double parameters. So the add method is said to be “overloaded” four times. Since the same action can be pe

JShell in Java 9

Image
One of the new features added by Java 9 is the JShell.  In this blog post,  I will be explaining how JShell works. What is JShell ? JShell provides REPL capabilities to Java. REPL stands for Read Evaluate Print Loop. Many languages like Python also provide REPL capabilities. REPL allows you to write Java code and test it without the need to compile it.   How to launch JShell Step 1 – Make sure you have JDK 9 installed   Step 2 -Open a Command prompt and navigate to the JDK\bin folder   Step 3 – Type JShell How to Use JShell Type the code that you want to test. I have typed 4+5. Press Enter   Step 5 – View the results Example 2  – Using a Sysout statement Example 3 – Assigning a value to a variable and using it How to exit JShell Type /exit

Java 8 BiConsumer Interface Example

In this blog post, I will be explaining how the Java 8 functional interface BiConsumer works. To know more about functional interfaces, you can refer this blog post. Edit The BiConsumer interface provides a method called accept. It accepts 2 parameters of any data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameters passed in. The BiConsumer interface is a specialization of the Consumer interface. To see an example of the Consumer interface, refer to this blog post. BiConsumer example with Two Integer parameter Consider the following code snippet: </pre>public class BiConsumerDemo {public static void main(String args[]){BiConsumer<Integer,Integer> displaySum = (input1,input2) -> System.out.println("Sum of inputs is "+(input1+input2));displaySum.accept(4,8);}}<pre> Here, we have implemented the BiConsumer.accept method using a lambda expression.  This accept method accepts 2 Integer a

Hibernate Persistence Life Cycle and Entity States

Image
In this blog post, I will be explaining the Hibernate Persistence Life Cycle and Entity States. What Are Entity States Given an object that is mapped via Hibernate, it can be in any one of 3 different states – transient, persistent and detached. Transient A transient object is an object that is not associated with a session and that does not have a database record. When you create a new object of a POJO class, that entity instance is in the transient state. Transient objects exist only in memory, Hibernate does not manage transient objects. Persistent A persistent object is an object that has a database record and that is associated with an active session. So the moment you invoke session.save on a transient object, it moves to the persistent state. Once an object is in the persistent state, hibernate tracks changes to it and automatically saves these changes to the database when the session is flushed. Detached An object that has a database record but is not associated with a session

How to find the largest number in an array

In this blog post, I will be demonstrating how you can find the largest number in an array or list. Consider the following code snippet: package demo;public class FindLargestNumberDemo {public static void main(String[] args) {int myArray[] = {2,4,6,8,10,45,9,18,90,12};int largest = 0;for(int num:myArray) {if(num &amp;amp;amp;gt; largest)largest = num;}System.out.println("Largest number is "+largest);}}   Here, we are declaring an array with a list of values. We are then iterating through the elements in the array. We are also declaring a variable called largest and setting its value to 0. Each element in the array is compared to the variable largest. If is is greater than largest, the variable largest is assigned the current element. This is continued for all the elements in the input array. So when this code is executed, it will print the following output:    

Why is Java Platform Independent

A very common interview question is to ask a candidate to explain how Java is platform independent. So let me explain this here. Consider the following simple Java code: public class HelloWorldDemo {public static void main(String[] args) {System.out.println("This is my first Java program!");}} So you can see that the code is in simple English text.  After you write the code you need to compile it. Compilation is the process where the code is converted into a format that is understood by the underlying machine. The underlying machine does not understand the code that we write in English, so it must be converted to a format that it understands. In languages like C or C++, the code is compiled into executable files (files with .exe extension) that are directly executed on the operating system.  So if you have an exe file of a C program for Windows, the exe file will not run as it is on a Linux machine. This is because the exe file created is operating system specific. On the oth

SpringBoot - What and Why

Recently, everyone is talking about how Spring Boot is much better compared to Spring and how it is modular and easy to set up. So in this blog post, I will explain a bit about what Spring Boot is and how it works Edit What is Spring Boot? As per the definition on the Spring.io site, “ Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run ” SpringBoot sits on top of Spring. It helps you to get started with a Spring application quickly without having to write a lot of boilerplate code.  In addition, it provides embedded servers like Tomcat, Jetty etc. So even if you are creating a web application, you can just create a standalone application and deploy it in the embedded server. So you don’t need to waste any time writing boilerplate code, doing XML configuration, adding Jar files or bothering about deploying on a server. You can just focus on writing your code, Spring Boot will do the rest. Why Spring Boot Proble

Java 8 Function Interface Example

In this blog post, I will be explaining how the Java 8 functional interface Function works. To know more about functional interfaces, you can refer  this  blog post. Edit The Function interface provides a method called apply. It accepts a single parameter of any data type and returns a result of any data type. So it basically applies the logic in the apply method to the input parameter and returns the result. Function Interface Example with String Input and Integer return type Consider the following code snippet: public class FunctionDemo {public static void main(String[] args) {Function<String,Integer> lengthChecker = (str) -> {return str.length();};String input = "Hello World";System.out.println("Length of "+input+" is "+lengthChecker.apply(input) );input = "Test";System.out.println("Length of "+input+" is "+lengthChecker.apply(input) );}} Here, we have written a Function implementation that accepts a String

Java 8 forEach loop explained with code samples

Java 8 introduced a lot of new features like functional interfaces, lambda expressions, etc. These provide a totally new way of programming for developers. One such feature is the forEach support added to the Collection interfaces. In this blog post, I will be covering this feature in detail. Edit What is forEach Java 8 added a new method called forEach to all the Collection interfaces via the Iterable interface. You can use this method to iterate through a Collection internally without the need for an explicit for loop. Before Java 8 Prior to Java 8, if we wanted to iterate through a Collection like a List , we had to write code similar to the following: public class ForEachDemo {public static void main(String args[]){List <Integer> list = Arrays.asList(5,3,11,15,9);for(int num:list){System.out.println("Number is "+num);}}} So you need to write a for loop to iterate through the elements in the List. In the body of the for loop, you can write the code that you wa

Java 8 BiPredicate Example

In this blog post, I will be explaining how the Java 8 functional interface BiPredicate works. To know more about functional interfaces, you can refer to this blog post. Edit The BiPredicate interface provides a method called test. This method accepts two parameters of any data type and returns a boolean. The BiPredicate interface is a specialization of the Predicate interface. While the Predicate interface accepts a single argument of any data type, the BiPredicate interface accepts two parameters of any data type. To see an example of the Predicate interface, refer to  this  blog post. BiPredicate method with Two Integer arguments Consider the following code snippet: public class BiPredicateDemo {public static void main(String[] args) {BiPredicate<String,String> isSubString = (str1,str2) -> {return (str1.indexOf(str2)>0 || str1.startsWith(str2));};System.out.println("Hello World has substring as Hello = "+isSubString.test("Hello World","Hel

How to sort a List on objects in Java using a Compator

In this blog post, I will be explaining how you can sort a List of objects in Java using the Comparator interface. Input List Suppose, there is a Person class as follows: public class Person {private String firstName;private String lastName;private int age;public Person(String firstName,String lastName,int age){this.firstName=firstName;this.lastName=lastName;this.age=age;//getter and setter methods public String toString(){ return firstName+" "+lastName+":"+age; }}} And you have a list of Person objects as follows: Person person1 = new Person("Mickey", "Mouse",34); Person person2 = new Person("Donald", "Duck",45); Person person3 = new Person("Peppa", "Pig",12); List<Person> people = new ArrayList<Person>(); people.add(person1); people.add(person2); people.add(person3); Using Comparator to sort in increasing order of age And suppose you want to sort them in the increasing order of a

How to obtain a list of files in a folder

In this blog post, I will be explaining how you can obtain a list of files in a folder. Consider the following code snippet: package learnjava.io;import java.io.File;public class FilesInFolderDemo {public static void main(String[] args) {String folderName = "F:/TestFolder";File file = new File(folderName);if (file.exists() && file.isDirectory()) { // check if file exists & is a folderFile[] files = file.listFiles(); //get list of filesif (files.length > 0) {System.out.println("There are " + files.length + " files in the folder");for(int i = 0; i < files.length;i++){System.out.println("File name is "+files[i]);}} else { //empty folder!System.out.println("Folder is empty !");}} else {System.out.println("Folder "+folderName+" is missing or is not a folder");}}}   There is a method called File.list on the file interface. If the File object corresponding to the specified path is a directory, then this m