Posts

Showing posts from May, 2019

Java 9 Private Interface Methods with code sample

In this blog post, I will be explaining Java 9 private interface methods. This is another of Java 9’s new features. Introduction Java 8 introduced default and static methods in interfaces. Default methods are nothing but methods with some method bodies. Such methods have the keyword “ Default ” specified. Private interface methods allow code reuse in default methods.  So if there is some common code across two or more default methods, this code can be placed in a private method Code Sample public interface MyInterface { default void method1() { commonCode(); System.out.println("Code for method1"); } default void method2() { commonCode(); System.out.println("Code for method2"); } private void commonCode() { System.out.println("Common code"); }} In the above example, the interface MyInterface has 2 default methods, method1 and method2 .In addition, there is a method commonCode which is a private method. This is invoked from both

How to count the number of vowels and consonants in a String

In this blog post, I will be demonstrating a Java program that counts the number of vowels and consonants in a String. Consider the following code sample: public class CountVowelsAndConsonantsDemo { private static List<Character> vowels = Arrays.asList('a','e','i','o','u','A','E','I','O','U'); public static void main(String[] args) { System.out.println("Enter a String:"); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); char[] inputArr = input.toCharArray(); int vowelCount = 0; int consonantCount = 0; for(char c:inputArr){ if(vowels.contains(c)){ vowelCount++; } else consonantCount++; } System.out.println("Number of vowels:"+vowelCount); System.out.println("Number of consonants:"+consonantCount); }}   The code declares and initalizes a list ‘vowels’ with all the vowels in lowercas

Java 8 Method Reference operator explained

Java 8 introduced an operator represented by a double colon(::), known as the “Method Reference” operator.   In this blog post, I will be explaining this operator. A basic understanding of lambda expessions is required in order to understand method references. Edit What is the Method Reference operator? The method reference operator can be used to refer to a method. Normally, you can implement a functional interface using a lambda expression. Sometimes, your code may already have a method that has the same functionality that you want your lambda expression to implement. So instead of re-writing the code using a lambda expression, you can implement the lambda expression via the existing method. Code Sample Consider the following code: @FunctionalInterfacepublic interface Shape { public void draw();} This is a functional interface called Shape. It has a single method called “draw()”. Now consider the following code for a class ShapeDrawingDemo public class ShapeDrawingDemo { pub

How to create Spring Boot REST Service and Test it via Postman

Image
In this blog post, I will be explaining how you can create a Spring Boot REST service.  If you would like to see how to create a basic HelloWorld Spring Boot application refer to this blog post. Edit Project Creation and Setup Step 1 – Create a new Maven Project (Refer to this blog post)   Step 2 – Add the following Spring Boot dependencies to the POM file and save. <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.2.RELEASE</version></parent><dependencies><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency></dependencies> Edit Writing Code Step 3 – Create Person class as follows package com.learnjava.model;public class Person { private int id; private String name; private int age; public int getId() { return id; } p

Hibernate Caching Mechanisms Explained

In this blog post, I will be explaining Hibernate caching. Caching is the ability to buffer the data retrieved from the database. So the cache stores recently used data items. So if the same items are requested, these items are then returned from the cache thus reducing the number of calls that are made to the database. This increases the performance of an application Hibernate supports 3 types of cache – First Level, Second Level, and Query Cache. First level cache The first-level cache is nothing but the session cache. It caches data in the session. This cache is automatically enabled, programmers do not need to do anything. Hibernate stores all objects in the session.  So once Hibernate associates an object with a session, it remains in the session till the session is closed. So even if we try to load the object again, a database call is not made if the object is in the session. So also, when the code updates an object, all updates are delayed until the session is committed or close

Stream API anyMatch explained with code samples

In this blog post, I will be demonstrating the anyMatch method provided by Java 8 Stream API. Edit In order to understand the Stream API in detail, refer to this blog post. Code Sample with Integer You can use the anyMatch method to determine if any element in a Collection matches a particular condition. Consider the following code snippet: public class AnyMatchDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11); boolean found = input.stream().anyMatch(num -> num > 9); System.out.println("number > 9 "+found); }} This code checks if there is any number in the input collection that is greater than 9 . First, the code obtains a Stream on the input ArrayList using the stream() method. Then the code invokes the anyMatch method on the stream instance. This method accepts a Predicate instance. Predicate is an in-built functional interface.  Refer this blog post for a detailed Predicate

How to setup Tomcat in Eclipse

Image
In this blog post, I will demonstrate how to set up Tomcat in Eclipse. Step 1 – Visit Tomcat Site and select Tomcat 9 Go to the Tomcat site – http://tomcat.apache.org/. Click on Tomcat 9 in the left pane as shown below: Step 2 – Download the appropriate version I will be downloading the 64-bit windows version Step 3 – Extract the contents of the zip file to an appropriate folder The zip file will contain a folder with the name as “apache-tomcat-9.0.19”. Copy this to an appropriate folder Step 4 – Open Eclipse. Go to servers tab Step 7 – Right click –> New –> Server Step 8 – Select Tomcat 9.0 Server Step 9 – Click Next. Select Tomcat installation directory and JRE 1.8. Step 10 – Click Finish Further Reading Fundamentals of Apache Tomcat Beginning with Eclipse IDE Apache Tomcat Beginners to Advanced Java Programming in Eclipse

JSON Syntax and Benefits explained with code samples

In this blog post, I will be explaining JSON Syntax and benefits. We will be taking a look at how it compares to XML as well. What is JSON JSON stands for JavaScript Object Notation. It is a lightweight transfer protocol. It is based on the JavaScript language. JSON is used primarily in web services to transfer data.  Data sent via JSON is concise and easy to read. Why was JSON required? Prior to JSON, XML was used to transfer data between web services. The downside of using XML is that it is very verbose. For example, suppose you have a Person class as follows:   public class Person { private String firstName; private String lastName; private int age; //Getter and setter methods } And suppose we create a Person list with 3 Person objects as follows: List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Mickey","Mouse",35)); personList.add(new Person("Donald","Duck",30)); personList.add(new Person("Peppa&q

Lambda expressions in Java 8 explained with code samples

You Java 8 introduced a new feature called lambda expressions. In this blog post, I will be explaining lambda expressions in detail. Edit What are lambda expressions Lambda expressions are used to define anonymous functions, that is a function without a name.  Lambda expressions and functional interfaces together help in writing clean code. A functional interface is nothing but an interface with a single method. In order to understand more about functional interfaces, you can refer to this blog post. Lambda expressions can be used to implement functional interfaces. Lambda expression syntax The general syntax of a lambda expression is as follows: (parameters) -> {method body} Parameters Parameters specify the parameters to be passed to the lambda expression. You can pass one or more parameters. You need to enclose the parameters in parentheses. If there is only one parameter, you can skip the parentheses. Also, parameters are optional. If the lambda expression does not accept

How to find the number of digits in a number

This blog post demonstrates how to count the number of digits in a String.   Method 1 – Using division private static int countDigits(int input){int count = 1;if(input > 10){int quotient = 0;do{count ++;quotient = input/10;input = quotient;}while(quotient > 9);}return count;} The code checks if the number is greater than 10. If so, it divides the number by 10 and checks the quotient. It continues doing this as long as the quotient is greater than 9. Method 2 – Using Strings private static int countDigits(int input){String str = String.valueOf(input);return str.length();} Here, the input number is converted to a String and then its length is used to find the number of digits.

What is REST API

Image
In this blog post, I will be explaining what a REST API is. What is REST REST stands for Representational State Transfer. It is a design pattern for web services. Web services that follow this design pattern are known as RESTful web services. There are 2 main components in a REST API. Client The person or application that uses the services is the client. The client can be a web application, mobile application or even an individual developer. Server The server provides some functionality. The client application makes an HTTP call to the server. Any HTTP method (i.e. GET, POST, PUT, DELETE) can be used. The server then acts on the request by the client. So if the client sends an HTTP GET request, the server returns the requested information. If the client sends an HTTP POST request, the server performs the necessary operation with the data sent by the client. How REST works The server exposes functionality as REST endpoints which are simply URLs. The client application needs to access th

Java If else

In this blog post, I will be explaining how the if else statement works in Java. What is if-else The if-else statement is used to check for a condition. If the condition specified after the “if” keyword is true, the code following the if keyword is executed. If the code following the if keyword is false, the code following the else keyword is executed. Syntax if(condition){//some code here}else{ // this part is optional//some code here} Code Sample 1 Consider the following code snippet: int a = 20;int b = 15;if(a > b){System.out.println("a is greater than b");}else {System.out.println("a is less than b");} Variables called a and b are declared and initialized to 20 and 15 respectively The if keyword is followed by a condition i.e. a > b Since a > b is true, the code within the if block is executed If a > b was false, the code within the else block would have been executed   When this above code is executed, it will print the following output: a is

Spring Boot JPA Example with Eclipse and Maven

Image
In this blog post, I will be demonstrating how you can insert records and query a database table via Spring Boot and JPA using Eclipse and Maven Edit Step 1 – Create a New Maven Project Create a new Maven project. (Refer to this blog post). This will create a project in Eclipse as follows: Step 2 – Add Spring Boot JPA dependencies to the pom file Add the following text to the pom.xml file: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.learnjava</groupId> <artifactId>SpringBootJPADemo</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId>

Hibernate interfaces explained

In this blog post, I will be explaining some of the interfaces that are commonly used in a Hibernate application Sample Code Consider the following code that queries a table via Hibernate: public class Main { public static void main(String[] args) { Person person = new Person("Mickey Mouse",35); //This corresponds to a table called Person with name and age fields SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.save(person); tx.commit(); session.close(); sessionFactory.close(); }} Configuration The Configuration object is the first Hibernate object that you will need to create in any Hibernate application. It encapsulates the Hibernate configuration file i.e. hibernate.cfg.xml . A typical Hibernate application usually creates a Configuration object only once during application initialization. The   configuration.configure

Java 8 Stream API explained with code samples

Java 8 introduced the Stream API. The Stream API along with lambda expressions can be used to perform bulk operations on the elements in a Collection. Not only that, you can pipeline the Stream operations to perform a number of sequential operations. Edit How do Streams work? A new method called stream has been added to all the Collection interfaces, this returns a  java.util.Stream interface. There are various methods on this stream interface that perform the corresponding operation on the Stream instance. Suppose you have an integer array. Suppose you want to find all the elements that are greater than the value 9. Before Streams and Java 8, you would need to write code like the following: public class FilterStreamDemo {public static void main(String[] args) {List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11);List<Integer> output = new ArrayList<Integer>();for(int num:input){if(num >= 9)output.add(num);}}} So this code iterates through the inpu

Java 8 UnaryOperator Example

In this blog post, I will be explaining how the Java 8 functional interface UnaryOperator works. To know more about functional interfaces, you can refer this blog post. Edit The UnaryOperator interface extends the Function interface. It inherits the apply method in the Function interface. The lambda expression passed to the UnaryOperator is used to provide an implementation for the apply method in the Function interface.   UnaryOperator example with Integer data type. Consider the following code snippet: public class UnaryOperatorDemo {public static void main(String[] args) {UnaryOperator<Integer> increaseBy5 = num -> num+5;System.out.println("Output with input 7 is "+increaseBy5.apply(7));}} Here, we have implemented the UnaryOperator.apply method using a lambda expression.  This method simply increases the value of the input number by 5 and returns it. So when you execute this code, it will print the following output: Output with input 7 is 12 UnaryOpera