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