Monday, August 20, 2018

Java8 - Learn Method Reference Tutorials with examples

Method reference basics

java introduced method reference in java8 version. Method reference allows the developer to call a method or constructor by their names. Method references are one more short way of writing lambda expression. Method references use the symbol "::" to separate class/object/constructor from method name Sometimes we used to get the compile-time warning like "The target type of this expression must be a functional interface" so this error is because the need to assign method reference or lambda expression to functional interface

method reference syntax

Classname:: methodname
Instancename:: methodname
Constructorname::new
Various types of method references introduced.
  • Static methods reference
  • Instance method reference 
  • Constructor reference 

Static method reference example

 Static methods are global to class, They can directly call using Classname.staticmethod() with java8, You can call using Classname::static-method
public class MethodReferenceExample {

 public static void main(String[] args) {
  // Using lambda expression
  BooleanTest lambdaExample = (n) -> PositiveNumberCheck.isPositive(n);
  System.out.println(lambdaExample.test(2));
  System.out.println(lambdaExample.test(-2));

  // Using method reference
  BooleanTest methodRefExample = PositiveNumberCheck::isPositive;
  System.out.println(methodRefExample.test(2));
  System.out.println(methodRefExample.test(-2));
 }
}

@FunctionalInterface
interface BooleanTest {
 boolean test(int n);
}
class PositiveNumberCheck {
 public static boolean isPositive(int n) {
  return n >= 0;
 }
}
And the output of the above code execution
true
false
true
false

Instance method reference example

Instance methods work on instances of a class. Prior to java 8, we used to call instances method using new class(). method name with java8, You can call object:: instance-method
import java.util.function.Function;
public class MethodReferenceExample {
 public Integer IncrementByOne(Integer value) {
  return value + 1;
 }
 public static void main(String[] args) {
  Function<Integer, Integer> function = new MethodReferenceExample()::IncrementByOne;
  System.out.println(function.apply(5));
 }
}
And the output is
6

Construction reference example 

Construction reference can be called using the new operator. Reference to construction is executing via functional interface Here is an example for construction reference
import java.util.function.Consumer;
public class MethodReferenceExample {

 public static void main(String[] args) {
  Consumer<String> function = Emp::new;
  function.accept("Hello");
 }
}
class Emp {
 Emp(String msg) {
  System.out.print(msg);
 }
}
And the output is
Hello
Read More

ES6 features- Arrow Functions Examples | ES6 tutorials

In this blog post, We are going to learn the basics of Arrow functions in javascript with examples.

Why Arrow Function 

Let us create a normal function declaration in javascript. The function has a name, parameters, and body.
function incrementByOne(value) {
   return value + 2;
 }
incrementByOne(2);
The same above code is rewritten with new syntax -the same function with shorter syntax. This is an arrow function and omitted function name, curly braces and return statement. Implicit return is not required. Syntax contains fat arrow =>
var incrementByOne = value => value + 2
incrementByOne(2);
Syntax
(parameters) => { statements/expression }
here are parameters can be optional or many statements which have no return type curly braces is not required Expression is code which requires curly braces Ways to declare Arrow functions. We will see different cases of declaring arrow functions.
no parameters syntax
() => { statements/expression } 
One parameter syntax
value => { ... } 
Multiple parameters Syntax
(x, y) => { ... } 
Arrow functions example
var strs = [
  'one',
  'two',
  'three',
  'four'
];
console.log(strs.map(strs => strs.length));

Arrow functions errors/undefined examples 

This will not work as expected in the below cases.

new and constructor usage

with arrow functions throws Uncaught TypeError: MyObj is not a constructor
function MyObj1() { 
}
var myobj1=new MyObj1()
console.log(myobj1); // outputs object
var MyObj = () => {};
var myobj = new MyObj(); 

console.log(myobj); // TypeError: MyObj is not a constructor

Prototype method usage

Array functions with prototype method return undefined.
var MyObj = () => {};
console.log(MyObj.prototype); // outputs undefined
function MyObj1() { 
}
console.log(MyObj1.prototype); // outputs object
yield keyword also will not work in arrow functions
Read More

Learn JSDoc - Javascript API document Generator tutorials

Javascript Documentation

JsDoc is a  documentation generator for javascript language. This tool is used to generate code documentation in HTML format of a javascript source code and it is similar to Javadoc in java language. Strong documentation is one of the factors for the successful software application.JSDoc parse javascript source  with content from /** */ and outputs HTML documentation.
This blog post covers JSDoc tutorials with examples

Install and Setup JSDoc

To Play with this, first, you need to install it. the installation provides command line tools - jsdoc. This library available as npm package manager.
First make sure that Nodejs is installed, npm and node command works successfully by the following command.
B:\blogger>npm --version
5.6.0
B:\blogger>node --version
v8.10.0
Once installed nodejsm Next step is to install jsDoc npm package
npm install -g jsdoc
This installs jsdoc package in a global location. I am doing the installation on windows. see Global npm install location on windows which is a npm location folder on the window is %APPDATA%\npm\node_modules\jsdoc. This is a global location for node_modules module folder To find the jsdoc version, Please issue the command below
B:\blogger>jsdoc --version
JSDoc 3.5.5 (Thu, 14 Sep 2017 02:51:54 GMT)

JSDoc Basic Example

The simple function declared with two parameters with return type The sample code is in helloworld.js
/**
* Adding two numbers.
* @param {value1} firstParameter First parameter to add.
* @param {value2} secondParameter Second Parameter to add.
* @returns {string}
*/
function add(value1, value2) {
 return value1+value2;
}
Then run the following command to generate HTML documentation.
jsdoc helloworld.js
Generated HTML file as per the below screenshot

Learn JSDoc Library examples with tutorials

Syntax

/**
* Adding two numbers.
* @param {string} firstParameter First parameter to add.
* @param {string} secondParameter Second Parameter to add.
* @returns {string}
*/
Explanation
  • Jsdoc contains multiline comments in addition to the first character is asterisk Each comment includes symbol @ and tag name. @param is one tag here Annotation types, It includes type name in braces @param {string} name

JSdoc comments example 

Comments are similar to multi-line comments and the difference is extra asterisk symbol Comments contain HTML tag as well
// Single line comment
/*
 *  multi-line comment
 */
/**
 * Jsdoc comments
 */

JSDoc function example 

Added few metatags @fileOverview,@Author,@Version to the function
/**
 * This is a hello world function.
 * @fileOverview Employee functions.
 * @author Kiran Babu
 * @version 1.0.0
 * @param {string} value - A string param
 * @return {string} Return a string
 *
 * @example
 *
 *     displayEmp('Welcome')
 */
function displayEmp(msg) { return msg }
JSDoc javascript Documentation for classes

How to return the method as void? 

You have to use the @return tag to document the method function with type. Type can be used in curly braces In javascript, a void exists as type, you can also use undefined.
@returns {void} returns nothing
@returns {undefined} returns undefiend
What are valid param tag types in jsdoc?
@param tag is used to tag a parameter types to a function or method. You can also use @arg or @argument instead of @param @tag contains name, type and descriptio of a parameter to a function
/**
 * @param {string} argument name of the employee.
 */
Here, name is argument type is string enclosed in curly braces description is name of the employee You can use javascript inbuilt data types as a values for type parameter Boolean,Null,Number,String,Undefined,Symbol,Object, Optional and default parameter declaration Parameters declared using @param tag, To make it this param option. Let us declare optional parameter say the message of type string
@param {string} [message] // or
@param {string=} message
@param {string} [message='hello'] // defualt value initlization

How to declare the mixed type of parameters? 

Use | symbol separator to add multiple types for a single parameter in a method or function declaration.
/**
 * Utility method
 * @param {(string|number)} argument The input parameter to function
 * @returns {(string|number)} The modified return value from a function.
 */
function doSomething(argument) {
    return argument;};
how to represent a multidimensional array of objects param type?
Multidimensional is an array of array of objects. which can be represented in jsdoc comments using type - Object.<Array[]>

How to write a comment for a callback of a function?

 Jsdoc provides a @callback tag. It has information like parameters and returns value about the callback function

/**
 * Callback for multiplying two numbers.
 *
 * @callback multiCallback
 * @param {int} multiply - An integer.
 */

/**
 * Multiply two numbers, output the results to a callback function.
 *
 * @param {int} x - An integer.
 * @param {int} y - An integer.
 * @param {multiCallback} callback - A callback to execute.
 */
function Multiply(a, b, multiCallback) {
  multiCallback(a*b);
}

How to Document javascript classes? 

@class or @constrcutor are used to mark it as a class or construction which can be created using the new operator
/**
 * Creates a new Employee.
 * @class Employee class
 */
function Employee() {
 /** @lends Employee */
    {
        /**
         * Create a `Employee` instance.
         * @param {string} name - The Employee's name.
         */
        initialize: function(name) {
            this.name = name;
        },
}
var e = new Employee();
@lend tag used to document all members of a class.

JSDoc Frequently Used annotations

Jsdoc supports following tags and syntax is mentioned. All this syntax should be used included in jsdoc syntax (Adding asterisk to multiline comments)
Tag Description Usage/Syntax
@Author Adds Author of code, supports to add email @author Kiran
@class Marks function as a class instance canbe created using new keyword @class Employee class
@constructor Marks function as a constructor and same as @class @constructor Employee class
@deprecated Specifies a comment to tell that this method is going to be depreated @deprecated from version 2.5
@throws To indicate the execption or error that a method might throught this @throws {Exception} @throws Throws an error if parameter is null
@param Adding documention for parameters to method or function @param {Number} numericValue numeric value to parameter.
@private mark this as private @private
@return or @returns return value documentation of a method or function. @returns {string}
@version version number of a code. @version 1.0
@interface This makes as an interfaces @interface Animal
@static Marker for Static variable, This can be accessed without instance @static
@typedef Marker for custom data types. These can be used in other tags like normal type params @typedef {(number|string)} customType
@todo Document the things need to complete in future @todo Write Edge cases and documentaion for this method.
@lends Document all the members of a class or object @lends Emploee
Read More

Sunday, August 19, 2018

Learn ES7 features | Es2016 javascript tutorials

In this blog post, I will cover Es7 features tutorials with examples.

ECMAScript 2016 or ES2016 or Es7 introduction

Learn ES7 features tutorials with examples

In my previous posts, Posted lot articles on Es6/Es2015 features. Javascript is a popular scripting language for building software applications. ES7 is also called as ECMAScript 2016 or ES2016. Every release to javascript introduced many features. Previous version - ES6(ECMAScript 2015) released lot features including language and API changes. Es7 or ECMAScript 2016 is minor release which contains only two features
  • Array.prototype.includes
  • Exponentiation Operator

Array.prototype.includes() method 

Es7 introduced includes in the array object. includes() method check an element/object exists in an array of elements/objects.
if exists, returns true, else returns false.
includes() method is an replacement of indexOf() method of prior to es7 code.
Syntax
Array.prototype.includes(element) :boolean
Parameters are an element - Element to search in an array Return value - returns the Boolean value true -element contains in Array Includes checks element using the sameValueZero algorithm to find an element Includes checks element using the sameValueZero algorithm to find an element

var numericArray = [9, 21, 5];
console.log(numericArray.includes(21)); // outputs true
console.log(numericArray.includes(2)); // outputs false
Includes method is a like of indexOf() method of ES6 or prior versions. ES6 or Es5 - checking element in an array using index() method Prior to Es6 versions of javascript, We used indexOf() method to search element The same above code can be rewritten as follows
var numericArray = [9, 21, 5];
console.log(numericArray.indexOf(21)>=0); // outputs true
console.log(numericArray.indexOf(2)>=0); // outputs false
indexOf() method used to check the element in an array. It returns the position of a matched element in the array or -1 if element not found. The developer has to write a code to check position to return a boolean value
arr.includes(x)
arr.indexOf(x) >= 0
Both methods treat +0 and -0 is the same
console.log([-0].includes(+0)) // === true)
console.log([+0].includes(-0)) // === true)
console.log([-0].indexOf(+0)>=0) // === true)
console.log([+0].indexOf(-0)>=0) // === true)

Difference between Array.prototype.includes and Array.prototype.IndexOf method. 

Both have the same purpose for finding an element in an array. includes method checks undefined and NaN elements, Index method does not NaN is at a global object and its value is Not-a-Number. NaN and Undefined are valid values in javascript
Includes IndexOf
Returns Boolean value - true of false Return numeric value >=0 or -1
Handles NaN values correctly. it will be very useful for comparing NaN values
console.log([NaN].includes(NaN))// outputs true
Inconsistency in Nan Value handling
console.log([NaN].indexOf(NaN)) // outputs false
Undefined value checks return true and comparison works as expected
console.log( [, , ].includes(undefined)>=0) // === true)
Undefined checks retruns false
console.log( [, , , ,].indexOf(undefined)>=0) // === true)
Includes() makes the developer life easy for dealing with element comparison in array data structure.

Exponentiation Operator

 the name itself says it is an operator dealing with mathematical operations. The exponential operation multiplies the number by exponent times 4 exponential 2 or 4 power 2 is 4* 4=16.
 In Es6 and prior versions, To do exponential operations, You have to use the Math.pow method.

 Es6 and Prior Version Exponentiona operator example

console.log(Math.pow(3,4)) // 81 console.log( Math.pow(5,2)) // 25

Infix  Operator Example

With Es7/Es2016, New operator introduced to handle exponential operator Infix operator ** is used for exponential The same syntax can be rewritten using new es7 syntax
console.log(3**4)) // 81
console.log( 5**2)) // 25

Exponential operator assignment example 

This can be also used as assignment expressions. Below is a code for usage of an assignment expression.
let value = 2
value **= 5
console.log(value === Math.pow(2,5)) // true
Read More

ES 6 features - New String methodsb| Learn Es6 tutorials

Es6 introduced new methods of a String object. In this blog post, I will cover the new string methods with examples
Newly introduced String methods can be generic and Unicode methods
Generic methods
  • startsWith()
  • endsWith()
  • includes()
  • repeat()

String.prototype.startsWith() method example

startsWith() method returns 
true - if the passed string with search string is matched from the starting index position, If index position is specified, It checks at the nth position 
false - search string is not matched
Syntax
startsWith(searchstring,index)
The two arguments are
1. String to search -  substring to be searched
2. Index position - It is a position on which search starts from. By default is zero
const message = "This is a new string methods";
console.log(message.startsWith("This is")); // true
console.log(message.startsWith("Thias is")); // false
console.log(message.startsWith("is", 4)); // false
console.log(message.startsWith("is", 5)); // true

String.prototype.endsWith() method example

endsWith() method also  take two arguments
This method returns true if string end is matched with other string
Syntax
endsWith(searchstring,index)
It has two arguments
1.Search string - string to search that matched from end
2. Index position - It is a position to match with string, this is optional
const message = "This is a new string methods";
console.log(message.endsWith("methods")); // true
console.log(message.endsWith("methodsa is")); // false
console.log(message.endsWith("is", 4)); // true
console.log(message.endsWith("is", 5)); // false

String.prototype.includes() method example

This return true if the search substring contains in a string
includes(searchstring,index)
It has two arguments
1.Search string - string to be matched with given string
2. Index position - It is starting position to begin searching the string, This is optional
const message = "this is tesing include";

console.log(message.includes("tesing")); // true
console.log(message.includes("adfadf")); // false
console.log(message.includes("is", 8)); // false
console.log(message.includes("is", 2)); // true

String.prototype.repeat() method example

This method repeats the given string for given number times.
It gives the output concatenate strings
str.repeat(count)
parameter - the number of times to repeat the string
const message = "cloud";
console.log(message.repeat(2)); // cloudcloud
console.log(message.repeat(3)); // cloudcloudcloud

Unicode methods

es6 introduced methods for dealing with Unicode strings.
Here are the methods for
String.fromCodePoint
String.prototype.codePointAt;
String.prototype.normalize;
Read More

ES 6 features - template String literals | Learn Es6 tutorials

In this post, I will document the es6 feature - template string literals with examples
Es6 introduced template literals feature. It is a syntactical change for string initialization

Prior to Es6 versions, Es5 Template Strings Example

The string is a group of characters/words enclosed in the single or double quote.
if you want to add variable inside a string, It is very difficult to add the string as string need to concatenate and add the variables
var name = 'Frank';
var message = 'Hello ' + name + ',  How are you doing?';
with this approach, String manipulations is a tedious task and possibility of error occurrence is more.
String literals are enclosed in either single quote or double quote
With Es6, Back-ticks are introduced for string literals for interpolation

Es6 Template String literals Example

The same code can be rewritten with a simple way using the back-ticks symbol
var name = 'Frank';
var message = `Hello ` + name + `,  How are you doing?`;
console.log(message); // Hello Frank,  How are you doing?

Template Literals Strings Introduction

Es6 declared strings and added domain specific syntax for interpolation, Expressions, Multi-line strings.
There are two types of template literals
Template Literals
These are string literals that allow string interpolation and multiple lines
Tagged template literals
These are functions calls which contain parameters passed via template strings

String interpolation Expression example

Below template string contains placeholder. Dollar symbol and curly braces are used for dynamically placing variable value. This is called interpolation
var m = 10;
var n = 4;
console.log(`Sum  is ${m + n}`)

Multiline String creation example

prior to ES6, we used to declare multi-line strings by appending line break
String msg="Template strings are introduced in es6.\n Developer friendly for declaring string literals"
With es6, We will rewrite the same as below
String msg=`Template strings are introduced in es6.
Developer friendly for declaring string literals`;
Just need to define a String literal with separate lien enclosed in back-tick (`....`) symbol.
The output is the same for both strings examples.

Tagged template string example

tagged templates allow you to call a function with template strings
The function has two arguments
The first argument is an array of values
the second argument is the remaining interpolation variable
Function returned the manipulated string as output
var name= 'Tom';
var salary = 5000;
function myfunction(stringsarray, nameExpression, salaryExpression) {
  var array0 = stringsarray[0]; // Employee
  var array1 = stringsarray[1];  // salary is 
  return `${array0}${nameExpression}${array1}${salaryExpression}`;
}
var result = myfunction`Employee ${ name } salary is  ${salary }`;
console.log(result);

Output of the above code execution is
Employee Tom salary is  5000

String raw() Method example

This is a static method used to get the raw string from the template string literals. So escape characters interpretation are ignored and return the same
Syntax
String.raw`templateString`
var str =`Temlate \n String ` 
console.log(str)  
var rawString = String.raw`Template \n String ` 
console.log(rawString)
var name = 'Frank';
var rawString1 = String.raw`Hi\n${name}, How are you doing?`;
console.log(rawString1); 
Output of the above code execution is
Temlate 
 String 
Template \n String 
Hi\nFrank, How are you doing?
The escape character is ignored for interpretation.interpolation expression will not be ignored.

























Read More