Wednesday, June 30, 2021

Demystifying Java SE Level for Jakarta EE

Oracle Java SE, Oracle Jakarta EE, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career, Oracle Java Study Material

As I mentioned in Hashtag Jakarta EE #76, the Jakarta EE Platform project is in the process of determining the Java SE requirements for Jakarta EE 10. In this post, I try to shed some light on the implications of the various options currently up for a vote. What do these options actually mean for:

a) the Jakarta EE API developers

b) the vendors/projects implementing Jakarta EE specifications, and

c) the application developers.

I have discussed the options and the implications for these three groups below.

Option 1: source=Java SE 11, bin=Java SE 11, TCK=Java SE 11+

Java SE 11 as source/language level and binary level for all API JARs. Compatible Implementations are free to pass TCKs using any Java SE version at 11 or higher.

a) API developers are restricted to the language features in Java SE 11. This means that features such as Records can not be used in the APIs. The API JARs must be compiled to Java SE 11 class level.

b) Implementors can implement their compatible implementations using any

language features from any Java SE version. They may choose to certify using any version from 11 and higher. For example, a vendor may choose to support only Java SE 17 and higher if they wish. Or they may choose to support any Java SE version from 11 and higher.

c) Application developers can develop their applications using any language features from any Java SE version. If they use Java SE 16, or higher, they are able to use Records in their applications as they would like. However, some mapping, or conversion, may be needed when interacting with the Jakarta EE APIs. The upper limit of the Java SE version will depend on what version their selected implementation (runtime) supports.

Option 2: source=Java SE 11, bin=Java SE 17, TCK=Java SE 17+

Java SE 11 as source/language level and Java SE 17 as the binary level for all API JARs. Compatible Implementations are free to pass TCKs using any Java SE version at 17 or higher.

a) API developers are restricted to the language features in Java SE 11. This means that features such as Records can not be used in the APIs. The API JARs must be compiled to Java SE 17 class level.

b) Implementors can implement their compatible implementations using any

language features from any Java SE version. They have to certify using Java SE 17 or higher.

c) Application developers can develop their applications using any language features from any Java SE version. If they use Java SE 16, or higher, they are able to use Records in their applications as they would like. Some mapping, or conversion, may be needed when interacting with the Jakarta EE APIs.

Option 3: source=Java SE 17, bin=Java SE 17, TCK=Java SE 17+

Oracle Java SE, Oracle Jakarta EE, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career, Oracle Java Study Material
Java SE 17 as source/language level and binary level for all API JARs. Compatible Implementations are free to pass TCKs using any Java SE version at 17 or higher.

a) API developers can use any language features from any Java SE version. This means that features such as Records can be used in the APIs. The API JARs must be compiled to Java SE 17 class level.

b) Implementors can implement their compatible implementations using any language features from any Java SE version. They have to certify using Java SE 17 or higher.

c) Application developers can develop their applications using any language features from any Java SE version. If they use Java SE 16, or higher, they are able to use Records in their applications as they would like.

Source: javacodegeeks.com

Monday, June 28, 2021

Difference Between Android and Java

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Guides, Oracle Java Career

Android vs Java

Java is one of the most popular object oriented programming languages in the world. Java is heavily used for software and web development. Recently, Java has become a popular language for mobile-based applications as well. Android is a mobile phone based platform developed by Google. Android development is most of the times java-based. Large portion of Java libraries are available in Android platform, but there are many other (non-java) libraries existing in Android (for user interfaces, etc.) as well.

Java

Java is one of the most widely used object oriented (and class-based) programming languages used for software development to web development, today. It is a general purpose and concurrent programming language. It was originally developed by Sun Microsystems in 1995. James Gosling is the father of the Java programming language. Oracle Corporation now owns Java (after buying Sun Microsystems recently). Java Standard Edition 6 is its current stable release. Java is a strongly typed language that supports a range of platforms from Windows to UNIX. Java is licensed under GNU General Public License. Java’s syntax is very much similar to C and C++. Java source files have the .java extension. After compiling Java source files using the javac compiler, it will produce .class files (containing the Java bytecode). These bytecode files can be interpreted using the JVM (Java Virtual Machine). Since the JVM can be run on any platform, Java is said to be multi-platform (cross-platform) and highly portable. Typically, end users use the JRE (Java runtime Environment) to run the Java bytecode (or Java Applets on web browsers). Software developers use the Java Development Kit (JDK) for application development. This is a superset of JRE, which includes a compiler and a debugger. A nice feature of Java is its automatic garbage collection, where objects that are no longer required are removed from memory automatically.

Android

Android is a mobile phone platform developed by Google. A large portion of Java 5.0 libraries is supported in Android. Therefore, it can be said that Android development is java-based. Many of the Java libraries that are not supported either have better replacements (other similar libraries) or are simply not needed (such as libraries for printing, etc.). Libraries like java.awt and java.swing are not supported because Android has other libraries for user interfaces. Android SDK supports other third party libraries like org.blues (Bluetooth support). Ultimately, Android code is compiled in to Dalvik opcodes. Davilk is a special virtual machine optimized for mobile devices with limited resources such as power, CPU and memory.

What is the difference between Android and Java?

Java is a programming language, while Android is a mobile phone platform. Android development is java-based (most of the times), because a large portion of Java libraries is supported in Android. However, there are key differences. Unlike Java, Android applications do not have a main function. They have onCrete, onResume, onPause and onDestroy functions that should be overwritten by the developers. Java code compiles to Java bytecode, while Android code compiles in to Davilk opcode.

Source: differencebetween.com

Friday, June 25, 2021

Difference Between Exception and Error

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Guides, Code Java, Oracle Java Exception, Oracle Java Error

Exception vs Error

Unexpected behavior is bound to occur when a program is running. This could be due to exceptions or errors. Exceptions are events, which can disturb the normal program flow. Errors are conditions that can be considered irrecoverable. Exceptions are mostly related to the application itself, while errors are related to the system on which the program is running.

More Info: 1Z0-900: Java EE 7 Application Developer

What is an Exception?

Exception is an event, which can disturb the normal program flow. The name exception comes from “exceptional event”. Throwing an exception is the process of creating an exception object and handing it off to the runtime system. Exception object is created by the method in which the exception occurred. Exception object contains useful information such as the type and the description of the exception. When the runtime system receives the exception object, it will try to find somebody to handle it within the call stack by traversing it in the reverse order (in which the methods were called). Call stack is the ordered list of methods, which were called prior to the method in which the exception occurred. The runtime system is successful if it finds a method with an exception handler. Exception handler is a block of code that can officially handle the said exception. If the runtime system finds an appropriate handler (i.e. type of exception matches the type that can be handled), it will pass the exception object to the handler. This is called catching the exception. However, if the exception cannot be handled, the program will terminate. In Java, exceptions inherit from ‘Throwable class.’ NullPointerException and ArrayIndexOutOfBoundsException are two common exceptions in Java.

What is an Error?

An error is a condition that can be considered irrecoverable such as the program requiring an amount of memory larger than what is available. These errors cannot be handled at runtime. If an error occurs, the program will terminate. In Java, errors inherit from Throwable class. Errors usually stand for serious problems that the programmer (or the application) should not try to catch. Errors are simply abnormal conditions, which are never expected to occur under normal circumstances, and therefore never foreseen. For example, OutOfMemoryError, StackOverflowError and ThreadDead are such errors. Methods should never have handlers for errors.

What is the difference between Exception and Error?

Both errors and exceptions are unwanted occurrence during the execution of a program. However, they have key differences. Exceptions can be foreseen by the programmer, while an error is difficult to foresee. Exceptions can be checked or unchecked. But errors are always unchecked. Exceptions typically indicate an error caused by the programmer. However, errors occur due to a system error or an inappropriate usage of a resource. Therefore, exceptions should be handled at the application level, while errors should be taken care of at the system level (only if possible). After handling an exception, you are guaranteed to return to normal program flow. But even if an error is caught, the programmer may not know how to handle it in the first place. Unlike traditional error handling, exceptions allow separating error-handling code from regular code.

Wednesday, June 23, 2021

Difference Between Java and Spring

Oracle Java, Oracle Spring, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Spring Preparation

Java vs Spring

Java is one of the most popular object oriented programming languages in the world. Java is heavily used for software and web development. Spring is an open source application framework. Although it is not dependent on any programming model, Spring framework has become very popular among Java programmers. Spring framework acts as a replacement or an addition to Java’s own EJB (Enterprise Java Beans).

What is Java?

Java is one of the most widely used object oriented (and class-based) programming languages used for software development to web development, today. It is a general purpose and concurrent programming language. It was originally developed by Sun Microsystems in 1995. James Gosling is the father of the Java programming language. Oracle Corporation now owns Java (after buying Sun Microsystems recently). Java Standard Edition 6 is its current stable release. Java is a strongly typed language that supports a range of platforms from Windows to UNIX. Java is licensed under GNU General Public License. Java’s syntax is very much similar to C and C++.

Java source files have the .java extension. After compiling Java source files using the javac compiler, it will produce .class files (containing the Java bytecode). These bytecode files can be interpreted using the JVM (Java Virtual Machine). Since the JVM can be run on any platform, Java is said to be multi-platform (cross-platform) and highly portable. Typically, end users use the JRE (Java runtime Environment) to run the Java bytecode (or Java Applets on web browsers). Software developers use the Java Development Kit (JDK) for application development. This is a superset of JRE, which includes a compiler and a debugger. A nice feature of Java is its automatic garbage collection, where objects that are no longer required are removed from memory automatically.

What is Spring?

Spring is an open source application framework. It was developed by Rod Johnson and the first version was released in 2004. Spring 3.0.5 is the current version of the Spring framework. It is licensed under Apache 2.0 license. Any Java application can use the core features of the Spring framework. Spring has become widely used within the Java community, even though the framework is independent of any programming model. Spring framework is used either as a replacement or an addition to EJB model. Some of the most important modules of Spring framework are IoC (Inversion of Control), AOP (Aspect Oriented Programming), MVC (Model View Controller), Transaction Management, Data Access, Authentication, Authorization, Remote Access Management, Batch processing, Messaging and Testing.

What is the difference between Java and Spring?

Oracle Java, Oracle Spring, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Spring Preparation

Java is a programming language, while Spring is an open source application framework. Therefore, they cannot be directly compared. However, Java EE (which is Java’s own server programming platform) is often compared against Spring framework. In fact, Spring framework is very popular among Java programmers (even though Spring is language independent and can be used with any programming model) because it is often used as a replacement or an addition to EJB (which come with Java EE).

Monday, June 21, 2021

Java 8 IntStream With Working Examples

Oracle Java Tutorial and Material, Oracle Java Certification, Core Java, Oracle Java Preparation, Oracle Java Career

A quick guide to understand primitive int representation of Stream as interface IntStream to support integer operations and with the useful examples.

More Info: 1Z0-819: Oracle Java SE 11 Developer

1. Overview

In this tutorial, We’ll learn how to use the IntStream in java 8 and it uses with example programs.

For int primitives, the Java IntStream class is a specialization of the Stream interface. It’s a stream of primitive int-valued items that can be used in both sequential and parallel aggregate operations.

AutoCloseable and BaseStream interfaces are implemented by IntStream, which is part of the java.util.stream package.

We will learn the following topics in this course.

◉ IntStream Creation

◉ ForEach loop

◉ IntStream ranges

◉ IntStream min and max

◉ IntStream find

◉ IntStrem map

◉ IntStream filter

◉ IntStream distinct

◉ IntStream to Array

◉ IntStream to List

2. Creating IntStream

An IntStream can be generated in a variety of ways, but it cannot be created using a new keyword.

The IntStream objects are created using the methods listed below.

◉ IntStream.of()

◉ IntStream.range()

◉ IntStream.rangeclosed()

◉ IntStream.generate()

◉ IntStream.iterate()

Let us explore the ways to use these methods with example programs. to create an instance for IntStream with primitive int values.

2.1 IntStream.of()

This function returns a sequentially ordered stream with the provided values as its elements.

It is available in two forms: single element stream and multiple values stream.

IntStream of(int t) – Returns a stream consisting of a single supplied element.

IntStream of(int… values) – Returns a stream with all the components supplied.

package com.oraclejavacertified.java8.intstream;

import java.util.stream.IntStream;

public class IntStreamOf {

    public static void main(String[] args) {

        IntStream singleValue = IntStream.of(10);

        IntStream multipleValeus = IntStream.of(1, 5, 10, 20, 30);

    }

}

2.2 IntStream.range()

range() is used to generate the numbers in the order with incremental by one.

static IntStream range(int startInclusive, int endExclusive) — here the end range is exclusive.

IntStream range10to30 = IntStream.range(10, 20);

2.3 IntStream.rangeclosed()

rangeClosed() is also used to generate the numbers in the order with incremental by one but it includes the end index of this method.

static IntStream rangeClosed(int startInclusive, int endInclusive)

IntStream range10to15closed = IntStream.range(10, 15);

2.4 IntStream.generate()

Use the generate() method if you wish to generate random numbers with custom logic.

IntStream random = IntStream.generate( () -> { return (int) Math.random() * 5000;});

2.5 IntStream.iterate()

The iterate() method is identical to the generate() method, except instead of random values, it uses incremental or decrement custom logic for large values.

Due to the fact that the iterate() method generates an infinite stream of integers, you must use the limit() function to get the first n numbers.

IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);

3. IntStream forEach()


Typically we can use the traditional for loop for certain range. However, the same thing may be accomplished by using the IntStream.forEach() function instead.

package com.oraclejavacertified.java8.intstream;
 
import java.util.stream.IntStream;
 
public class IntStreamOf {
 
    public static void main(String[] args) {
         
        System.out.println("for loop");
        for(int i = 1000; i < 20000 ; i = i + 4000) {
            print(i);
        }
         
        System.out.println("intstream foreach loop");
        IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);
         
        iterate.forEach(n -> print(n));
         
         
    }
     
    private static void print(int n) {
        System.out.println(n);
    }
 
}

4. IntStream ranges 


Two methods are offered by the IntStream API to work with numbers generated in a defined range.

range(start, endExclusive): excludes the end index from the output range.

rangeClosed(start, endInclusive): this method includes the end index from the output range.

The below program output gives you clear understanding between range() and rangeClosed() methods.

IntStream range10to15range = IntStream.range(10, 15);
        IntStream range10to15closed = IntStream.rangeClosed(10, 15);
         
        System.out.println("range(10, 15) : "+Arrays.toString(range10to15range.toArray()));
        System.out.println("rangeClosed(10, 15) : "+Arrays.toString(range10to15closed.toArray()));

Output:

range(10, 15) : [10, 11, 12, 13, 14]
rangeClosed(10, 15) : [10, 11, 12, 13, 14, 15]

5. IntStream min and max


IntStream has utility methods for determining the minimum and maximum values from a series of numbers or random numbers.

Use min() method to retrieve the lowest value from int stream.

Use max() method to retrieve the highest value from int stream.

System.out.println("range(10, 15) min value : "+IntStream.range(10, 15).min().getAsInt());
System.out.println("range(10, 15) max value : "+IntStream.range(10, 15).max().getAsInt());

Output:

range(10, 15) min value : 10
range(10, 15) max value : 14

6. IntStream find value


Use findFirst() or findAny() methods on the InstStream object to get the first or any value.

findFirst() vs findAny() indepth

By default, IntStream is created as sequential stream unless call the parallel() on the IntStream.

For sequential streams, the findFirst() and findAny() methods return the same result. If the stream is parallel, however, the findAny() method gives a random value.

System.out.println("findFirst value : "+IntStream.iterate(10, i -> i + 2).limit(100).findFirst().getAsInt());
System.out.println("findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).findAny().getAsInt());
 
System.out.println("parallel findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).parallel().findAny().getAsInt());

Output:

findFirst value : 10
findAny value : 10
parallel findAny value : 160

7. IntStream map() or flatMap()


Java 8 IntStream With Working Examples
We can transform the IntStream into the new form using map() method but flatMap() method does the flatten the IntStreams into primitives.

Usage of map() and flatMap() does not give much difference with IntStream usage.

IntStream mapInput = IntStream.iterate(10, i -> i + 1).limit(10);
 
System.out.println("map input stream : "+Arrays.toString(mapInput.toArray()));
 
IntStream mapOutput = mapInput.map( i -> i * 2);
 
System.out.println("map Output stream : "+Arrays.toString(mapOutput.toArray()));
 
IntStream input1 = IntStream.iterate(10, i -> i + 1).limit(10);
 
System.out.println("flat map : "+Arrays.toString(input1.flatMap( i -> IntStream.of(i)).toArray()));

Output:

map input stream : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
map Output stream : [20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
flat map : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

8. IntStream filter


Use filter() method to filter the integer values based on the given IntPredicate condition.

After applying the filter() method then next you can call forEach() or collect() method to convert it into List or Set.

IntStream stream = IntStream.range(100, 200);
 
// filter by number divisible by 5 and 7
System.out.println("numbers divisible by 5 and 7 are : ");
stream.filter(i -> (i % 5 == 0 && i % 7 == 0)).forEach(System.out::println);
 
IntStream stream2 = IntStream.range(100, 200);
 
List<Integer> primes = stream2.filter(IntStreamOf::checkPrime).boxed().collect(Collectors.toList());
 
System.out.println("Prime numbers (100, 200) are "+primes);

Output:

numbers divisible by 5 and 7 are : 
105
140
175
Prime numbers (100, 200) are [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]

9. IntStream distinct()


Use distinct() method to remove the duplicate values from IntStream.

Arrays.toString(IntStream.of(1, 2, 3, 1, 2, 3).distinct().toArray());

Output:

[1, 2, 3]

10. IntStream to Array and List or Set


Use toArray() method to collect the output of IntStream into Array.

Use collect() method to collect the output of IntStream into List or Set.

To remove the duplicates from int stream, you can collect the results into Set rather than using distinct() method. But distinct() is recommended.

int[] intArray = IntStream.of(1, 2, 3, 1, 2, 3).toArray();
System.out.println("int array : "+Arrays.toString(intArray));
 
List<Integer> list = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toList());
System.out.println("IntStream to List : "+list);
 
Set<Integer> set = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toSet());
System.out.println("IntStream to Set : "+set);

Source: javacodegeeks.com

Friday, June 18, 2021

Java Convert File Contents to String

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career

A quick guide on how to convert the file contents to String using Java Files api and with example programs.

1. Overview

In this tutorial, you’ll learn how to convert File contents to String in java.

If you are new to java 8, please read the how to read the file in java 8? we have already shown the different ways to read the file line by line.

Java new Files api has two useful methods to read the file.

readAllLines()

readAllBytes()

Let us write the examples on each method to convert file to string in java.

2. Java File to String – Files.readAllLines()

In the below example program, first we have stored the file location in the string variable.

Next, took the default char set for file encoding using Charset.defaultCharset().

Next, invoke  Files.readAllLines() method with the file path.

This method returns a List of strings as List<String>.

Finally, use java 8 stream api collect() and joining() methods to convert List to String.

package com.oraclejavacertified.files.tostring;

import java.io.IOException;

import java.nio.charset.Charset;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.List;

import java.util.stream.Collectors;

/**

 * Java example to convert File To String.

 * 

 * @author oraclejavacertified.blogspot.com

 *

 */

public class JavaFilesToString {

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

        // file location

        String filePath = "/CoreJava/src/main/resources/dummy.txt";

        // charset for encoding

        Charset encoding = Charset.defaultCharset();

        // reading all lines of file as List of strings

        List<String> lines = Files.readAllLines(Paths.get(filePath), encoding);

        // converting List<String> to palin string using java 8 api.

        String string = lines.stream().collect(Collectors.joining("\n"));

        // printing the final string.

        System.out.println("file as string ");

        System.out.println(string);

    }

}

Output:

file as string 

Line 1 : Hello Reader

Line 2 : Welcome to the java programt to . com blog

Line 3 : Here you find the articles on the java concepts

Line 4 : This is example to read this file line by line

Line 5 : Let us see the examples on Java 8 Streams API.

3. Java File to String – Files.readAllBytes()

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career
Next, call Files.readAllBytes() method which returns byte[] array as a result. Use String class to convert byte array to string with the default encoding technique.

The below program produces the same output as in the section 2.

public class JavaFilesToStringBytes {

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

        // file location

        String filePath = "/Users/venkateshn/Documents/VenkY/blog/workspace/CoreJava/src/main/resources/dummy.txt";

        // charset for encoding

        Charset encoding = Charset.defaultCharset();

        // reading all lines of file as List of strings

        byte[]  bytes = Files.readAllBytes(Paths.get(filePath));  

        // converting List<String> to palin string using java 8 api.

        String string = new String(bytes, encoding);

        // printing the final string.

        System.out.println("file as string ");

        System.out.println(string);

    }

}

Source: javacodegeeks.com

Wednesday, June 16, 2021

Announcing Java Management Service

Announcing Java Management Service, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Prep

Today we are introducing a new Oracle Cloud Infrastructure (OCI) native service to help manage Java runtimes and applications on-premises or on any cloud. Java Management Service (JMS) is now generally available (GA).

Oracle is the technological leader and steward of the Java ecosystem. Java is the #1 language for cloud development and deployment and has 30 billion active cloud Java Virtual Machines and over 50 billion total JVMs globally. Projects using Java are 2.5x more likely to be ahead of schedule compared to non-Java projects. *

With Java’s ubiquity and broad usage come significant management challenges. Java Management Service is designed to bring relief in this area and many others.

JMS offers a single pane of glass to manage Java deployments across the enterprise, answering questions such as:

◉ What are all the Java versions installed on my environment?

◉ What versions of Java are running in development and production?

◉ Which JDK distribution is each of these using?

◉ Are any unplanned Java applications running?

Are all my installed Java versions up to date with the latest security patches?

JMS will provide continuous insight based on telemetry data from the JVM to analyze security, performance, compliance, and efficiency metrics. For example, normally cryptography usage is a black box; expired certificates or disabled algorithms are often found only when something breaks or after a malicious attack.

Java Management Service is an included feature for Oracle Java SE customers. While there is no additional subscription cost to JMS, customers running it are billed for any usage beyond the OCI Monitoring free tier which supports several hundred million data points.

Announcing Java Management Service, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Prep
Figure 1: Architecture overview

JMS can track Java usage running on OCI, on on-premises desktops, laptops and servers, and third-party cloud services. It monitors the Java Development Kit (JDK), Java Runtime Environment (JRE), and GraalVM. A JMS agent installed on the managed instances collects Java usage telemetry data. Telemetry data is stored in the customer tenancy for privacy protection; there is no Oracle access beyond processing the data.

The OCI agent is installed in the customer’s tenancy for monitoring and producing reports. Only the customer can see the reports. Oracle cannot see the data and does not charge compute time for the use of the service, only for OCI Monitoring and only when use exceeds the OCI Monitoring free tier thresholds.

The following screen shots are a view of what this initial release of Java Management Service provides.

Announcing Java Management Service, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Prep
Figure 2 Java Management Service – Java installation report

Announcing Java Management Service, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Prep
Figure 3:  Java Management Service – application report

Source: oracle.com

Monday, June 14, 2021

Java Spark RDD reduce() Examples – sum, min and max operations

Java Spark RDD Reduce, Core Java, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career

A quick guide to explore the Spark RDD reduce() method in java programming to find sum, min and max values from the data set.

1. Overview

In this tutorial, we will learn how to use the Spark RDD reduce() method using 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.

2. Java Spark RDD – reduce() method

First let understand the syntax of java reduce() spark method.

public T reduce(scala.Function2<T,T,T> f)

This method takes the Function2 functional interface which is the concept of Java 8. But the Function2 is implemented in Scala language.

Function2 takes two arguments as input and returns one value. Here, always input and output type should be same.

3. Java Spark RDD reduce() Example to find sum


In the below examples, we first created the SparkConf and JavaSparkContext with local mode for the testing purpose.

We’ve provided the step by step meaning in the program.

We must have to pass the lambda expression to the reduce() method.

You might be surprised with the logic behind the reduce() method. Below is the explanation of its internals. As a developer, you should know the basic knowledge on hood what is going on.

Java Spark RDD Reduce, Core Java, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career
On the RDD, reduce() method is called with the logic of value1 + value2. That means this formula will be applied to all the values in each partition untill partition will have only one value.

If there are more than one partitions then all the outputs of partitions are moved to another data node. Then next, again the same logic value1 + value2 is applied to get the final result.

if only one partition is for the input file or dataset then it will return the final output of the single partion.

package com.oraclejavacertified.rdd.reduce;
 
import java.util.Arrays;
import java.util.List;
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
 
public class RDDReduceExample {
 
    public static void main(String[] args) {
         
        // to remove the unwanted loggers from output.
        Logger.getLogger("org.apache").setLevel(Level.WARN);
 
        // Getting the numbers list.
        List<Integer> numbersList = getSampleData();
         
        // Creating the SparkConf object
        SparkConf sparkConf = new SparkConf().setAppName("Java RDD_Reduce Example").setMaster("local");
 
        // Creating JavaSprakContext object
        JavaSparkContext sc = new JavaSparkContext(sparkConf);
         
        // Converting List into JavaRDD.
        JavaRDD<Integer> integersRDD =  sc.parallelize(numbersList);
         
        // Getting the sum of all numbers using reduce() method
        Integer sumResult = integersRDD.reduce( (value1, value2) -> value1 + value2);
 
        // printing the sum
         
        System.out.println("Sum of RDD numbers using reduce() : "+sumResult);
         
        // closing Spark Context
        sc.close();
         
    }
 
    /**
     * returns a list of integer numbers
     * 
     * @return
     */
    private static List<Integer> getSampleData() {
 
        return Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
 
    }
 
}

Output:

Sum of RDD numbers using reduce() : 45

4. Java Spark RDD reduce() min and max Examples


Next, let us find the min and max values from the RDD.

package com.oraclejavacertified.rdd.reduce;
 
import java.util.Arrays;
import java.util.List;
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
 
public class RDDReduceExample {
 
    public static void main(String[] args) {
         
        // to remove the unwanted loggers from output.
        Logger.getLogger("org.apache").setLevel(Level.WARN);
 
        // Getting the numbers list.
        List<Integer> numbersList = getSampleData();
         
        // Creating the SparkConf object
        SparkConf sparkConf = new SparkConf().setAppName("Java RDD_Reduce Example").setMaster("local");
 
        // Creating JavaSprakContext object
        JavaSparkContext sc = new JavaSparkContext(sparkConf);
         
        // Converting List into JavaRDD.
        JavaRDD<Integer> integersRDD =  sc.parallelize(numbersList);
         
        // Finding Min and Max values using reduce() method
         
        Integer minResult = integersRDD.reduce( (value1, value2) -> Math.min(value1, value2));
         
        System.out.println("Min of RDD numbers using reduce() : "+minResult);
         
        Integer maxResult = integersRDD.reduce( (value1, value2) -> Math.max(value1, value2));
         
        System.out.println("Max of RDD numbers using reduce() : "+maxResult);
         
        // closing Spark Context
        sc.close();
         
    }
 
    /**
     * returns a list of integer numbers
     * 
     * @return
     */
    private static List<Integer> getSampleData() {
 
        return Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
 
    }
 
}

Output:

Min of RDD numbers using reduce() : 1
Max of RDD numbers using reduce() : 9

Source: javacodegeeks.com

Friday, June 11, 2021

Java - Data Structures

Java - Data Structures, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation

The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes −

◉ Enumeration

◉ BitSet

◉ Vector

◉ Stack

◉ Dictionary

◉ Hashtable

◉ Properties

All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework, which is discussed in the next chapter. −

The Enumeration

The Enumeration interface isn't itself a data structure, but it is very important within the context of other data structures. The Enumeration interface defines a means to retrieve successive elements from a data structure.

For example, Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements.

To have more detail about this interface, check The Enumeration.

The BitSet

The BitSet class implements a group of bits or flags that can be set and cleared individually.

This class is very useful in cases where you need to keep up with a set of Boolean values; you just assign a bit to each value and set or clear it as appropriate.

For more details about this class, check The BitSet.

The Vector

The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements.

Like an array, elements of a Vector object can be accessed via an index into the vector.

The nice thing about using the Vector class is that you don't have to worry about setting it to a specific size upon creation; it shrinks and grows automatically when necessary.

For more details about this class, check The Vector.

The Stack

The Stack class implements a last-in-first-out (LIFO) stack of elements.

You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others.

When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off.

For more details about this class, check The Stack.

The Dictionary

The Dictionary class is an abstract class that defines a data structure for mapping keys to values.

This is useful in cases where you want to be able to access data via a particular key rather than an integer index.

Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a specific implementation.

For more details about this class, check The Dictionary.

The Hashtable

Java - Data Structures, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation
The Hashtable class provides a means of organizing data based on some user-defined key structure.

For example, in an address list hash table you could store and sort data based on a key such as ZIP code rather than on a person's name.

The specific meaning of keys with regard to hash tables is totally dependent on the usage of the hash table and the data it contains.

For more detail about this class, check The Hashtable.

The Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.

The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.

For more detail about this class, check The Properties.

Source: tutorialspoint.com

Wednesday, June 9, 2021

The Subs Bench

Core Java Tutorial and Material, Oracle Java Career, Oracle Java Preparation, Oracle Java Exam Prep

How do I subclass a list element declared in my interface?

In a current project, we’re looking at our strong types having both interfaces and concrete implementations. There’s a reason for this that’s NOT about making things mockable.

Read More: 1Z0-816: Oracle Java SE 11 Programmer II

What’s nice and obvious is that this is possible:

public interface Bar {

}

public interface Foo {

    Bar getBar();

}

public class BarImpl implements Bar {

}

public class FooImpl implements Foo {

    public BarImpl getBar() { ... }

}

Despite the fact that the FooImpl subclass returns a subclass of the interface’s declared getter everything compiles happily, because a subclass can be substituted for a base class and still meet the Liskov substitution principle.

However, there’s a problem if you try to do this:

public interface Foo {

   List<Bar> getBars();

}

public class FooImpl implements Foo {

   // compiler error...

   public List<BarImpl> getBars() { ... }

}

In the Java generic type system, List<BarImpl> is not a subclass of List<Bar>. The folks who designed this stuff are pretty clever, and there’s probably a very good technical reason why this is the case.

The question is – can it be solved?

public interface Foo<T extends Bar> {

    // we know this is "at least" a Bar

    List<T> getBars();

}

public class FooImpl implements Foo<BarImpl> {

    // compiles great

    public List<BarImpl> getBars() { ... }

}

For lots of List or Optional of things, this might seem a bit cumbersome, but it is how it’s done… apparently.

Source: javacodegeeks.com

Monday, June 7, 2021

Stream.reduce() in Java with examples

Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Java Exam Prep

Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements.

More Info: 1Z0-900: Java EE 7 Application Developer

reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element.

Syntax :

T reduce(T identity, BinaryOperator<T> accumulator);

Where, identity is initial value 

of type T and accumulator is a 

function for combining two values.

sum(), min(), max(), count() etc. are some examples of reduce operations. reduce() explicitly asks you to specify how to reduce the data that made it through the stream.

Let us see some examples to understand the reduce() function in a better way :

Example 1 :

// Implementation of reduce method

// to get the longest String

import java.util.*;

class GFG {

// Driver code

public static void main(String[] args)

{

// creating a list of Strings

List<String> words = Arrays.asList("GFG", "LPI", "for",

"LPIQuiz", "LPIforLPI");

// The lambda expression passed to

// reduce() method takes two Strings

// and returns the longer String.

// The result of the reduce() method is

// an Optional because the list on which

// reduce() is called may be empty.

Optional<String> longestString = words.stream()

.reduce((word1, word2)

-> word1.length() > word2.length()

? word1 : word2);


// Displaying the longest String

longestString.ifPresent(System.out::println);

}

}

Output :

LPIforLPI

Example 2 :


// Implementation of reduce method
// to get the combined String
import java.util.*;

class GFG {

// Driver code
public static void main(String[] args)
{

// String array
String[] array = { "LPI", "for", "LPI" };

// The result of the reduce() method is
// an Optional because the list on which
// reduce() is called may be empty.
Optional<String> String_combine = Arrays.stream(array)
.reduce((str1, str2)
-> str1 + "-" + str2);

// Displaying the combined String
if (String_combine.isPresent()) {
System.out.println(String_combine.get());
}
}
}

Output :

LPI-for-LPI

Example 3 :


// Implementation of reduce method
// to get the sum of all elements
import java.util.*;

class GFG {

// Driver code
public static void main(String[] args)
{

// Creating list of integers
List<Integer> array = Arrays.asList(-2, 0, 4, 6, 8);

// Finding sum of all elements
int sum = array.stream().reduce(0,
(element1, element2) -> element1 + element2);

// Displaying sum of all elements
System.out.println("The sum of all elements is " + sum);
}
}

Output :

The sum of all elements is 16

Example 4 :


Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Java Exam Prep
// Implementation of reduce method
// to get the product of all numbers
// in given range.
import java.util.*;
import java.util.stream.IntStream;

class GFG {

// Driver code
public static void main(String[] args)
{

// To get the product of all elements
// in given range excluding the
// rightmost element
int product = IntStream.range(2, 8)
.reduce((num1, num2) -> num1 * num2)
.orElse(-1);

// Displaying the product
System.out.println("The product is : " + product);
}
}

Output :

The product is : 5040

Friday, June 4, 2021

The Secret Weapon of Top Performing Companies? It’s All in Who You Ask.

Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career 

William Blake once said, “What is now proved was once only imagined.” Java has been the platform of choice for millions of developers over the past 25 years to take what’s imagined and make it real.

Read More: 1Z0-900: Java EE 7 Application Developer

In his new book, “Ask Your Developer: How to harness the power of software development to win the 21st century”, author Jeff Lawson shares an analogy about the ongoing pressure of businesses to stay ahead of their competitors with innovation. He writes, “In Ford v. Ferrari, the film about Ford’s quest to win the 24 Hours of Le Mans race, there’s a great scene where Ford has finally managed to defeat Ferrari at Le Mans with an astonishing racer called the GT40. “She’s a hell of a machine,” Ken Miles, the driver, tells Carroll Shelby, the designer. But instead of basking in the glory, Miles and Shelby immediately start talking about ways to make the GT40 faster…Everyone feels the pressure to go faster, do more work in less time with fewer people, keep from falling behind.”


The Secret Weapon of Top Performing Companies? It’s All in Who You Ask.

“Business transformation” and “digital transformation” seem to have become today’s lingua franca and the mechanisms by which companies look to stay ahead of their competitors and to more effectively meet the needs of their customers.

As Jeff and I will discuss during our upcoming fireside chat webinar April 8 (Americas) and 13 (EMEA and APAC), “The Secret Weapon of Top Performing Companies? It’s All in Who You Ask” successful business transformation requires drawing from the strength of all your assets, particularly people and technology. From the “people” perspective, top performing companies engage the developer in their business transformation strategy planning. While this seems logical, it’s not entirely common. More often, companies look to developers to implement requirements, not necessarily participate in the conversation to scope them out. Developers are the very people with the most knowledge of how application investments can be best leveraged and modernized to meet business goals. These successful companies don’t just hand the car design over to the engineers without knowing what is possible. The engineer is at the table the whole time.

From a technology perspective, applications are the work horse that will drive the car to victory. However, challenges of maintaining applications on supported and unsupported software versions, which can open you up to security and stability risk, and managing a complex application estate, can take your most creative development resources from “full throttle” to “neutral”. 

As we increasingly shift towards a digital economy, the pace of innovation and transformation continues to accelerate, driving companies to look at new ways of winning. Companies are shifting how they work, how they deliver services and how they adjust to customer preferences. Keeping your application portfolio stable and secure while having the agility to modernize with microservices and cloud-native development is crucial in the ongoing race for market share and customer mindshare. Today’s advantage becomes tomorrow’s commodity and you must have the agility to move to what’s next to stay in the race.

Oracle, with its Java SE Subscription service, which now includes the GraalVM Enterprise entitlement at no additional cost, supports its customers thru their application evolution journey. Java SE Subscription protects the investment across the entire Java application base, and GraalVM Enterprise delivers higher performance while consuming less resources. With this powerful combination, Oracle keeps our customers driving forward at the pace of their business.

Source: oracle.com

Wednesday, June 2, 2021

Apache Arrow on the JVM: Streaming Reads

JVM Exam Prep, JVM Certification, JVM Tutorial and Material, JVM Career, Oracle Java Preparation, Oracle Java Exam Prep

Previously we wrote Arrow Data to a Stream. Now we shall read those data from a stream.

Just like on the previous blog the we shall implement the Closeable interface. This is needed to close the RootAllocator and free-up memory.

We shall pass a ReadableByteChannel and thus get the stream into read objects. 

package com.gkatzioura.arrow;

import java.io.Closeable;

import java.io.IOException;

import java.nio.channels.ReadableByteChannel;

import java.util.ArrayList;

import java.util.List;

import org.apache.arrow.memory.RootAllocator;

import org.apache.arrow.vector.IntVector;

import org.apache.arrow.vector.VarCharVector;

import org.apache.arrow.vector.ipc.ArrowStreamReader;

public class DefaultEntriesReader implements Closeable {

    private final RootAllocator rootAllocator;

    public DefaultEntriesReader() {

        rootAllocator = new RootAllocator(Integer.MAX_VALUE);

    }

    public List<DefaultArrowEntry> readBytes(ReadableByteChannel readableByteChannel) throws IOException {

        List<DefaultArrowEntry> defaultArrowEntries = new ArrayList<>();

        try(ArrowStreamReader arrowStreamReader = new ArrowStreamReader(readableByteChannel, rootAllocator)) {

            var root = arrowStreamReader.getVectorSchemaRoot();

            var childVector1 = (VarCharVector)root.getVector(0);

            var childVector2 = (IntVector)root.getVector(1);

            while (arrowStreamReader.loadNextBatch()) {

                int batchSize = root.getRowCount();

                for (int i = 0; i < batchSize; i++) {

                    var strData = new String(childVector1.get(i));

                    var intData = childVector2.get(i);

                    DefaultArrowEntry defaultArrowEntry = DefaultArrowEntry.builder().col1(strData).col2(intData).build();

                    defaultArrowEntries.add(defaultArrowEntry);

                }

            }

            return defaultArrowEntries;

        }

    }

    @Override

    public void close() throws IOException {

        rootAllocator.close();

    }

}

JVM Exam Prep, JVM Certification, JVM Tutorial and Material, JVM Career, Oracle Java Preparation, Oracle Java Exam Prep
Let’s wrap it up with a write and a Read

package com.gkatzioura.arrow;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.nio.channels.Channels;

import java.util.stream.Collectors;

import java.util.stream.IntStream;

public class ArrowMain {

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

        var originalEntries = IntStream.rangeClosed(0, 11)

                             .boxed()

                             .map(i -> new DefaultArrowEntry("data-"+i, i)).collect(Collectors.toList());

        var outputStream = new ByteArrayOutputStream();

        try(var arrowWriter = new DefaultEntriesWriter()) {

            arrowWriter.write(originalEntries, 10, Channels.newChannel(outputStream));

        }

        byte[] introBytes = outputStream.toByteArray();

        var inputStream = new ByteArrayInputStream(introBytes);

        try(var arrowReader = new DefaultEntriesReader()) {

            var entries =arrowReader.readBytes(Channels.newChannel(inputStream));

            for (DefaultArrowEntry entry : entries) {

                System.out.println("Read "+entry.getCol1()+" "+entry.getCol2());

            }

        }

    }

}

Source: javacodegeeks.com