×

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be easier to read and more organised using arrow functions.

They are unidentified functions, arrow functions (the functions without a name and not bound with an identifier). They can declare without the function keyword because they don't return any value. It is not possible to utilise arrow functions as constructors. The context is either lexically or statically specified within the arrow functions. They go by the name Lambda Functions in many linguistic contexts.

Arrow functions are not compatible with the new keyword since they lack a prototype attribute.

The syntax for defining the arrow function

const functionName = (arg1, arg2, ?..) => {  
    //The main body of the function  
}

An Arrow Function or Lambda Function is composed of three parts:

Parameters: The arguments may be an optional part of any function.

Fat arrow notation/lambda notation: It is used to represent the arrow (=>).

Statements: The function's instruction set is represented by it.

Let's use an illustration to try to understand it.

We are defining three functions in the example below that display Function Expression, Anonymous Function, and Arrow Function.

Program

// expression of a function  
var myop1 = function show() {  
 console.log("expression of a function");     
}    
// Anonymous operation 
var myop2 = function () {  
    console.log("It is an Anonymous operation");     
   }     
//Arrow operator 
var myop3 = () => {  
    console.log("It is an Arrow operator");     
   };  
myop1();  
myop2();  
myop3();  

Output

Arrow operator in Java

Syntactic Variations

The following are some syntactic modifications for the arrow functions:

Optional parentheses for the single parameter

Program

var num = a => {  
    console.log(a);  
}  
num(115);  

Output

Arrow operator in Java

Braces are optional for single statements, and they are left empty if no parameters are needed.

Program

var show = () => console.log("Java Program");  
show();  

Output:

Arrow operator in Java

Arrow Function with Parameters

When utilising an arrow function, you must supply parameters inside parentheses if you need to pass more than one.

Program

var show = (u,v,w) => {  
    console.log(u + " " + v + " " + w );  
}  
show(124,256,524);  

Output:

Arrow operator in Java

Arrow operator with default arguments

In ES6, if no value is supplied to the function or the value is undefined, the arguments may be initialised with default values. The following code provides an illustration for the same:

Program

var show = (u, v=456) => {
    console.log(u + " " + v);
}
show(126);

The value of v in the preceding function is set to 456 by default. If no value for v is explicitly supplied, 456 will always be assumed by the function.

Output

Arrow operator in Java

If the function passes the parameter's value manually, the default value of "v" will be replaced. It is demonstrated in the following example:

Program

var show = (u, v=456) => {  
    console.log(u + " " + v);  
}  
show(126,549);  

Output

Arrow operator in Java

Arrow function with Rest parameters

The number of values you can provide into a function is not limited by rest parameters, but they all need to be of the same type. Another way to put it is that rest parameters function as hold for numerous arguments of the same type.

The spread operator with three periods should be preceded with the parameter name when expressing the remainder parameter (not more than three or not less than three).

The illustration for the same may be seen in the example below:

Program

var show = (u, ...args) => {  
    console.log(u + " " + args);  
}  
show(111,222,333,444,555,666,777,888);  

Output:

Arrow operator in Java

Arrow Function without Parentheses

Parentheses are not required if you just have one parameter to pass.

Program

var show = u => {  
    console.log(u);  
}  
show("Java Program");   

Output:

Arrow operator in Java

Advantages of Arrow Functions

The following are some benefits of utilising arrow functions:

1.It reduces the code size: The size of the code is decreased when the arrow function syntax is used. Using the arrow function allows us to write less code.

2.Return statement and Functional braces are optional for single line functions: In ES5, the return statement in the functions must be defined, however in ES6, the return statement is not necessary for single-line functions. For the single-line functions, functional brackets are likewise not required.

Syntax in ES5

function show(num){  
return num/2;  
}  

Syntax in ES6

var show = num => num/2;  
console.log(show(112));  

Program without Return Keyword

var show = num => {  
    num/2;  
}  
console.log(show(48));  

Output:

Arrow operator in Java

Program with Return Keyword

var show = value => {  
   return value/2;  
}  
console.log(show(48));  

Output:

Arrow operator in Java

3.Lexically bind the context: The arrow function lexically or statically binds the context. In contrast to conventional functions, arrow functions handle this differently. There is no binding for this in the arrow function. This term is used to identify the objects that called a regular function, which may be anything from a window to a button to a document.

In contrast, this term always refers to the object that specifies the arrow function in the case of arrow functions.

Let's use the following bit of code to try and understand it:

Program

If the array of numbers in a class contains a value lower than 30, we shall put the value into the child queue.

The following may be accomplished in ES5:

this.num.forEach(function(num) {   
    if (num < 30)   
        this.child.push(num);   
}.bind(this));  

Use the arrow function in ES6 to do this.

this.num.forEach((num) => {   
    if (num < 30)   
        this.child.push(num);   
});  

Therefore, utilising the arrow function eliminates the need for implicit binding because it executes automatically.

As we've seen, the arrow function decreases the amount of lines while also simplifying the drafting of functions.


Related Topics

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

Factorial Program in Java using Recursion

Factorial Program in Java Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to...

3 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.