Unit-3 Java
Unit-3 Java
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
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
   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
Java lambda expression is treated as a function, so compiler does not create .class file.
No Parameter Syntax
   1. () -> {
   2. //Body of no parameter lambda
   3. }
   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.
Output:
Drawing 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:
Output:
Output:
Hello, Sonoo
Hello, Sonoo
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.
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:
Example 2
Output:
Thread is running...
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:
Example 2
Output:
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.
   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.
   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:
   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.
   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
   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.
Output:
This class provides three different encoders and decoders to encrypt information at
each level. You can use these methods at the following levels.
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.
 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
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.
  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:
   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:
Output:
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:
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
Output:
You can use catch and finally blocks with try-with-resources statement just like an
ordinary try statement.
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.