0% found this document useful (0 votes)
5 views

Unit-3 Java

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit-3 Java

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Java Functional Interfaces

An Interface that contains exactly one abstract method is known as functional


interface. It can have any number of default, static methods but can contain only one
abstract method. It can also declare methods of object class.

Functional Interface is also known as Single Abstract Method Interfaces or SAM


Interfaces. It is a new feature in Java, which helps to achieve functional programming
approach.

Example 1

1. @FunctionalInterface
2. interface sayable{
3. void say(String msg);
4. }
5. public class FunctionalInterfaceExample implements sayable{
6. public void say(String msg){
7. System.out.println(msg);
8. }
9. public static void main(String[] args) {
10. FunctionalInterfaceExample fie = new FunctionalInterfaceExample();
11. fie.say("Hello there");
12. }
13. }

Output:

Hello there
A functional interface can have methods of object class. See in the following example.

Example 2

1.
2. @FunctionalInterface
3. interface sayable{
4. void say(String msg); // abstract method
5. // It can contain any number of Object class methods.
6. int hashCode();
7. String toString();
8. boolean equals(Object obj);
9. }
10. public class FunctionalInterfaceExample2 implements sayable{
11. public void say(String msg){
12. System.out.println(msg);
13. }
14. public static void main(String[] args) {
15. FunctionalInterfaceExample2 fie = new FunctionalInterfaceExample2();
16. fie.say("Hello there");
17. }
18. }

Output:

Hello there

Invalid Functional Interface

A functional interface can extends another interface only when it does not have any
abstract method.

1. interface sayable{
2. void say(String msg); // abstract method
3. }
4. @FunctionalInterface
5. interface Doable extends sayable{
6. // Invalid '@FunctionalInterface' annotation; Doable is not a functional inter
face
7. void doIt();
8. }

Output:

compile-time error

Example 3

In the following example, a functional interface is extending to a non-functional


interface.

1. interface Doable{
2. default void doIt(){
3. System.out.println("Do it now");
4. }
5. }
6. @FunctionalInterface
7. interface Sayable extends Doable{
8. void say(String msg); // abstract method
9. }
10. public class FunctionalInterfaceExample3 implements Sayable{
11. public void say(String msg){
12. System.out.println(msg);
13. }
14. public static void main(String[] args) {
15. FunctionalInterfaceExample3 fie = new FunctionalInterfaceExample3();
16. fie.say("Hello there");
17. fie.doIt();
18. }
19. }

Output:

Hello there
Do it now
Java Predefined-Functional Interfaces
Java provides predefined functional interfaces to deal with functional programming by
using lambda and method references.

You can also define your own custom functional interface. Following is the list of
functional interface which are placed in java.util.function package.

Interface Description

BiConsumer<T,U> It represents an operation that accepts two input arguments


and returns no result.

Consumer<T> It represents an operation that accepts a single argument and


returns no result.

Function<T,R> It represents a function that accepts one argument and


returns a result.

Predicate<T> It represents a predicate (boolean-valued function) of one


argument.

BiFunction<T,U,R> It represents a function that accepts two arguments and


returns a a result.

BinaryOperator<T> It represents an operation upon two operands of the same


data type. It returns a result of the same type as the operands.

BiPredicate<T,U> It represents a predicate (boolean-valued function) of two


arguments.

BooleanSupplier It represents a supplier of boolean-valued results.

DoubleBinaryOperator It represents an operation upon two double type operands


and returns a double type value.

DoubleConsumer It represents an operation that accepts a single double type


argument and returns no result.

DoubleFunction<R> It represents a function that accepts a double type argument


and produces a result.

DoublePredicate It represents a predicate (boolean-valued function) of one


double type argument.
DoubleSupplier It represents a supplier of double type results.

DoubleToIntFunction It represents a function that accepts a double type argument


and produces an int type result.

DoubleToLongFunction It represents a function that accepts a double type argument


and produces a long type result.

DoubleUnaryOperator It represents an operation on a single double type operand


that produces a double type result.

IntBinaryOperator It represents an operation upon two int type operands and


returns an int type result.

IntConsumer It represents an operation that accepts a single integer


argument and returns no result.

IntFunction<R> It represents a function that accepts an integer argument and


returns a result.

IntPredicate It represents a predicate (boolean-valued function) of one


integer argument.

IntSupplier It represents a supplier of integer type.

IntToDoubleFunction It represents a function that accepts an integer argument and


returns a double.

IntToLongFunction It represents a function that accepts an integer argument and


returns a long.

IntUnaryOperator It represents an operation on a single integer operand that


produces an integer result.

LongBinaryOperator It represents an operation upon two long type operands and


returns a long type result.

LongConsumer It represents an operation that accepts a single long type


argument and returns no result.

LongFunction<R> It represents a function that accepts a long type argument and


returns a result.

LongPredicate It represents a predicate (boolean-valued function) of one


long type argument.
LongSupplier It represents a supplier of long type results.

LongToDoubleFunction It represents a function that accepts a long type argument and


returns a result of double type.

LongToIntFunction It represents a function that accepts a long type argument and


returns an integer result.

LongUnaryOperator It represents an operation on a single long type operand that


returns a long type result.

ObjDoubleConsumer<T> It represents an operation that accepts an object and a double


argument, and returns no result.

ObjIntConsumer<T> It represents an operation that accepts an object and an


integer argument. It does not return result.

ObjLongConsumer<T> It represents an operation that accepts an object and a long


argument, it returns no result.

Supplier<T> It represents a supplier of results.

ToDoubleBiFunction<T,U> It represents a function that accepts two arguments and


produces a double type result.

ToDoubleFunction<T> It represents a function that returns a double type result.

ToIntBiFunction<T,U> It represents a function that accepts two arguments and


returns an integer.

ToIntFunction<T> It represents a function that returns an integer.

ToLongBiFunction<T,U> It represents a function that accepts two arguments and


returns a result of long type.

ToLongFunction<T> It represents a function that returns a result of long type.

UnaryOperator<T> It represents an operation on a single operand that returnsa a


result of the same type as its operand.
Java Lambda Expressions
Lambda expression is a new and important feature of Java which was included in Java
SE 8. It provides a clear and concise way to represent one method interface using an
expression. It is very useful in collection library. It helps to iterate, filter and extract data
from collection.

The Lambda expression is used to provide the implementation of an interface which


has functional interface. It saves a lot of code. In case of lambda expression, we don't
need to define the method again for providing the implementation. Here, we just write
the implementation code.

Java lambda expression is treated as a function, so compiler does not create .class file.

Why use Lambda Expression


1. To provide the implementation of Functional interface.
2. Less coding.

Java Lambda Expression Syntax


1. (argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.

No Parameter Syntax

1. () -> {
2. //Body of no parameter lambda
3. }

One Parameter Syntax

1. (p1) -> {
2. //Body of single parameter lambda
3. }
Two Parameter Syntax

1. (p1,p2) -> {
2. //Body of multiple parameter lambda
3. }

Let's see a scenario where we are not implementing Java lambda expression. Here, we
are implementing an interface without using lambda expression.

Without Lambda Expression


1. interface Drawable{
2. public void draw();
3. }
4. public class LambdaExpressionExample {
5. public static void main(String[] args) {
6. int width=10;
7.
8. //without lambda, Drawable implementation using anonymous class
9. Drawable d=new Drawable(){
10. public void draw(){System.out.println("Drawing "+width);}
11. };
12. d.draw();
13. }
14. }

Output:

Drawing 10

Java Lambda Expression Example


Now, we are going to implement the above example with the help of Java lambda
expression.

@FunctionalInterface //It is optional


interface Drawable{
public void draw();
}
public class LambdaExpressionExample2 {
public static void main(String[] args) {
int width=10;

//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}

Output:

Drawing 10

A lambda expression can have zero or any number of arguments. Let's see the
examples:

Java Lambda Expression Example: No Parameter


1. interface Sayable{
2. public String say();
3. }
4. public class LambdaExpressionExample3{
5. public static void main(String[] args) {
6. Sayable s=()->{
7. return "I have nothing to say.";
8. };
9. System.out.println(s.say());
10. }
11. }

Output:

I have nothing to say.


Java Lambda Expression Example: Single
Parameter
1. interface Sayable{
2. public String say(String name);
3. }
4.
5. public class LambdaExpressionExample4{
6. public static void main(String[] args) {
7.
8. // Lambda expression with single parameter.
9. Sayable s1=(name)->{
10. return "Hello, "+name;
11. };
12. System.out.println(s1.say("Sonoo"));
13.
14. // You can omit function parentheses
15. Sayable s2= name ->{
16. return "Hello, "+name;
17. };
18. System.out.println(s2.say("Sonoo"));
19. }
20. }

Output:

Hello, Sonoo
Hello, Sonoo

Java Lambda Expression Example: Multiple


Parameters
1. interface Addable{
2. int add(int a,int b);
3. }
4.
5. public class LambdaExpressionExample5{
6. public static void main(String[] args) {
7.
8. // Multiple parameters in lambda expression
9. Addable ad1=(a,b)->(a+b);
10. System.out.println(ad1.add(10,20));
11.
12. // Multiple parameters with data type in lambda expression
13. Addable ad2=(int a,int b)->(a+b);
14. System.out.println(ad2.add(100,200));
15. }
16. }

Output:

30
300
Java Method References
Java provides a new feature called method reference in Java 8. Method reference is
used to refer method of functional interface. It is compact and easy form of lambda
expression. Each time when you are using lambda expression to just referring a
method, you can replace your lambda expression with method reference. In this
tutorial, we are explaining method reference concept in detail.

Types of Method References


There are following types of method references in java:

1. Reference to a static method.


2. Reference to an instance method.
3. Reference to a constructor.
1) Reference to a Static Method
You can refer to static method defined in the class. Following is the syntax and example
which describe the process of referring static method in Java.

Syntax

ContainingClass::staticMethodName

Example 1

In the following example, we have defined a functional interface and referring a static
method to it's functional method say().

1. interface Sayable{
2. void say();
3. }
4. public class MethodReference {
5. public static void saySomething(){
6. System.out.println("Hello, this is static method.");
7. }
8. public static void main(String[] args) {
9. // Referring static method
10. Sayable sayable = MethodReference::saySomething;
11. // Calling interface method
12. sayable.say();
13. }
14. }

Output:

Hello, this is static method.

Example 2

In the following example, we are using predefined functional interface Runnable to


refer static method.
1. public class MethodReference2 {
2. public static void ThreadStatus(){
3. System.out.println("Thread is running...");
4. }
5. public static void main(String[] args) {
6. Thread t2=new Thread(MethodReference2::ThreadStatus);
7. t2.start();
8. }
9. }

Output:

Thread is running...

2) Reference to an Instance Method


like static methods, you can refer instance methods also. In the following example, we
are describing the process of referring the instance method.

Syntax

1. containingObject::instanceMethodName

Example 1

In the following example, we are referring non-static methods. You can refer methods
by class object and anonymous object.

1. interface Sayable{
2. void say();
3. }
4. public class InstanceMethodReference {
5. public void saySomething(){
6. System.out.println("Hello, this is non-static method.");
7. }
8. public static void main(String[] args) {
9. InstanceMethodReference methodReference = new InstanceMethodRefe
rence(); // Creating object
10. // Referring non-static method using reference
11. Sayable sayable = methodReference::saySomething;
12. // Calling interface method
13. sayable.say();
14. // Referring non-static method using anonymous object
15. Sayable sayable2 = new InstanceMethodReference()::saySomething; //
You can use anonymous object also
16. // Calling interface method
17. sayable2.say();
18. }
19. }

Output:

Hello, this is non-static method.


Hello, this is non-static method.

Example 2

In the following example, we are referring instance (non-static) method. Runnable


interface contains only one abstract method. So, we can use it as functional interface.

1. public class InstanceMethodReference2 {


2. public void printnMsg(){
3. System.out.println("Hello, this is instance method");
4. }
5. public static void main(String[] args) {
6. Thread t2=new Thread(new InstanceMethodReference2()::printnMsg);
7. t2.start();
8. }
9. }

Output:

Hello, this is instance 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

1. ClassName::new

Example

1. interface Messageable{
2. Message getMessage(String msg);
3. }
4. class Message{
5. Message(String msg){
6. System.out.print(msg);
7. }
8. }
9. public class ConstructorReference {
10. public static void main(String[] args) {
11. Messageable hello = Message::new;
12. hello.getMessage("Hello");
13. }
14. }

Output:

Hello
Java 8 Stream
Java provides a new additional package in Java 8 called java.util.stream. This package
consists of classes, interfaces and enum to allows functional-style operations on the
elements. You can use stream by importing java.util.stream package.

Stream provides following features:

o Stream does not store elements. It simply conveys elements from a source such
as a data structure, an array, or an I/O channel, through a pipeline of
computational operations.
o Stream is functional in nature. Operations performed on a stream does not
modify it's source. For example, filtering a Stream obtained from a collection
produces a new Stream without the filtered elements, rather than removing
elements from the source collection.
o Stream is lazy and evaluates code only when required.
o The elements of a stream are only visited once during the life of a stream. Like
an Iterator, a new stream must be generated to revisit the same elements of the
source.

You can use stream to filter, collect, print, and convert from one data structure to other
etc. In the following examples, we have apply various operations with the help of
stream.

Java Example: Filtering Collection without using Stream


In the following example, we are filtering data without using stream. This approach we
are used before the stream package was released.

1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11. }
12. public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. List<Float> productPriceList = new ArrayList<Float>();
22. for(Product product: productsList){
23.
24. // filtering data of list
25. if(product.price<30000){
26. productPriceList.add(product.price); // adding price to a productPri
ceList
27. }
28. }
29. System.out.println(productPriceList); // displaying data
30. }
31. }

Output:

[25000.0, 28000.0, 28000.0]

Java Stream Example: Filtering Collection by using Stream


Here, we are filtering data by using stream. You can see that code is optimized and
maintained. Stream provides fast execution.

1. import java.util.*;
2. import java.util.stream.Collectors;
3. class Product{
4. int id;
5. String name;
6. float price;
7. public Product(int id, String name, float price) {
8. this.id = id;
9. this.name = name;
10. this.price = price;
11. }
12. }
13. public class JavaStreamExample {
14. public static void main(String[] args) {
15. List<Product> productsList = new ArrayList<Product>();
16. //Adding Products
17. productsList.add(new Product(1,"HP Laptop",25000f));
18. productsList.add(new Product(2,"Dell Laptop",30000f));
19. productsList.add(new Product(3,"Lenevo Laptop",28000f));
20. productsList.add(new Product(4,"Sony Laptop",28000f));
21. productsList.add(new Product(5,"Apple Laptop",90000f));
22. List<Float> productPriceList2 =productsList.stream()
23. .filter(p -> p.price > 30000)// filtering data
24. .map(p->p.price) // fetching price
25. .collect(Collectors.toList()); // collecting as list
26. System.out.println(productPriceList2);
27. }
28. }

Output:

[90000.0]
Default Methods In Java 8
Before Java 8, interfaces could have only abstract methods. The implementation of
these methods has to be provided in a separate class. So, if a new method is to be
added in an interface, then its implementation code has to be provided in the class
implementing the same interface. To overcome this issue, Java 8 has introduced the
concept of default methods which allow the interfaces to have methods with
implementation without affecting the classes that implement the interface.

Java provides a facility to create default methods inside the interface. Methods which
are defined inside the interface and tagged with default are known as default methods.
These methods are non-abstract methods.

Java Default Method Example


In the following example, Sayable is a functional interface that contains a default and
an abstract method. The concept of default method is used to define a method with
default implementation. You can override default method also to provide more specific
implementation for the method.

Let's see a simple

1. interface Sayable{
2. // Default method
3. default void say(){
4. System.out.println("Hello, this is default method");
5. }
6. // Abstract method
7. void sayMore(String msg);
8. }
9. public class DefaultMethods implements Sayable{
10. public void sayMore(String msg){ // implementing abstract method
11. System.out.println(msg);
12. }
13. public static void main(String[] args) {
14. DefaultMethods dm = new DefaultMethods();
15. dm.say(); // calling default method
16. dm.sayMore("Work is worship"); // calling abstract method
17.
18. }
19. }
Hello, this is default method
Work is worship

Static Methods inside Java 8 Interface


You can also define static methods inside the interface. Static methods are used to
define utility methods. The following example explain, how to implement static
method in interface?

1. interface Sayable{
2. // default method
3. default void say(){
4. System.out.println("Hello, this is default method");
5. }
6. // Abstract method
7. void sayMore(String msg);
8. // static method
9. static void sayLouder(String msg){
10. System.out.println(msg);
11. }
12. }
13. public class DefaultMethods implements Sayable{
14. public void sayMore(String msg){ // implementing abstract method
15. System.out.println(msg);
16. }
17. public static void main(String[] args) {
18. DefaultMethods dm = new DefaultMethods();
19. dm.say(); // calling default method
20. dm.sayMore("Work is worship"); // calling abstract method
21. Sayable.sayLouder("Helloooo..."); // calling static method
22. }
23. }

Output:

Hello there
Work is worship
Helloooo...
Abstract Class vs Java 8 Interface
After having default and static methods inside the interface, we think about the need
of abstract class in Java. An interface and an abstract class is almost similar except that
you can create constructor in the abstract class whereas you can't do this in interface.

1. abstract class AbstractClass{


2. public AbstractClass() { // constructor
3. System.out.println("You can create constructor in abstract class");
4. }
5. abstract int add(int a, int b); // abstract method
6. int sub(int a, int b){ // non-abstract method
7. return a-b;
8. }
9. static int multiply(int a, int b){ // static method
10. return a*b;
11. }
12. }
13. public class AbstractTest extends AbstractClass{
14. public int add(int a, int b){ // implementing abstract method
15. return a+b;
16. }
17. public static void main(String[] args) {
18. AbstractTest a = new AbstractTest();
19. int result1 = a.add(20, 10); // calling abstract method
20. int result2 = a.sub(20, 10); // calling non-abstract method
21. int result3 = AbstractClass.multiply(20, 10); // calling static method
22. System.out.println("Addition: "+result1);
23. System.out.println("Substraction: "+result2);
24. System.out.println("Multiplication: "+result3);
25. }
26. }

Output:

You can create constructor in abstract class


Addition: 30
Substraction: 10
Multiplication: 200

Java Base64 Encode and Decode


Java provides a class Base64 to deal with encryption. You can encrypt and decrypt your
data by using provided methods. You need to import java.util.Base64 in your source
file to use its methods.

This class provides three different encoders and decoders to encrypt information at
each level. You can use these methods at the following levels.

Basic Encoding and Decoding


It uses the Base64 alphabet specified by Java in RFC 4648 and RFC 2045 for encoding
and decoding operations. The encoder does not add any line separator character. The
decoder rejects data that contains characters outside the base64 alphabet.

URL and Filename Encoding and Decoding


It uses the Base64 alphabet specified by Java in RFC 4648 for encoding and decoding
operations. The encoder does not add any line separator character. The decoder rejects
data that contains characters outside the base64 alphabet.

MIME
It uses the Base64 alphabet as specified in RFC 2045 for encoding and decoding
operations. The encoded output must be represented in lines of no more than 76
characters each and uses a carriage return '\r' followed immediately by a linefeed '\n'
as the line separator. No line separator is added to the end of the encoded output. All
line separators or other characters not found in the base64 alphabet table are ignored
in decoding operation.

Nested Classes of Base64

Class Description
Base64.Decoder This class implements a decoder for decoding byte data using the Base64
encoding scheme as specified in RFC 4648 and RFC 2045.

Base64.Encoder This class implements an encoder for encoding byte data using the Base64
encoding scheme as specified in RFC 4648 and RFC 2045.

Base64 Methods

Methods Description

public static Base64.Decoder getDecoder() It returns a Base64.Decoder that decodes


using the Basic type base64 encoding scheme.

public static Base64.Encoder getEncoder() It returns a Base64.Encoder that encodes using


the Basic type base64 encoding scheme.

public static Base64.Decoder getUrlDecoder() It returns a Base64.Decoder that decodes


using the URL and Filename safe type base64
encoding scheme.

public static Base64.Decoder getMimeDecoder() It returns a Base64.Decoder that decodes


using the MIME type base64 decoding
scheme.

public static Base64.Encoder getMimeEncoder() It Returns a Base64.Encoder that encodes


using the MIME type base64 encoding
scheme.

public static Base64.Encoder getMimeEncoder(int It returns a Base64.Encoder that encodes using


lineLength, byte[] lineSeparator) the MIME type base64 encoding scheme with
specified line length and line separators.

public static Base64.Encoder getUrlEncoder() It returns a Base64.Encoder that encodes using


the URL and Filename safe type base64
encoding scheme.
Base64.Decoder Methods

Methods Description

public byte[] decode(byte[] It decodes all bytes from the input byte array using the Base64
src) encoding scheme, writing the results into a newly-allocated output
byte array. The returned byte array is of the length of the resulting
bytes.

public byte[] decode(String It decodes a Base64 encoded String into a newly-allocated byte array
src) using the Base64 encoding scheme.

public int decode(byte[] src, It decodes all bytes from the input byte array using the Base64
byte[] dst) encoding scheme, writing the results into the given output byte array,
starting at offset 0.

public ByteBuffer It decodes all bytes from the input byte buffer using the Base64
decode(ByteBuffer buffer) encoding scheme, writing the results into a newly-allocated
ByteBuffer.

public InputStream It returns an input stream for decoding Base64 encoded byte stream.
wrap(InputStream is)

Base64.Encoder Methods

Methods Description

public byte[] encode(byte[] It encodes all bytes from the specified byte array into a newly-
src) allocated byte array using the Base64 encoding scheme. The
returned byte array is of the length of the resulting bytes.

public int encode(byte[] src, It encodes all bytes from the specified byte array using the
byte[] dst) Base64 encoding scheme, writing the resulting bytes to the
given output byte array, starting at offset 0.

public String It encodes the specified byte array into a String using the Base64
encodeToString(byte[] src) encoding scheme.
public ByteBuffer It encodes all remaining bytes from the specified byte buffer into
encode(ByteBuffer buffer) a newly-allocated ByteBuffer using the Base64 encoding
scheme. Upon return, the source buffer's position will be
updated to its limit; its limit will not have been changed. The
returned output buffer's position will be zero and its limit will be
the number of resulting encoded bytes.

public OutputStream It wraps an output stream for encoding byte data using the
wrap(OutputStream os) Base64 encoding scheme.

public Base64.Encoder It returns an encoder instance that encodes equivalently to this


withoutPadding() one, but without adding any padding character at the end of the
encoded byte data.

Java Base64 Example: Basic Encoding and Decoding

1. import java.util.Base64;
2. publicclass Base64BasicEncryptionExample {
3. publicstaticvoid main(String[] args) {
4. // Getting encoder
5. Base64.Encoder encoder = Base64.getEncoder();
6. // Creating byte array
7. bytebyteArr[] = {1,2};
8. // encoding byte array
9. bytebyteArr2[] = encoder.encode(byteArr);
10. System.out.println("Encoded byte array: "+byteArr2);
11. bytebyteArr3[] = newbyte[5]; // Make sure it has enough size to
store copied bytes
12. intx = encoder.encode(byteArr,byteArr3); // Returns number of bytes written
13. System.out.println("Encoded byte array written to another array: "+byteAr
r3);
14. System.out.println("Number of bytes written: "+x);
15.
16. // Encoding string
17. String str = encoder.encodeToString("JavaTpoint".getBytes());
18. System.out.println("Encoded string: "+str);
19. // Getting decoder
20. Base64.Decoder decoder = Base64.getDecoder();
21. // Decoding string
22. String dStr = new String(decoder.decode(str));
23. System.out.println("Decoded string: "+dStr);
24. }
25. }

Output:

Encoded byte array: [B@6bc7c054


Encoded byte array written to another array: [B@232204a1
Number of bytes written: 4
Encoded string: SmF2YVRwb2ludA==
Decoded string: JavaTpoint

Java Base64 Example: URL Encoding and Decoding

1. import java.util.Base64;
2. publicclass Base64BasicEncryptionExample {
3. publicstaticvoid main(String[] args) {
4. // Getting encoder
5. Base64.Encoder encoder = Base64.getUrlEncoder();
6. // Encoding URL
7. String eStr = encoder.encodeToString("http://www.javatpoint.com/java-
tutorial/".getBytes());
8. System.out.println("Encoded URL: "+eStr);
9. // Getting decoder
10. Base64.Decoder decoder = Base64.getUrlDecoder();
11. // Decoding URl
12. String dStr = new String(decoder.decode(eStr));
13. System.out.println("Decoded URL: "+dStr);
14. }
15. }

Output:

Encoded URL: aHR0cDovL3d3dy5qYXZhdHBvaW50LmNvbS9qYXZhLXR1dG9yaWFsLw==


Decoded URL: http://www.javatpoint.com/java-tutorial/

Java Base64 Example: MIME Encoding and Decoding


1. package Base64Encryption;
2. import java.util.Base64;
3. publicclass Base64BasicEncryptionExample {
4. publicstaticvoid main(String[] args) {
5. // Getting MIME encoder
6. Base64.Encoder encoder = Base64.getMimeEncoder();
7. String message = "Hello, \nYou are informed regarding your inconsistenc
y of work";
8. String eStr = encoder.encodeToString(message.getBytes());
9. System.out.println("Encoded MIME message: "+eStr);
10.
11. // Getting MIME decoder
12. Base64.Decoder decoder = Base64.getMimeDecoder();
13. // Decoding MIME encoded message
14. String dStr = new String(decoder.decode(eStr));
15. System.out.println("Decoded message: "+dStr);
16. }
17. }

Output:

Encoded MIME message:


SGVsbG8sIApZb3UgYXJlIGluZm9ybWVkIHJlZ2FyZGluZyB5b3VyIGluY29uc2lzdGVuY3kgb2Y
g
d29yaw==
Decoded message: Hello,
You are informed regarding your inconsistency of work
The try-with-resources statement
In Java, the try-with-resources statement is a try statement that declares one or more
resources. The resource is as an object that must be closed after finishing the program.
The try-with-resources statement ensures that each resource is closed at the end of
the statement execution.

You can pass any object that implements java.lang.AutoCloseable, which includes all
objects which implement java.io.Closeable.

The following example writes a string into a file. It uses an instance of FileOutputStream
to write data into the file. FileOutputStream is a resource that must be closed after the
program is finished with it. So, in this example, closing of resource is done by itself try.

Try-with-resources Example 1
1. import java.io.FileOutputStream;
2. public class TryWithResources {
3. public static void main(String args[]){
4. // Using try-with-resources
5. try(FileOutputStream fileOutputStream =newFileOutputStream("/java7-new-
features/src/abc.txt")){
6. String msg = "Welcome to javaTpoint!";
7. byte byteArray[] = msg.getBytes(); //converting string into byte array
8. fileOutputStream.write(byteArray);
9. System.out.println("Message written to file successfuly!");
10. }catch(Exception exception){
11. System.out.println(exception);
12. }
13. }
14. }

Output:

Message written to file successfuly!

Output of file

Welcome to javaTpoint!
Try-with-resources Example : Using Multiple
Resources
1. import java.io.DataInputStream;
2. import java.io.FileInputStream;
3. import java.io.FileOutputStream;
4. import java.io.InputStream;
5. public class TryWithResources {
6. public static void main(String args[]){
7. // Using try-with-resources
8. try( // Using multiple resources
9. FileOutputStream fileOutputStream =new FileOutputStream("/java7-
new-features/src/abc.txt");
10. InputStream input = new FileInputStream("/java7-new-features/src/abc.txt")){
11. // -----------------------------Code to write data into file-------------------
-------------------------//
12. String msg = "Welcome to javaTpoint!";
13. byte byteArray[] = msg.getBytes(); // Converting string into byte array

14. fileOutputStream.write(byteArray); // Writing data into file


15. System.out.println("------------Data written into file--------------");
16. System.out.println(msg);
17. // -----------------------------Code to read data from file-------------------
--------------------------//
18. // Creating input stream instance
19. DataInputStream inst = new DataInputStream(input);
20. int data = input.available();
21. // Returns an estimate of the number of bytes that can be read from this i
nput stream.
22. byte[] byteArray2 = new byte[data]; //
23. inst.read(byteArray2);
24. String str = new String(byteArray2); // passing byte array into String constructor

25. System.out.println("------------Data read from file--------------");


26. System.out.println(str); // display file data
27. }catch(Exception exception){
28. System.out.println(exception);
29. }
30. }
31. }

Output:

------------Data written into file--------------


Welcome to javaTpoint!
------------Data read from file--------------
Welcome to javaTpoint!

You can use catch and finally blocks with try-with-resources statement just like an
ordinary try statement.

Note - In a try-with-resources statement, catch or finally block executes after


closing of the declared resources.

Try-with-resources Example: using finally block


1. import java.io.FileOutputStream;
2. public class TryWithResources {
3. public static void main(String args[]){
4. try( FileOutputStream fileOutputStream=
5. new FileOutputStream("/home/irfan/scala-workspace/java7-new-
features/src/abc.txt")){
6. // -----------------------------Code to write data into file------------------------------
--------------//
7. String msg = "Welcome to javaTpoint!";
8. byte byteArray[] = msg.getBytes(); // Converting string into byte array
9. fileOutputStream.write(byteArray); // Writing data into file
10. System.out.println("Data written successfully!");
11. }catch(Exception exception){
12. System.out.println(exception);
13. }
14. finally{
15. System.out.println("Finally executes after closing of declared resources.");
16. }
17. }
18. }

Output:
Data written successfully!
Finally executes after closing of declared resources.

Suppressed Exceptions
If a try block throws an exception and one or more exceptions are thrown by the try-
with-resources, the exceptions thrown by try-with-resources are suppressed. In other
words, we can say, exceptions which are thrown by try-with-resources are suppressed
exceptions.

You can get these exceptions by using the getSuppress() method of Throwable class.

ADVERTISEMENT

Java added a new constructor and two new methods in Throwable class to deal with
suppressed exceptions.

Constructor Description

protected Throwable(String message, Throwable cause, It constructs a new throwable with the
boolean enableSuppression, boolean writableStackTrace) specified detail message, cause,
suppression enabled or disabled, and
writable stack trace enabled or disabled.

Method Description

public final void It appends the specified exception to the exceptions that were
addSuppressed(Throwable suppressed in order to deliver this exception. This method is
exception)/td> thread-safe and typically called (automatically and implicitly) by
the try-with-resources statement. It throws following
exceptions: IllegalArgumentException: if exception is
throwable, a throwable cannot suppress
itself. NullPointerException: if exception is null.

public final Throwable[] It returns an array containing all of the exceptions that were
getSuppressed() suppressed by the try-with-resources statement. If no
exceptions were suppressed or suppression is disabled, an
empty array is returned.

You might also like