Pages

Monday, 6 January 2020

Introduction to SQL


Structure Query Language: It is a tool which is used to communicate with the database
Types of SQL statements
1. Data Definition Language(DDL)
e.g. CREATE, ALTER, DROP, RENAME, TRUNCATE
2. Data Manipulation Language(DML)
e.g. SELECT, INSERT, UPDATE, DELETE
3. Data Control Language(DCL)
e.g. GRANT & REVOKE
4. Transaction Control Language(TCL)
e.g. COMMIT ROLLBACK

Data Definition Language(DDL)
A set of statements that allow the user to define or modify data structures and objects, such as tables.

The CREATE statement
It is used for creating entire databases and database objects like tables.
How to create a database in MySQL?
CREATE DATABASE sales;
How to create a table in SQL.
CREATE TABLE <table_name>(
<col_name> <data_type> 
<col2_name> <data_type>);

For example:
CREATE TABLE sales (
    purchase_number INT,
    customer_id INT,
    item_code VARCHAR(10)
);

The ALTER statement
It is used when altering existing objects

ALTER TABLE sales
ADD COLUMN date_of_purchase DATE;

ALTER TABLE sales
ADD PRIMARY KEY(purchase_number);

ALTER TABLE sales
ADD UNIQUE KEY (item_code);

ALTER TABLE sales
DROP INDEX item_code;

ALTER TABLE sales
CHANGE COLUMN customer_id customer_id INT DEFAULT 0;

ALTER TABLE sales
CHANGE customer_id  cust_id INT;

ALTER TABLE sales
MODIFY cust_id INT NOT NULL;


The DROP statement
It is used for deleting a database object.
DROP TABLE sales;

The RENAME statement
It allows you to rename an object.
RENAME TABLE sales TO sale;

The TRUNCATE statement
Instead of deleting an entire table through DROP, we can also remove its data and continue to have the table as an object in the database.
TRUNCATE TABLE customers;

Data Manipulation Language (DML)
Its statements allow us to manipulate the data in the tables of a database

The SELECT statement
It is used to retrieve data from database objects, like tables
SELECT * FROM sales;

The INSERT statement
It is used to insert data into tables
INSERT INTO… VALUES…;
INSERT INTO sales (purchase_number, date_of_purchase) VALUES(1, ‘2017-10-11’);
INSERT INTO sales VALUES(1, ‘2017-10-11’);

The UPDATE statement
It allows you to renew existing data from your tables.

UPDATE sales
SET date_of_purchase = '2017-12-12'
WHERE purchase_number = 1;

The DELETE statement
With DELETE, you can specify precisely what you would like to be removed functions similarly to the TRUNCATE statement

TRUNCATE vs. DELETE
TRUNCATE allows us to remove all the records contained in a table whereas
with DELETE, you can specify precisely what you would like to be removed.

DELETE FROM sales;
TRUNCATE TABLE sales;

DELETE FROM sales
WHERE
purchase_number = 1;

Next Topic: SQL DATA TYPE

Friday, 3 January 2020

JDBC Statements

Statement
PreparedStatement
CallableStatement
1.Statement
Statement is an interface available in java.sql package.
Subclass of Statement interface is provided by Driver vendor. You can create the Statement object using the following methods of Connection interface.
public Statement createStatement();
public Statement createStatement(int,int);
public Statement createStatement(int,int,int);
You can call one of the following methods on Statement object to submit the SQL statement to Database.
public int executeUpdate(String sql);
public ResultSet executeQuery(String sql);
public boolean execute(String sql);

public int executeUpdate(String sql)
When you want to submit INSERT or UPDATE or DELETE SQL statements then use executeUpdate() method which returns the number of records inserted or updated or deleted.

public ResultSet executeQuery(String sql)
When you want to submit SELECT SQL statements the use executeQuery() method which returns the ResultSet object contains the records returned by the SELECT statement.

public boolean execute(String sql)
When you want to submit INSERT, UPDATE, DELETE, SELECT SQL statements then use execute() method which returns the boolean value.
If the returned value is true which means that SELECT SQL statement is submitted and the ResultSet object is created. Use the following method of statement to get the ResultSet object
public ResultSet getResultSet();
If the returned value is false which means that INSERT, UPDATE or DELETE SQL statement is submitted and the integer number is available which represents the number of records
inserted, updated or deleted. Use the following method of Statement to get the integer number available
public int getUpdateCount();
Using the single Statement object, you can submit any type of SQL statement and any number of SQL statements.
For example:
Statement st = con.createStatement();
String sql1 = "insert...";
String sql2 = "update...";
String sql3 = "delete...";
String sql4 = "select...";
boolean b1 = st.execute(sql1);
int x = st.executeUpdate(sql2);
int y = st.executeUpdate(sql3);
ResultSet rs = st.executeQuery(sql4);
When you submit the SQL statement using Statement object then SQL statement will compiled and executed every time.
Total time = req.time + compile time + execution time + res.time
           = 5ms + 5ms + 5ms + 5ms =20ms.
1 SQL stmt = 20ms.
100 SQL stmts = 2000ms.
When you provide dynamic values for the SQL statement then you need to use concatination operator, Formatter or format() of String class etc to format the query.
int sid =101;
String name = "Shail";
String email= "shail@gmail.com"
long phone = 1234567890;
String sql ="insert into student values(" +sid+ ","+name+","+email+","+phone+")";
String sql = String.format("insert into student values(%d,'%s','%s',%d)",sid,name,email,phone);
Formatter fmt = new Formatter();
String sql = fmt.format("insert into student values(%d,'%s','%s',%d)",sid,name,email,phone).toString();

2.PreparedStatement
PreparedStatement is an interface available in java.sql package.
PreparedStatement is extending the Statement interface.
Subclass of PreparedStatement interface is provided by Driver vendor.
You can create the PreparedStatement object using the following methods of Connection interface.
public PreparedStatement prepareStatement(sql);
public PreparedStatement prepareStatement(sql,int,int);
public PreparedStatement prepareStatement(sql,int,int,int);
You can call one of the following methods on PreparedStatement object to submit the SQL statment to Database.
public int executeUpdate();
public ResultSet executeQuery();
public boolean execute();
Using the single public PreparedStatement prepareStatement(sql);object, you can submit only one SQL statement.
For example:
String sql = "insert...";
 PreparedStatement ps = con.prepareStatement(sql);
int x = ps.executeUpdate();
When you submit the SQL statement using PreparedStatement object then SQL statement will be compiled only once first time and pre-compiled SQL statement wil be
executed every time.
Total time = req.time + compile time + execution time + res.time
           = 5ms + 5ms + 5ms + 5ms =20ms.
First time = 20ms
Second time onwards = 5ms +0ms + 5ms + 5ms = 15ms.
100 SQL stmts =20ms+99*15ms
              =20ms + 1485ms.
              =1505ms.
PreparedStatement gives you the place holder mechanism for providing the data dynamically to the SQL statement. You need to use the "?" symbol for the placeholder.
To provide the value for placeholder, you need to invoke the setter method depending on the placeholder data type.
public void setInt(int paramIndex, int val);
public void setString(int paramIndex, String val);
public void setLong(int paramIndex, long val);
public void setDouble(int paramIndex, double val); etc
int sid =101;
String name = "Shail";
String email= "shail@gmail.com"
long phone = 1234567890;
String sql = "insert into student values(?,?,?)";
ps=con.prepareStatement(sql);
ps.setInt(1,sid);
ps.setString(2,name);
ps.setString(3,email);
ps.setLong(4,phone);

3.CallableStatement
CallableStatement is an interface available in java.sql package.
CallableStatement is extending PrepareStatement interface.
Subclass of CallableStatement interface is provided by the Driver vendor.
You can create the CallableStatement object using the following methods of Connection interface.
public CallableStatement prepareCall(sql);
public CallableStatement prepareCall(sql,int,int);
public CallableStatement prepareCall(sql,int,int,int);
You can call the following mmethod on CallableStatement object to submit the SQL statement to database.
public boolean execute();
Using the single CallableStatement object, you can submit call to only one procedure.
For example:
String sql "call p1(?,?)";
CallableStatement cs = con.prepareCall(sql);
cs.setInt(1,10);
cs.setInt(2,20);
cs.execute();
When you submit the call to stored procedure using CallableStatement object then pre-compiled stored procedure will be executed directly.
Total time = req.time + compile time + execution time + res.time
           = 5ms + 0ms + 4*5ms + 5ms =30ms.
4 SQL stmts * 25 times.
  =30*25.
  =750.
CallableStatement gives you the placeholder mechanism for providing the data dynamically to the procedure parameters. You need to use  the "?" symbol for the placeholder.
To provide the value for placeholder, you need to invoke the setter methods depending on the placeholder date type.
public void setInt(int paramIndex, int val);.
public void setString(int paramIndex, String val);
public void setLong(int paramIndex, long val);
public void setDouble(int paramIndex, double val); etc

You need to use the following method to specify the OUT parameter.
public void registerOutParameter(int parameterIndex,int sqlType);
sqlType is a constant from java.sql.Types class.
You need to use the following method to access the result of OUT parameter.
public int getInt(int paramIndex);
public String getString(int paramIndex);
public long getLong(int paramIndex);
public double getDouble(int paramIndex);

Parameters

Servlet Instance Creation
  • By default, the servlet instance will be created when the first client will send the request to the servlet.
  • Only one instance will be created for one servlet and will be used to process all the requests by using multiple threads.
  • If you want to create the instance while starting the server or container then you can use the following:
In web.xml
<servlet>
<load-on-startup>X</load-on-startup>
</servlet>
In Annotation
@WebServlet(loadOnStartup=X)

Note: X will be int type value. It must be +ve integer.
It indicates in which order the servlet instance will be created.

Parameters
  • Parameter is name-value pair.
  • Parameter name and value are of type String.
  • The parameter is read-only i.e web container stores the parameter in the corresponding object and you can read and use that value. You can not modify the parameters.
There are 3 types of parameters
  1. ServletRequest Parameters
  2. ServletConfig Parameters
  3. ServletContex Parameters
ServletRequest Parameters
Client submitted data which is coming from web client to web server along with HTTP request are called as request parameters
Web container collects client submitted data and stores that in HttpServletRequest object as request parameters. As a developer, you can collect that data from the request object as follows.

Case 1:
String name = request.getParameter("name");
String[] course = request.getParameterValues("course");

Case 2:
You can access the parameter names and values as Map
Map<String,String[]> map = request.getParameterMap();
Set pnames = map.keySet();
Iterator it = pnames.iterator();
while(it.hasNext()){
String parameterName = (String)it.next();
Object val = map.get(parameterName);
String[] values = (String[])val;
for(String value: values){
System.out.println(value);
}
}

Case 3:
To access only request parameters
Enumeration<String> ens = request.getParameterNames();
List<String> list = Collections.list(ens);
for(String pn : list){
String pv = request.getParameter(pn);
System.out.println(pn+" "+pv);
}

The container is storing multiple values for the same key in the map in the form of a String array.
Map<String,String[]> map = ...;
String course[] = new String[2];
course[0]="Java";
course[1]="JDBC";
map.put("course",course);

ServletConfig Parameters
  • ServletConfig is an interface available in javax.servlet package and web container vendor are responsible to provide the subclass for this interface.
  • Every servlet will have its own ServletConfig object and can not be shared.
  • When you want to use any data which is common for all the users but specific to a particular servlet that data can be specified as config parameters or init parameters.
With Servlet 2.x: Specify the config parameters in web.xml
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.mak.servlets.HelloServlet</servlet-class>
<init-param>
<param-name>email</param-name>
<param-value>mak@gmail.com</param-value>
</init-param>
</servlet>
With servlet 3.x: specify the config parameters in servlet class with annotations
@WebServlet(name="helloServlet",urlPatterns={"hello.do"},
initParams={@WebInitParam(name="email",value="mak@gmail")})
public class HelloServlet extends HttpServlet{}

Web container collects data from either web.xml or annotation and stores that in ServletConfig object as config parameters. As a developer, you can collect that data from the config object as follows.
String email = config.getInitParameter("email");
You can override the following method in the servlet class to acess the ServletConfig
public void init(ServletConfig cfg)

You can use the following inheritance method from HttpServlet
public ServletConfig getServletConfig()
Here when HttpServlet class init() implementation will be invoked(from init() method) then the config object will be returned otherwise null will be returned.

Assume that HttpServlet class is implemented as follows
public abstract class HttpServlet...{
private ServletConfig config;
public void init(ServletConfig config){
this.config=config;
}
public ServletConfig getServletConfig(){}
...
}

Case 1:
class AServlet extends HttpServlet{
protected void service(...){
ServletConfig cfg = getServletConfig(); // inherited
//return the config object
//Since init() method from HttpServlet will be called and config will be initialized.
}
}

Case 2 :
class BServlet extends HttpServlet{
public void init(ServletConfig cfg){
super.init(cfg);    // invoking the HttpServlet init() method
}
protected void service(...){
ServletConfig cfg = getServletConfig();
//returns the config object
// Since init() method from your class will be called and you are calling HttpServlet init() so config will be initialized.
}
}

Case 3:
class CServlet extends HttpServlet{
public void init(ServletConfig cfg){
}
protected void service(...){
ServletConfig cfg = getServletConfig(); // inherited
//returns null value
// Since init() method from your class will be called and you are not calling HttpServlet init() so config won't be initialized.
}
}

ServletContext Parameters
  • ServletContex is an interface available in javax.servlet package and container vendor is responsible to provide the subclass for this interface.
  • One web application will have only one ServletContext object i.e ServletContext object can be shared with all the servlets running in the container.
  • When you want to use any data which is common for all the users and common to all the servlets then data can be specified as context parameters in the web.xml as
  • follows.
web.xml
<context-param>
<param-name>website</param-name>
<param-value>www.google.com</param-value>
</context-param>

Web container collects data from web.xml and stores that in ServletContext object as context parameters. As a developer, you can collect that data from the context object as follows:
String web = context.getInitParameter("website");
You can use the following method with ServletConfig or ServletContext object to access the corresponding parameter names.
Enumeration<String> ens = sc.getInitParameterNames();
List<String> list = Collections.list(ens);
for(String pn: list){
String pv = sc.getInitParameter(pn);
System.out.printl(pv);
}

Thursday, 2 January 2020

Introduction

JDBC is a technology which is used to interact with the database from Java Application
JDBC Technology is a part of Java Standard Edition
JDBC is a Specification provided by Java vendor and implemented by Java Vendor or DB vendor.

JDBC Versions
JDBC 3.0 is released under J2SE 1.4.2
No updation under J2SE 5.0
JDBC 4.0 is released under Java SE 6
JDBC 4.1 is released under Java SE 7
JDBC 4.2 is released under Java SE 8

Java Program which is using JDBC API  is called as JDBC Program.
Two packages provided under JDBC API called:
java.sql
javax.sql

Classes and Interfaces under java.sql package
DriverManager
Types
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
ResultSetMetaData
DatabaseMetaData

Classes and Interfaces under javax.sql package
RowSet
JdbcRowSet
CachedRowSet
DataSource

Types of JDBC Drivers
There are four types of JDBC drivers
Type I Driver:   JDBC ODBC Bridge Driver
Type II Driver:  Partial Java and Partial Native Driver
Type III Driver: Net Protocol Driver
Type IV Driver: Pure Java Driver

Pros and Cons of Types of Drivers


Advantages
Disadvantages
Type I Driver
Type I is very easy to use and maintain.
Type I is suitable for migrating an application to Java without changing existing ODBC setup.
No extra software is required for Type I implementation.
The performance of Type I is acceptable.
Type I driver implementation is possible in window OS only because ODBC drivers are available only with windows.
The performance of this driver is not excellent but acceptable.
Type II Driver
Type II is faster than all other drivers.
In Type II both client and server machine will have the database library.
When the database is migrated then you will get much maintenance because you need to re-install client-side libraries in all the client machines.
Type III Driver
In Type III, client-side DB libraries are moved to the middleware server called the IDS server.
Because of this, client-side maintenance is reduced.
You need to purchase extra software called the IDS server.
Because of having a middleware server between your program and database server, performance will be reduced
Type IV Driver
This driver is best among all the drivers and highly recommendable to use.
Negligible


Note: Type I driver support is removed from Java 8.

Type IV Driver
Name
Pure Java Driver
Vendor
Database Vendor
Username
<Database Username>
Password
<Database Password>
Software Required
Database, Java

For Oracle
Driver Class
oracle.jdbc.driver.OracleDriver
URL
Jdbc:oracle:thin:@<host>:<port>:<serverName>
e.g. jdbc:oracle:thin:@localhost:1521:XE
Classpath
ojdbc14.jar
ojdbc6.jar

For MySQL 
Driver Class
com.mysql.jdbc.Driver
URL
jdbc:mysql://<host>:<port>/<dbName>
e.g. jdbc:mysql://localhost:3306/testdb
Classpath
mysql.jar

Architecture
Type IV Driver

Steps to Write JDBC Program
Step 1: Load the Driver class.
Step 2: Establish the Connection between the JDBC program and Database.
Step 3: Prepare the SQL statement.
Step 4: Create the JDBC statement.
Step 5: Submit the SQL statement to Database using JDBC statement.
Step 6: Process the result.
Step 7: Close all the resources.

Create the below database and table in MySQL
create database testdb;
use testdb;
create table student(sid int primary key,name varchar(20),state varchar(20));

JDBC Program to insert a record into the database(MySQL)
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;

  5. public class JdbcDemo {
  6. public static void main(String[] args) {
  7. Connection con = null;
  8. Statement st = null;
  9. try {
  10. // Step 1:Load the Driver class.
  11. Class.forName("com.mysql.jdbc.Driver");
  12. // Step 2: Establish the connection.
  13. final String url = "jdbc:mysql://localhost:3306/testdb";
  14. con = DriverManager.getConnection(url, "root", "password");
  15. // Step 3: Prepare the SQL statement.
  16. String sql = "insert into student values(101,'Anu','M.P')";
  17. // Step 4: Create JDBC statement
  18. st = con.createStatement();
  19. // Step 5: Submit the SQL statement to Database using JDBC statement.
  20. int x = st.executeUpdate(sql);
  21. // Step 6: Process the result.
  22. if (x == 1) {
  23. System.out.println("Record Inserted");
  24. } else {
  25. System.out.println("Record Not Inserted");
  26. }
  27. } catch (ClassNotFoundException | SQLException e) {
  28. e.printStackTrace();
  29. } finally {
  30. // Step 7: Close all the resources.
  31. try {
  32. if (con != null)
  33. con.close();
  34. if (st != null)
  35. st.close();
  36. } catch (SQLException e) {
  37. System.out.println("Exception occur while closing the resources");
  38. }
  39. }
  40. }
  41. }


Servlet


Servlet is a web technology that is used to develop server-side web components.
Web components reside in server and perform the following:
                       Receive the incoming request data
                       Process the request
                       Prepare the HTML response
Servlets will be used to develop Dynamic Web application
One web application can have one or more web components like Servlets and JSPs.
One web container can have one or more web applications
One web server will have only one web container.
Client-Server

Steps to develop and run the first Servlet 4.x based Web App.
1. Consider the login requirement.
Assignment

2. Create the Dynamic Web Project in STS/eclipse as follows:
            Select File->New->Dynamic Web Project 
                  Project Name: Lab1
                  Click on New Runtime button (for the first time)
                                Select Apache Tomcat v9.0 and click on Next button
                                Browse the Tomcat Home Directory i.e D:\apache-tomcat-9.0.30
                                Click on the finish button
                 Click on the finish button
3. Observe the following Directory structure of Dynamic Web Project in STS.
4. Create login.html under the WebContent folder.
5. Create a package com.demo.servlets under Java Rsources>src
6. Create LoginServlet.java file in package com.demo.servlets.
7. Deploy into Tomcat 9 as follows
                 Right-click on Lab1
                 Select Run As->Run on Server
8. Open the Browser
9. Provide the following URL
   http://localhost:8080/Lab1/login.html

Required Files
login.html
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="ISO-8859-1">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <form action="login.do">
  9. <h1>Account Login</h1>
  10. <p>Username</p>
  11. <input type="text" name="username"/>
  12. <p>Password</p>
  13. <input type="password" name="password"/>
  14. <p><input type ="submit" value="Login"/></p>
  15. </form>
  16. </body>
  17. </html>
LoginServlet.java
  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;

  8. @WebServlet("/login.do")
  9. public class LoginServlet extends HttpServlet {
  10. private static final long serialVersionUID = 1L;
  11. protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. String username= request.getParameter("username");
  13. String password= request.getParameter("password");
  14. System.out.println(username);
  15. String message="";
  16. if(username.equals(password)) {
  17. message ="<h1>Welcome"+username+"<h1>";
  18. }else {
  19. message="<h1> Invalid username or password</h1>";
  20. }
  21. PrintWriter out = response.getWriter();
  22. out.write(message);
  23. out.flush();
  24. out.close();
  25. }
  26. }


Friday, 27 December 2019

Java 8 Date Time API


Why did Java 8 introduce a new date and time API when it already had classes such as Date and Calendar?
Below are the main reasons
1.Bad API design. For example, The Date class has both date and time components, if you only want time information and not date-related information, you have to set the date-related value to zero. Some aspects of the classes are unintuitive as well. For example, in the Date constructor, the range of date values is 1 to 31 but the range of month values is 0 to 11(not 1 to 12).
2.Java.util.Date,java.util.Calendar,java.time.SimpleDateFormatter classes are not thread-safe.

Java 8 provides very good support for date and time-related functionality in the newly introduced package java.time package.
Most of the classes in this package are immutable and thread-safe. We will learn LocalDate, LocalTime, LocalDateTime,Instant,Period, Duration,TemporalUnit and DateTimeFormatter.

The java.time package consists of four sub-packages
java.time.temporal: Access date/time fields and units.
java.time.format: Formats the input and output of date/time objects.
java.time.zone: Handles time zones.
java.time.chrono: Supports calendar systems such as Japanese and Thai Calendars.

LocalDate
java.time.LocalDate represents a date without time or time zone. LocalDate is represented in the ISO-8601 calendar system in a year-month-day format(YYYY-MM-DD). For example,2019-12-27.

How to get today's date?
LocalDate today = LocalDate.now();

LocalTime
java.time.LocalTime class is similar to LocalDate except that LocalTime represents time without dates or time zones. The time is in the ISO-8601 calendar system format HH:MM:SS: nanosecond.

How to get the current time?
LocalTime  currentTime = LocalTime.now();

LocalDateTime
This class java.time.LocalDateTime represents both data and time without time zones.
You can think of LocalDateTime as a logical combination of the LocalTime and LocalDate classes. The date and time formats use the ISO-8601 calendar system:
YYYY-MM-DD HH:MM: SS.nanosecond. For example,
LocalDateTime dateTime =LocalDateTime.now();

Instant
Represents machine time starting from Unix epoch(1970-01-01T00:00:00Z)
Typically used for timestamps
Instant instant = Instant.now();

What is the difference between LocalDateTime and Instant?
LocalDateTime uses the default time zone, but Instant does not.
For examaple,
LocalDateTime dateTime =LocalDateTime.now();//2019-12-27T15:27:27.139835100
Instant instant = Instant.now();//2019-12-27T09:57:27.139835100Z

Period
Represents the amount of time in terms of years, months and days.
Typically used for difference between two LocalDate objects.
How to find out when medicine will expire?
 LocalDate manufactureDate = LocalDate.of(2018,Month.MARCH,15);
 LocalDate expiryDate = LocalDate.of(2021, Month.JULY, 20);
 Period expire = Period.between(manufactureDate, expiryDate);
 System.out.println(expire);//P3Y4M5D, here P-> Period, Y-> Year, M-> Month, D-> Day
System.out.println(expire.getYears()+"Years "+expire.getMonths()+"Months "+expire.getDays()+"Days");//3Years 4Months 5Days

Duration
Represents the amount of time in terms of hours, minutes, seconds and fractions of seconds.
Typically used for difference between two LocalTime objects.

How to find out how many hours to go, to wish your best friend's birthday?
LocalDateTime comingMidnight = LocalDateTime.of(LocalDate.now().plusDays(1),LocalTime.MIDNIGHT);
LocalDateTime now1 = LocalDateTime.now();
Duration duration =Duration.between(now1, comingMidnight);
System.out.println(duration);//PT8H9M29.7853329S, Here PT-> Period Time, H-> Hour, M-> Minute, S->Second

TemporalUnit
The TemporalUnit interface is the part of java.time.temporal package.
It represents date or time units such as seconds, hours, days, months, years, etc.
The enumeration java.util.temporal.ChronoUnit implements TemporalUnit interface.
Instead of using constant values, it is better to use their equivalent enumeration values. Beacuase using enumeration values in ChronoUnit results in more readable code;further, you are less likely to make mistakes. For example,
System.out.println(Duration.of(1, ChronoUnit.MINUTES).getSeconds());//60
System.out.println(Duration.of(1, ChronoUnit.HOURS).getSeconds());//3600
System.out.println(Duration.of(1, ChronoUnit.DAYS).getSeconds());//86400

Time Zone
There are three important classes related to time zones that you need to know in order to work with dates and times across time zones.
  1. ZoneId
  2. ZoneOffset
  3. ZoneDateTime
ZoneId
The java.time.ZoneId class represents time zones. Time zones are typically identified using an offset from Greenwich Mean Time(GMT, also known as UTC/Greenwich).
For example, the time zone of India is Asia/Calcutta
System.out.println(ZoneId.systemDefault());//Asia/Calcutta

ZoneOffset
It represents the time-zone offset from UTC/Greenwich. For example, zone ID "Asia/Calcutta" has a zone offset of +5:30(plus 5 hours and 30 minutes) from UTC/Greenwich.
The ZoneOffset class is the child class of ZoneId class.

ZonedDateTime
If you want all three- date, time, and time zone together. For that, you can use the ZoneDateTime class.
LocalDate currentDate = LocalDate.now();
 LocalTime currentTime = LocalTime.now();
 ZoneId myZone = ZoneId.systemDefault();
 ZonedDateTime zoneDateTime = ZonedDateTime.of(currentDate,currentTime,myZone);
System.out.println(zoneDateTime);//2019-12-27T16:14:59.424905800+05:30[Asia/Calcutta]

Formatting Dates and Times
Using java.time.format.DateTimeFormatter class you can format the date and time according to your requirement.
DateTimeFormatter class provides many predefined constants for formatting date and time values.
Here is a list of a few such predefined formatters.
ISO_DATE(2019-12-27)
ISO_TIME(11:30:25.624)
ISO_ZONED_DATE_TIME(2019-12-27T16:14:59.424905800+05:30[Asia/Calcutta])
RFC_1123_DATE_TIME(Thu,26 Dec 2019 11:27:30+0530)
For example,
  LocalTime wakeupTime = LocalTime.of(6,0,0);
  System.out.println(DateTimeFormatter.ISO_TIME.format(wakeupTime));// 06:00:00

If you want to use a custom format instead of any of the predefined format. To do so, you can use the
ofPattern() method in the DateTimeFormatter class.
DateTimeFormatter customFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(customFormat.format(LocalDate.of(2019,Month.MARCH,01)));//01/03/2019

Important letters and their meanings for creating patterns for dates
G(era: BC,AD)
y(year of the era: 2020,20)
Y(week based year: 2020,20)
M(month:3,Mar,November)
w(week in year: 12)
W(week in month: 3)
E(day name in week: Sun, Sunday)
D(day of year: )
d(day of month)

Example:
class DateFormatter{
public static void main(String[] args) {
String[] dateFormats = { "d-M-y",
                                                 "dd-MM-yy",
                                                  "dd-MMM-yyy",
                                                  "dd-MM-yyyy", 
                                                   "D-MM-yyyy",
                                                   "DD-MM-yyyy",
                    "DDD-MM-yyyy",
                                                    "d - MMM- Y",
                                                    "w'th week of' YY",
                                                    "w'th week of' YYY",
                                                   "E, dd'th' MMMM,YYYY",
                    "EE, dd'th' MMMM,YYYY",
                                                    "EEE, dd'th' MMMM,YYYY",
                                                    "EEEE, dd'th' MMMM,YYYY" };
Arrays.stream(dateFormats)
.forEach(i -> System.out.println(DateTimeFormatter.ofPattern(i).format(LocalDate.now())));

}
}

Important letters and their meanings for creating patterns for time
a(marker for the text a.m/p.m marker)
H(hour:value range 0-23)
k(hour value range 1-24)
K(hour in an a.m/p.m :value range 0-11)
h(hour in a.m/p.m : value range 1-12)
m(minute)
s(second)
S(fraction of a second)
z(time zone: general time-zone format)

class TimeFormatter{
public static void main(String[] args) {
String[] timeFormats = {    "h:mm",
                                            "hh 'o''clock'",
                                            "H:mm a",
                                            "hh:mm:ss:SS",
                                            "K:mm:ss a"
                                                          };
Arrays.stream(timeFormats)
.forEach(i -> System.out.println(DateTimeFormatter.ofPattern(i).format(LocalTime.now())));

}
}

Saturday, 14 December 2019

Collection

The collection framework is very important for fresher and experienced developers. You must have a good hold on it if you want to crack java interviews. You are supposed to prepare theoretical, coding and scenario-based questions related to this topic. I will try to explain each concept and interview questions of the Collection framework in a simple way. Almost, in all the interview it is asked that what is the difference between List, Set, Map, etc. How will you choose which Collection is suitable for a particular situation? With the help of the below diagram, you can answer the above questions with confidence. So please spend some time in the below diagram.

Collection Framework