Angular 5.0 New things

Angular team has released Angular 5.0 on 1st Nov 2017.

They focused on most new features and bug fixes. This release continues our focus on making Angular smaller, faster, and easier to use.

Following things are New:

Angular CLI 1.5 and Angular 5.0.0

Now we are in CLI 1.5, if you install CLI 5.0, automatically you will get the angular 5.0 versions default in your package.json file in angular app.

 Typescript updated  to 2.4

Dynamic import expressions are a new feature and part of ECMAScript that allows users to asynchronously request a module at any arbitrary point in your program.

RXJS was updated to 5.5 version:

This recent release of RxJS fully empowers developers to avoid the side effects of the

previous import mechanism with a new way of using RxJS called “lettable operators”.

These new operators eliminate the side effects and the code splitting .

Tree shaking problems that existed with the previous ‘patch’ method of importing operators.

instead of :

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/filter';

names = allUserData

.map(user =>

.filter(name => name);

user below like this:

import { Observable } from 'rxjs/Observable';

import { map, filter } from 'rxjs/operators';

names = allUserData.pipe(

map(user =>,

filter(name => name),


Buid optimizes.,Bundle size reduced, Speed the app

Ahead -of -time compiler

Converts your angular code before browser downloads and run it

Aot:  faster rendering . few async reauests, smaller download

watch mode files ngc –watch. This command will watch your file what are the file executing

Easier to build progressvie web apps

The build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decreases the size of your JavaScript bundles, and increases the boot speed of your application for your users.

Their goal is to make this angular default option for most developers

->service workers

->small, easier and more powerfull

->Http client module feature added.  from

import { HttpClientModule } from '@angular/common/http';

removed map(res=> res.jon()) calls which no longer needed with http client module.

depreacted http in 5.0 version,  for now you can use http in 5.0 but its depreacted. In future they may removed from angular 5.0

Angular Form validation

They added some new feature on forms.

angular 4 form validates the form when we entered the characters.

but in angular 5 they inclueded validation on blur and submit

validation and value updates on `blur` or on `submit`, instead of on every input event

Template Driven Forms


<input name="firstName" ngModel>


<input name="firstName" ngModel [ngModelOptions]={updateOn: 'blur'}>


Validations will be done on submit.

Or you can add for each individual with ngModel options

<input name ="firstName" ngModel[ngModelOptions]={updateOn: 'blur'}>

Or simply you can use the reactive forms

Reactive Forms


new FormGroup(value);

new FormControl(value, [], [myValidator])


new FormGroup(value, {updateOn: 'blur'}));

new FormControl(value, {updateOn: 'blur', asyncValidators: [myValidator]})

Changes with pipes

DepreactedI 18 Npipes module

old pipes will depreacted but you can use now. In future they may removed from angular 5.0

Increase standardization across browsers

Internationalized Number, Date & Currency

Router Life cycle Events:

New lifecycle events to the router, allowing developers to track the cycle of the router from the start

of running guards through to completion of activation. These events could be used for things such as showing a spinner on a specific router outlet when a child is updating or to measure performance of guards and/or resolvers. Allow develpers to track the routing cycle used to do things like show spinners, measures performance of guards

GuardsCheckStart, ChildActivationStart, ActivationStart, GuardsCheckEnd, ResolveStart, Resolve End,

ActivatonEnd, ChildActivationEnd

An example of using these events to start/stop a spinner might look like this:

class MyComponent {

constructor(public router: Router, spinner: Spinner) { => {

if (e instanceof ChildActivationStart) {


} else if (e instanceof ChildActivationEnd) {






Angular Universal State Transfer API and DOM Support

Easily share application state between the server side and client side versions of your application.

And helping developers to perform  server side rendering (SSR) of Angular applications.

By rendering your Angular applications on the server and then bootstrapping on top of the generated HTML, you can add support for scrapers and crawlers that don’t

Support JavaScript, and you can increase the perceived performance of your application.

In 5.0.0, the team has added ServerTransferStateModule and the corresponding BrowserTransferStateModule. This module allows you to generate information as part of your rendering with platform-server, and then transfer it to the client side so that this information does not need to be regenerated

This means when you fetch the data over http, by transfer data from there server, this means developers no need to make 2nd HTTP request

It supported more DOM manipulations out of the box within server side contexts, improving our support for 3rd party JS and Component libraries that aren’t server-side aware

Improvements on compiler:

They improved compiler to supports incremental compilation. Its provide faster rebuilds,

It builds with AOT, and added new feature to Decorators. And made it possible to smaller bundles

By remove the whitespaces.

Typescript Transforms

Typescript transform, making incremental rebuilds dramatically faster

You can take advantage of this by running ng serve with the AOT flag turned on.

You can take advantage of this by running ng serve with the AOT flag turned on.

ng serve –aot

This will become the default in a future release of the CLI

On this transforms, we don’t need a genDir anymore, and outDir has been changed: we are now always emitting generated files for packages in node_modules.

Preserve Whitespace

Tabs, newlines, and spaces in your templates are recreated and included in the build by the compiler.

You can now choose whether or not to preserve whitespace coming from your components and your application.
1) You can specify this as part of each component’s decorator, where it currently defaults to true.


templateUrl: 'about.component.html',

preserveWhitespaces: false


export class AboutComponent {}

2) specify in tsconfig.json file also: by default its true.

"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "es2015",
"types": []
"angularCompilerOptions": {
"preserveWhitespaces": false
"exclude": [

Decorator Support :

Expression lowering in decorators for lambdas and the value of useValue, useFactory and data in object literals. This allows you to use values that can only be calculated at runtime in decorators for expressions that are lowered.

You can now use a lambda instead of a named function, meaning you can execute code without affecting your d.ts or your public API.


provider: [{provide: SOME_TOKEN, useFactory: () => null}]


export class MyClass {}

-> lower expressions as part of useValue.


provider: [{provide: SOME_TOKEN, useValue: SomeEnum.OK}]


export class MyClass {}

Replace the ReflectiveInjector with StaticInjector

In order to remove even more polyfills, we’ve replaced the ReflectiveInjector with the StaticInjector.

This injector no longer requires the Reflect polyfill, reducing application size for most developers.





Please refer angular blog for more info:

update to angular 5.0 from this below site

If you want to update your angular app to 5.0, just go to below website and give your current version in the fields.

Categories: Angular

Java – HashMap in-detail explanation

HashMap works based on hashing algorithm, As per Java doc HashMap has below four constructors,

Constructor Description
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
HashMap​(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).
HashMap​(int initialCapacity,
float loadFactor)
Constructs an empty HashMap with the specified initial capacity and load factor.
HashMap​(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the specified Map.

Let’s write simple java program, to examine how Map works internally

  1. Create a simple Map and add one key and value to it

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");


We just created Simple Map, which takes key as Integer and Value as String, and added “1” as Key and “Java” as value. By using eclipse debug feature, lets see what’s inside the map


It created 16 blocks(0-15) and inserted 1st block with key as Integer “1” and Value as String “Java”. Please check the red box, rest all boxes initialized with  null.

2. Add second key and value to the same map

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");

map.put(2, "Angular");


lets see the map in eclipse debug again


Now the map contains two keys (1,2) and two values (“Java”, “Angular”) as expected, but the keys are added exactly at 1st block and 2nd block respectively, why?

because as we know Map works based on hashing algorithm, whenever we insert key to map, it calls the Object#hashcode() method, based on the value of hashCode(), it will insert the key into that block.

In above case, Integer class overrides the hashCode with its primitive int value, thats why (1,java) got stored in 1st block and (2,Angular) got store in 2nd block.

3. Lets do the same experiment with our own Class

Create a simple Employee class like below

private static class Employee{
int id;
String name;

Employee(int id, String name){ = id; = name;

Use this class as Key to the map and examine the same way

public static void main(String[] args) {
Map<Employee, String> map = new HashMap<>(10);
map.put(new Employee(1, "Ramesh"), "Java");
map.put(new Employee(2, "Sathish"), "Angular");

We have added two keys as Employee objects and Values as just strings, lets see in which block the keys got stored this time


This time, it stored in 8th block and 14th block(why? simple answer because of hashCode of Employee objects), to confirm this, lets override hashCode() of Employee to constant value and check the map. If our analysis correct it has to store all the key’s in the same block.

Update Employee class accordingly

private static class Employee{
int id;
String name;
Employee(int id, String name){ = id; = name;
public int hashCode() {
return 10;

We dont need to change anything to our map, lets see now where the keys got stored


Yes, only 10th block got filled with two objects, why? because both employee objects returned the same hashCode (i.e 10). But how does Map recognized those two objects are not duplicate? As we know internally Map#Key is an entrySet(java.util.Set) it called equals method to verify whether the key is duplicate or not.

While retrieving the value from Map also, first it will check the hashCode of the given key and based on that it will go to that block, after finding the block it will call equals() to get the exact value.

So overriding the hashCode() to constant is not at all recommendable. and when we override the hashCode() we should not forget to override the equals() method as well(i.e hashCode()/equals() contract).



Categories: Java

Angular 4: Service example

Welcome to Angular 4 services

Angular services are for building out code that can be shared across multiple components. And these are singletons. services restrict the instantiation of a class to one object. It means the methods and properties can be shared throughout your application from a single shared instance.

These services are best way to store the session data and perfect place to call the web services. And the data is shared to the components with the injecting service. Without hitting the web services we can use the session data in the application. But If you refresh the browser the session service data will be empty. So remember that condition.

In this tutorial, we provide a basic angular 4 service example using the Angular CLI.

We’ll be using the Angular CLI to create our app. Create a new Angular project by running:

ng new AngularServiceEx

This will create the new project named as AngularServiceEx project.

And navigate to root application by cd  AngularServiceEx. And run the below command

npm install

This command will download all your dependencies from your package.json file.

And run the below command to create the service in the project.

ng g service reference

It will create the reference.service in the ’app’ folder automatically. We don’t need to do anything.  It will create the two files in our Angular app

  • a reference.service.tsfile under the src/app directory
  • a reference.service.spec.tsfile under the src/app directory

We will write the service code in the service.ts file.  And service.spec.ts file will used for unit testing.

The ng g service command won’t automatically configure your root module app.module.ts to provide the service.

Services must import the Injectable from the angular/core package, like below. see the angular. io website for more info on services.

import { Injectable } from ‘@angular/core’; 

And services uses the  injectable decorator. @Injectable() . The @Injectable decorator simply provides dependency injection for the service.

Don’t forget to add the decorator in the service.ts file. If we don’t add it will not work.

Service must have the export keyword.  Everything like class or component should use ‘export’  keyword. Then only it is possible to use the class or component or anything in the project. And service name should end with .service.  For ex:  reference.service.ts file. If we have lengthy name we need add the ‘–‘ in the service name. That is for code readability.

Example: save-user-info.service.ts

Service structure:

 import { Injectable } from '@angular/core';


export class ReferenceService {

constructor() {  console.log(“welcome! Reference Service”);  }


To include the service in your app, you must import it and include it as a provider in app.module.ts or we can add the service in providers of component meta data also. But it will be available in the particular component only. But it’s better to use the service in the providers of app.module.ts. Service will create the instance every time, whenever you come to the component.  By registering the service as a provider, you make it available everywhere in the application.


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReferenceService } from './reference.service'

declarations: [ AppComponent ],
imports: [ BrowserModule ],
providers: [ReferenceService],
bootstrap: [AppComponent]

export class AppModule { }

Accessing the Service from a component:


Services must be imported by the component. We will import our reference service in open the auto-generated app.component.ts and replace it with the following:

import { Component } from '@angular/core';
import { ReferenceService } from './reference.service'

selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']

export class AppComponent {
constructor(public reference: ReferenceService){


Service with HTTP methods :

We will have to interact with Database to get the data and post the data. For that we will write the web service api in the Angular services. We will have to call the HTTP POST or HTTP GET methods with REST API in the service to store that data in the DATABASE or retrieve the data from the DATABASE.

Let’s see the Example with real Json file:

We will use the Reference Service. And we will write the http method in the reference service. That http method should be called in the component methods to get the data or post the data to the REST side. For now will go through with angular services with Json file.Will add one json file in the project. In the angular every request and response will be in the Json  only. You need to add the json file in the assets folder under src folder of your project. You may get 404 json file not found, if you add the json file somewhere other than assets location folder.

Json file:

Created the json folder in the assets folder in ‘src/assets’. See example json data.


{ “id”: 10, "firstName": "Sathish" , "lastName": "Kotha" },

{ “id”: 11, "firstName": "Ramesh", "lastName": "Kotha" },

{ “id”: 12, "firstName": "Ragav" , "lastName": "Raju" }


Employee class:

We need to create the Employee model class. It’s a type of json data, remember every where we need export the class. This model class is a typescript format. Type the below command.

ng g class Employee

This will create the Employee model class in the app folder.

typically you declare types in a model which can then be reused throughout the rest of the application. With TypeScript, frontend applications can now benefit from strongly typed models!

This is pretty straightforward for declaring individual variables,

A simple example of this is a Employee class that defines a firstName and lastName variables that’s are string and an id variable that must be a number:

export class Employee  {

id: number;

firstName: string;

lastName: string;



In the service, we will  import the Http from “@angular/http”; with http we will use the http get the post and request methods. To get the all the methods we need to include the http in the constructor. for more info on http please refer

And import some rxjs. These are reactive extension java script. Rxjs is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or in the server-side using Node.js. We will use some methods from the Rxjs in angular services like map and observable and catch. We will use these in the services.

Don’t instantiated the service with new keyword, it will create error prone and memory leak.

import { Injectable } from '@angular/core';

import { Http } from '@angular/http';

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/catch';

import { Observable } from 'rxjs/Observable';

import { Employee } from './employee';


export class ReferenceService {

constructor(private http: Http) { }

getAllEmployees(): Observable< Employee[] > {

try {

return this.http.get(‘assets/service.json') .map(this.extractdata).catch(this.handleerror) ;

// Api Full path like, http://localhost:4200/assets/service.json

}   catch (error) { console.log(error); }  }

extractData(res: Response) {

const body = res.json();

return body || {};   }

handleError(error: any) { return Observable.throw(error); }

In the above service  http reference is used to call the http methods. We created one method is get all employees, we are calling http.get method with json link. This get method will get the json data. Then it will come to  map method, it is used to extract the JSON content from the response coming as the observable type. if you got any error while calling the http method it will come to catch method,from there it will directly throw the error with observable throw method.


Import the reference service in the component as below and one more thing we need the ngOn Init life cycle method. Every component has to implement the ngOnInit method. And this method will call after the constructor. It’s used like a main method. When you come to component, ng On Init method will call, you can call any number of methods in the ngOnInit method.

import { Component, OnInit } from '@angular/core';

import { ReferenceService } from './reference.service';

import { Employee } from './employee';


selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']  })

export class AppComponent implements OnInit  {

title = 'Angular Service app';

employeesInfo: any;

constructor(public referService: ReferenceService) { }

getAllEmployeesInfo() {

this.referService.getAllEmployees() .subscribe((result: Employee[]) => {

console.log('the employess data:' + result);

this.employeesInfo = result;      },

(error: any) => {  console.log('error in employees method');      });   }

ngOnInit() {  this. getAllEmployeesInfo();  }


In above component, service method is called in component method getAllEmployeesInfo with reference service http method. And when we got the output it will come to subscribe result.  There we are assigning the result to our variables. If we get any error when calling the api it will come to error block. This error will return from catch of Observable  throw error.


<h1 style="text-align: center">  Welcome to {{title}}!</h1>
<h3  style="text-align: center">ALL employeesInfo here</h3>
<div style="text-align: center;">
<div *ngFor="let emp of employeesInfo">
<b>Emp ID</b> {{}}

<b>  First Name is :</b> {{emp.firstName}}

<b>Last Name is :</b> {{emp.lastName}}</div>

Above html we are using title in curly brackets. It’s a two way bindings. Whatever we add it automatically convert the value. And one more new word is “*ngFor” structural directives. This is used to iterate the json data in the html. We have the multiple employes the data in the “ employessInfo”  variable. So we need to include the ng for here to iterate the data in the html. We add the reference value in the ng for. With that will call the inside object data.

Service used in the Module:

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

import { ReferenceService } from './services/reference.service';


declarations: [ AppComponent ],

imports: [ BrowserModule, HttpModule ],

providers: [ReferenceService],

bootstrap: [AppComponent] })

export class AppModule { }

Above app.module we have imported reference service and app component , All components should be added in the declarations field. And service should go to provides. Httmodule is also imported to imports. And last app component will be added in the bootstrap , bootstrap will added to project from here

if you don’t add the service in the providers you will get following error. One more thing we need to add the http module in the app module imports. Don’t add the http in the imports. If you don’t include. You will get below error.

EXCEPTION: No provider for service!

Clone the repository and install all it’s dependencies:

# Clone repo

git clone

# Enter into directory

cd AngularServiceEx

# Install dependencies

npm install

Categories: Angular

Java9 : ServiceLoader

java.util.ServiceLoader class loads the service providers/implementations at run time. While compile time ServiceLoader just need to know Service interface. With the Java9 modularity, we can add service implementation modules dynamically at run time, And Application can have new implementation with out effecting anything,

lets check with an example, create a module EventsAPI with an interface


package events.api;

public interface EventService {
 public String getName();


module events.api {
 exports events.api;

Create an implementation to the EventService interface in another module called FacebookEvents


package events.api.facebook;
import events.api.EventService;

public class FacebookEventService implements EventService{

 public FacebookEventService() {
     System.out.println("FacebookEventService Constructor");
 public String getName() {
    return "facebook events";



module events.api.facebook {
 requires events.api;

 provides events.api.EventService
 with events.api.facebook.FacebookEventService;


FacebookEvents module requires EventsAPI, because it need to have access to interface.

And it provides EventService implementation with FacebookEventService.

Lets create a Client module EventsClient to consume EventsAPI



module client.calendar {
requires events.api;
uses events.api.EventService;

We are going to use ServiceLoader to find the implementations of EventService interface, here ServiceLoader requires uses keyword on EventService, otherwise compiler will throw an error.

Finally Client Test class


package client.calendar;
import java.util.ServiceLoader;
import events.api.EventService;

public class Calendar {
public static void main(String[] args) {
System.out.println("Calendar events..!!!");
ServiceLoader<EventService> events = ServiceLoader.load(EventService.class);

for(EventService event : events) {
System.out.println(event.hashCode() + " : " +event.getName());
for(EventService event : events) {
System.out.println(event.hashCode() + " : " +event.getName());

In the EventsClient module, we din’t mention anything about FacebookEvents module, while running the above add FacebookEvents module, the output will be


Calendar events..!!!
FacebookEventService Constructor
1627960023 : facebook events
FacebookEventService Constructor
745160567 : facebook events

ServiceLoader found the EventService implementation FacebookEventService and showed the output, lets add another implementation to the EventService interface and examine the output from above client


module events.api.twitter {
requires events.api;
provides events.api.EventService
with events.api.twitter.TwitterEventService;

same as FacebookEventService, will have TwitterEventService which will implement EventService interface


package events.api.twitter;

import events.api.EventService;

public class TwitterEventService implements EventService{

public TwitterEventService() {
System.out.println("TwitterEventService Constructor");

public String getName() {
return "twitter events";

Run the EventsClient/ by adding TwitterEvents module on the modulepath, output as follows

Calendar events..!!!
TwitterEventService Constructor
249515771 : twitter events
FacebookEventService Constructor
1627960023 : facebook events
TwitterEventService Constructor
321142942 : twitter events
FacebookEventService Constructor
745160567 : facebook events

We have just added TwitterEvents module in the run time, ServiceLoader is able to load the TwitterEventService and gave the desired output.

Source code is available at

Thanks for reading..!!

Categories: Java, Java9

Angular 4: Component Example

Welcome to the new concept of components in angular 4.

Definition: component is a angular class , Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components.

Components always have a template and only one component can be instantiated per an element in a template.
A component must belong to an NgModule in order for it to be usable by another component or application. To specify that a component is a member of an NgModule, you should list it in the declarations field of that NgModule In app.module file.

we can create the component by using this command.

ng g component ‘component name’

this command will create the component ts file and html and spec.ts and css files with your component name. no need to create the component manually.


First We need to import the angular Component class from the Angular package: @angular/core

import { Component } from '@angular/core'; 

we will use this component with the component decorator @component

Component decorator must have the selector and template. if you don’t add these fields component will not valid. because Angular uses the selector to show the html content in the app. You will find the selectors in the chrome console Elements. This selectors will add dynamically to the DOM when your change the routers. The component should have less than 400 lines of code.

Selector : css selector that identifies this component in a template. means we can use the html templates with selector in the application. another advantage is we can use the selector  tag any where in the application to show the content of template html, its one of the best feature in Angular.

 selector: ‘app’,

Template:  inline-defined template for the view. Means it’s the html code, we can write html code in the template, or we can directly give the html src by giving the template url. If we have less html code its easy to add the html content in the template. no need to create another external html file.

 template: `{{title}}`,

TemplateUrl:  Template url is the external file containing a html template for the view. If we have multiple lines of  html content, its better to keep one html file. we can give the html url path in the ‘templateUrl’ field.

templateUrl: ‘./app.component.html’,

Same for styles: css styles we can add two ways by adding styles, styleUrls fields. we should write the styles in the brackets [], it is style guide.

Style:  Inline-defined styles to be applied to this component’s view means whatever we write the styles in the component, that css styles applied to html content in template or template Url. If we have less content of styles, we can add the styles in the styles filed.

styles: [‘h1 { font-weight: normal; }’]

styleUrls: list of urls to stylesheets to be applied to this component’s view. If we have multiple styles ,its better to keep the external css files

styleUrls: [‘./app.component.css ]

Component Structure:

import { Component } from '@angular/core';
selector: 'app',
template: 'Hello

styles: [‘h4 { font-weight: normal; }’]
export class welcome { title: string = 'World'; }

Here component class must add export. then only it will available in the project. we need to add ‘export’ keyword before the component class


Every Angular app has at least one NgModule class, the root module, conventionally named AppModule. Angular apps are modular and Angular has its own modularity system called NgModules. We will add the components in the ‘declarations’ of this module file.

Import statement  for the module:

import { NgModule } from '@angular/core';

NgModule is a decorator to use the ng module.

most important properties are:

  • declarations the view classes that belong to this module.All component class names  must add in the declarations.  Angular has three kinds of view classes: componentsdirectives, and pipes.
  • exports the subset of declarations that should be visible and usable in the component templates of other modules.
  • imports other modules whose exported classes are needed by component templates declared. We must add the the modules in the ‘imports’ field. whatever we use the modules, that should be place in the imports.
  • providers creators of services that this module contributes to the global collection of services; they become accessible in all parts of the app. These providers are for services. whatever you have services , that services should be add in the provider field. providers will tell to angular how to inject a service.

bootstrap – the main application view, called the root component, that hosts all other app views. Only the root module should set this bootstrap property.

Module  Structure:

import { NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
imports: [ BrowserModule ],
providers: [ Logger ],
declarations: [ AppComponent ],
exports: [ AppComponent ],
bootstrap: [ AppComponent ]

export class AppModule { }

The module declares some objects to be public by marking them with the export key word.


Launch an application by bootstrapping its root module. During development you’re likely to bootstrap the AppModule in a main.ts file like this one

import { platformBrowserDynamic } from '@angular/platform-browser';
import { AppModule } from './app/app.module';

Source code present in the Github 

Categories: Angular

Java9: Welcome to Module world

Java 9 has been released on September 21 officially, Eclipse is supporting Java 9 from  Eclipse Oxygen.1a (4.7.1a), Lets jump into module world..!!!

Download Java 9 from here, and add it to Eclipse Installed JRE’s as below

Eclipse - JRE

That’s it, we are good to write Java 9 module programs in Eclipse.

  1. Create First java project and add to it, right click on the project java9-module-info

module first {


Module should start with keyword module followed by its name. currently it doesn’t requires anything or it doesn’t export anything.

2. Let’s create Second java project,

module second {
exports second; --<em> second module is exporting a package "second"</em>
} — create a simple Java class with public sayHello() method in second package

package second;

public class Second {
public void sayHello() {
System.out.println("Welcome to module world..!!");

Second java class will be available to other modules, as it is exporting second package.

3. Update first module – as below

module first {
requires second;

Now first module requires second module, but it will fail with module can not be resolved compilation error

“second cannot be resolved to a module”

we need to add second module as dependency to first module.


Check the new thing called modulepath

3. Create in first package as below

package first;

import second.Second; // we are accessing from second module

public class FirstTest {

public static void main(String[] args) {
Second second = new Second();

Running the above would print “Welcome to module world..!!

source code can be found at Github

Categories: Java, Java9

Angular 4: Set up

Angular 4: Set Up

Welcome to Angular Family, It is one of the most power full and faster framework developed by Google. One of its feature is Single Page Application(SPA), It has only one index.html in entire application, Whatever we use all other htmls will include in main index.html. As it is Single Page Application, there is no browser reload. We will get know all the things in the later sections.

Now we will proceed with the installation of angular 4, We will see the basic angular 4 program in Type script.

Angular 4 installation:

Install Node.js

First we need to install the node.js to get access of npm commands.

i) Download it from this site –

ii) Setup node.js exe file with ‘npm package manager’. After installation done,
Verify that you are running node v4.x.x or higher and npm 3.x.x or higher by running the commands node -v and npm -v in a terminal/console window. Other below node versions will produce errors.

iii) Download the visual studio for better writing angular code from below website.

Install the Angular CLI Globally.

You need to install the angular cli(command line interface) to use the ng command. It will use to create the angular project.

1)Creating a Angular Project

Open a terminal window. Generate a new project by running the below command:

It takes some time to create the project. after creating the project, you need to download the npm packages in your project. Just type cd AngularApp to goto your project location
And type below command to download the dependencies of your package.json file.

you will see the node-modules folder above src folder of your project.

2) Serve the application

Just type the below command in your terminal to launch the server.

The ng serve command launches the server, watches your files, and rebuilds the app as you make changes to those files.

Using the –open (or just -o) option will automatically open your browser on


Your app greets you with a message:

app works!

Your project structure.

Out put:



Categories: Angular Tags:

Java 8 : Predicate example

March 23, 2014 1 comment

Java 8 introduces functional style of programming.

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

Here we have list with integers, if we want to print even numbers from it, will write something like below

public List<Integer> printEvenNumbers(List<Integer> list){

List<Integer> result = new ArrayList<Integer>();

for(Integer i : list){

if(i%2 == 0){




return result;


Now if we want to print odd numbers, so will write something like below

public List<Integer> printOddNumbers(List<Integer> list){

List<Integer> result = new ArrayList<Integer>();

for(Integer i : list){

if(i%2 != 0){




return result;


Except the if condition, everything is copy pasted. Again if we want the numbers only divisible by 3, again we have to copy paste entire code just by changing the if condition.

If we have a chance to pass the if condition as a argument to method, then we would have achieved both requirements with only one method, for this java 8 introduced an interface called java.util.function.Predicate<T>

Complete example:

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateTest{

public static void main(String [] a)  {

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

System.out.println("Print all numbers:");
condition(list, (n)->true);

System.out.println("Print no numbers:");
condition(list, (n)->false);

System.out.println("Print even numbers:");
condition(list, (n)-> n%2 == 0 );

System.out.println("Print odd numbers:");
condition(list, (n)-> n%2 == 1 );

System.out.println("Print numbers greater than 5:");
condition(list, (n)-> n > 5 );


public static void condition(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list)  {
if(predicate.test(n)) {
System.out.println(n + " ");

Categories: Java

Java 8 : Double Colon operator

March 17, 2014 2 comments

Double Colon operator introduced in Java 8, We use it as method reference.

Syntax : ClassName::MethodName

for example, if we want to print a list :

List<String> strings = Arrays.asList("one","two");


here forEach is a new method added to the List interface in java 8. System.out is the PrintStream Class and println is method in it.

Complete Example:

import java.util.*;

public class DoubleColon{

public static void display(String name){
System.out.println("Name : "+name);
public static void main(String[] args){
List<String> names = Arrays.asList("one","two","three");

Categories: Java

Java 8 : Functional Interface Example

March 16, 2014 11 comments

To Support lambda expressions in Java 8, they introduced Functional Interfaces.

An interface which has Single Abstract Method can be called as Functional Interface.

Runnable, Comparator,Cloneable are some of the examples for Functional Interface. We can implement these Functional Interfaces by using Lambda expression.

For example:

Thread t =new Thread(new Runnable(){
   public void run(){
     System.out.println("Runnable implemented by using Lambda Expression");

This is the old way of creating a Thread.

As Runnable is having Single Abstract Method, we can consider this as a Functional Interface and we can use Lambda expression like below.

Thread t = new Thread(()->{
   System.out.println("Runnable implemented by using Lambda Expression");

Here instead of passing Runnable object we just passed lambda expression.

Declaring our own Functional Interfaces:

We can declare our own Functional Interface by defining Single Abstract Method in interface.

public interface FunctionalInterfaceTest{
void display();
//Test class to implement above interface
public class FunctionInterfaceTestImpl {
      public static void main(String[] args){
     //Old way using anonymous inner class
     FunctionalInterfaceTest fit = new FunctionalInterfaceTest(){
        public void display(){
           System.out.println("Display from old way");
     fit.display();//outputs: Display from old way
     //Using lambda expression
     FunctionalInterfaceTest newWay = () -> {System.out.println("Display from new Lambda Expression");}
        newWay.display();//outputs : Display from new Lambda Expression

We can annotate with @FunctionalInterface annotation, to tell compile time errors. It is optional

for ex:

public interface FunctionalInterfaceTest{
   void display();
   void anotherDisplay();//shows an error, FunctionalInterface should have only one abstarct method.

Default Method:

Functional interface can not have more than one abstract method but it can have more than one default methods.

Default methods are introduced in Java 8, to add new methods to interface with out disturbing the implemented classes.

interface DefaultInterfaceTest{
  void show();
  default void display(){
     System.out.println("Default method from interface can have body..!");
public class DefaultInterfaceTestImpl implements DefaultInterfaceTest{
   public void show(){
         System.out.println("show method");
   //we dont need to provide any implementation to default method.
   public static void main(String[] args){
          DefaultInterfaceTest obj = new DefaultInterfaceTestImpl();
;//out puts: show method
          obj.display();//outputs : Default method from interface can have body..!

Main use of default method is with out forcing the implemented class , we can add a method to an interface.

Multiple Inheritance:

If the same default method is there in two interfaces and one class is implementing that interface, then it will throw an error.

//Normal interface with show method

interface Test{

  default void show(){
     System.out.println("show from Test");


//Another interface with same show method

interface AnotherTest{

   default void show(){
      System.out.println("show from Test");


//Main class to implement above two interfaces

class Main implements Test, AnotherTest{
//here is an ambiguity which show method has to inherit here

This class wont compile because there is an ambiguity between Test, AnotherTest interfaces show() method, to resolve this we need to override show() method to Main Class.

class Main implements Test, AnotherTest{

   void show(){
      System.out.println("Main show method");


Categories: Java