Java Archives - Code-Adda

In Java 8&nbsp;<em>method references has introduced</em>, which will refer to methods or constructors without invoking them. These syntactic shortcuts create lambdas from existing methods or constructors. Basically, lambda expressions in Java are methods implemented without an enclosing class body and constructors created by lambdas are often referred to as&nbsp;<em>constructor references</em>, which consider to be a subset of method references.

In Java 8 method references has introduced, which will refer to methods or constructors without invoking them. These syntactic shortcuts create lambdas from existing methods or constructors. Basically, lambda expressions in Java are methods implemented without an enclosing class body and constructors created by lambdas are often referred to as constructor references, which consider to be a subset of method references.

In short, not all methods can be implemented as lambdas. But only those which declared inside candidate functional interface (an interface which contains only one abstract method called as functional interface) are the privileged ones.

So, we will see here how we can convert method parameters based on anonymous implementations of functional interfaces into lambdas:

Any implementation of a Functional interface can be converted to lambda expression.

When we will observe here, all that we need to be done is eliminating the elements which could be implicitly available to the compiler and separating the parameters and the actual expression by “->” operator.

So, one question here arises then when we should go for method references?

Simply we can use method references anywhere we can use Lambda Expressions, which means that a Functional Interface is needed, but only if the Lambda Expression would invoke a single, already defined, method & do nothing else.

The method signature must also match that of the Functional Interface being used. For eg, when used in conjunction with a Predicate, which requires a single input argument & returns a Boolean value, that method would need to accept an argument & return a Boolean value. We will not be able to use method references if we need to invoke more than one method within a Lambda Expression or if we need to pass extra arguments into the method.

In Java 8, we can perform method reference by following 4 types:

1Reference to a static type

[code lang="java"]

package com.code.adda.java8.methodReference.staticMethods;

 

public class ReferencesToStaticMethodsDemo {

public static void main(String[] args)

   {

      new Thread(ReferencesToStaticMethodsDemo::getThreadValue).start();

      new Thread(() -&amp;gt; getThreadValue()).start();

      new Thread(new Runnable()

                 {

                    @Override

                    public void run()

                    {

                     getThreadValue();

                    }

                 }).start();

   }

 

   static void getThreadValue()

   {

      String name = Thread.currentThread().getName();

      for (int i = 0; i &amp;lt; 8; i++)

      {

         System.out.printf(&quot;%s: %d%n&quot;, name, i);

        

         try

         {

            Thread.sleep((int) (Math.random()*5));

         }

         catch (InterruptedException ie)

         {

         ie.printStackTrace();

         }

      }

   }

}

 

[/code]


Output:


Thread-0: 0

Thread-1: 0

Thread-1: 1

Thread-1: 2

Thread-0: 1

Thread-1: 3

Thread-0: 2

Thread-0: 3

Thread-0: 4

Thread-0: 5

Thread-0: 6

Thread-0: 7

Thread-1: 4

Thread-1: 5

Thread-2: 0

Thread-1: 6

Thread-2: 1

Thread-2: 2

Thread-2: 3

Thread-1: 7

Thread-2: 4

Thread-2: 5

Thread-2: 6

Thread-2: 7


Here, there are three ways to pass a unit of work described by the getThreadValue() method to a new Thread object whose associated thread is started:

  • It will pass a method reference to the static getThreadValue() method
  • It will pass an equivalent lambda whose code block executes getThreadValue()
  • It will pass an instance of an anonymous class that implements Runnable and runs getThreadValue() method.

2. Reference to an Instance Method of a Particular Object

The object reference on which an instance method is invoked is known as the Receiver of the method invocation.

We can specify the receiver of the method invocation: provide it implicitly when the method is invoked.

a) Bound receiver,

b) Unbound receiver.

a) Bound receiver: it can provide Explicitly when the method is invoked

Syntax: objectRef::instanceMethod


[code lang="java"]

package com.code.adda.java8.methodReference.instanceMethod;

 

import java.util.function.Function;

 

public class ReferencesToInstanceBound {

  public Integer factorial(int n) { // instance method

  if(n==0 || n==1){

  return 1;

  }

    return n * factorial(n-1);

  }

 

  public static void main(String[] args) {

  

//using lambda  

ReferencesToInstanceBound cal = new ReferencesToInstanceBound();

    Function&amp;lt;Integer, Integer&amp;gt; funLambda = (a) -&amp;gt; cal.factorial(a);

    System.out.println(&quot;By Using lambda expression: &quot;+funLambda.apply(4));

 

    // bound type

    Function&amp;lt;Integer, Integer&amp;gt; funBoundType = cal::factorial;

    System.out.println(&quot;Using a method References To Instance bound type: &quot;+funBoundType.apply(5));

 

  }

}

 

[/code]


Output:

By References To Instance: 24

References To Instance bound type: 120

b) Unbound receiver:  it can provide implicitly when the method is invoked.


[code lang="java"]

package com.code.adda.java8.methodReference.instanceMethod;

 

import java.util.function.BiFunction;

 

public class ReferencesToInstanceUnBound {

 

public Integer factorial(int n) { // instance method

return n == 0 || n == 1?1:n * factorial(n - 1);

}

 

public static void main(String[] args) {

 

ReferencesToInstanceUnBound referencesToInstanceUnBound = new ReferencesToInstanceUnBound();

// using lambda

 

BiFunction&amp;lt;ReferencesToInstanceUnBound, Integer, Integer&amp;gt; funLambda = (a, b) -&amp;gt; a.factorial(b);

System.out.println(&quot;By Using lambda expression: &quot; + funLambda.apply(referencesToInstanceUnBound, 5));

 

// UnBound type

BiFunction&amp;lt;ReferencesToInstanceUnBound, Integer, Integer&amp;gt; funUnBoundType = ReferencesToInstanceUnBound::factorial;

System.out.println(&quot;Using a method References To Instance Unbound type: &quot;

+ funUnBoundType.apply(referencesToInstanceUnBound, 6));

 

}

}

[/code]


Output:

By Using lambda expression: 120

Using a method References To Instance Unbound type: 720


BiFunction<T,U,R> : Represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function.

Ref: https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html

3. Reference to an instance method of an arbitrary object of a particular type

Syntax :  ContainingType::methodName


[code lang="java"]

package com.code.adda.java8.methodReference.instanceMethodArbitrary;

 

import java.util.function.Function;

 

interface Factorial {

default int calculate(int n) {

return n == 0 || n == 1 ? 1 : n * calculate(n - 1);

}

}

 

public class ReferenceToInstanceArbitraryObj implements Factorial {

 

@Override

public int calculate(int n) { // calculate Fibonacci series using recursion

return n &amp;lt;= 1 ? n : calculate(n - 1) + calculate(n - 2);

 

}

 

public void calculateValue(int value) {

// By Using Uses this::calculate method

Function&amp;lt;Integer, Integer&amp;gt; function1 = this::calculate;

System.out.println(&quot;this::calculate(): Fibonacci Series = &quot;);

for (int i = 0; i &amp;lt;= value; i++) {

System.out.print(function1.apply(i) + &quot; &quot;);

}

// By Using Factorial.calculate() method

Function&amp;lt;Integer, Integer&amp;gt; function2 = Factorial.super::calculate;

System.out.println(&quot;\nFactorial::calculate(): Factorial = &quot; + function2.apply(value));

}

 

public static void main(String[] args) {

ReferenceToInstanceArbitraryObj obj = new ReferenceToInstanceArbitraryObj();

obj.calculateValue(6);

}

}

 

[/code]


Output:

this::calculate(): Fibonacci Series = 0 1 1 2 3 5 8

Factorial::calculate(): Factorial = 30

4. Reference to a constructor

Syntax:  ClassName::new


[code lang="java"]

package com.code.adda.java8.methodReference.toConstructor;

 

@FunctionalInterface

interface ISquare {

Square getSquare(int fact);

}

 

class Square {

public Square(int n) {

System.out.print(&quot;Sqauare Value by Reference to a constructor: &quot; + n * n);

}

}

 

public class MethodRefToCnstructor {

 

public static void main(String[] args) {

ISquare sqr = Square::new;

sqr.getSquare(6);

 

}

 

}

[/code]


Output:

Sqauare Value by Reference to a constructor: 36





Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners

Description
This is the best course to learn to program in Java in Spanish from scratch and without any experience in this fabulous programming language. This is the first course where we will study the Fundamentals of Java, and we will take you step by step until you acquire the bases of the Java language and you can start to study more advanced Java topics.

The content is divided into perfectly structured levels, each level supported by the previous one, with the aim of adding Java knowledge incrementally and so you can focus on mastering the issues little by little and gradually. So ensure the success of your Java training.

We will also offer support for any doubts about the didactic material included in this Java Fundamentals course.

We manage a new teaching methodology that we have called Speed ​​Learning. This methodology consists of concise videos that go directly to the point to be studied, complemented by eBooks with explanations and step-by-step images (which you can print, or search for any text you need, or use for your offline study), since As we know we can not do text search within a video. In addition, our methodology includes perfectly structured and very didactic exercises that will allow you to accelerate your eLearning learning. No loss of time in videos where you have to watch the instructor codify an exercise, too much theory, little practice or anything like that. Our Speed ​​Learning methodology guarantees that in the shortest possible time you will acquire the necessary knowledge for the Java professional and working world.

The Java Fundamentals course includes the following topics for study:

Lesson 1 - Starting with Java Technology

The amazing world of Java programming

What is Java technology (from a practical approach)

Our first Java program from scratch

Lesson 2 - Variables and Operators in Java

Use of Variables in Java and what we use them for

Types of Data in Java and how they are classified

Management and Classification of operators in Java

Lesson 3 - Control statements in Java

Using the if-else structure and where to use it

Handling the switch structure and when applying it

Lesson 4 - Handling Loops in Java

Use of the for loop and its use

Using the while loop and how to apply it

Use of the do-while loop and when to use it

Lesson 5 - Object Oriented Programming

Introduction to Object Oriented Programming (OOP)

Handling Classes in Java

Use of Objects in Java

Lesson 6 - Functions in Java

Declaration of Methods or Functions in Java

Use and call of functions in Java

Lesson 7 - Data Management in Java

Using Arrays in Java

Management of Matrices in Java

Lesson 8 - Inheritance in Java

Inheritance Management in Java

Use of superclasses and subclasses in Java

Final Level Laboratory

Final Exercise where everything learned in this Level is integrated

At the end you get a certificate of having completed the Java Fundamentals course.

We wait for you on the other side.

Ing. Ubaldo Acosta

Founder of Global Mentoring

Passion for Java Technology

Who this course is for:

Anyone who wants to learn how to program in Java
Basic knowledge
Basic knowledge of PC use
Basic management of an operating system such as Windows, Mac or Linux
It is not necessary to know how to program, we will start from scratch !!!
The attitude and desire to start coding and learning Java once and for all from scratch!
What will you learn
Have the basics of the programming language with Java
You will know the basic syntax of the Java language
Manage the concept of Variables and Operators in Java
We will study Object Oriented Programming with Java
You will learn the Control Statements and Loops in Java
We will see the concept of Functions with Java
We will study the concept of Inheritance in Java
We will learn to use Arrays in java
We will handle the concept of Matrices in Java
We will learn to Design Classes in Java
We will make a final application with everything learned in the course
To know more:

Java Essentials : Learn Core Java From Basic to Advance

Java Essentials : Learn Core Java From Basic to Advance

Learn Java Programming Using Practical Assignments. Start Building Back-end Web Applications Robust Test Automation Frameworks By End Of The Course. Learn More!

Description
This is only Java related course and it's great because it covers just the right amount of Java which is needed to leaning programming, java.

This is a comprehensive yet simple course on java programming language and it concentrates on Java programming concepts.

*************************** No Prior Coding Experience Needed ***************************

This course assumes that you have no programming background. If you have some experience then, it's just a bonus point. You have never code, have some experience or have a lot of experience any other programming language, this course is one stop place for you.

Java is one of the most and useful programming languages to learn You can build back-end of web applications and build robust test automation framework. Specially for Selenium WebDriver GUI automation, Java is most popular choice and has the largest community.

Each lecture consist of a video screencast and code files

There are quizzes, homework to test your knowledge

High focus on practice and asking questions

You will also learn coding best practices

Market is never short of jobs in Java programming language, there are ample of jobs in both Java development and Automation Testing using Java.

What are you waiting for? Enroll today and learn the powerful Java language !!!

Basic knowledge
Nothing else! It’s just you, your computer and your hunger to get started today
Java concepts are covered in the course, no experience needed
Windows/MAC computer
What will you learn
You will be able to EXPLAIN, DESIGN and IMPLEMENT efficient java Programs
You will be confident to clear test automation interviews
Understand the concepts of Object Oriented Programming Language
Complete understanding of java
Expert-level knowledge of Java code (+ advanced tips and tricks used by the pros)
Suitable for beginner programmers and ideal for users who learn faster when shown
To learn more:

Fundamentos de Java: Aprende Java desde cero, sin misterios | Simpliv

Fundamentos de Java: Aprende Java desde cero, sin misterios | Simpliv

Fundamentos de Java: Aprende Java desde cero, sin misterios

Description
This is the best course to learn to program in Java in Spanish from scratch and without any experience in this fabulous programming language . This is the first course where we will study the Java Fundamentals, and we will take you step by step until you acquire the basics of the Java language and so you can start studying more advanced Java topics.

The content is divided into perfectly structured levels , each level supported by the previous one, with the aim of adding Java knowledge incrementally so that you can focus on mastering the issues little by little and gradually. So ensure the success of your Java training.

In other offer support of any doubt teaching materials included in this course Fundamentals of Java.

To make matters worse, we handle a new teaching methodology that we have called Speed ​​Learning. This methodology consists of concise videos that go directly to the point to study, complemented with eBooks with explanations and step-by-step images (which you can print, or search for any text you need, or use for your offline study), since as we know we cannot do text search within a video. In addition, our methodology includes perfectly structured and very didactic exercises, which will allow you to accelerate your eLearning learning. Without wasting time on videos where you have to watch the instructor codify an exercise, too much theory, little practice or anything like that. Our Speed ​​Learning methodology guarantees that in the shortest possible time you will acquire the necessary knowledge for the professional and professional world of Java.

The Java Fundamentals course includes the following topics of study:

Level. Java basics

Lesson 1 - Starting with Java Technology

The amazing world of Java programming
What is Java technology (from a practical approach)
Our first Java program from scratch
Lesson 2 - Variables and Operators in Java

Use of Variables in Java and what we use them for
Data types in Java and how they are classified
Operator Management and Classification in Java
Lesson 3 - Control sentences in Java

Use of the if-else structure and where to use it
Management of the switch structure and when to apply it
Lesson 4 - Cycle Management in Java

Use of the for cycle and its use
Use of the while cycle and how to apply it
Use of the do-while cycle and when to use it
Lesson 5 - Object Oriented Programming

Introduction to Object Oriented Programming (OOP)
Class Management in Java
Using Objects in Java
Lesson 6 - Functions in Java

Declaration of Methods or Functions in Java
Use and call of functions in Java
Lesson 7 - Data Management in Java

Using Arrangements in Java
Matrix Management in Java
Lesson 8 - Inheritance in Java

Inheritance Management in Java
Use of superclasses and subclasses in Java
Final Level Laboratory

Final Exercise where everything learned in this Level is integrated
At the end you get a certificate of having completed the Java Fundamentals course.

We wait for you from the other side.

Ing. Ubaldo Acosta

Founder of Global Mentoring

Passion for Java Technology

Who this course is for:

Anyone who wants to learn to program in Java
Basic knowledge
Basic knowledge of PC use
Basic operation of an operating system such as Windows, Mac or Linux
It is not required to know how to program, we will start from scratch !!!
The attitude and desire to start coding and learning Java once and for all from scratch !!!
What will you learn
Have the basics of the programming language with Java
You will know the basic syntax of the Java language
Will handle the concept of Variables and Operators in Java
We will study Object Oriented Programming with Java
You will learn Control Sentences and Cycles in Java
We will see the concept of Functions with Java
We will study the concept of Inheritance in Java
We will learn to use Arrangements in java
We will handle the concept of Matrices in Java
We will learn to Design Classes in Java
We will make a final application with everything learned in the course
To continue: