الخميس، 30 أبريل 2020

Kotlin Program to Convert a Stack Trace to a String

1. Introduction


In this article, You'll learn how to convert kotlin stack trace to a String programmatically. 

This is part of the Kotlin Program Series


Kotlin Program to Convert a Stack Trace to a String

Kotlin Program To Convert String to Date

1. Introduction


In this article, you'll learn how to convert String to Date in Kotlin. The string can be any valid date format but you should convert the String date format to an actual date object.

Example: 

String = "2020-05-01";
Converted Date: 2020-05-01 

A converted date is in a form of the Date object.

This is part of the Kotin Programming Series.


Kotlin Program To Convert String to Date

Spring Boot ActiveMQ In Memory Example - Publisher Consumer

1. Introduction


In this article, You will learn how to Create an ActiveMQ Inmemory publisher and consumer model example in Spring Boot.

All the messages that are pushed to the queue will be stored in the memory rather than storing into the database. In the next article,  you can find out "Spring Boot with Standalone ActiveMQ Example"

Spring Boot ActiveMQ InMemory Example - Publisher Consumer


For today's example, you are not required to have active MQ in your local machine. Because we are storing the messages in memory with spring boot in-memory Active MQ.

الثلاثاء، 28 أبريل 2020

Kotlin Program to Convert List (ArrayList) to Array

1. Introduction


In this article, you'll learn how to convert List to Array in Kotlin.

This is part of the Kotlin Programming Series. Here you can find more programs in kotlin.

This can be done simply by calling the toArray() method on the collection object.

Kotlin Program to Convert List (ArrayList) to Array

Java Program To Shell Sort - Step by Step

1. Introduction


In this tutorial, We will learn how to implement the Shell Sort program in java.

First, We'll understand Shell Sort Algorithm then next see the java program on Shell Sort.

Shell sort is an algorithm that first sorts the elements far apart from each other and successively reduces the interval between the elements to be sorted. It is a generalized version of the insertion sort. In shell sort, elements at a specific interval are sorted.

Shell sort, also known as Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting elements far apart from each other and progressively reducing the gap between them.

Java Program To Shell Sort - Step by Step

Kotlin Program to Get Current Date and Time

1. Introduction


In this tutorial, You'll learn how to get the current date and time in kotlin. Further, you will see the examples how to get the default date and time, getting date in a specified pattern or format and also showing programs on locales.

Java : jdk1.8.0_251
Kotlin: 1.3

Kotlin Program to Get Current Date and Time


If you are new to Kotlin, you can set up Kotlin in Intelleji Idea.

الاثنين، 27 أبريل 2020

Create and Run First Kotlin Project In IntelliJ IDEA

1. Introduction


In this article, First how to create a kotlin project in IntelliJ IDEA IDE and next you'll learn how to create a class in Kotlin. Finally, running first Hello World program in Kotlin.

2. Create a Kotlin Project in IntelliJ IDEA


First, you should download the IntelliJ IDEA from jetbrains website.

download  IntelliJ IDEA


After downloading, open the IntelliJ IDEA IDE. Go to "File" menu then next click on "New" next click on "Project".

ArrayList clone() – ArrayList deep copy and shallow copy

1. Introduction


ArrayList clone() – ArrayList deep copy and shallow copy. ArrayList clone() method is used to create a shallow copy of the list. In the new list, only object references are copied. If we change the object state inside the first ArrayList, then the changed object state will be reflected in the cloned ArrayList as well.

Next, You can see more tutorials on "Collection Series"

ArrayList clone() – ArrayList deep copy and shallow copy

Kotlin Hello World - You First Kotlin Program

Kotlin Hello World Program - 

Your First Program in Kotlin, Hello World Example in Kotlin.

In this post, We will learn how to write Hello World in Kotlin Programming Language.

You can get the Kotlin perspective in eclipse from link here step by step explanation with screenshots.

This is part of Kotlin Tutorial series.


Kotlin Hello World - You First Kotlin Program

Official Guide for eclipse



Kotlin Hello World - You First Kotlin Program

You have to install Kotlin plugin for eclipse then have to move to Kotlin perspective.

السبت، 25 أبريل 2020

How To Load Outside Property Files In Spring Boot





1. Introduction


In this tutorial, we'll learn how to load the properties from external loccation that is from outside of jar file. Loading the properties file from an external location can be done in multiple ways but you should decide which one is suitable for your scenario.

Spring Boot 2 Tutorials

How To Load Outside Property Files In Spring Boot


2. Loading from application.properties


By default, Spring boot will load all the properties from the application.properties file which is located at "src/main/resources".

Building Calculator Application in Spring Boot - @Bean Example



1. Introduction


In this tutorial, We'll learn how to build a simple calculator application using spring boot framework. This is mainly demonstrating to understand @Bean and @Componet annotations usage and how the dependencies are getting injected by the application context.

First, We will see the creation of the calculator interface and its implementation classes.

Next, Creating the Bean with @Bean annotation using the method injection technique.

Finally, Understanding the execution and dependency injections.

Further, You can read examples of bean creation using @Component and @Bean annotations.


الخميس، 23 أبريل 2020

Java 8 - Difference between Stream API map() and filter() methods


Java 8 Stream - map() VS filter() 

1. Overview


In this tutorial, We'll be learning what are the differences between map() and filter methods in java 8 Stream API. Many developers have started using these methods in real-time applications but many of them not suer about these methods when and how to use. Let us start writing a simple program to understand the differences.

Both of these methods are present in Stream API and which is used to perform sequential and parallel operations. Apart from this point, these two methods are intermediate operations and return a Stream as a result.

Note: map() and filter() methods can be invoked on a single stream. There is no restriction to use the only operation at a time.

We will see first syntax for both methods and examples. At the last will talk about similarities and differences between them.


Java 8 - Difference between Stream API map() and filter() methods


Spring Boot @Component Annotation - Bean Creation Examples

Spring Boot @Component

1. Introduction


In this article, We'll learn how to use @Component annotation in spring or sprig boot application. This looks similar to the use of @Bean annotation and can be used for bean creation.

2. Spring or Spring Boot @Component Annotation


@Component annotation is a class-level annotation that can not be used on the method level. If you define any class with @Component annotation that should be known to the spring application context.
How to make the component class scanned by spring boot is to specify the package of the class to @ComponentScan annotation or use @SpringBootApplication(scanBasePackages = "com.javaprogramto.component").

Spring Boot @Component Annotation - Bean Creation Examples

الأربعاء، 22 أبريل 2020

Singleton Scope Examples in Spring Boot

1. Introduction


In this article, We'll be learning how to create a singleton bean in Spring Boot and Spring applications. Once a bean is declared as singleton then spring container will create exactly only one instance for that bean. But, We can make bean scope as singleton as a result container will create only once instance as similar to the Singleton Desing Pattern.

By Default, A bean in spring is treated as singleton scoped. But, This can be changed to prototype as well with <bean> tag attribute and @Scope annotation.

Spring Boot Singleton Scope Examples

2. Singleton With @Scope Annotation


First of all, we will see now how to create and next, how to make bean as a singleton with @Scope annotation. @Scope Annotation has attribute value that takes the value as ConfigurableBeanFactory.SCOPE_SINGLETON or ConfigurableBeanFactory.SCOPE_PROTOTYPE

Another this is we already discussed in the previous article, Bean creation with @Bean annotation.


الثلاثاء، 21 أبريل 2020

Spring Boot @Bean - Creating Bean In Spring

Spring Boot Bean Creation

1. Introduction


In this tutorial, We'll learn how to Create Bean in Spring and Spring Boot frameworks. We'll look at @Bean annotation along with its scopes and Method Injection examples.

@Bean annotation is introduced in Spring framework to avoid XML level configurations. This can be used in Spring Boot application.

@Bean and @Component are almost are same and used to create the bean but seems like same as produces same as a result.


bean creation in spring boot


2. Spring Boot @Bean Creation Syntax


In Spring Boot, @Bean is a method level annotation and should not be used in any class. And also this annotation tells that it returns a bean that is to be managed by the spring container and registered with spring application context or BeanFactory.


OrderInfo.class
[class OrderInfo{
@Bean
public Customer getCustomer(){
return new Customer();
}
}]

This method returns a bean of the Customer.

الأحد، 19 أبريل 2020

Spring Boot: Customize Whitelabel Error Page Step By Step With ErrorController

1. Introduction


In this tutorial, We'll learn how to customize the error page in spring boot application. We are going to cover how to disable the default error page and how we can customize the Whitelabel error page.

By default, Spring Boot shows the Whitelabel error page for any server related errors. But, the default showed the error is not relevant to our application and what is the problem. Actually, We should not use this page in the production environment. So, We need to show our customized and maintenance message on the error page.

Dependencies required:


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

I am running all examples code with spring boot version 2.2.6 release.

2. Whitelabel Error Page


Writing example code to display the default Whitelabel error page.

@GetMapping("/error")
 public String getDefaultPage(@RequestHeader(name = "errorcode") String errorCode) {
  logger.info("error code : " + errorCode);
  return "error";
 }

الجمعة، 17 أبريل 2020

How To Set Base Path or Context Path In Spring Boot?

1. Introduction


In this tutorial, We'll be learning how to set a base path in a new spring boot application? And also how the existing context path can be changed to new values in different ways.

2. Setting Property in application.properties


Older and new versions of spring boot support in doing our own base path using configurations file that is application.properties.

Spring Boot 1.x:

spring.data.rest.basePath=/api/v1

Spring Boot 2.x:

server.servlet.context-path=/api/v1

The main difference is path is called a base path in 1.x and context path in 2.x but the meaning of both is the same.

Both of these change to proceeding with "/api/v1".

الخميس، 16 أبريل 2020

How to Read HTTP Headers in Spring REST Controllers

1. Introduction


In this tutorial, We'll learn different ways to read HTTP headers in spring boot rest controllers.

In this article, first, we'll be using @RequestHeader a notion to access the HTTP headers individually and all together at once. At last, We'll look at the next level to read HTTP Headers using the @RequestHeader attribute.

2. Accessing HTTP Headers


2.1 One at a time (Individually)

To access a specific header, Just use the @RequstHeader annotation at the method argument and specify which header value should be retrieved. In the below example, we are trying to get the locale value that passed as part of the header.

الأربعاء، 15 أبريل 2020

Spring Boot - Configure Jetty Server

1. Introduction


In this article, You'll learn how to configure the jetty server in spring boot instead of the default tomcat server.

After creating a new spring boot application just start the application. That generates the following log and look at the last two lines that mentioning Tomcat Started on port 8080.

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.2.6.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.javaprogram</groupId>
 <artifactId>spring-boot-app</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>spring-boot-app</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

Spring Boot Remove Embedded Tomcat Server, Enable Jetty Server

1. Introduction


In this tutorial, We'll learn how to remove the Tomcat server from the Spring Boot application. Actually, Spring boot by default comes up with the embedded server once we add "spring-boot-starter-web" dependency.

But, Spring boot gives us the flexibility to use tomcat or not. If we do not want we can exclude this default server.

Default, Spring boot comes with 3 types of embed servers Tomcat, Jetty and undertow.

First, we'll see how to exclude tomcat and next add jetty server.

Create the First Spring Boot Application and How to Test Rest API.

السبت، 11 أبريل 2020

Collections sort() in Java - List Custom Sort Example

1. Introduction


In this tutorial, You'll learn how to sort Custom objects in java. First, We'll show the example program to sort List of Strings and Next move to the Custom sorting of Arraylist of Employee's. Sorting is done by Empoyee Id, Name and age. All examples shown are on GitHub at the end of this article.

2. Collections.sort() Example


Collections class has a method sort() which takes List implementation such as ArrayList, LinkedList etc.

Now, Creating a list with String values and sort the values using Collections.sort() method.

Collections.sort() method does the sorting in ascending order by default. All the values are added to the list must implement Comparable interface.

If null is passed to sort() method it throws java.lang.NullPointerException.

الجمعة، 10 أبريل 2020

HelloWorld.java - Java Program to Print Hello World

1. Introduction


In this tutorial, We'll learn how to print "Hello World" in java. This is called as first java program to beginners to the programming language. If you understand each and every word in this program then you are good to start learning java concepts.

Java Program To Shutdown Computer in Windows

1. Introduction


In this tutorial, We'll learn how to shut down computers in java using a command "shutdown -s -t". It takes time when you want to do shutdown the computer.

2. Java Program To Shutdown Computer


The below program takes the number of seconds as input and will use the Runtime class to execute the windows command with the help of exec() method.

الخميس، 9 أبريل 2020

How To Find Maximum Value from ArrayList in Java - Collections.max()

1. Introduction


In this article, We'll learn how to find the maximum (max) value from ArrayList. Finding the max value from ArrayList from Collection API is done by running a loop over all the elements or can be found max value with the Collections.max() method.

Collections.max(): Returns the maximum element of the given collection, according to the natural ordering of its elements.

Example programs to find the max value from a list of wrapper objects and a list of custom or user-defined objects.

Corona Virus (COVID19) India Live Updates 5916+ Cases - More Deaths 179+

Corona Virus (COVID19) India Live Updates 5916+ Cases

Coronavirus is now spread going on in 204 countries in the world and it became very dam dangerous now,

Coronavirus is spreading very fastly worldwide in all countries. It is first started in China that changing the world's future now badly. Now India also started seeing Corona cases. Now India has reached 3052 and more growing rapidly but not entered into third stage. One common point is all corona patients are returned from different countries mainly from Italy, Italy, and Spain. 


15,24,266 Passengers screened at the airport

Kadapa new corona cases


Ref




Corona Virus (COVID19) India Live Updates Cases - Latest Stats

الأربعاء، 8 أبريل 2020

4 Ways To Add Minutes To Date or Current Date Time

1. Introduction


In this article, We'll learn how to add minutes to the date. This is a common useful example program as part of the Date API.

2. Adding Minutes to Date Example


We'll explore different ways of adding mins to date.

2.1 Using Date Constructor


Adding 10 mins to the current time.

// Adding 10 mins using Date constructor.
Calendar date = Calendar.getInstance();
System.out.println("Current Date and TIme : " + date.getTime());
long timeInSecs = date.getTimeInMillis();
Date afterAdding10Mins = new Date(timeInSecs + (10 * 60 * 1000));
System.out.println("After adding 10 mins : " + afterAdding10Mins);

Output:

Current Date and TIme : Wed Apr 08 21:53:45 IST 2020
After adding 10 mins : Wed Apr 08 22:03:45 IST 2020

How To Sort HashMap in java Based on Keys and Values

1. Introduction


In this tutorial, We'll learn how to sort HashMap in java based on keys and values. You might have used HashMap widely in your experience but HashMap does not preserve the insertion order and no sorting is done to the keys and values. It just retrieves from its Nodes and LinkedList.

If you have a requirement to sort hashmap by value and sort hashmap by value in java then you need to perform the sorting explicitly because HashMap API is not having the ready-made methods to use. You are at the place now you will learn how to sort HashMap by keys and values using TreeMap. If you answer this then next you will be asked "How to sort HashMap without using TreeMap"

Sorting TreeMap By Value (+ Java 8)

Java String charAt() Method examples (Find Char At a Given Index)

1. Introduction

In this article, We'll learn how to find the character at an index with String charAt in java.

The Java String charAt(int index) method returns the character at the specified index in a string. The index value should be between 0 and (length of string-1). For example, s.charAt(0) would return the first character of the string represented by instance s. Java String charAt method throws IndexOutOfBoundsException if the index value passed in the charAt() method is a negative number or less than zero or greater than or equal to the length of the string (index<0|| index>=length()). IndexOutOfBoundsException means index if out of its range and it occurs at runtime.

Java String charAt() Examples 

Syntax:

public char charAt​(int index)


Java String charAt() Method example (Find Char At a Given Index)


We will show the example programs on the following use cases. 

1: Finding first, mid and last index of the given string.
2: IndexOutOfBoundsException when using charAt() method.
3: Printing String char by char using charAt() method.
4: Printing even numbers of index characters.
5: Printing odd number index characters
6: Counting number of occurrences of a character

الثلاثاء، 7 أبريل 2020

How To Compare Two Strings In Java? (With '==' Operator and equals() Method)

1. Introduction


In this tutorial, We'll learn how to compare two strings in java. Most of the developers use double equal operator "==" to compare two strings. My friend used "==" many times in his project but later faced an issue in production. Then he changed to String.equals() method.

Let us see what is the difference between "==" and equals() method in Strings Comparision.

2. Comparison with "==" Operator


Is this bad to use "==" operator for strings comparison. When this should be used?

Take a look at the following example program that uses "==" operator.

How to Create An Immutable Class in java?

1. Immutable Class in Java


This is a common nterview question for 2-4 years java experienced developer. In this tutorial, We'll learn "How to Create Immutable Class in java?" You'll learn why we need to create Immutable class and what are the advantages and as well the disadvantages of it.

Immutable class means it cannot be modified once it is created. If any modification on an immutable object then the result will give another immutable object.

How to Create An Immutable Class in java?

Builtin API immutable classes:

String, StringBuffer, and all wrapper classes, etc.

Java Map Sort By Values - Sort TreeMap Or HashMap By Value + Java 8

1. Introduction


In this article, We'll learn how to sort Map by Values in ascending or descending order. In the previous article discussed how to sort the TreeMap in ascending or reverse order.

Map can be anything such as HashMap or TreeMap which needs to be sorted based on its values rather than keys.

Always, TreeMap does sorting based on its keys but not on values, but in the interview first, they will ask how to sort the Map. If you give the answer then the next question is on sorting values alone.

الاثنين، 6 أبريل 2020

3 Ways to Fix Git Clone "Filename too long" Error in Windows [Fixed]

1. Introduction


In this tutorial, We'll learn how to fix the git clone error "Filename too long" in windows operating systems Powershell and GitHub Application. This happens when doing a git clone from remote repositories.

Most used Git Commands

This error does not come for the UNIX or mac users. So they can push the long length file names to git but the issues occur only for the windows users. Because this capability is disabled by default in the Windows operating system.

Usually, Git has a limit of 4096 characters for a filename, except on Windows when Git is compiled with MSYS. It uses an older version of the Windows API and there's a limit of 260 characters for a filename.


3 Ways to Fix git "Filename too long" Error in Windows [Fixed]

الأحد، 5 أبريل 2020

TreeMap in Java with Examples (Sorting Ascending or Descending or Reverse order)

1. Introduction


In this article, We'll learn how to use TreemMap in java. It is a Red-Black tree based NavigableMap implementation.  TreeMap extends AbstractMap and implements NavigableMap. The main difference between them is that HashMap is an unordered collection while TreeMap is sorted in the ascending order of its keys. TreeMap is an unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.

TreeMap is mainly used to sort the keys in ascending order or descending order.

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

TreeMap in Java with Example (ascending or descending or reverse order)

Java Program To Convert List to Array (java 8 + Guava)

1. Introduction


In this tutorial, We'll learn how to convert List to Array in java. We are going to show the example programs using List, java 8 and Guava API methods.

Java Program To Convert List to Array (java 8 + Guava)

السبت، 4 أبريل 2020

LinkedHashMap in Java With Example Programs + Java 8 New Methods

1. Introduction


In this tutorial, We'll learn LinkedHashMap API in java with example programs.

LinkedHashMap is used to store the key-value pairs as similar to the HashMap. But, LinkedHashMap extends HashMap and AbstractMap implements Map interface. The main advantage of LinkedHashMap is it preserves the insertion order that meanwhile iterating it pull the Entry Objects how the order keys are inserted into LinkedHashMap.

Iterating over collection in java

We have discussed HashMap in-depth with all methods examples including java 8 concepts. It is good to go over the HashMap article that makes you answer interview questions on all of its methods.


If you do not understand at any point just leave your question in comments.

LinkedHashMap in Java With Example Programs + Java 8 New Methods


الجمعة، 3 أبريل 2020

Java Examples to Create New Empty File and A Temporary File

1. Overview


In this tutorial, We'll be learning how to create a file in java and how to create a temp file in java.

Example programs demonstrated in the following methods.

createNewFile()
createTempFile()

Example Programs on Files

createNewFile(): method is used to create a new empty file.
createTempFile(): method is used to create a temporary file.

Java Examples to Create New Empty File and A Temporary File



الأربعاء، 1 أبريل 2020

Java ArrayList indexOf() Example to find the Object exists in List or Not

1. Introduction


In this article, We will learn the ArrayList class indexOf() method. Let us take a look into how to find the value or object that is present in the list or not. And also what are the valid arguments to pass and what are the exceptions will be thrown at run time exception.

String class also has indexOf() method

Java ArrayList indexOf() Example to find the Object exists in List or Not