Java Unit 3 Part 3 (1)
Java Unit 3 Part 3 (1)
sayable2.say();
}
}
Output:
Hello, this is non-static method.
Hello, this is non-static method.
3) Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are referring constructor
with the help of functional interface.
Syntax
ClassName::new
Example
interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Output:
Hello
4.Stream In Java
Introduced in Java 8, Stream API is used to process collections of objects. A stream in Java is
a sequence of objects that supports various methods which can be pipelined to produce the
desired result.
Syntax
lOMoARcPSD|38190532
Stream<T> stream;
Here T is either a class, object, or data type depending upon the declaration.
A stream is not a data structure instead it takes input from the Collections, Arrays or I/O
channels.
Streams don’t change the original data structure, they only provide the result as per the
pipelined methods.
Each intermediate operation is lazily executed and returns a stream as a result, hence various
intermediate operations can be pipelined. Terminal operations mark the end of the stream and
return the result.
Different Operations On Streams
There are two types of Operations in Streams:
Intermediate Operations
Terminate Operations
Intermediate Operations
Intermediate Operations are the types of operations in which multiple methods are
chained in a row.
No Storage
Pipeline of Functions
Laziness
Can be infinite
Can be parallelized
Can be created from collections, arrays, Files Lines, Methods in Stream, IntStream etc.
1. map()
The map method is used to return a stream consisting of the results of applying the given
function to the elements of this stream.
1. collect()
The collect method is used to return the result of the intermediate operations performed on
the stream.
Note: Intermediate Operations are running based on the concept of Lazy Evaluation, which
ensures that every method returns a fixed value(Terminal operation) before moving to the
next method.
class Demo {
public static void main(String args[])
{
// create a list of integers
List<Integer> number = Arrays.asList(2, 3, 4, 5);
System.out.println(result);
System.out.println(show);
System.out.println(squareSet);
System.out.println(even);
}
}
Output
Base 64 is an encoding scheme that converts binary data into text format so that encoded
textual data can be easily transported over network un-corrupted and without any data
loss.(Base 64 format reference).
The Basic encoding means no line feeds are added to the output and the output is mapped to a
set of characters in A-Za-z0-9+/ character set and the decoder rejects any character outside of
this set.
Explanation: In above code we called Base64.Encoder using getEncoder() and then get the
encoded string by passing the byte value of actualString in encodeToString() method as
parameter.
Explanation: In above code we called Base64.Decoder using getDecoder() and then decoded
the string passed in decode() method as parameter then convert return value to string.
import java.util.*;
public class GFG {
public static void main(String[] args)
{
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an encoded String to decode
String encode = "SW5kaWEgVGVhbSB3aWxsIHdpbiB0aGUgQ3Vw";
// print encoded String
System.out.println("Encoded String:\n+ encoded);
// decode into String from encoded format
byte[] actualByte = Base64.getDecoder() .decode(encoded);
Java provides a new method forEach() to iterate the elements. It is defined in Iterable and
Stream interface. It is a default method defined in the Iterable interface. Collection classes
which extends Iterable interface can use forEach loop to iterate elements.
This method takes a single parameter which is a functional interface. So, you can pass
lambda expression as an argument.
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression--------------");
gamesList.forEach(games -> System.out.println(games));
} }
Output:
------------Iterating by passing lambda expression--------------
Football Cricket Chess Hocky
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing method reference---------------");
gamesList.forEach(System.out::println);
} }
Output:
------------Iterating by passing method reference---------------
Football Cricket Chess Hocky
In Java, the Try-with-resources statement is a try statement that declares one or more
resources in it. A resource is an object that must be closed once your program is done using
it. For example, a File resource or a Socket connection resource. The try-with-resources
statement ensures that each resource is closed at the end of the statement execution. If we
don’t close the resources, it may constitute a resource leak and also the program could
exhaust the resources available to it.
You can pass any object as a resource that implements java.lang.AutoCloseable, which
includes all objects which implement java.io.Closeable.
By this, now we don’t need to add an extra finally block for just passing the closing
statements of the resources. The resources will be closed as soon as the try-catch block is
executed.
Syntax: Try-with-resources
Exceptions:
Now, let us discuss both the possible scenarios which are demonstrated below as an example
as follows:
Case 1: Single resource
Case 2: Multiple resources
// Class
class GFG {
try (
// Adding resource
FileOutputStream fos = new FileOutputStream("gfgtextfile.txt")) {
Resource are closed and message has been written into the gfgtextfile.txt
used anywhere you use a type. For example, if you want to avoid NullPointerException in
your code, you can declare a string variable like this:
@NonNull List<String>
List<@NonNull String> str
Arrays<@NonNegative Integer> sort
@Encrypted File file
@Open Connection connection
void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException
Note - Java created type annotations to support improved analysis of Java programs. It
supports way of ensuring stronger type checking.
For compatibility reasons, repeating annotations are stored in a container annotation that is
automatically generated by the Java compiler. In order for the compiler to do this, two
declarations are required in your code.
1. Declare a repeatable annotation type
2. Declare the containing annotation type
@Repeatable(Games.class)
@interfaceGame{
String name();
String day();
}
The value of the @Repeatable meta-annotation, in parentheses, is the type of the container
annotation that the Java compiler generates to store repeating annotations. In the following
example, the containing annotation type is Games. So, repeating @Game annotations is
stored in an @Games annotation.
@interfaceGames{
Game[] value();
}
Note - Compiler will throw a compile-time error, if you apply the same annotation to a
declaration without first declaring it as repeatable.
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
// Declaring repeatable annotation type
@Repeatable(Games.class)
@interfaceGame{
String name();
String day();
}
// Declaring container for repeatable annotation type
@Retention(RetentionPolicy.RUNTIME)
@interfaceGames{
Game[] value();
}
// Repeating annotation
@Game(name = "Cricket", day = "Sunday")
@Game(name = "Hockey", day = "Friday")
@Game(name = "Football", day = "Saturday")
public class RepeatingAnnotationsExample {
public static void main(String[] args) {
// Getting annotation by type into an array
Game[] game =
RepeatingAnnotationsExample.class.getAnnotationsByType(Game.class);
for (Gamegame2 : game) { // Iterating values
System.out.println(game2.name()+" on "+game2.day());
}
}
}
OUTPUT:
Cricket on Sunday
Hockey on Friday
Football on Saturday
Java Module System is a major change in Java 9 version. Java added this feature to collect
Java packages and code into a single unit called module.
In earlier versions of Java, there was no concept of module to create modular Java
applications, that why size of application increased and difficult to move around. Even JDK
itself was too heavy in size, in Java 8, rt.jar file size is around 64MB.
To deal with situation, Java 9 restructured JDK into set of modules so that we can use only
required module for our project.
Apart from JDK, Java also allows us to create our own modules so that we can develop
module based application.
The module system includes various tools and options that are given below.