Tuesday, February 27, 2018

Java-8 Features

interface Formula {
    double calculate(int a);

    default double sqrt(int a) {
        return Math.sqrt(a);
    }
}

Formula formula = new Formula() {
    @Override
    public double calculate(int a) {
        return sqrt(a * 100);
    }
};

formula.calculate(100);     // 100.0
formula.sqrt(16);



List names = Arrays.asList("peter", "anna", "mike", "xenia");

Collections.sort(names, new Comparator() {
    @Override
    public int compare(String a, String b) {
        return b.compareTo(a);
    }
});

Collections.sort(names, (String a, String b) -> {
    return b.compareTo(a);
});

Collections.sort(names, (a, b) -> b.compareTo(a));



@FunctionalInterface
interface Converter {
    T convert(F from);
}
Converter converter = (from) -> Integer.valueOf(from);
Integer converted = converter.convert("123");
System.out.println(converted);    // 123


Converter converter = Integer::valueOf;
Integer converted = converter.convert("123");
System.out.println(converted);   // 123

class Something {
    String startsWith(String s) {
        return String.valueOf(s.charAt(0));
    }
}

Something something = new Something();
Converter converter = something::startsWith;
String converted = converter.convert("Java");
System.out.println(converted);    // "J"

class Person {
    String firstName;
    String lastName;

    Person() {}

    Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

interface PersonFactory
{
    P create(String firstName, String lastName);
}

PersonFactory personFactory = Person::new;
Person person = personFactory.create("Peter", "Parker")

http://winterbe.com/posts/2014/03/16/java-8-tutorial/


Java-8 Tutorial

   lambda expression is a function:

  (parameters) -> expression
or
    (parameters) -> { statements; }


1. (int x, int y) -> x + y                          // takes two integers and returns their sum

2. (x, y) -> x - y                                  // takes two numbers and returns their difference

3. () -> 42                                         // takes no values and returns 42

4. (String s) -> System.out.println(s)          
// takes a string, prints its value to the console, and returns nothing

5. x -> 2 * x                                       // takes a number and returns the result of doubling it

6. c -> { int s = c.size(); c.clear(); return s; }  // takes a collection, clears it, and returns its previous size

Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method 'compareTo' is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions.

IntOperation is  a functional interface since it contain single method.

interface IntOperation { int operate(int i); }

 IntOperation iop = x -> x * 2;  
  System.out.println(iop.operate(5));

 class Bar { int i; Foo foo = i -> i * 2; }; //member variable - leagal

   void bar() { int i; Foo foo = i -> i * 2; }; // local variable Illegal: variable i is already defined


UnaryOperator factorial = i -> i == 0 ? 1 : i * factorial.apply( i - 1 );


   Runnable r = () -> {System.out.println("Hello World");};
   new Thread(r).start();

Referance : (::)
1. static method referance (Type :: Method Name)
2.instant method referance (Type :: Method Name)
2. construtor method referance (Type :: New)


Method references are handles to such existing methods.

String::valueOf
Integer::compare

ReferenceType::Identifier

Constructor references are created using syntax similar to that for method references, but with the method name replaced with the keyword new

     List strList = Arrays.asList("1","2","3");
    List intList = strList.stream().map(Integer::new).collect(Collectors.toList());
         System.out.println(intList);


Default Methods ::

declare concrete methods in the form of default implementations.

public interface Sized {
        public default boolean isEmpty() {
            return size() == 0;
        }
        public int size();
    }

most specific default-providing interface is selected. 
 interface A{  public default boolean isEmpty() { return true;  }  }
 interface B{ public default boolean isEmpty() { return true;  }  }
 public class HelloWorld implements A,B-> //Compilation Error


  interface A { default void hello() { System.out.println("Hello World from A"); }}
     interface B extends A { default void hello() { System.out.println("Hello World from B"); } //Override Here - since its most specific  }
public class HelloWorld implements B,A{ No Compilation error // B will be printed

Diamond problem // - No Compilation Error
 interface A { default void m() {} ;}
    interface B extends A {}
    interface C extends A {}
    public class HelloWorld implements B,C{


 interface A { default void m() {} ;}
    interface B extends A { default void m() {} ; }
    interface C extends A { default void m() {} ; }
    public class HelloWorld implements B,C{  // Compilation Error


 interface A { default void m() {} ;}
    interface B extends A { }
    interface C extends A { default void m() {} ; }
    public class HelloWorld implements B,C{    //No Compilation Error


 interface A { default void m() {} ;}
    interface B extends A { default void m() {} ; }
    interface C extends A { }
    public class HelloWorld implements B,C{ // No - Compilation Error


 interface A {default void m() { System.out.println("hello from A"); } }
 IntStream.range(0, 5(Count)).forEach(i -> A.m());  // 5 times m method will be printed


void repeat(int count, Runnable action) {
    IntStream.range(0, count).forEach(i -> action.run());
}
repeat(3, () -> System.out.println("Hello!"));


List list = new ArrayList<>();
iterator.forEachRemaining(list::add);

A stream is a sequence of values. The package java.util.stream


filter Predicate T ➞ boolean Stream stream containing input elements that satisfy the Predicate

map Function T ➞ R Stream stream of values, the result of applying the Function to each input element

sorted Comparator (T, T) ➞ int Stream stream containing the input elements, sorted by the Comparator

limit, skip Stream stream including only (resp. skipping) first n input elements
sample eager/terminal operations

reduce BinaryOperator (T, T) ➞ T Optional result of reduction of input elements (if any) using supplied BinaryOperator

findFirst Predicate T ➞ boolean Optional first input element satisfying Predicate (if any)

forEach Consumer T ➞ void void void, but applies the method of supplied Consumer to every input element

Primitive Wrapper Classes are Immutable in Java

All primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.


// Java program to demonstrate that prmitive
// wrapper classes are immutable
class Demo
{
    public static void main(String[] args)
    {
        Integer i = new Integer(12);
        System.out.println(i);
        modify(i);
        System.out.println(i);
    }

    private static void modify(Integer i)
    {
        i = i + 1;
    }
}


Output :

12
12


Functional programming






Difference between Design Pattern and Design Principle

Object Oriented Principle:
Single Responsiblity Principle
Open/Closed Principle
Dependancy Principle
Interface Segregation Principle


OO principle is a set of guidelines that ensures OOP concept. Based on the OOP concept, this defines ways to design better way, a better design. The basic OO design principle is SOLID.

A Design pattern provides a general solution to a design problem. Please note “design pattern” can be applied to noon object oriented word too. So A OO design patterns (OODPs) are those which provide a general solution to object oriented design based OO principle. Design patterns are discovered, not invented. There are several ways to define OODPs and most famous one is BSC [Behavioral Structural Creational].


Design Principle = SOLID (i.e. Dependency Inversion Principle)
Design Pattern = Gof (i.e. Abstract Factory Pattern)

Patterns are common solutions to object-oriented programming problems.
Actually patterns based on principles

*Design Principle : * Software design principles represent a set of guidelines that help us to avoid having a bad design. like: Open Close Principle

*Design Pattern : * a Design Pattern is a general reusable solution to a commonly occurring problem within a given context in software design. Like: Singleton

Principles are rules while patterns are their concrete examples



Functional Programming vs Impeaitive Programming

In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

In contrast, imperative programming changes state with commands in the source code,

Functional Programming in Javascript










Functional Programming vs Object Oriented Programming


how to avoid mutation in javascript



Sunday, February 25, 2018

SQL Cheet Sheet


Regex Cheet Sheet


Maven Cheet Sheet


JVM Cheet Sheet


Junit Cheet Sheet


Git Cheet Sheet


Java-8 Cheet Sheet


Generics Cheet Sheet


Docker Sheet Sheet


Collections Cheet Sheet


Java-9 Features

The Java SE 9 feature release includes both enhancements in Java SE 9 API or Technology aditions and changes in JDK 9. A Java Programmer interested in Oracle Certified Associate, Java SE 9 Programmer (OCAJP 9) and Oracle Certified Professional, Java SE 9 Programmer (OCPJP 8) Java 9 Certifications must know the following features and enhancements.
Keep watching MyExamCloud Java Certification page about latest books, mock exams, practice tests for Java 9 OCAJP and OCPJP Certifications.
Java 9 is an amazing new version of Java. This object-oriented programming language is still number one among others and you need to get more improvements from time to time. These improvements will allow you to take your apps to the next level right away. We will talk a little about Java 9 and what this new version of Java has in store for you. We will let you know about Java 9 module system, REPL which is used to test Java Constructs, Try with resources improvements, Process API changes, Factory methods in collections, Stream API changes, and much more. So read on if you want to know more.

Java 9 Module System

Oracle realized that Monolithic Jars had a lot of limitations when it comes to developing Java-based apps. So, the tech titan has developed something called Module System to solve this issue right away. You will also find 92 modules in the JDK 9 but this might also turn out to be different in the final release.
Example:
module com.myexamcloud.test {}
module com.myexamcloud.user {}
module com.myexamcloud.admin {}
module com.myexamcloud.mentor {}
module com.myexamcloud.author {}
module com.myexamcloud.affiliate {}

Try With Resources Improvement

Java SE 7 used a construct to handle exception called Try-With-Resources and this exception managed resources in an automatic fashion. Oracle wanted to improve the readability and verbosity to this methods in the new version of Java. You can also find many tutorials online to find out more about this.
Before Java 9
1.
void methodBeforeJava9() throws IOException {
2.
BufferedReader myReader1 = new BufferedReader(new FileReader(“customers.txt”));
3.
try (BufferedReader myReader2 = myReader1) {
4.
System.out.println(myReader2.readLine());
5.
}
6.}
After Java 9
1.
void methodAfterJava9() throws IOException {
2.
BufferedReader myReader1 = new BufferedReader(new FileReader(“customers.txt”));
3.
try (myReader1) {
4.
System.out.println(reader1.readLine());
5.
}
6.}

Java 9 REPL

The Java 9 REPL is a very useful feature in the latest version of Java you can use to test and execute Java Constructs. And you will do this very easily. You can also download this features from Oracle`s website.
>jshell
|  Welcome to JShell — Version 9-ea
|  For an introduction type: /help intro
jshell> int num = 100
num ==> 100
jshell> System.out.println(“num value = ” + num )
num value = 100

Process API Improvements

Process API is coming with many improvements. You will find it easier to manage and control any OS process thanks to some new methods and classes that Oracle has added up here. You can also find some tutorial online that will allow you to learn more about this interesting part of this.
Example:
ProcessHandle currentProcess = ProcessHandle.current();
System.out.println(” Process Id: = “ + currentProcess.getPid());

Factory Methods for Map, Map.Entry, Immutable List, and Set

You can now use many factory methods to quickly create any kind of Set, Map.Entry objects, Set, and Immutable List. You will use these utility methods to create non-empty or empty Collection objects. Oracle used a verbose and tedious approach in the famous Collections.unmodifiableXXX methods. But now you will see that Oracle has overcome these shortcomings by adding up some utility methods to Map, Set and List interfaces.
List emptyTestList = List.of();
List testList = List.of(“Java 8”,“Java 7”,“Java 9”);
Map emptyMap = Map.of();
Map myMap = Map.of(1, “Java”, 2, “C++”, 3, “Python”);

Private methods in Interfaces

Oracle has been concerned about the re-usability features and redundant code in Java 8, and they have solved the problem in Java SE 9 by introducing private methods in the new interfaces.
1.
public interface Customer {
2.
private Double currentBalance() {
3.
// Method implementation goes here.
4.
}
5.
private static void displayCustomerInfo() {
6.
// Method implementation goes here.
7.
}
8.}

Stream API Improvements

You will also find out that Oracle has added 4 methods to the important java.util.Stream interface. These are also default methods because Steam is just an interface. dropWhile and takeWhile are two of the most important methods that you will find here. You should now a lot of about these methods if you have to deal with any Functions programming language.
Stream.of(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
.takeWhile(i -> i < 10)
.forEach(System.out::println);

Reactive Streams

You will use the Reactive Streams API in this new Java SE 9 because Oracle has included it here. You will be using the Java language to implement Parallel, Asynchronous, and Scalable applications. Reactive programing is truly an important approach to develop many applications today because they offer a lot of beautiful benefits.
Following APIs are introduced in Java SE 9 to develop Reactive Streams.
java.util.concurrent.Flow.Processor
java.util.concurrent.Flow.Publisher
java.util.concurrent.Flow.Subscriber
java.util.concurrent.Flow

CompletableFuture API Improvements

You will see that CompletableFuture API has many improvements that will allow you to solve many problems right away. You will enjoy better sub-classing and some utility methods. You will be using delayedExecutor() to return an important new Executor so that you can submit a task to the important default executor.
Executor exe = CompletableFuture.delayedExecutor(20L, TimeUnit.SECONDS);

Diamond Operator for the Anonymous Inner Class

Oracle has removed a lot of limitations in the use of the famous Diamond operator with the important Anonymous Inner Class. They have done this in the Java 9 and you will truly reap the benefits in no time.
1.
public List getCustomer(String id) {
2.
// Code to get Customer details
3.
return new List(customer) {};
4.}
Here we are using just “List” without specifying the type parameter.

Optional Class Improvements

The java.util.Optional class has many useful new methods that you will love using right away. You can use any stream() to work on any Optional object here. If you have a value in the Optional object, you can use a stream() method to return an important sequential Stream with this value.
Stream cust = getCustomer(id)
Stream custStream = cust.flatMap(Optional::stream)

Enhanced @Deprecated annotation

Oracle has enhanced the important @Deprecated annotation so that you can get more information on deprecated API. You will also manage to analyze data about static usage by using a tool to do this with deprecated APIs. Since and ForRemoval are the two methods added to serve this information.

Multi-Resolution Image API

Oracle has worked hard to release the important multi-Resolution Image API. T here is an important interface in this API which is called MultiResolutionImage. You will manage to encapsulate a lot of images with different widths and heights in this interface over time.

HTTP 2 Client

Oracle released HTTP 2 Client API to support both WebSocket features and HTTP/2 protocol. HTTP client will replace the famous HttpURLConnection API right away. Oracle will work hard to release the famous HTTP 2 Client API right under “java.net.http” package. It will give you the support you need for both HTTP/2 and HTTP/1.1 protocols.

Other miscellaneous Java 9 Features

You can also use many APIs in Java 9 including the important Stack-walking API. You will get access to a lot of stack trace information when you harness the power of this API right away.

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...