Gadgets

Monday, 17 September 2018

Go Live api

Default and Static methods in interface:
========================================
a class which contains only service requirement specifications is called interface, in other words it is like conract between client and service provider.
a class which contains only method declarations not implementation.

Before java8:-
==============
Interface allows only method declarations, which is declared by public abstract keywrods and permits variable innitializations which is declared by public static final keywrods.

Note:- if we declared or not with the permited keywords, by default interface will take it.
Example:
=========
interface MyInterface{
public abstract void message();
void add();
public static final String PAN_NUMBER = "AWWPV6319H";
int id = 1214;
}

From java8:-
============
From java8 interface allows default and static methods.

Deafult Method in Interface:-
==============================
If we want to create a deafult method in interfce then we need to use "default" keyword with method signature

Example1:-
======== 
public interface MyInterface {
public abstract void message();
default void defaultMessage(){
System.out.println("Java8 new feature default method :: MyInterface");
}
}

Example2:-
==========
public interface MyInterface {
public abstract void message(String str);
default void defaultMessage(String str){
System.out.println("Java8 new feature default method :: MyInterface");
}
}

public class Test implements MyInterface, MyInterface2 {
public static void main(String[] args) {
Test test = new Test();
test.message();
test.message("Hello World");
test.defaultMessage();
test.defaultMessage("Hello World");
}

@Override
public void message() {
System.out.println("Interface method override");
}
@Override
public void message(String str) {
System.out.println(str);
}
}

Advantages of Default method in interface:-
===========================================
=> without effecting implementation classes, we can add defualt method to the interface in between implementation process
=> java8 interface provide base implementation using default method, so that we dont need to do base implementation in seperate class.
=> 


Static Methods in java8 interface:-
===================================
If we want to create a static method in interfce then we need to use "static" keyword with method signature but we can’t override them in the implementation classes
Example1:-
==========
public interface MyInterface {
static void staticMessage(){
System.out.println("Java8 new feature static method");
}
}

Example2:-
===========
public interface MyInterface2 {
static void staticMessage(String str){
System.out.println(str);
}
}

public class Test implements MyInterface, MyInterface2 {
public static void main(String[] args) {
Test test = new Test();
MyInterface.staticMessage();
test.staticMessage();
}
static void staticMessage(){
System.out.println("Class Static method");
}
}

importent points about static method in interface:-
======================================================

=> Interface static method is part of interface, we can’t override it in implementation class.
if we try to override static method in implementation class, it will give compiletime error.
public interface MyInterface {
static void staticMessage(){
System.out.println("Java8 new feature static method");
}
}

public class Test implements MyInterface{
public static void main(String[] args) {
Test test = new Test();
MyInterface.staticMessage();
}
}

=> Static method helps us providing security because end user class can't override, he can just use that method.
=> 


Java Functional Interfaces:-
=============================
An interface with exactly one abstract method is known as Functional Interface.If we try to add two or more abstract methods to functional interface it throws complietime error.
A new annotation @FunctionalInterface has been introduced to mark an interface as Functional Interface. that annotation tell us the interface is Functional Interface 
@FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces.

java.lang.Runnable with single abstract method run() is a great example of functional interface.

Example:-
=========

@FunctionalInterface
interface MyInterface{
public void message();
}


Lambda Expression:-
===================
A lambda expression is an anonymous function. A function that doesn’t have a name and doesn’t belong to any class.
To create a lambda expression, we specify input parameters on the left side of the lambda operator ->, and place the expression or block of statements on the right side of lambda operator. 

Syntax:-
=========
(input-parameters) -> (function-body)

Example:-
=========
(a, b) -> (a+b)
Here takes that values of a, b and return of these.

Example without Parameters:-
============================
public class LambdaTest {
public static void main(String[] args) {
MyInterface with = ()->{
System.out.println("With lambda exp message");
};
with.message();
}
}

@FunctionalInterface
interface MyInterface{
public void message();
}
Example with Parameters:-
=========================
public class Test {
public static void main(String[] args) {
MyInterface with=(a,b)->(a+b);
System.out.println(with.sum(10, 20));
MyInterface without = new MyInterface(){
@Override
public int sum(int a, int b) {
return a+b;
}
};
System.out.println(without.sum(20, 20));
}
}

interface MyInterface{
public int sum(int a, int b);
}

Lambda Expression  Advantages:-
===============================
1. To provide the implementation of Functional interface.
2. Less coding, Lambda expression decrease the number of lines code
3. We can use Lambda Expressions instead of anonymous inner classes, before java8 we used anonymous inner classes

Lambda expression only has body and parameter.
1. No name – function is anonymous so we don’t care about the name
2. Parameter list
3. Body – This is the main part of the function.
4. No return type


forEach and EachOrdered():-
=========================
forEach:-
========
forEach method is used to iterate elements, it is avaible in java.lang.Iterable interface
forEach() method is one example for java8 new feature default method in Iterable interface

default void forEach(Consumer<? super T> action)

forEach method takes java.util.function.Consumer object as argument, so it helps in having our business logic at a separate location that we can reuse in another implementation classes

Consumer:-
=========
Consumer is functional interface interoduced in java8 and available in java.util.function.
it contain only one abstract method and default method, this Consumer interface is best example for java8 new feature of function interface and default method.


Example:-
=========
public class NewForEach {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i<=10; i++){
list.add(i);
}
ConsumerTest test = new ConsumerTest();
list.forEach(test);
list.add(20);
}
}

class ConsumerTest implements Consumer<Integer>{
@Override
public void accept(Integer count) {
System.out.println(count);
}
}


Inside forEach we can use lambda expression method because Iterable interface also single abstract interface that mean function interface


Example:-
========
public class ForEachWithLambda {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("D");
list.add("C");
list.add("B");
list.add("E");
list.forEach(str->System.out.println(str));
}
}

Advantages of forEach Method:-
===============================
1. Implemetation code in seperate place that we can reuse in another class
2. Inside forEach we can use lambda expression
3. we can work with streams using forEach method



forEachOrder:-
===============
forEachOrder is used to iterate the elements, it is avaible in java.util.stream which is interduced in java8
it is same like forEarch meathod but the difference is forEachOrder method iterate the elements in specified order.
when working with parallel streams, we recomand to use the forEachOrdered() method when the order matters. 

Example:-
=========
public class ForVsForEach {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("D");
list.add("C");
list.add("B");
list.add("E");
// forEachOrdered print in specified order
list.parallelStream().forEachOrdered(str->System.out.println(str));
// forEach print randomly 
list.parallelStream().forEach(str->System.out.println(str));
}
}


java.util.Date
===============
public class Date

introduced in JDK1.0

This Date class represents current Date and Time with milliseconds.

Date date = new Date();
System.out.println(date); // Sat Oct 13 15:54:14 IST 2018

In this Date class we have methods to get year, month, hour, minute, etc.

java.util.Calendar
===================
public abstract class Calendar

introduced in JDK1.1

Calendar class provides methods to get date and time with milliseconds and also we have lot of methods in calendar class to get week, day of year etc

Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime()); // Sun Oct 14 12:11:24 IST 2018
System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); // 287


java.time API
=================

java.time API introduced in JDK1.8

This Package provides classes and method to represent date, time, durations, periods etc

the below classes which are included in java.time package

LocalDate : This class represents date without a time-zone, Example 2018-10-13. (yyyy-mm-dd)
LocalTime : This class represents time without a time-zone, Example 17:08:55.086. (hh:mm:ss:ms)
LocalDateTime : This class represents date and time without a time-zone, Example 2018-10-13T19:14:12.639
Clock : A clock providing access to the current instant, date and time using a time-zone that is Coordinated Universal Time (UTC) time. Example 2018-10-14T08:27:17.130Z
ZonedDateTime : this class provides date-time with a time-zone, example 2018-10-14T14:01:10.887+05:30[Asia/Calcutta]
ZoneId : this class provides zone ids
Year : this class provide year, example 2018
YearMonth : this class provide year and month, example 2018-10 
MonthDay : this class provide month and day, example --10-14
Duration : this class provide duration between two times or specific time duration (represents min duration nano)
Period : this class provides methods to get period between two dates, example P1Y7M2D
OffsetDateTime : this class provides date-time with an offset, example 2018-10-14T15:32:11.766+05:30.
OffsetTime : this class provides time with an offset, example 15:35:32.831+05:30.

UTC Time starts from IceLand (Reykjavik city) and Ghana (Accra city)


DateFormat : java.text.DateFormat


Stream API:-
============
Stream API interduced in java8 for Bulk Data Operations, This API contains classes, interfaces, and enum to do operations on data.
the main feature of Stream API is allows to iterate the data in sequential and parallel and also filter the data.

Before java8 with out stream:-
==============================
Suppose if we want to iterate over a list of integers and find out sum of all the integers greater than 90 then we implement like below without steams

Example:-
==========

public class WithoutStream {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i=10; i<=100; i++){
list.add(i);
}
Iterator<Integer> itr = list.iterator();
int sum = 0;
while (itr.hasNext()) {
int num = itr.next();
if (num > 90) {
sum += num;
}
}
System.out.println(sum);
}
}

1. in the above example just we want to do sum of all the integers greater than 90 but we are iterating one by one and doing sum
2. it is sequentail order
3. there more number of lines code.

to overcome this problem we have stream API

After Java8 Stream API:-
=========================

public class WithoutStream {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i=10; i<=100; i++){
list.add(i);
}
int sum = list.stream().filter(i -> i>90).mapToInt(i -> i).sum();
System.out.println(sum);
}
}

In the above example, the stream() method returns a stream of all the numbers and the filter() method returns greater than 90 number, 
the sum() method sum all the numbers which are greaterthan 90. All these operations are happening parallelly.
1. It will take less time to excute 
2. reduces implementation code


Wednesday, 27 July 2016

Basic responsive mobile menu

A simple basic responsive mobile menu


In this post, I explained how to create a basic responsive mobile menu using bootstrap and @mediaqueries.
Here it is for beginners to create a basic responsive mobile menu using bootstrap and @mediaqueries. I explained clearly with less coding, so I hope you can understand very easily by reading my post.






Tablet View



Sunday, 24 July 2016

Basic responsive webpage

A simple basic responsive webpage

In this post, I explained how to create a basic responsive webpage using HTML5, CSS and @media queries.
Here it is for beginners to create a basic responsive webpage using HTML5, CSS and @media queries. I explained clearly with less coding, so I hope you can understand very easily by reading my post.



Mobile View


Tablet View


Desktop View


Monday, 21 March 2016

Java web project using Servlet and JSP

Java Project using Servlet and JSP

In this article I explained a java project, it contains registration, login, update profile, change password, delete profile, logout, and forgot password operations.
I posted code here clearly and I drawn a flow chart for clear understanding.
Create the project in Netbeans
Create the Hibernate project in Netbeans

Saturday, 12 March 2016

Hibernate web application with CRUD operations using eclipse IDE

Hibernate CRUD operations in Eclipse

Here we have hibernate web application with CRUD operations using eclipse IDE and using Netbeans IDE 
Here I have created a registration form and servlet to insert data into database, and same as I done operations retrieve, update, and delete.
You need to follow the below steps to create hibernate application:
1.      Create the Dynamic web project
2.      Load the required jar files
3.      Create the persistent class
4.      Create the mapping file for persistent class
5.      Create the configuration file
6.      Create the classes that store, retrieve, update, and delete.
7.      Run the application

It is very simple to understand, don’t feel like it is hard and programs are so long.

Read also: 

Wednesday, 9 March 2016

java program for super keyword

Write a java program to given the example for “super” keyword.


super() is used to invoke super class constructors and super keyword is refer super class members.
in this program i did show the difference with and without super keyword.
by using super keyword we can access parent class properties.

public class SuperTest {
       int number=10;
       SuperTest(){
        System.out.println("parent class constructor ");
       }     
}
class Test extends SuperTest{    
       int number=20;      
       Test(){
              super();
              System.out.println("using super keyword :" +super.number);
              System.out.println("with out using super keyword :" +number);
       }     
       public static void main(String[] args) {
              Test obj=new Test();      
       }
}

OUTPUT:

/*
parent class constructor
using super keyword :10
with out using super keyword :20
*/

Tuesday, 8 March 2016

java program for static variables, methods, and blocks.

Write a java program to demonstrate static variables, methods, and blocks.

We can access static variables, blocks, and methods without creating object as shown in the below program.
JVM first check for the main method and after checking the main method it will execute static block after that execute remaining code.
public class StaticTest {
       static int id=1214; 
       static{
              String name="narendar";
              System.out.println("static block "+name);
       }
       static void display(){
              String group="CSIT";
              System.out.println("static method "+group);
       }     
       public static void main(String[] args) {
              System.out.println("static variable "+id);
              display();          
       }
}

Output:

/*
static block narendar
static variable 1214
static method CSIT

*/

java program for exception handling mechanism

 Write a java program that describes the exception handling mechanism.

To handle exception we use try, catch, finally block. In try block we write risky code. If any exception will occur in try block, that exception handle in catch block. Try block will execute if exception is occur or not.
In this program we will get ArithmeticException in try block, we are handling that exception in catch block.
We will get output catch-finally block instead of try block.
public class ExceptionTest {
       public static void main(String[] args)
       {
              try
              {
                     int a=10;
                     int b=0;
                     int c=a/b;
                     System.out.println(c);
              }
              catch(ArithmeticException ae)
              {
                     System.out.println(10);                 
              }
              finally
              {
                     System.out.println("finally");
              }            
       }
}

OUTPUT:

/*
10
Finally
*/

Example for command line arguments

Write a java program give example for command line arguments.

public class CammandTest {
       public static void main(String[] args) {
              System.out.println(args[0]);
              System.out.println(args[1]);
              System.out.println(args[0]+args[1]);
       }
}

OUTPUT:

/* D:\Java>java CammandTest javathub blogspot
javathub
blogspot
javathubblogspot*/

Monday, 7 March 2016

Default values of all primitive data types

Write a java program to display default value of all primitive data types of java.

Default Values of all primitive data types:


Data Type
Default Value
byte
0
short
0
int
0
long
0L
float
0.0f
double
0.0d
char
‘u0000’
String
null
boolean
false

public class DefaultValue {
       byte b;
       short s;
       int i;
       long l;
       float f;
       double d;
       char ch;
       String str;
       boolean flag;      
       public static void main(String[] args) {             
              DefaultValue dv=new DefaultValue();
              System.out.println("byte value : " +dv.b);
              System.out.println("short value : " +dv.s);
              System.out.println("int value : " +dv.i);
              System.out.println("long value : " +dv.l);
              System.out.println("float value : " +dv.f);
              System.out.println("double value : " +dv.d);
              System.out.println("char value : " +dv.ch);
              System.out.println("String value : " +dv.str);
              System.out.println("boolean value : " +dv.flag);
       }
}

OUTPUT:

byte value : 0
short value : 0
int value : 0
long value : 0
float value : 0.0
double value : 0.0
char value :
String value : null
boolean value : false
we get blank space for char data type