Java 9 – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Mon, 11 Jan 2021 12:59:48 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Java 9 – Java2Blog https://java2blog.com 32 32 Java 9 JShell tutorial https://java2blog.com/java-jshell-tutorial/?utm_source=rss&utm_medium=rss&utm_campaign=java-jshell-tutorial https://java2blog.com/java-jshell-tutorial/#respond Sun, 11 Oct 2020 18:46:04 +0000 https://java2blog.com/?p=10430 The Java JShell is a command-line tool that is introduced in Java 9 version. It helps to execute/test Java statements in a single line.
It is based on REPL (Read Evaluate Print Loop) that reads a code statement, execute that and print the output, statement after statement. It reads the statement and immediately shows the result in the next line.

If you are familiar with Scala or Python language, then you would know about the REPL tool.

It is a powerful tool that allows executing statements, expressions, class, loop, methods, etc.

We can use it to test our code or logic without writing code into a file and then compile it. It reduces the effort for just checking the code logic.

For example, if we want to print a simple Hello world message, first we need to save code into a file and then compile and execute it. While by using the JShell, we write the print a statement and get the result immediately.

Saving data into a file requires additional steps like compiling and executing the code while JShell does it quickly in a single step.

For more understanding, let’s take an example.

public class Test 
{  
    public static void main(String[] args) 
    {  
        System.out.println("Hello World");
    }  
}

Output

Hello World

Hello World Example Using JShell

JShell

Now, we can easily understand that JShell has more advantages than writing code into a file. But it helps execute instant code only. To create an application, we will have to save source code into a file.

What can we do with JShell?

We can execute code that includes statements, loops, expressions, class, methods, etc.

It also provides several built-in commands to control the JShell environment. For example, to check the created Variables, we can use /vars command. We will discuss these commands later in this article.

How to start and stop JShell?

To start with JShell, open the command prompt in the case of windows and terminal for Linux and Mac OS and then type jshell command.

>jshell

It will open jshell in the same window with a welcome message with Java version. In case of windows, see the below screenshot.

start-jshell

To stop the JShell, just type the /exit command which will bring out to normal command prompt.

jshell> /exit
| Goodbye

Creating variable in JShell

After starting the JShell, let’s create some variables and print their values.

jshell> int a = 10;
a ==> 10
jshell> int b = 20;
b ==> 20
jshell> int multiply = a*b;
multiply ==> 200
jshell> System.out.println(multiply);
200
jshell>

If we don’t provide any variable and enter any value, then jshell will hold the value in a dynamic variable. See the example here. Java automatically creates these variables.

jshell> 30
$1 ==> 30
jshell> 50
$2 ==> 50

JShell as a Calculator

We can use JShell as a calculator to get instant result of numeric calculations. See the example:

jshell> 10+20
$1 ==> 30
jshell> 10*10
$2 ==> 100
jshell> 200/10
$3 ==> 20
jshell> 20+30+50+40
4 ==> 140

Creating Methods in JShell

Like variables, we can create our methods to perform business logic.

jshell> int multiply(int a, int b){
…> return (a*b);
…> }
| created method multiply(int,int)
jshell> int result = multiply(10,20);
result ==> 200

Creating Class in JShell

Like method, we can create class as well by typing class definition.

Here is an simple example of creating a class called Country

jshell> class Country {
…> String name;
…> Country(String name)
…> {
…> this.name=name;
…> }
…>
…> public String getCountryName()
…> {
…> return name;
…> }
…> }
created class Country

You can declare the objects as below:

jshell> Country c1= new Country(“India”);
c1 ==> Country@754ba872

jshell> c1.getCountryName();
$4 ==> “India”

As you can see, we have created a Country object named c1 and called getCountryName() method on it.

Executing Algebraic Expressions in JShell

We can execute any valid expression using the JShell to check the expression’s outcome.

jshell> a = 10
a ==> 10
jshell> b = 20
b ==> 20
jshell> (a*a)+(b*b)+2*a*b; // algebraic expression
$1 ==> 900

Executing Conditional Statements in JShell

We can test conditional statements like if-else to check program control flow instantly in the JShell.

jshell> int a = 20;
a ==> 20
jshell> int b = 50;
b ==> 50
jshell> if(a System.out.println(“A is less than B”);
…> }else{
…> System.out.println(“B is less than A”);
…> }
A is less than B
jshell>

JShell Commands

Apart from executing Java code, JShell provides some built-in commands to handle the code. Some of them we are discussing here.

List the Variables

To check all the created variables for our current session, we can use /vars command. It will populate all the variables.

jshell> /vars
| int sum = 30
| int $1 = 30
| int $2 = 50
| int $3 = 30
| int $4 = 100
| int $5 = 20
| int $6 = 140
| int result = 30
| int $7 = 900
| int a = 20
| int b = 50

List the Methods

To get a list of all the created methods in the current session, use /methods command.

jshell> /methods
| int multipy(int,int) jshell>

Import Java Packages

During starting JShell, it imports some packages by default to provide basic functionalities to the user. We can check these default packages by using the /import command.

jshell> /import
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
jshell>

Check history of commands

To check history of commands, we have executed so far, we can use /history command.

jshell> /import
int a=10;
int b=20;
int multiply=a*b;
System.out.println(multiply);
int multiply(int a,int b){
return (a*b);
}
jshell>

Edit code in JShell Edit Pad

If you just need to write few lines of code, you can use inline editor. But when you want to write quite a few line of code, then you can /edit command to change your code.
For example:
Let’s say you want to edit method multiply(), you can use /edit multiply command.

jshell> /edit multiply

You will see below JShell Edit pad where you can make changes.
jshell
Once you are done with changes, you can click Accept button to accept the changes.

Load external Java code to JShell

We can also load code from external file using /open command.
Let’s see with the help of example:
Here is content of file C://divide.java

int x=10;
int y=2;

int divide(int a,int b)
{
    return a/b;
}

Now we can use following command to load the file.

jshell> /open C://divide.java

openCommandOutput
As you can see variables x,y and method divide loaded into the jshell.

Drop variables,methods, classes from Jshell

We can drop variables,methods, classes from Jshell using /drop command.

Let’s say you want drop method divide from JShell. You can use following command

Now we can use following command to load the file.

jshell> /drop divide
| dropped method divide(int,int)

As you can see, method divide() dropped from the JShell.

JShell help

We can use /help command to get more information about the command.
Here is the screen shot for the /help command:

Conclusion

This tutorial is all about the Java JShell tool, which is introduced in Java 9. We discussed this tool with the help of several examples. We suggest you try this tool your own and enjoy Java coding in a new way.

]]>
https://java2blog.com/java-jshell-tutorial/feed/ 0
Java 9: Stream API Improvements https://java2blog.com/java-9-stream-api-improvements/?utm_source=rss&utm_medium=rss&utm_campaign=java-9-stream-api-improvements https://java2blog.com/java-9-stream-api-improvements/#respond Sat, 10 Oct 2020 19:23:42 +0000 https://java2blog.com/?p=10521 In Java 9, following methods are added to Stream interface of stream package. These methods are default and static.

The takeWhile() Method

This method is included in Stream interface and used to collect the elements into a stream. It takes all the elements till the condition specified as predicate.

For example, we want to collect a few elements from a stream of elements; for this purpose, we can use takeWhile() method.

The following is the syntax of the method.

default Stream takeWhile(Predicate predicate)

Example

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

public class Main{
    public static void main(String[] args){
        List list = Stream.of(20,30,40,62,85,21)  
                .takeWhile(i -> (i<85)).collect(Collectors.toList());
        System.out.println(list); // collecting into a list

        // traverse elements
        Stream stream = Stream.of(20,30,40,62,85,21);
        stream.takeWhile(num -> num < 85).forEach(num -> System.out.println(num));
    }
}

Output

[20, 30, 40, 62] 20
30
40
62

The dropWhile() Method

This method is just opposite of takeWhile(). It drops the result when the specified condition occurs and takes rest of elements.

If stream is ordered then it returns a stream that contains remaining elements after dropping the elements. If the stream is unordered, it returns a stream that includes the remaining elements after dropping a subset of elements. The following is the syntax of the method.

default Stream dropWhile(Predicate predicate)

Example

package myjavaproject;

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

public class Main{
    public static void main(String[] args){
        List list = Stream.of(20,30,40,62,85,21)  
                .dropWhile(i -> (i<85)).collect(Collectors.toList());
        System.out.println(list); // collecting into a list

        // traverse elements
        Stream stream = Stream.of(20,30,40,62,85,21);
        stream.dropWhile(num -> num < 85).forEach(num -> System.out.println(num));
    }
}

Output

[85, 21] 85
21

The ofNullable() Method

This method is used for null checking and returns either a sequential Stream of a single element or an empty Stream. The syntax of the method is given below.

static  Stream ofNullable(T t)

Example

import java.util.stream.Stream;

public class Main{
    public static void main(String[] args){
        Stream stream = Stream.ofNullable(12);
        stream.forEach(System.out::print);

        stream = Stream.ofNullable(null);
        stream.forEach(System.out::print); // empty stream
    }
}

Output

12

The iterate() Method

This method is added into Java 9 that helps to iterate over a sequence of stream and takes three arguments. The first argument is called seed and used to initialize a stream, the second argument is called predicate and used to specify the condition while third argument is used to generate next elements.

The syntax of the method is given below.

static  Stream iterate(T seed, Predicate hasNext, UnaryOperator next)

Example

import java.util.stream.Stream;

public class Main{
    public static void main(String[] args){
        Stream stream = Stream.iterate(1, a->a<5, a->a+1);
        stream.forEach(System.out::println);
    }
}

Output

1
2
3
4

This is similar to writing a for loop as below:

for(int i=1;i<5;i++)
{
   System.out.println(i)
}

That’s all about Java 9 Stream API improvements.

]]>
https://java2blog.com/java-9-stream-api-improvements/feed/ 0
Java 9 – Process API Improvements https://java2blog.com/java-9-process-api-improvements/?utm_source=rss&utm_medium=rss&utm_campaign=java-9-process-api-improvements https://java2blog.com/java-9-process-api-improvements/#respond Wed, 23 Sep 2020 18:41:31 +0000 https://java2blog.com/?p=10534 In this post, we will see about Java 9 process API improvements.
Java improved its Process API in Java 9 version that includes new methods for Process class and two new interfaces ProcessHandle and ProcessHandle.Info. These methods are used to create a new process and get process information like process status, running time, process id, etc. We can also get the current running process and its information.

The Process Class

Java Process class is located in java.lang package and provides methods to control the processes started by ProcessBuilder.start and Runtime.exec.

Start a new Process?

We can call start() method of ProcessBuilder class to start a new process. It will return an instance of Process class that further can be used to get process-related information.

Process process = new ProcessBuilder("vim").start(); // vim is an editor in Linux

Methods

Although Process class contains several methods but here we are listing the new methods added into Java 9 version.

MethodDescription
boolean supportsNormalTermination()It returns true if the implementation of destroy() is to normally terminate the process, else returns false.
ProcessHandle toHandle()It returns a ProcessHandle for the Process.
long pid()It returns the native process ID of the process.
Stream children()It returns a snapshot of the direct children of the process.
Stream descendants()It returns a snapshot of the descendants of the process.
ProcessHandle.Info info()It returns a snapshot of information about the process.
CompletableFuture onExit()It returns a CompletableFuture for the termination of the Process.

Example to get Process Id

After creating a process (in the above example), we are getting process id using pid() method of Process class. See the example below.

import java.io.IOException;

public class Main{
    public static void main(String[] args) throws IOException {
        Process process = new ProcessBuilder("vim").start();
         // Get process id
         System.out.println(process.pid());
    }
}

Output

Process Id: 10754

Example to get Process Information

Here is an example to get more information about the process such as hashcode, children and class.

import java.io.IOException;

public class Main{
    public static void main(String[] args) throws IOException {
        Process process = new ProcessBuilder("vim").start();
         // Get created process info
         System.out.println(process.pid());
         System.out.println(process.info());
         System.out.println(process.hashCode());
         System.out.println(process.isAlive());
         System.out.println(process.children());
         System.out.println(process.getClass());
         System.out.println(process.descendants().count());
    }
}

Output

15066
[user: Optional[irfan], cmd: /usr/bin/vim.basic, startTime: Optional[2020-09-17T07:50:15.080Z], totalTime: Optional[PT0S]] 1418481495
true
java.util.stream.ReferencePipeline$2@65ab7765
class java.lang.ProcessImpl
0

ProcessHandle Interface

This interface is added into Java 9 to provide control of native or created processes. It provides additional support for process handling. We can use its current() method to get current process handler. Let’s see an example.

public class Main{
    public static void main(String[] args) {
        ProcessHandle processHandle = ProcessHandle.current(); // current process
        System.out.println("Process Id: "+processHandle.pid());
    }
}

Output

Process Id: 17044

Methods

The following are the methods of ProcessHandle Interface.

MethodDescription
static Stream allProcesses()It returns a snapshot of all processes visible to the current process.
Stream children()It returns a snapshot of the current direct children of the process.
int compareTo(ProcessHandle other)It compares this ProcessHandle with the specified ProcessHandle for order.
static ProcessHandle current()It returns a ProcessHandle for the current process.
Stream descendants()It returns a snapshot of the descendants of the process.
boolean destroy()It requests the process to be killed.
boolean destroyForcibly()It requests the process to be killed forcibly.
boolean equals(Object other)It returns true if other object is non-null, is of the same implementation, and represents the same system process; otherwise it It returns false.
int hashCode()It returns a hash code value for this ProcessHandle.
ProcessHandle.Info info()It returns a snapshot of information about the process.
boolean isAlive()It tests whether the process represented by this ProcessHandle is alive.
static Optional of(long pid)It returns an Optional for an existing native process.
CompletableFuture onExit()It returns a CompletableFuture for the termination of the process.
Optional parent()It returns an Optional for the parent process.
long pid()It returns the native process ID of the process.
boolean supportsNormalTermination()It returns true if the implementation of destroy() normally terminates the process.

Example

We will use ProcessHandle interface to get more information of currently running process.

public class Main{
    public static void main(String[] args) {
        ProcessHandle processHandle = ProcessHandle.current();
        System.out.println("Get Process Info: ");
        System.out.println("Process Id: "+processHandle.pid());
        ProcessHandle.Info pHandleInfo = processHandle.info();
        System.out.println(pHandleInfo.arguments().isPresent());
        System.out.println(pHandleInfo.arguments().isEmpty());
        System.out.println(pHandleInfo.command().isPresent());
        System.out.println(pHandleInfo.totalCpuDuration().get());
        // process user name
        System.out.println(pHandleInfo.user().get());
    }
}

Output

Process Id: 12437
true
false
true
PT0.11S
irfan

ProcessHandle.Info Interface Methods

It is a nested interface of ProcessHandle interface and used to provide support for Process handling.

MethodDescription
Optional arguments()It returns an array of Strings of the arguments of the process.
Optional command()It returns the executable pathname of the process.
Optional commandLine()It returns the command line of the process.
Optional startInstant()It returns the start time of the process.
Optional totalCpuDuration()It returns the total cputime accumulated of the process.
Optional user()It returns the user of the process.

That’s all about Java 9 Process API improvements.

]]>
https://java2blog.com/java-9-process-api-improvements/feed/ 0
Java try with resources https://java2blog.com/java-try-with-resources/?utm_source=rss&utm_medium=rss&utm_campaign=java-try-with-resources https://java2blog.com/java-try-with-resources/#respond Sat, 19 Sep 2020 18:16:36 +0000 https://java2blog.com/?p=10455 In this post, we will see about Java try with resources Statement.
Java try with resources is a feature of Java which was added into Java 7. It helps to close all the resources declared within try block. It automatically closes the resources after being used. A resource can be any file or a database connection.
For example, if we are working with File handing then after opening a file, it requires to be closed after reading or writing data. In early versions of Java, we have to explicitly close the resource, but from Java 7, we don’t need to worry about to close the resources.

What type of resources can be handled automatically?

Java says, any object that implements java.lang.AutoCloseable interface and java.io.Closeable interface, can be used as a resource.

Let’s start with examples to understand the topic.

Older approach to close the resources

This is an older approach that we used to handle file related operations.
Notice, we manually closed the resource using close() method.

import java.io.FileOutputStream;

public class Main{
    public static void main(String[] args){
        try {
            FileOutputStream fileOutputStream =new FileOutputStream("info.txt");
            fileOutputStream.write("Java2blog is a technical blog".getBytes());
            System.out.println("File is written");
            fileOutputStream.close(); // closing resource
        }catch(Exception e) {
            System.out.println(e);
        }
    }
}

Output:

File is written

Java 7 try with resources

The try with resources was introduced with Java 7 and helps to reduce the effort to close the resources manually. Now, we don’ need to use close() method. See the example.

import java.io.FileOutputStream;

public class Main{
    public static void main(String[] args){
        try (FileOutputStream fileOutputStream = new FileOutputStream("info.txt")){
            fileOutputStream.write("Java2blog is a technical blog".getBytes());
            System.out.println("File is written");
            // fileOutputStream.close(); No need to close manually 
        }catch(Exception e) {
            System.out.println(e);
        }
    }
}

Output:

File is written

Syntax

The following is the syntax of try with resources that includes function like parenthesis to collect resources.

try(  
        // resources    
        ){
    // body of try block

}catch( // Exception ) {
    // handler code
}

Note: Prior to Java 7 version, only finally block is used to ensure that a resource is closed properly.

Example

Let’s take one more example of Java try with resources. Here, we are creating database connection and not closing the connection because it will be handled by new try block.
Notice, we used multiple resources inside it that means it can handle multiple resources as well.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main{
    public static void main(String[] args){
        try(    Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/employee","user_name","user_password");  
                Statement stmt=con.createStatement();  
                ResultSet rs=stmt.executeQuery("select * from emp");  
                )
        {   
            while(rs.next()){    
                System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));    
            }  
        }   
        catch(Exception e){    
            System.out.println(e);  
        }    
    }
}

Java 9 Try with resources Improvements

In Java 9, try with resources is improved that allows to declare or create the resources outside the try block. Before Java 9, it was not possible, and compiler generates error.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Main{
    public static void main(String[] args) throws FileNotFoundException{
        FileOutputStream fileOutputStream = new FileOutputStream("info.txt"); // Outside the try block
        try (fileOutputStream){
            fileOutputStream.write("Java2blog is a technical blog".getBytes());
            System.out.println("File is written");
        }catch(Exception e) {
            System.out.println(e);
        }
    }
}

Output:

File is written

See, we declared the resource outside the try with resources and compiler compiles the file successfully, but in case of Java 7 or Java 8, we can not do this.

Finally block with try with resources

Although Java try with resources does resource cleanup tasks automatically but in case, if there is any resource which does not implement AutoCloseable interface need to be closed in finally block.
In this example, we are using finally block with try with resources.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Main{
    public static void main(String[] args) throws FileNotFoundException{
        FileOutputStream fileOutputStream = new FileOutputStream("info.txt");
        try (fileOutputStream){
            fileOutputStream.write("Java2blog is a technical blog".getBytes());
            System.out.println("File is written"); 
        }catch(Exception e) {
            System.out.println(e);
        }
        finally {
                // resource releasing code
            System.out.println("Finally block is executed");
        }
    }
}

Output:

File is written
Finally block is executed

Create Custom AutoCloseable Code

Any class that implements AutoCloseable interface can be used in try with resources. Let’s create a class and implements AutoCloseable interface. This class has some utility methods.
Notice, we did not call close() method of SetupConnection class, but it is called implicitly by the compiler. See the example and its output.

class SetupConnection implements AutoCloseable{
    void configureConnection() {
        System.out.println("Connection configured.");
    }   
    void connect() {
        System.out.println("Connected");
    }
    @Override
    public void close() throws Exception {
        System.out.println("Connection is closed.");
    }
}

public class Main{
    public static void main(String[] args){
        SetupConnection con = new SetupConnection();
        try (con){
            con.configureConnection();
            con.connect();
        }catch(Exception e) {
            System.out.println(e);
        }
    }
}

Output:

Connection configured.
Connected
Connection is closed.

That’s all about Java Try with resources.

]]>
https://java2blog.com/java-try-with-resources/feed/ 0
Java 9 – Javadoc Improvement https://java2blog.com/java-9-javadoc-improvement/?utm_source=rss&utm_medium=rss&utm_campaign=java-9-javadoc-improvement https://java2blog.com/java-9-javadoc-improvement/#respond Sat, 19 Sep 2020 12:57:22 +0000 https://java2blog.com/?p=10576 Java has upgraded its Javadoc for better user interaction and user-experience. It includes a simplified search, HTML generator, Doclet API, etc.

What is Javadoc

The Javadoc is a tool like javac and a part of JDK. It is used to generate HTML documentation of Java source code. If you ever visit to oracle site you will see the Java documentation which is generated by Javadoc. The upgraded Javadoc has the following features.

Simplified Doclet API

In Java 9, old Doclet API has been replaced with a new simplified API. Although the existing API is still supported and available but you can use the new Doclet API.

Support for HTML5

It supports the HTML5 for better user interface and tools. So the new Javadoc is based on HTML5 version.

Improved Search

Javadoc provides a new search box to find class, packages, methods. It provides better suggestion and accurate search in a moment.

Support for Module System

It helps to generate documentation based on new Java platform module system.
Let’s take an example.

How to create HTML Javadoc from Java source file.

Let’s create an example to generate new HTML5 documentation from a Java source file. Here, we created a Calculate class that contains some methods.

package com.java2blog;
/**
* It provides methods to compute basic arithmetic operations.
* @author Irfan
* @version 1.0
* 
*/
public class Calculate {

/**
* Returns sum of two integer numbers
*
* @param a and b of integer type
*/
public int add(int a, int b){
    return(a+b);
}
/**
* Returns subtraction of two integer numbers
*
* @param a and b of integer type
*/
public int sub(int a, int b){
    return(a-b);
}
/**
* Returns multiply of two integer numbers
*
* @param a and b of integer type
*/
public long mult(int a, int b){
    return(a*b);
}
/**
* Returns division of two integer numbers
* 
* @param a and b of integer type
*/

public float div(int a, int b){
    return(a/b);
}
}

Run Javadoc Command

To create Javadoc, use the following command. execute it using cmd or terminal after reaching to Java file location.

javadoc -d . -html5 Calculate.java

It will generate populate some messages to the console which are processing instructions.

Loading source file Calculate.java...
Constructing Javadoc information...
Standard Doclet version 11.0.8
Building tree for all the packages and classes...
Generating ./com/java2blog/Calculate.html...
Generating ./com/java2blog/package-summary.html...
Generating ./com/java2blog/package-tree.html...
Generating ./constant-values.html...
Building index for all the packages and classes...
Generating ./overview-tree.html...
Generating ./index-all.html...
Building index for all classes...
Generating ./allclasses-index.html...
Generating ./allpackages-index.html...
Generating ./deprecated-list.html...
Building index for all classes...
Generating ./allclasses.html...
Generating ./allclasses.html...
Generating ./index.html...
Generating ./help-doc.html...

Now open the directory in which Calculate.java file is stored. You will find several html files there, open index.html file into the browser and the page would be like this.

Click on the Calculate class and you will see the class structure.

Scroll down the page and you will see the list of method belongs to Calculate class.

And you can see a new search box, search here with any text and you will get the suggestions.

Well, this is all about Javadoc, It is easy and good tool to create a informative HTML doc using Source code.

]]>
https://java2blog.com/java-9-javadoc-improvement/feed/ 0
Java 9 – @SafeVarargs Annotation https://java2blog.com/java-9-safevarargs-annotation/?utm_source=rss&utm_medium=rss&utm_campaign=java-9-safevarargs-annotation https://java2blog.com/java-9-safevarargs-annotation/#respond Sat, 19 Sep 2020 09:37:24 +0000 https://java2blog.com/?p=10573 In this post, we will see about @SafeVarargs Annotation in Java 9.
The @SafeVarargs is an annotation that is used to perform safe operations. When a method takes variable arguments, then it may cause to unsafe operation, so the @SafeVarargs annotation tells to the compiler to perform safe operations. For example, if we don’t use the annotation the compiler reports warning: Type safety: Potential heap pollution via varargs parameter.

We can use this annotation to final and static and private (from Java 9) methods only of a class. See the example below.

@SafeVarargs annotation

Let’s see few examples with final and static methods.

@SafeVarargs with Final Method

In this example, we have a final methods that takes var-args parameters so we used @SafeVarargs annotation. See the example.

import java.util.ArrayList;
import java.util.List;

class DemoPrint{
    @SafeVarargs
    final void display(List... lists) {
        for (List list : lists) {  
            System.out.println(list);  
        }  
    }
}
class Main {
    public static void main(String[] args){
        DemoPrint dp = new DemoPrint();  
        List list = new ArrayList();  
        list.add("Python");  
        list.add("Java");  
        dp.display(list);
    }
}

Output

[Python, Java]

@SafeVarargs with Static Method

Java allows using @SafeVarargs annotation with static methods as well. See the example with below.

import java.util.ArrayList;
import java.util.List;

class DemoPrint{
    @SafeVarargs
    static void display(List... lists) {
        for (List list : lists) {  
            System.out.println(list);  
        }  
    }
}
class Main {
    public static void main(String[] args){
        List list = new ArrayList();  
        list.add("Python");  
        list.add("Java");  
        DemoPrint.display(list);
    }
}

Output

[Python, Java]

Java 9 @SafeVarargs Improvement

In Java 9, It is allowed to use @SafeVarargs annotation with private methods as well. Here, we have a private method displayString() that takes string type var-args.

import java.util.ArrayList;
import java.util.List;

class DemoPrint{
    @SafeVarargs
    static void display(List... lists) {
        for (List list : lists) {  
            System.out.println(list);  
        }  
    }
}
class Main {
    @SafeVarargs
    private void displayString(String...strings ) {
        for (String str : strings) {
            System.out.println(str);
        }
    }

    public static void main(String[] args){
        List list = new ArrayList();  
        list.add("Python");  
        list.add("Java");  
        DemoPrint.display(list);
        Main main = new Main();
        main.displayString("Java","is","a","Awesome","Language");
    }
}

Output

[Python, Java] Java
is
a
Awesome
Language

Please note that if you use @SafeVarargs in private method before Java 9, you will get a compilation error.

Without @SafeVarargs annotation

In case, we don’t use the annotation the compile will report a warning message to console with output.

class Main {

    private void displayString(String...strings ) {
        for (String str : strings) {
            System.out.println(str);
        }
    }

    public static void main(String[] args){
        Main main = new Main();
        main.displayString("Java","is","a","Awesome","Language");
    }
}

Output

Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Java
is
a
Awesome
Language

That’s all about Java 9 @SafeVarargs Annotation.

]]>
https://java2blog.com/java-9-safevarargs-annotation/feed/ 0
Java 9 – Anonymous Inner classes and Diamond Operator https://java2blog.com/java-9-anonymous-inner-classes-and-diamond-operator/?utm_source=rss&utm_medium=rss&utm_campaign=java-9-anonymous-inner-classes-and-diamond-operator https://java2blog.com/java-9-anonymous-inner-classes-and-diamond-operator/#respond Sat, 19 Sep 2020 09:25:46 +0000 https://java2blog.com/?p=10568 Type inference is a feature of Java that was introduced in Java 7. Now, Java compiler can infer type of a data automatically.
For example, if we create an ArrayList then we use the code like:

List list = new ArrayList(); // Before Java 7
List list = new ArrayList<>(); // From Java 7 and onward

You can see that Java 7 allows us to use empty diamond operator to avoid code redundancy. But we can use this Java collection only, what about the anonymous class?

If we do the same in Java 7 with anonymous class, means use empty diamond(<>) in an anonymous class then compiler reports an error. See the example below:

abstract class CalculateAble{
    abstract T add(T a, T b);

}

public class Main {

    public static void main(String[] args) {
        CalculateAble a = new CalculateAble<>() { // diamond operator is empty 
            public Integer add(Integer a, Integer b){  
                return a+b;   
            }  
        };
        int result = a.add(10, 20);
        System.out.println(result);
    }
}

Output

error: cannot infer type arguments for CalculateAble
CalculateAble a = new CalculateAble() {
^
reason: cannot use ” with anonymous inner classes

Note: The empty diamond operator with anonymous classes was not allowed in Java SE 7.

This is how we create an anonymous class in Java. It works fine with all the Java versions.

DemoCalculator a = new DemoCalculator() { // diamond operator is not empty 
            Integer show(Integer a, Integer b){  
                return a+b;   
            }  
        };

Anonymous class: Java 9 Improvement

Java improved its type inference feature and allowed us to use (diamond) in the anonymous class too. For example, if we create an anonymous class with empty diamond(<>), then the compiler does not report any error and will compile the code successfully.

Example: Anonymous class with diamond operator

Let’s execute this example using Java 9 and higher version and see. It will execute fine.

abstract class CalculateAble{
    abstract T add(T a, T b);

}

public class Main {

    public static void main(String[] args) {
        CalculateAble a = new CalculateAble<>() { // diamond operator is empty 
            public Integer add(Integer a, Integer b){  
                return a+b;   
            }  
        };
        int result = a.add(10, 20);
        System.out.println(result);
    }
}

Output

30

Well, this is all about the use of diamond operator in an anonymous class in Java 9 version.

]]>
https://java2blog.com/java-9-anonymous-inner-classes-and-diamond-operator/feed/ 0
Java 9 – Private methods in interface https://java2blog.com/java-9-private-methods-interface/?utm_source=rss&utm_medium=rss&utm_campaign=java-9-private-methods-interface https://java2blog.com/java-9-private-methods-interface/#respond Sat, 19 Sep 2020 08:49:44 +0000 https://java2blog.com/?p=10476 In this topic, we will discuss the private and private static methods inside an interface.

interface in Java is a concept which is used to achieve abstraction. In early versions of Java, an interface can contain only abstract methods and constants until Java 8 which allows to add default and static methods as well.

In Java 9, interface allows creating private and private static methods. It means now an interface can have the following:

  1. Abstract methods
  2. Constant variables
  3. Default methods (added in Java 8)
  4. Static methods (added in Java 8)
  5. Private methods (added in Java 9)
  6. Private static methods (added in Java 9)

Now, let’s understand what is private method and why it is important.

Interface Private Method

A private method declared inside an interface is similar to declared inside a class. It is declared using private access modifier to keep it limited to the interface. These methods can’t be accessible outside the interface and don’t inherit to the interface or implementing class.

The primary purpose behind to add private method was to share common code between non-abstract methods within the interface. Let’s see an example.

interface Drinkable{
    default void breakTime() {
        coffee();
    }
    private void coffee() {
        System.out.println("Let's have a Coffee");
    }
}

public class Main implements Drinkable{
    public static void main(String[] args){
        Main main = new Main();
        main.breakTime();
    }
}

Output:

Let’s have a Coffee

Interface Private Static Methods

Like private instance methods, private methods can be static as well. A private static method can not be accessible from outside the interface and can only be accessible inside the default or static methods.

interface Drinkable{
    default void breakTime() {
        coffee();
        tea();
    }
    private void coffee() {
        System.out.println("Let's have a Coffee");
    }
    private static void tea() {
        System.out.println("Let's have a Tea");
    }
}

public class Main implements Drinkable{
    public static void main(String[] args){
        Main main = new Main();
        main.breakTime();
    }
}

Output:

Let’s have a Coffee
Let’s have a Tea

If we want to share code between instance methods, private instance methods and private static methods both can be used. But If we want to share code between static methods, use private static methods only. See, what happens, if we try to access a private method inside a static method.

interface Drinkable{
    static void breakTime() {
        coffee(); // Error : Cannot make a static reference to the non-static method
    }

    private void coffee() {
        System.out.println("Let's have a Coffee");
    }
}

public class Main implements Drinkable{
    public static void main(String[] args){
        Main main = new Main();
        //main.breakTime();
    }
}

Output:

Error : Cannot make a static reference to the non-static method

Key-points to remember

  1. Interface private methods must have implementation body; they can’t be declared as abstract methods.
  2. A static method can call only private static method, but a default method can call both the static and non-static(instance) private methods.
  3. The interface private methods support sharing common code between non-abstract methods(default, static and private).

Conclusion

This topic is all about the private methods in the interface. This feature makes the interface more powerful and advance. Now, interface supports both private and private static methods within an interface.

That’s all about Java 9 Private methods in interface.

]]>
https://java2blog.com/java-9-private-methods-interface/feed/ 0
Java 9 Underscore(_) keyword https://java2blog.com/java-9-underscore-keyword/?utm_source=rss&utm_medium=rss&utm_campaign=java-9-underscore-keyword https://java2blog.com/java-9-underscore-keyword/#respond Thu, 17 Sep 2020 17:59:49 +0000 https://java2blog.com/?p=10551 In this post, we will see about Underscore keyword, which is introduced in java 9.

Underscore In Java

Underscore(_) is a symbol that is used to combine multi-words in a single identifier sometimes refers to a variable in a programming context.

In Java, to create a lengthy variable, we prefer to use underscore (_) such as employee_id, employee_name etc.

Apart from it, underscore can be used to represent a variable and can hold any type of value . Since Java 8, we could use underscore as variable name such as = 10, = 10.5, etc. But in Java 9, underscore is a reserve word and cannot be used as an identifier.
Let’s see an example.

Underscore as variable in Java 8

This example is executed by using Java 8 and produce output with a warning message. See the output.

public class Main{
    public static void main(String[] args) {
        int _ = 10; // valid till Java 8
        System.out.println(_);
    }
}

Output

10
warning: ‘_’ used as an identifier
(use of ‘_’ as an identifier might not be supported in releases after Java SE 8)

Underscore as variable in Java 9

If we execute this example with Java 9 then it reports an error. See the example.

public class Main{
    public static void main(String[] args) {
        int _ = 10; // valid till Java 8
        System.out.println(_);
    }
}

Output

error: as of release 9, ‘_’ is a keyword, and may not be used as an identifier

Although, we can not use underscore alone as a variable name, but we can use it with other alphabets. See some possible examples.

Here is an example:

public class Main{
    public static void main(String[] args) {
        int _a = 10; // valid
        System.out.println(_a);
        int a_ = 20; // valid
        System.out.println(a_);
        int a_b = 20; // valid
        System.out.println(a_b);
        int _ = 10; // invalid
        System.out.println(_);
    }
}
Output
10
20
20
Error: ‘_’ should not be used as an identifier, since it is a reserved keyword from source level 1.8 on

That’s all about Java 9 underscore keyword.

]]>
https://java2blog.com/java-9-underscore-keyword/feed/ 0