Friday, December 31, 2021

Java 8 Default and Static Methods - Interface New Concepts

1. Overview


In this Java 8 new concept, We are going to learn today what is the Default Method in Java 8 and why it is introduced in java 8 changes.

Java 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8. For example, the List interface is not having the forEach() method. If they add this method as an abstract method then all List implementation classes must have to provide the implementation since it is common functionality to iterate the list. So they had to introduce this concept to enhance features and support for the backward classes.

Java 8 Default and Static Methods

Java 8 Nashorn Javascript With Examples

1. Overview

In this tutorial, you will learn how to use javascript in java and how to integrate them with each other.

Usage of javascript in java can be done with the newly added Nashorn JavaScript engine in java 8.

This completely replaces the old version of the Rhino javascript engine and it gives 2 to 10 times better performance than the older one because it does the code compilation in memory and passes the byte code to the JVM directly.

And also it uses the dynamic loading feature is introduced in java 7 to enhance the performance and completely replaces the Rhino Engine.

Java 8 Nashorn Javascript


Let us start writing the examples using the code from the command line, java, and javascript code.

Note: Before using jjs tool,  you should remember that "The jjs tool is planned to be removed from a future JDK release"

2. Nashorn jjs - Command-Line Engine

JDK 1.8 is equipped with the command line interpreter that is called "jjs". jjs is used to run the javascript files as below.

jjs tool can be found at the location $JAVA_HOME/bin

jjs> jjs first_script.js

And also jjs can be used as interactive shells such as REPL. To start a REPL, do not pass any arguments to it.

javprogramto-MacBook-Pro-2$ jjs
Warning: The jjs tool is planned to be removed from a future JDK release
jjs> 
jjs> 

You can print the content on to console using print() method and it takes string content.

jjs> print("Hello World")
Hello World
jjs> print("welocome to javaprogramto.com blog for java 8 tutorial")
welocome to javaprogramto.com blog for java 8 tutorial
jjs> 

3. Running js file as a shell script

As you run the shell script file from the command line like "./hello.sh" in a similar way you can run the javascript file. 

Just add bang pointing to jjs location "#!$JAVA_HOME/bin/jjs"

Let us write a simple code and save it as hello.js file.

#!$JAVA_HOME/bin/jjs
var greeting = "Hello World, Welcome";
print(greeting);

Now, run this script from the command line with "./hello.js" and observe the below output.

$ ./hello.js
Warning: The jjs tool is planned to be removed from a future JDK release
Hello World, Welcome
$ 

Like this, you can use java code from the js file also. In the next, sections you will understand how to use java code in javascript files.

4. Passing Arguments to JJS

jjs command can work with the arguments also. When you use jjs command to start the interactive mode, you can pass as many as arguments you need.

And all of the passed arguments are stored in a variable "arguments". By using this builtin keyword in javascript, you can get all of these argument values.

Note: You need to pass the double hyphen "--" after jjs command.

Let us run the sample code as "jjs -- one two threee"

Arguments Example:

$ jjs -- one two threee
Warning: The jjs tool is planned to be removed from a future JDK release
jjs> print("given  argument  values are "+arguments.join(" , "))
given  argument  values are one , two , threee
jjs>$ 

5. Call JavaScript from Java

Java 8 api is added with a built-in engine that is called an Embedded Script Engine which creates a runtime environment to execute the javascript code on the JVM for a dynamic language.

Use ScriptEngineManager class to get the script engines that are managed by JVM.

Next, get the nashorn script engine using getEngineByName("nashorn") and pass the right name to it.

Finally, call eval() method to run the native javascript code from java and eval() returns an Object if you are executing arithmetic operations. In such cases, you need to use explicit type casting to the right object types. It is the time now to play with the javascript notations.

package com.javaprogramto.java8.nashorn;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class CallJavaScriptFromJavaExample {

    public static void main(String[] args) throws ScriptException {

        // creating java script engine
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

        // getting the nashorn engine
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

        // evaluating the javascript statement  to  print
        nashorn.eval("print('hello , this is first javascript example in java') ");

        // summing 2  numbers in  js  from  java code.
        Integer i = (Integer) nashorn.eval("1 + 2");
        
        System.out.println("sum from javascript : " + i);
    }
}
 

Output:

hello , this is first javascript example in java
sum from javascript : 3
 

You can observe the output that printed the content using the javascript print() method and the addition of two numbers.

6. Exceptions  from NashornScriptEngine

If you pass the invalid or wrong javascript syntax to eval() method then. it will throw a runtime exception saying "ScriptException" with different reasons.

If you miss the ending or closing quotes. for the print() method then it. will say "<eval> Missing close quote"

 Warning: Nashorn engine is planned to be removed from a future JDK release
 Exception in thread "main" javax.script.ScriptException: <eval>:1:57 Missing close quote
 pirnt('hello , this is first javascript example in java) 
                                                          ^ in <eval> at line number 1 at column number 57
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:477)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:544)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:531)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:409)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:162)
 	at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
 	at com.javaprogramto.java8.nashorn.CallJavaScriptFromJavaExample.main(CallJavaScriptFromJavaExample.java:16)
 Caused by: jdk.nashorn.internal.runtime.ParserException: <eval>:1:57 Missing close quote
 pirnt('hello , this is first javascript example in java) 
                                                          ^
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Lexer.error(Lexer.java:1860)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Lexer.scanString(Lexer.java:1006)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Lexer.lexify(Lexer.java:1717)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.getToken(AbstractParser.java:135)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.nextToken(AbstractParser.java:216)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.nextOrEOL(AbstractParser.java:173)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.next(AbstractParser.java:160)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.scanFirstToken(Parser.java:293)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.parse(Parser.java:323)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.parse(Parser.java:285)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.Context.compile(Context.java:1500)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.Context.compileScript(Context.java:1467)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.Context.compileScript(Context.java:750)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:542)
 	... 5 more
 

If you pass the invalid method name then it will give an error.

nashorn.eval("invoke(10, 20)");
 

Error:

Warning: Nashorn engine is planned to be removed from a future JDK release
Exception in thread "main" javax.script.ScriptException: ReferenceError: "invoke" is not defined in <eval> at line number 1
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:477)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:461)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:413)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:409)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:162)
	at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
	at com.javaprogramto.java8.nashorn.CallJavaScriptFromJavaExample.main(CallJavaScriptFromJavaExample.java:18)
Caused by: <eval>:1 ReferenceError: "invoke" is not defined
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291)
	at jdk.scripting.nashorn/jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1616)
	at jdk.scripting.nashorn.scripts/jdk.nashorn.internal.scripts.Script$Recompilation$1$\^eval\_/0x00000008001dc040.:program(<eval>:1)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:655)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:513)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:527)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:456)
	... 5 more
 

7. Call Java From JavaScript

In the previous section,  we. have seen how to call native javascript code from java classes. 

Next, let us see how to use java classes in JavaScript files.

Let us create a sample javascript code that uses the java class BigDecimal.

Call Java.type() method to use the java classes from javascript and pass the class name along with the package name. Then that class is loaded into the nashorn engine and returns its object. So, we've stored it in the var variable.

Calling Java Methods from JavaScript Example:

var BigDecimalClass = Java.type('java.math.BigDecimal');

function calculate(amount, percentage) {

    var result = new BigDecimalClass(amount).multiply(new BigDecimalClass(percentage)).divide(
        new BigDecimalClass("100"), 2, BigDecimalimalClass.ROUND_HALF_EVEN);

    return result.toPlainString();
}
var result = calculate(1000,20);
print("Final value : "+result);
 

Output:

$ jjs sample.js 
Final value : 200.00
$ 
 

Any java class can be used inside the javascript code such as adding key-value pairs. to HashMap.

Save the below file as hashmap.js

Example to use HashMap from Javascript:

var HashMap = Java.type('java.util.HashMap')
var map = new HashMap()
map.put('hello', 'world')
print("map values : "+map)
 

Output:

$ jjs hashmap.js 
map values : {hello=world}
$ 
 

8. Conclusion

In this article,  you've seen the new javascript engine nashorn added in java 8.

Examples on how to call javascript from java and vice versa.

Now, you can call javascript functions, pass bindings, and use java objects from both languages using jjs tool.

All examples shown are over GitHub.

Examples of Nashorn engine on GitHub

Removal of Nashorn

ScriptEngine API

Tuesday, December 28, 2021

How to compare two HashSet for equality in Java 8? (Fastest Way)

1. Overview


In this article, You'll learn how to compare two Sets in Java using Stream API.

Java HashSet class equals() method takes Object but when you are calling on a set object then you must pass the HashSet or Set implementation object.

Compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

Let us see the examples using equals(), containsAll() method of the Set interface. In the end, We'll explore how to compare two HashSet in java 8.

How to compare two HashSet for equality in Java 8? (Fastest Way)


Java UnknownHostException - Invalid Hostname for Server - How to Fix It?

1. Introduction

In this tutorial, We'll learn what is UnknownHostException and What is the cause to produce it. And also learn how to prevent it.  UnknownHostException is a common exception and will show the best ways to prevent this exception.

Hierarchy:

java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.rmi.RemoteException
java.rmi.UnknownHostException


2. When is the Exception Thrown?


UnknownHostException is thrown if and if only there was a problem with a domain name or mistake in typing. And also indicates that the IP Address of a website could not be determined.

Java Program to Check Leap Year (With Examples)

1. Overview

In this tutorial, you'll learn how to check the given year is a leap year or not.

Everyone knows that leap year comes for every 4 years and February month with 29 days.

But, when we do the logic in java it is bit different and should know the complete formula to evaluate leap year.


Java Program to Check Whether an Alphabet is Vowel or Consonant

1. Overview

In this tutorial, you'll learn how to check the given alphabet is a vowel or consonant in java.

We are going to solve this question using if else and switch statements.

To understand the programs in this article, you should have knowledge on the following topics.





Wednesday, December 22, 2021

Java Program to Calculate Standard Deviation

1. Overview

In this tutorial, you'll learn how to calculate the standard deviation in java using for loop and its formula.


2. Example to calculate standard deviation

Let us write a simple java program to find the standard deviation for an individual series of numbers.

First create a method with name calculateStandardDeviation(). Create an array with integer values and. pass this array to the calculateStandardDeviation() method. This method has the core logic to get the standard deviation and. returns to main method.

package com.javaprogramto.programs.arrays.calculation;

public class StandardDeviation {

	public static void main(String[] args) {

		int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

		double standardDeviation = calculateStandardDeviation(array);

		System.out.format("Standard deviation : %.6f", standardDeviation);

	}

	private static double calculateStandardDeviation(int[] array) {

		// finding the sum of array values
		double sum = 0.0;

		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}

		// getting the mean of array.
		double mean = sum / array.length;

		// calculating the standard deviation
		double standardDeviation = 0.0;
		for (int i = 0; i < array.length; i++) {
			standardDeviation += Math.pow(array[i] - mean, 2);

		}

		return Math.sqrt(standardDeviation/array.length);
	}

}
 

Output:

Standard deviation : 2.581989
 

3.  Conclusion

In this article, you've seen how to find the standard deviation in java.

As usual, the shown example is over GitHub.


4 Solutions To Uncaught ReferenceError: $ is not defined jQuery Error

1. Overview


In this tutorial, We will be discussing how to solve the famous jQuery error "Uncaught ReferenceError: $ is not defined jQuery Error" that occurs for every developer who started working on jQuery API.

More on JQuery

This error comes into existence if you are trying to use a $ variable that is not defined yet using the var keyword. In jQuery world, it's a short name of jQuery() function and most commonly used in $(document).ready(function()). When dom is loaded, you are making some stuff using jQuery then there might be chances of corrupting the jQuery library or jQuery file location. This indicates with an error saying "uncaught reference error $ is not defined". This is the most generic error even if you are working on Angular Js, Ajax, Html, and MVC, laravel or rails .. any framework that is related to javascript. Because all of these are built on top of JavaScript.

In my experience, I have seen the junior developers or whose background is java, .Net, C#, Android technologies, and these developers is not having enough knowledge of JavaScript. JavaScript understanding is a must to work on jQuery or any JavaScript framework such as Angular, React or vue.js or ember.js. Once you know the basic concepts of JavaScript, you can troubleshoot any problems easily.



Java 8 Collectors Examples In Depth

1. Overview


In this tutorial, We'll be learning to Java 8 Collectors API in-depth with all methods and example programs. Collectors is a public final class that extends the Object class.

Read this article completely with patience. You will definitely become a master in Java 8’s Collectors by end of this post.

Collectors class provides various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc

Java 8 Collectors Examples In Depth

Java 8 - Stream Group By - Collectors.GroupingBy() Examples

1. Overview

In this tutorial, We will learn how to perform the groupingby operation in java 8

If you have worked in the Oracle database, you must have seen the group by the operator in many complex SQL queries.

You will learn the following techniques in this lesson.

  • How to java stream group by operation?
  • Java stream group by count?
  • Java 8 stream group by and sort?
  • Java stream group by reduce?
  • java stream group by multiple fields?
  • group by with custom objects?

In a similar way, we can implement the group by clause from java 8 onwards. Java 8 Stream API is added with the data grouping capabilities as part of Collectors api.

Collectors API is to collect the final data from stream operations.

Java 8 - Stream Group By - Collectors.GroupingBy() Examples

Java List or ArrayList Max Size (With Examples)

1. Overview

In this tutorial, We'll understand what is the limit of ArrayList or List implementations that can hold the maximum size.

But this is completely different from finding maximum value from ArrayList.

Before finding the max size of ArrayList, we need to understand that ArrayList collection API is implemented based on the ordinary arrays of java.

If the new ArrayList<Integer>(5) then a new ArrayList with the size of 5 is created and it can store 5 integer values.

Java List or ArrayList Max Size

Java Program to Find the Biggest of 3 Numbers

1. Overview


In this w3schools java programming series, You'll be learning today how to find the biggest of 3 numbers. This is also a very basic interview question. But the interviewer will look for the optimized and fewer lines code. We will show you all the possible programs and how most of java developers think.

For example, given three numbers 4 67 8. Among these three 67 is bigger. For this, we need to perform a comparison with all numbers.

How to add 3 numbers in java?

Custom Container Configuration in Spring Boot 2

1. Introduction


In this tutorial, We'll learn how to use EmbeddedServletContainerCustomizer and ConfigurableEmbeddedServletContainer in Spring Boot 2. But, these two are not present in the newer version of spring boot 2. These two are part of earlier versions 1.x. But, an alternative for the same functionality is provided with WebServerFactoryCustomizer interface and ConfigurableServletWebServerFactory class.

All these interfaces are mainly used to set the configurations for the container such as setting up the port, adding basepath or context path and also these can be set to the specific embed servers such as tomcat or jetty or undertow.

Custom Container Configuration in Spring Boot 2

Gradle - could not determine java version 11.0.8 or any version [Fixed]

1. Overview

In this tutorial, We'll learn how to fix the gradle error "could not determine java version" from 9.0.1, 11.0.8, 11.0.12, 13.0.2, 14.0.2, 15.0.1 or 16.0.1 or any versions.

This is the common error that you face when working with the Gradle and you have the right java version also on the machine.

This solution will work for any java version or Gradle version.

[Fixed] Java lang exceptionininitializererror com sun tools javac code typetags

1. Overview

In this tutorial, We'll learn how to fix the error "Java lang exceptionininitializererror com sun tools javac code typetags" when working with maven build.


Java lang exceptionininitializererror com sun tools javac code typetags

Tuesday, December 21, 2021

Java Array Sort Descending Order or Reverse Order

1. Overview

In this tutorial, We'll learn how to sort the arrays in revere order in java.
Sorting arrays is done with the help of Comparator interface which works very well for the custom objects.

Array of ints or any primitive/wrapper types  can be sorted in descending order using Arrays.sort() method.

Arrays.sort(T[], Collections.reverseOrder());
Arrays.sort(ints, Collections.reverseOrder());
Arrays.sort(stringArray, Collections.reverseOrder());
Arrays.sort(empArray, Collections.reverseOrder());

Let us write the few examples on arrays reverse order sorting.

Java Array Sort Descending Order

Monday, December 20, 2021

Kotlin Program to Join Two Lists

1. Introduction


In this article, You'll learn how to join two lists in kotlin programming language. List API has addAll() method and apache ListUtils.union() method to add two lists in kotlin.

First, we'll see the example program with built-in api method addAll() and next further using ListUtils.union() method from apache commons api.

Kotlin Program to Join Two Lists



How To Compare Two Arrays In Java and New Java 8 API

1. Overview

In this article, you'll learn how to compare two arrays in java and how to work with comparing the contents of arrays using the deep level technique.

Comparing arrays means the first array type should be the same and contents also should be the same in both arrays.

All the examples are prepared with Arrays.equals() and Arrays.deepEquals() methods.

How To Compare Two Arrays In Java and New Java 8 API

Java Difference Between Float and Double Data Types

1. Overview

In this tutorial, We'll learn what are the differences between float and double data types in java.

Float and double data types are used to represent the floating-point values but there are few differences and you must know all of these when using them. 

First, let us understand float vs double and then next when to use which double and float?

Any fixed value is assigned to a variable is called literal in java. double and floating data storage variables are called Floating literals.

All examples shown are placed in GitHub and a link is given at the end of the article.


Java Difference Between Float and Double Data Types

Sunday, December 19, 2021

Java Float To String Conversion Examples

1. Introduction


In this article, We'll learn how to convert Float values to String. This is a common scenario to the developers and how conversions can be done using Java API methods.

String and Float classes have been provided with utility methods and these methods are always defined as static because directly can be accessed with the class names.

All examples are designed to show the conversion of primitive float and wrapper float to String objects.

Java Float To String Conversion Examples


Java Extends Keyword in Depth for Beginners

1. Overview

In this tutorial, we'll learn how to use extends keyword in java with examples.

Extends keyword is used only in the inheritance chain in java and it cannot be used in any other places.

In Java, Interfaces and classes can use extends keyword.

All examples are shown in this article are available on GitHub at the end of the article.

Java Extends Keyword


Saturday, December 18, 2021

Java Final Keyword in Depth for Beginners

1. Overview

In this tutorial, We'll learn how to use the final keyword in java with example programs.

Final is one of the keywords in java and final is used to restrict access to java entities.

Interestingly, the final keyword can be used on variable, method and class levels.

Java Final Keyword

All examples are shown in this article are available on GitHub.

Java Finally Block: Does Finally Execute After Return?

1. Introduction


In this tutorial, You'll be learning core java concepts as part of exception handling "Java finally block when return statement is encountered"

This is a famous interview question "will finally block is executed after return statement".
Answer is Yes, The finally block is executed even after a return statement in the method. So, finally block will always be executed even whether an exception is raised or not in java.

Finally Block: Will a finally block execute after a return statement in a method in Java?


We will look into the following in this article.
  • Finally block is executed right after try or catch blocks.
  • Scenarios where finally() block not executed
  • Does finally block Override the values returned by the try-catch block?
  • When happens to finally block execution if System.exit(1) is invoked?

Friday, December 17, 2021

How to Create Constants In Java?

1. Overview


In this core java tutorial series, You'll learn today how to create a constant in java and what is the best way to create a java constant.
A constant is a variable whose value cannot be changed once it has been assigned. In fact, java does not have any built-in keyword to create constantly. But, Java provides a set of modifiers final and static. These can be applied to the variables to make them effectively constant.

Constants can make your program more easily read and understood by others. In addition, a constant is cached by the JVM as well as your application, so using a constant can improve performance.

First, let us go through on final and static keywords in java.

Java ArrayList Insert/Replace At Index

1. Overview

In this tutorial, We'll learn how to insert or replace an element at a specified index into ArrayList java.

Use the ArrayList.add(int index, Object value) method to add any object or element at the specific index of ArrayList and use ArrayList.set(int index, E  value) to replace the value at the specific index of ArrayList in java.

Let us explore the examples

All examples shown in this article are on GitHub and a link is given at the end of the post.

Java ArrayList Insert/Replace At Index

Java Array Insert - Add Values At The Specific Index

1. Overview

In this tutorial, We'll learn how to insert an element at the specific index for the given array in java.

if you are new to java, Please read the below articles on arrays.



This can be done in two ways. Let us write the example code to insert the value at any given position.

All examples shown in this article are present in GitHub and it is provided at the end of the article.

Java Array Insert - Add Values At The Specific Index


Thursday, December 16, 2021

How To Check If int is null in Java

1. Overview

In this tutorial, We'll learn how to check if primitive int is null or not in java.

First, let us write the simple example program and see what is the output if we check int is not null using != operator.

How To Check If int is null in Java


Tuesday, December 14, 2021

Java 8 Streams Filter With Multiple Conditions Examples

1. Overview


In this tutorial, We'll learn how to utilise stream filter() with several filter conditions (can be more than one condition).

Normally, we apply a single condition to streams using filter() method with lambda and then store the results in Lists or Sets.

However, we'll learn how to use the filter() method with as many condition filters as we require.

More filters can be applied in a variety of methods, such as using the filter() method twice or supplying another predicate to the Predicate.and() method.

In the next sections, we'll look at examples with single and multiple conditions.

GitHub link is given at the end of the article for the shown examples.

Java 8 Streams Filter With Multiple Conditions Examples



Java Spark RDD reduce() Examples - sum, min and max opeartions

1. Overview

In this tutorial, we will learn how to use the Spark RDD reduce() method using the java programming language. Most of the developers use the same method reduce() in pyspark but in this article, we will understand how to get the sum, min and max operations with Java RDD.

Java Spark RDD reduce() Examples

Monday, December 13, 2021

Java Insert Dimensions To Complete Referencetype [Fixed]

1. Overview

In this tutorial, We'll learn how to fix the common compile time error "Syntax error, insert "Dimensions" to complete ReferenceType" in java.

This error occurs when you are working with the java generic types.

It is suggested to follow the generic naming conventions and rules with collection api.

Compile time error

Syntax error, insert "Dimensions" to complete ReferenceType.

At the end of the article, we've given GitHub link for the examples shown in this post.

Java Insert Dimensions To Complete Referencetype [Fixed]

Java StringBuilder Insert - At Any Index and Any type of data

1. Overview

In this article, we will learn how to insert value or string at a particular index into StringBuilder in java.

StringBuilder is a mutable sequence of characters and it is recommended to use the non-synchronization applications.

StringBuilder class has a useful method insert() which takes the index and object as arguments.
When the data is added to the string builder at the given index then the remaining characters next to the given index are shifted to the right side. This is a costly operation in case of you have millions of characters in it.


Java StringBuilder Insert


Saturday, December 11, 2021

Free Adsense Ad Code Converter | HTML to XML Parser Tool

1. Introduction


Today, We are showing you how to convert the Adsense Ad Code to be parsed by the HTML page. This is absolutely a free tool and works 100%. You do need to have set up a local computer to do this type of conversion. We made it online now to convert HTML to the XML parser.

Free Google One Click Adsense Ad Code Converter 2019 | HTML to XML Parser Tool | Online Code Generator


Top 133 Oracle Exadata Interview Questions

Oracle Exadata Interview Questions:

Study the latest Exadata Interview Questions today here. If you are preparing for Oracle Exadata Interview Questions for Experienced or Freshers, you are at the right place to get the best questions and answers. Gathered all interview questions on Exadata from various websites into one place here. I hope, this makes it easier to prepare for interviews.

Here, We make sure that you refresh your technical knowledge on Exadata(pre-configured combination to run the Oracle Database).

Top 133 Oracle Exadata Interview Questions

Java 8 Streams if else logic

1. Overview

In this tutorial, We'll learn how to use if/else statements in java 8 streams.

If you are new to the java 8 stream,  It is recommended to read the in-depth on the basics of java 8 streams.

First, we will see the simple to find the even numbers from the given list of numbers.

Next, we will write the java 8 examples with the forEach() and streams filter() method.

Java 8 Streams if else logic


Java TreeMap Comparator

1. Overview

In this tutorial, We'll learn how to add a custom comparator to the TreeMap in java to sort by key and also sort by values.

If you are new to java comparators, please read an in-depth article on Java comparators with java 8 stream api. 

Java TreeMap Comparator

Friday, December 10, 2021

Java 8 Stream Collect() Examples

1. Overview

In this tutorial, We will learn how to use the Stream.collect() method in Java 8 Stream api.

Many of you know that Stream.collect() method is added as part of the new JDK 8 Streams.

Stream collect() method is used to collect the output of stream operations into the collection such as List, Set or Map. Sometimes we can collect into LinkedList, TreeSet or even into the String.

Additionally, we can perform the group by, partition by operations on the streams with Collect() method.

Let us explore the usages of Stream.collect() method with examples.

Java 8 Stream Collect() Examples



2. Java 8 Stream Collect() to List using Collectors.toList()


The below is the first example using Stream.collect() method on the stream pipe line. First created a stream object using stream() method and converted the each value in the stream to uppercase using word.toUpperCase() method. 

Finally, called the collect() method by passing the Collectors.toList() method which collect the each word from the stream into a List. The returned list is the instance of ArrayList and it is the default collection object created by toList() method.


package com.javaprogramto.java8.collectors.collect;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Examples to Java 8 Stream collect() method
 * 
 * @author JavaProgramTo.com
 *
 */
public class StreamCollectExample {

	public static void main(String[] args) {

		List<String> words = Arrays.asList("hello", "how", "are", "you", "doing", "mate");
		
		List<String> list = words.stream()
				.map(word -> word.toUpperCase())
				.collect(Collectors.toList());
		
		System.out.println("Collectors.toList() : "+list);

	}

}
 
Output:
Collectors.toList() : [HELLO, HOW, ARE, YOU, DOING, MATE]
 

3. Java 8 Stream Collect() to Set using Collectors.toSet()


Furthermore, The below example is to get the numbers length is 3 and remove the duplicates from stream. Finally, collecting the stream output into Set.

And also collected the same output into the List to observe the difference between the toList() and toSet() methods.

toSet() method returns default HashSet object. If you want to get the LinkedHashSet object then you need to use the Collectors.toCollection() method with specifying the LinkedHashSet class.

In the later section of this tutorial, you will learn how to get the different Set object other than default HashSet.

List<String> numbers = Arrays.asList("one", "two", "one", "two", "three", "four");

// using toSet()
Set<String> set = numbers.stream()
 	.filter(number -> number.length() == 3)
	.collect(Collectors.toSet());

// without duplicates
System.out.println("Set removes the duplicates : ");
set.forEach(System.out::println);

// using toList()
List<String> list2 = numbers.stream()
	.filter(number -> number.length() == 3)
	.collect(Collectors.toList());

// without duplicates
System.out.println("List with duplicates: ");
list2.forEach(System.out::println);
 
Output:
Set removes the duplicates : 
one
two
List with duplicates: 
one
two
one
two
 

4. Java 8 Stream Collect() to Map using Collectors.toMap()


Next, In the below example program, we will learn how to convert the stream intermediate output to the Map using Collectors.toMap() method.
List<String> words = Arrays.asList("hello", "how", "are", "you", "doing", "mate");
		
Map<String, Integer> wordsLength = words.stream()
		.collect(Collectors.toMap(Function.identity(), String::length));

System.out.println("toMap() output: ");
wordsLength.forEach((key, value) -> System.out.println(key + " = "+value));
 
Output:
toMap() output: 
how = 3
doing = 5
are = 3
mate = 4
hello = 5
you = 3
Function.identity() is used to get the same object as a key and remember that always identity() method returns the map key when using toMap() method in java 8.

By default, toMap() method returns the HashMap object and if you want TreeMap you can use the overloaded toMap() method as shown in the next section.

If you observe that input list has unique values and Map does not allow the duplicates keys. So what happens if the input has duplicate values as below?
List<String> numbers = Arrays.asList("one", "two", "one", "two", "three", "four");
 
If you run the toMap() logic with the above numbers list with duplicate values then it will through the runtime exception.
Exception in thread "main" java.lang.IllegalStateException: Duplicate key one (attempted merging values 3 and 3)
	at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:133)
	at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)
	at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
	at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
	at com.javaprogramto.java8.collectors.collect.StreamCollectExample.main(StreamCollectExample.java:45)
 
To work with the duplicate values, we need to use another toMap() overloaded method which takes another 3rd argument that takes care for duplicate keys.

We need to define the logic for duplicate key. If the key is duplicate then add "repeated" string to the value to know that key is repeated,

This the way to handle the duplicate keys with Collectors.toMap() method.
Map<String, String> wordsCount = numbers.stream()
	.collect(Collectors.toMap(Function.identity(), Function.identity(), (oldValue, newValue) -> oldValue+" repeated"));
		
System.out.println("toMap() with dupolicates: ");
wordsCount.forEach((key, value) -> System.out.println(key + " = "+value));
 
Output:
toMap() with duplicates: 
four = four
one = one repeated
three = three
two = two repeated 

5. Java 8 Stream Collect() to Collection such as LinkedList or TreeSet using Collectors.toCollection()


As of now, we have seen toList(), toSet(), toMap() methods and which returns default ArrayList, HashSet, HashMap object as default.

If you want to get the return objects as other collection objects such as LinkedList, LinkedHashSet then use Collectors.toCollection() method.

To cast to TreeMap, you need to use the toMap() method with the Supplier as 4th argument.
// toCollection() examples
// to linkedlist
List<String> linkedList = words.stream()
	.collect(Collectors.toCollection(LinkedList::new));

System.out.println("linkedList is instance of LinkedList = "+(linkedList instanceof LinkedList));

// to linkedhashset
Set<String> linkedhHashSet = words.stream().
	collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println("linkedhHashSet is instance of LinkedHashSet = "+(linkedhHashSet instanceof LinkedHashSet));

// to linkedhashset
Map<String, Integer> treeMap = words.stream()
	.collect(Collectors.toMap(Function.identity(), String::length, (oldValue, newValue) -> newValue, TreeMap::new));
System.out.println("treeMap is instance of TreeMap = "+(treeMap instanceof TreeMap));
	
 
Output:
linkedList is instance of LinkedList = true
linkedhHashSet is instance of LinkedHashSet = true
treeMap is instance of TreeMap = true	
 

6. Java 8 Stream API Collect Full Examples

package com.javaprogramto.java8.collectors.collect;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Examples to Java 8 Stream collect() method
 * 
 * @author JavaProgramTo.com
 *
 */
public class StreamCollectExample {

	public static void main(String[] args) {

		// toList() examples
		List<String> words = Arrays.asList("hello", "how", "are", "you", "doing", "mate");
		
		List<String> list = words.stream()
		.map(word -> word.toUpperCase())
		.collect(Collectors.toList());
		
		System.out.println("Collectors.toList() : "+list);

		
		List<String> numbers = Arrays.asList("one", "two", "one", "two", "three", "four");

		// using toSet()
		Set<String> set = numbers.stream().filter(number -> number.length() == 3).collect(Collectors.toSet());
		
		// without duplicates
		System.out.println("Set removes the duplicates : ");
		set.forEach(System.out::println);

		// using toList()
		List<String> list2 = numbers.stream().filter(number -> number.length() == 3).collect(Collectors.toList());
		
		// without duplicates
		System.out.println("List with duplicates: ");
		list2.forEach(System.out::println);
		
		// tomap() examples
		Map<String, Integer> wordsLength = words.stream().collect(Collectors.toMap(Function.identity(), String::length));
		
		System.out.println("toMap() output: ");
		wordsLength.forEach((key, value) -> System.out.println(key + " = "+value));
		
		Map<String, String> wordsCount = numbers.stream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldValue, newValue) -> oldValue+" repeated"));
		
		System.out.println("toMap() with duplicates: ");
		wordsCount.forEach((key, value) -> System.out.println(key + " = "+value));
		
		// toCollection() examples
		// to linkedlist
		List<String> linkedList = words.stream().collect(Collectors.toCollection(LinkedList::new));
		
		System.out.println("linkedList is instance of LinkedList = "+(linkedList instanceof LinkedList));
		
		// to linkedhashset
		Set<String> linkedhHashSet = words.stream().collect(Collectors.toCollection(LinkedHashSet::new));
		System.out.println("linkedhHashSet is instance of LinkedHashSet = "+(linkedhHashSet instanceof LinkedHashSet));
		
		// to linkedhashset
		Map<String, Integer> treeMap = words.stream().collect(Collectors.toMap(Function.identity(), String::length, (oldValue, newValue) -> newValue, TreeMap::new));
		System.out.println("treeMap is instance of TreeMap = "+(treeMap instanceof TreeMap));
	

	}

}

 

7. Conclusion


In this article, we've seen how to use the Collect() of java 8 Stream api with examples.

collect() method can be used to convert the stream into the List or Set or Map or LinkedList or TreeMap based on the need.

And also we can use collect() with the joining, groupingby(), partitionby(), counting().




Thursday, December 9, 2021

Java Arrays Sort Comparator

1. Overview

In this tutorial, we'll learn how to sort arrays in java with the comparator.

Comparator is used to write the custom sorting with the Collections or over Arrays.

If you are new arrays, read articles on Arrays.



At the end of the article, we have given the GitHub link where you can see all code at once and you can run the programs along with me.

It is easy to sort the arrays when the array is single-dimensional. Use Arrays.sort() method.

But if you have the user defined objects or two dimensional arrays then it is not possible to sort by using just the Arrays sort() method.

In this case, we need to use the Comparator interface to provide the custom logic for it.

First, we will start with the custom objects and then next show the two or more dimensional arrays.

You will see the different ways to create the comparator in jdk8, java 7 and before versions. All will produce the same output.

Java Arrays Sort Comparator

Wednesday, December 8, 2021

Java IS-A and HAS-A Relationship With Examples

Overview


Nowadays, Many programmers get confused with these IS-A and HAS-A relationships in java. It is a common interview question for freshers and experienced programmers to check their basic knowledge of oops principles.


We will discuss the following

1) IS-A Relationship (Inheritance)
2) HAS-A Relationship (Association)
3) Examples for each type
4) Interview Questions

Java IS-A and HAS-A Relationship With Examples




The main idea of these two principles is code reusability and easy code maintenance. You will see now how the code can be easily reusable in many places and used by many other programmers.

java lang ClassCastException [Fixed]

1. Overview

In this article, we will learn what is java.lang.ClassCastException in java and how to fix it.

We will look at the meaning of ClassCastException and a few examples of it.

java lang ClassCastException

Tuesday, December 7, 2021

Java 8 Comparator Comparing Reverse Order

 

1. Overview

In this tutorial, We'll learn how to use a comparator to sort the collection in reverse order.

In Java 8, Comparator interface is added with the reverse() method to reverse the collection using the existing comparator instead of creating another custom comparator.

First, let us learn how to reverse the comparator for comparing the objects from the collection before java 8 and next using Java 8 Comparator new methods.


Java 8 Comparator Comparing Reverse Order

Monday, December 6, 2021

Java 8 Comparator Lambda Examples

1. Overview


In this tutorial, We'll learn how to use the Comparator interface with lambda expression in Java 8 onwards.

Lambda expression is to replace the anonymous implementations and to reduce the boilerplate code.

This makes the code cleaner and focus more on the business logic rather than semantics.


Java community provided a few sets of rules and guidelines in creating the lambda statements.

Lambda syntax and invalid one are discussed in detail in the previous discussions "java 8 lambda expressions".

First, we will see the examples without lambda and then the next section will see the equivalent lambdas.

For sorting to work with lambda comparator, we have to use the Collections.sort() method.

Java Comparator Lambda Examples

Increasing or Extending an Array Length in 3 ways

1. Overview

In this tutorial, We'll see how many ways an array can be extended in java.

The actual array values are stored in contiguous memory locations. The answer may not be promptly obvious.

if you are new to the Java Array, It is worthful to read the beginner articles.


Increasing or Extending an Array Length in 3 ways

Java String substring() Method Example

1. Introduction


In this tutorial, You'll learn how to get the portion of a string using the substring() method of String API.

The name of this method indicates that it will fetch substring from an original string for a given index.

Java String substring() Method Example

String program to find the regionmatches() method.

Saturday, December 4, 2021

Java Program to Bitonic Sort

1. Overview


In this article, We'll learn about how to implement Bitonic sort in java.

Bitonic Sort is a classic parallel sorting algorithm. This is called as Bitonic Mergesort. It is also used as a construction method for building a sorting network.

Basically, it is a procedure of Biotonic sequence using bitonic splits.

How to write optimized bubble sort in java?

In java many sorting techniques can be implemented. But we have to choose the better one. This is very rarely used in real applications.


Java Program to Bitonic Sort



The bitonic sequence is said that when there is an index i exists such that either monotonically increasing and monotonically decreasing from index i and vice versa.


Eg. 7, 4, 2, 1, 9, 8, 7, 6, 5


Java 8 Comparator thenComparing()

1. Overview

In this tutorial, We'll learn how to use Comparator.thenComparing() method in java 8 streams.

thenComparing() method is used to sort the list of objects by multiple fields. 


And also thenComparing() method is used to merge or join two comparators as a single one. The merged comparator is used to sort the collection by multiple fields.

Syntax:
default Comparator<T> thenComparing(Comparator<? super T> other)
This method returns a lexicographic-order comparator with another comparator. If this Comparator considers two elements equal, i.e. compare(a, b) == 0, other is used to determine the order.

Java 8 Comparator thenComparing() - Sort By Multiple Fields


Java Comparator

1. Overview

In this tutorial, We'll learn how to use the Comparator interface in java.

A comparator interface is used to order the user-defined object in sorted order. This comparator interface has the capability to compare the same type of objects.

Comparator is used to sort the object in ascending or descending order.

We will write the example programs on custom objects with a single field or property.
And also how to sort the collection such as a list or set by multiple properties.

Java Comparator


Friday, December 3, 2021

Java Singleton Design Pattern with Best Practices

1. Introduction


In this article, We'll learn what is singleton pattern is in java and how to implement it. You will learn various ways to create singleton objects. This is the only design pattern that is used by every application in the software industry and also used extensively in java API such as Spring, apache or spark, etc. A question from the design pattern is a must in the interview and many questions come from this topic. This is my favourite interview question that I ask software developers. This question will check to understand many areas of core java such as private access modifier, static members, cloning, multithreading, deep cloning, serialization and deserialization and reflection api.

    
                                    Java Singleton Design Pattern with Best Practices

In this post, You will learn the frequently asked question on the singleton design pattern. If you are preparing for interviews, this will give you a clear picture of the singleton pattern.