Posts

Showing posts with the label interfaces

Java 8 LongConsumer example

In this blog post, I will be explaining how the Java 8 functional interface LongConsumer works. To know more about functional interfaces, you can refer this blog post. Edit The LongConsumer interface provides a method called accept . It accepts a single parameter of long data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in.The LongConsumer interface is a specialization of the Consumer  interface. While the Consumer interface accepts any data type, the LongConsumer interface accepts a long value. To see an example of the Consumer interface, refer to  this  blog post. LongConsumer Example Consider the following code snippet: public class LongConsumerDemo { public static void main(String args[]) { LongConsumer decrementBy5 = (num) -> System.out.println("Input:"+num+", Incremented Value:"+(num-5)); decrementBy5.accept(12); decrementBy5.accept(23); }}   Here, the Lon...

Java 8 IntConsumer Interface

In this blog post, I will be explaining how the Java 8 functional interface IntConsumer works. To know more about functional interfaces, you can refer this blog post. Edit The IntConsumer interface provides a method called accept. It accepts a single parameter of int data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in. The  IntConsumer interface is a specialization of the Consumer interface. While the Consumer interface accepts any data type, the  IntConsumer interface accepts an Integer value. To see an example of the Consumer interface, refer to  this  blog post. IntConsumer Example Consider the following code snippet: public class IntConsumerDemo { public static void main(String args[]) { IntConsumer incrementby5 = (num) -> System.out.println("Input:"+num+", Incremented Value:"+(num+5)); incrementby5.accept(12); incrementby5.accept(23); }}   Here, the IntConsumer....

Java 8 DoubleConsumer example

In this blog post, I will be explaining how the Java 8 functional interface DoubleConsumer works. To know more about functional interfaces, you can refer this blog post. Edit The DoubleConsumer interface provides a method called accept. It accepts a single parameter of double data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in. The  DoubleConsumer  interface is a specialization of the Consumer interface. While the Consumer interface accepts any data type, the DoubleConsumer interface accepts a Double value. To see an example of the Consumer interface, refer to  this  blog post. DoubleConsumer Example Consider the following code snippet: public class DoubleConsumerDemo { public static void main(String args[]) { DoubleConsumer squareGenerator = (num) -> System.out.println(num*num); double input = 5.0; squareGenerator.accept(input); }}   Here, the DoubleConsumer.accept method accepts a...

Java 8 BiFunction Example

In this blog post, I will be explaining how the Java 8 functional interface BiFunction works. To know more about functional interfaces, you can refer  this  blog post. Edit The BiFunction is a specialization of the Function interface that accepts 2 arguments. Just like Function it provides a method called apply. This method accepts 2 arguments of any data type and returns a result. So it basically applies the logic in the apply method to the input parameters and returns the result. BiFunction Interface Example with two integer inputs and Integer output Consider the following code snippet: private static void example1(){ BiFunction<Integer,Integer,Integer> multiplier = (a,b) -> {return a*b;}; int input1 = 6; int input2 = 8; System.out.println("Result of multiplying "+input1+" and "+input2 +" is "+multiplier.apply(input1,input2) ); } Here, we have written a BiFunction implementation that accepts 2 integer values, multiplies them and ret...

Java 8 UnaryOperator Example

In this blog post, I will be explaining how the Java 8 functional interface UnaryOperator works. To know more about functional interfaces, you can refer this blog post. Edit The UnaryOperator interface extends the Function interface. It inherits the apply method in the Function interface. The lambda expression passed to the UnaryOperator is used to provide an implementation for the apply method in the Function interface.   UnaryOperator example with Integer data type. Consider the following code snippet: public class UnaryOperatorDemo {public static void main(String[] args) {UnaryOperator<Integer> increaseBy5 = num -> num+5;System.out.println("Output with input 7 is "+increaseBy5.apply(7));}} Here, we have implemented the UnaryOperator.apply method using a lambda expression.  This method simply increases the value of the input number by 5 and returns it. So when you execute this code, it will print the following output: Output with input 7 is 12 UnaryO...

Java 8 Function Interface Example

In this blog post, I will be explaining how the Java 8 functional interface Function works. To know more about functional interfaces, you can refer  this  blog post. Edit The Function interface provides a method called apply. It accepts a single parameter of any data type and returns a result of any data type. So it basically applies the logic in the apply method to the input parameter and returns the result. Function Interface Example with String Input and Integer return type Consider the following code snippet: public class FunctionDemo {public static void main(String[] args) {Function<String,Integer> lengthChecker = (str) -> {return str.length();};String input = "Hello World";System.out.println("Length of "+input+" is "+lengthChecker.apply(input) );input = "Test";System.out.println("Length of "+input+" is "+lengthChecker.apply(input) );}} Here, we have written a Function implementation that accepts a String ...

Java 8 BiPredicate Example

In this blog post, I will be explaining how the Java 8 functional interface BiPredicate works. To know more about functional interfaces, you can refer to this blog post. Edit The BiPredicate interface provides a method called test. This method accepts two parameters of any data type and returns a boolean. The BiPredicate interface is a specialization of the Predicate interface. While the Predicate interface accepts a single argument of any data type, the BiPredicate interface accepts two parameters of any data type. To see an example of the Predicate interface, refer to  this  blog post. BiPredicate method with Two Integer arguments Consider the following code snippet: public class BiPredicateDemo {public static void main(String[] args) {BiPredicate<String,String> isSubString = (str1,str2) -> {return (str1.indexOf(str2)>0 || str1.startsWith(str2));};System.out.println("Hello World has substring as Hello = "+isSubString.test("Hello World","Hel...

Java 8 Consumer Interface example

In this blog post, I will be explaining how the Java 8 functional interface Consumer works. To know more about functional interfaces, you can refer this blog post. Edit The Consumer interface provides a method called accept. It accepts a single parameter of any data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in. Consumer example with Integer parameter Consider the following code snippet: public class ConsumerDemo {public static void main(String args[]){Consumer<Integer> squareGenerator = (input) -> System.out.println("Square of "+input +" is "+(input*input));squareGenerator.accept(6);}}} Here, we have implemented the Consumer.accept method using a lambda expression.  This accept method accepts an Integer argument. It squares it and prints the result to the console. So when this code is executed, it will print the following output: Square of 6 is 36 Consumer example with ...

Java 8 Functional Interface explained with code samples

Java 8 introduced the concept of functional interfaces. In this blog post, I will be explaining what a Java 8 functional interface is. Edit What is a functional interface? A functional interface is nothing but an interface that has only one abstract method. It can have more than one static and default methods, but it should have only one abstract method in order to qualify as a functional interface. Consider the following code snippet: package learnjava.java8;@FunctionalInterfacepublic interface MyFunctionalInterface {public void method1();public default void defaultMethod(){System.out.println("Default method");}public default void staticMethod(){System.out.println("Static method");}} Here, we have defined an interface called  MyFunctionalInterface . This has only one abstract method called method1 and so this is a functional interface. It also has a default and a static method. Note that we have specified the @FunctionalInterface annotation. This annotati...

Java 8 Static Interface methods with code samples

Just like default methods , Java 8 also supports static methods in interfaces. In this blog post, I will be explaining Java 8 static interface methods in detail. I will be covering what static methods are, how they work and why they were added. Edit What are static interface methods? Static interface methods are methods with the static keyword are with a method body. How do static interface methods work? Consider the following code snippet: </pre>public interface MyInterface {static public void staticMethod(){System.out.println("In staticMethod of interface");}}<pre> So in the code above, the staticMethod is a static interface method.  So we have defined a method with a method body within the interface. It has the static keyword specified. Prior to Java 8, the above code would have caused an error due to two reasons: There is a method with a method body within the interface There is a static method with in the interface How are they similar to default method...

Java 8 Default Interface methods explained

One of the new features provided by Java 8 is the support for default methods in interfaces. In this blog post, I will be explaining Java 8 default interface methods in detail. I will be covering what default methods are, how they work and why they were added. Edit What are default interface methods? Default methods are methods in an interface that have method bodies, They are specified with the  keyword “ default “. How do default interface methods work? Prior to Java 8, interfaces could not have method bodies.  So consider the following code snippet: public interface MyInterface {public void methodA();public void methodB(){System.out.println("In methodB");}}   This code causes a compilation error. This is because methodB has a method body.  However, if you are using Java 8, you can change the code as follows: public interface MyInterface {public void methodA();default public void methodB(){System.out.println("In methodB");}} So now, the def...

Java Interfaces explained

In this blog post, I will be explaining what Java interfaces are and how they can be used. What is an interface? An interface is a java construct that is used to specify a behavior that classes must implement. It does this by specifying methods without any method bodies. The code for the methods within the interface must be provided by the classes that implement the interface. So using an interface , you can specify what a class must do, but not how it does it. For example, consider the following code snippet: public interface Animal {public void speak();} This interface keyword specifies that this is an interface. Instead of the class keyword, the interface keyword is used, otherwise its body is very similar to a class. There is a speak method within this interface. There is no code in the speak method. Methods specified in an interface have no method bodies.  Code is not allowed in a method in an interface since the basic concept of an interface is to use it to specify what should be...

Java 8 BooleanSupplier Example

In this blog post, I will be explaining how the Java 8 functional interface BooleanSupplier works. To know more about functional interfaces, you can refer  this  blog post. Edit The  BooleanSupplier interface provides a method called getAsBoolean. This method does not accept any arguments. It returns a boolean value. The BooleanSupplier interface is a specialization of the Supplier interface that returns a boolean. To see an example of the Supplier  interface, refer to  this  blog post. BooleanSupplier example Consider the following code snippet: public class BooleanSupplierExample {public static void main(String[] args) {BooleanSupplier booleanSupplier = () -> true;System.out.println("Boolean flag = "+booleanSupplier.getAsBoolean());}} Here, we have implemented the getAsBoolean method using a lambda expression. This simply returns the value true. So when this code is executed, it will print the following output: Boolean flag = true You can get the source code for th...

What is a marker interface is Java

In this blog post, I will be explaining what is a marker interface in Java.   Marker Interface Definition A marker interface is simply an interface that has no methods. Some examples of marker interfaces in Java are Serialiazable , Cloneable ,  etc.   How Marker Interfaces work So if there are no methods in a marker interfaces, how do they work? In other words, how does a class that implements a marker interface know what methods to provide? The answer to this is that marker interface specify a design pattern  used to provide run-time type information about the objects.  The very fact that a class implements a marker interface indicates something to the JVM or compiler. So when the JVM sees an object of the marker Interface type, it will perform some special operation. You can also define your own marker interfaces and write code that behaves in a special way if the marker interface is implemented. So for ex. objects that belong to a class that implements the marker interface...

Difference between an abstract class and interface in Java

Another commonly asked interview question is to explain the difference between an abstract class and an interface. So in this blog post, I will give you a detailed explanation. What is an Abstract Class? An abstract class is a class that has one or more abstract method. An abstract method is a method that has the “abstract” keyword specified in the method definition. It does not have any method body, it is up to the subclass of the abstract class to provide an implementation for the abstract method. So why is an abstract class useful? Sometimes, you will want to create a super class that defines a method that all its sub classes must implement, but it leaves the exact implementation to the sub class. For ex. suppose you have a class called Shape, you can define an abstract method called draw. You can then have sub-classes for various shapes like Rectangle, Triangle, etc which provide implementations for the draw method. So while the “draw” method makes no sense ...

Java 8 Supplier Interface example

In this blog post, I will be explaining how the Java 8 functional interface Supplier works. To know more about functional interfaces, you can refer this blog post. Edit The Supplier interface provides a method called get.  This method does not accept any arguments. It can return any data type. Supplier example with Integer return type. Consider the following code snippet: public static void main(String[] args) {Supplier<Integer> getRandom = () -> new Random().nextInt(100);System.out.println("Random number 1 = "+getRandom.get());System.out.println("Random number 2 = "+getRandom.get());} Here, we have implemented the Supplier.get method using a lambda expression.  This get method simple returns a random integer less than 100. So when this code is executed, it will print the following output: Random number 1 = 98Random number 2 = 89 Supplier example with Date as return type Consider the following code snippet: public class SupplierDemo {public static vo...