Java Tutorial

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java BufferedWriter Java InputStreamReader Java File Java Read File Line By Line Java FileOutputStream Jar File in Java

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial

Java Differences

Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Static vs Non-static in Java C vs Java int vs Integer in Java Stack vs Heap in Java Java Array vs ArrayList

How to

How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to call a method in Java How to sort an array in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to achieve abstraction in Java How to call static method in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Parallel Arrays Sort in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hibernate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java

Functional Interface in Java 8

A brief introduction to Interface in Java:

Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or more abstract methods inside an interface. From Java 8 onwards we can also declare default as well as the static methods inside the interfaces.

An interface is declared with the keyword “interface”. It is implemented inside the class using the keyword “implements”. The main motive behind introducing the interfaces is to achieve the functionality like multiple inheritance and to reduce the interdependencies among different classes in Java.

The advantages of the interface over inheritance are discussed below:

1. To achieve the multiple inheritance:

Java does not directly support multiple inheritance. We cannot declare a child class that can inherit more than one parent class. This will give a compile time error. Let us try to understand this with the help of the programming illustration provided below.

/*A program to show that Java does not support multiple inheritance.*/

class A
{
   void method()
   {
      System.out.println("Class A");
   }
}
class B
{
   void method()
   {
      System.out.println("Class B");
   }
}


/*Trying to inherit two parent classes A and B */
class C extends A,B
{
   
}
//The main method
class Main
{
   public static void main(String args[])
   {
      C object=new C();
      object.method();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Main.java:17: error: '{' expected
class C extends A,B
                 ^
1 error

Why Java does not support multiple inheritance?

In the above program, we got a compile time error. It is proved that Java does not support multiple inheritance. Let us try to understand why does the multiple inheritance is declared illegal in Java.

In this program, we have created an object of the C class and tried to call the function “method”. Now, class C inherits two classes, that is, class A and class B. Both the parent class have the function named “method” inside them. Now when we will try to call the function “method” the compiler will get confused, it will not understand which function to call, the function “method” of class A or the function “method” of class B. Hence Java developers collaboratively decided to declare multiple inheritance illegal in Java.

How can we achieve multiple inheritance using the interface?

/*Java program to achieve multiple inheritance in Java using the interfaces*/

interface A
{
   abstract void show();
}
interface B
{
   abstract void show();
   abstract void display();
}
class C implements A,B
{
   public void show()
   {
      System.out.println("Calling the abstract method show() from class A.");
   }
   public void display()
   {
      System.out.println("Calling the abstract method display() from class B.");
   }
}
class Main
{
   public static void main(String args[])
   {
      C object=new C();
      object.show();
      object.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Calling the abstract method show() from class A.
Calling the abstract method display() from class B.

In the above program, we have show() method inside both the interfaces. But as the methods are abstract, we can only declare the implementation of those methods inside the class that implements the interface. In our case, the class is named C. Thus, if we create an object of C now, in the main class, and try to call the show method, unlike the previous case, this time the compiler will not get confused about which method to call because the implementation of both the show() method is same.

Hence, it is clear that with the help of interfaces we can achieve multiple inheritance in Java. If we declare the method name inside the interfaces, that is, declare abstract method inside interface and explain its implementation inside the class implementing the interface, then there is no chance of compilation error because it is very much clear to the compiler that which implementation it should show as an output.

2. The interface helps to achieve loose coupling:

The interface helps to reduce the interdependencies between the components of a system. The main problem with inheritance is the tight coupling. With the help of the interface, we can achieve loose coupling. Let us demonstrate the following with the help of Java programs.

/*Java program to show inheritance in java*/

class A
{
   void display()
   {
       System.out.println("Here we go.");
   } 
}
class B extends A
{
   
}
class C extends B
{
   
}
class Main
{
   public static void main(String args[])
   {
      A obj=new A();
      B obj1=new B();
      C obj2=new C();
      System.out.println("Printing display method inside A:");
      obj1.display();
      System.out.println();
      System.out.println("Printing display method inside B:");
      obj1.display();
      System.out.println();
      System.out.println("Printing display method inside C:");
      obj1.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Printing display method inside A:
Here we go.


Printing display method inside B:
Here we go.


Printing display method inside C:
Here we go.

In the 1st program, we have a parent class A with a method display() defined inside it. Here all the child classes, that is, class B and class C, inherits the parent class A. Thus the method display() also gets inherited.

Now, when we create an object of class B and try to print the display() method we get the display() method defined in class A. This is the same in the case of class C. when we create an object of class C and try to print the display() method we get the same display() method defined in class A.

Suppose later in future, we want to change the display method inside class A, provided, we do not want to change the display method inside the inherited class. Is it possible to do so? Yes, it is possible. But imagine the complexity. If it is a real world project with thousands of classes inheriting a parent class, for a minute change in parent class we need to override all the hundred and thousands of methods that inherits the parent classes. The money and time that will get wasted in this process is the sky limit.

/*Java program to show how we can achieve loose coupling using the interface in java*/

interface A
{
  void numbers();
}
class B implements A
{ 
   public void numbers()
   {
      System.out.println("Implementation of the method numbers() inside class B:");
      System.out.println("Hello B");
      System.out.println();
   }
}
class C implements A
{
    public void numbers()
   {
      System.out.println("Implementation of the method numbers() inside class C:");
      System.out.println("Hello C");
      System.out.println();
   }
}
class D implements A
{
    public void numbers()
   {
      System.out.println("Implementation of the method numbers() inside class A:");
      System.out.println("Hello D");
      System.out.println();
   }
}
class Main
{
   public static void main(String args[])
   {
      System.out.println("Achieving loose coupling through an interface.");
      System.out.println();
      B obj=new B();
      C obj1=new C();
      D obj2=new D();
      obj.numbers();
      obj1.numbers();
      obj2.numbers();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Achieving loose coupling through an interface.


Implementation of the method numbers() inside class B:
Hello B


Implementation of the method numbers() inside class C:
Hello C


Implementation of the method numbers() inside class A:
Hello D

Hence, it is possible to achieve loose coupling with the help of interface as all classes are independent of one another.

Introduction to functional interface

From the above programs, it is clear that with the help of the interface we get a lot of control over our methods. As we do not describe the characteristics of the abstract method inside the interface we get an opportunity to describe the characteristics of the abstract method inside the class implementing the interface. In fact, it is necessary to override the abstract method inside the class implementing the interface. Hence, in case, we want to make any changes inside the interface, there are no tight coupling issues, that is, overriding the hundred and thousands of methods in each and every class, since, all the classes are independent of one another.

Java 8 brought a lot of functionalities and new features. The interface in Java encountered some major and revolutionary changes. For the first time, in addition to the abstract method, the declaration of the static and default methods inside an interface was announced legal. The functional interface was defined for the first time.

Functional interfaces are those interfaces in Java that can have only one abstract method. In addition to an abstract method, they are free to have any number of default and static methods. The runnable interface in Java with the help of which we achieve multithreading and also the action listener interface, which contains the abstract method action performed, are some of the examples of the functional interfaces.

/* Java program to illustrate the general approach to override a method declared inside a functional interface with the help of implementing classes */

interface abc{
   public void show();
   static void print(){
      System.out.println("Static method print inside an interface abc.");
      System.out.println();
   }
   default void display(){
      System.out.println("default method display inside an interface abc.");
      System.out.println();
   }    
}
class xyz implements abc{
   public void show(){
      System.out.println("Overriden abstract method show within an interface abc with the help of implementing class xyz");
      System.out.println();
   }
}
public class Main{
   public static void main(String[] args){
      xyz obj=new xyz();
      obj.show();
      abc.print();
      obj.display();   
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Overriden abstract method show within an interface abc with the help of implementing class xyz


Static method print inside an interface abc.


default method display inside an interface abc.

/* Java program to illustrate how to override a method declared inside a functional interface with the help of the Anonymous class */

/*Declaring an interface named Anonymous with 2 abstract methods show and display*/
interface Anonymous
{
  void show();
  void display();
}
// The driver class
class Main
{
   public static void main(String[] args)
   {
      //Anonymous class implementation
      Anonymous object=new Anonymous()
      {
         /*Defining the abstract method show inside the anonymous class*/
         @Override
         public void show()
         {
           System.out.println("Overriden the show method with the help of the anonymous class.");
           System.out.println();
         }
        /*Defining the abstract method display inside the anonymous class*/
        @Override
         public void display()
         {
            System.out.println("Overriden the display method with the help of the anonymous class.");
            System.out.println();
         }
      };
        /*Calling the overridden methods show and display with the help of the object of the anonymous class*/
        object.show();
        object.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Overriden the show method with the help of the anonymous class.


Overriden the display method with the help of the anonymous class.

Functional interface and lambda expression are correlated to one another. It was necessary to bring functional interface in picture because the Java developers were working on to improve code readability by avoiding lengthy boiler plate codes and came up with the idea of lambda expression. These may seem confusing at the first place but in this section, we will discuss everything like why we can’t use normal interface with lambda expression? but before this let us revise the lambda expression in Java.

The main motive behind learning lambda expression is that it increases readability by cutting down the size of the program. The whole concept of lambda expression somewhat revolves around the functional interface. The lambda expression in java only works with the functional interface.

Lambda expression is an anonymous function that does not have a name and does not belong to any class. It is an enhanced version of an anonymous class. It provides a transparent and straightforward way to write our code and increases the code readability.

The syntax for the lambda expression is:

parameter -> expression body

The arrow operator was introduced in java through the lambda expression. It divides the code into two parts, that is, the parameters and expression body.

The characteristics of lambda expression are listed below:

  • Type declaration is not mandatory in the lambda expression.
  • It is not necessary to write the method name while using a lambda expression.
  • The parenthesis around parameters is optional.
  • We may or may not use the curly braces.
  • It is not necessary to use the return keyword with a lambda expression.

/* Java program to illustrate how we can easily override a method declared inside a functional interface with the help of the lambda expression */

/*Declaring an interface named lambda with one abstract method show and other default method display*/


interface Lambda
{
  void show();
  default void display()
  {
    System.out.println("This is the non abstract method inside the functional interface.");
  }
}
// The driver class
class Main
{
   public static void main(String[] args)
   {
      
      //Lambda expression implementation
      /*Overriding the abstract method inside the functional interface with the help of lambda expression*/
   Lambda object=()-> {System.out.println("Show method is overridden using a lambda expression.");
   System.out.println();
   };
   /*Calling the abstract method show and default method display.*/
   object.show();
   object.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Show method is overridden using a lambda expression.


This is the non abstract method inside the functional interface.

Why do we need the functional interface to work with lambda expression?

We have already discussed the following:

  • Type declaration is not mandatory in the lambda expression.
  • It is not necessary to write the method name while using a lambda expression.
  • The parenthesis around parameters is optional.
  • We may or may not use the curly braces.
  • It is not necessary to use the return keyword with a lambda expression.

Hence, if we have more than one abstract method then the compiler will get confused about which method to override and hence, we will get the compile time error.

/*Java program to show the importance of functional interface for implementing the lambda expression*/

interface Lambda
{
  void show();
  void show2();
  default void display()
  {
    System.out.println("Trying to implement lambda expression with non functional interfaces.");
    System.out.println();
  }
}
// The driver class
class Main
{
   public static void main(String[] args)
   {
      
      //Lambda expression implementation
      /*Trying to Override the abstract methods with the help of lambda expression*/
   Lambda object=()-> {System.out.println("The method is overridden using a lambda expression.");
   System.out.println();
   };
   /*Calling the abstract method show and default method display.*/
   object.show();
   object.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Main.java:22: error: incompatible types: Lambda is not a functional interface
   Lambda object=()-> {System.out.println("The method is overridden using a lambda expression:");
                 ^
    multiple non-overriding abstract methods found in interface Lambda
1 error



ADVERTISEMENT
ADVERTISEMENT