Difference between Web Sites and Web Applications

In order to start with Advance Java, we need to first understand what is the difference between Web Sites and Web Application.

Websites
A website is a collection static files, HTML pages, images and other static resources, by static we mean those resources which are not going to changes with user interaction. When user visit the same website and performs some action they will get the same output, for example a college website which only provides informational data is not going to change with user interaction.

Web Applications
Web applications on other hand are dynamic, they are part of some website which provides dynamic functionality to the website. When user interacts with web applications out may change depending on the inputs provided by the user. With the help of web application we can make our sites interactive. Examples of web applications are www.amazon.com, www.flipkart.com etc.

How a web application works?
In order to fulfill user's request web application runs a program or group of programs on server and then produces some output for the users. Most of the interactions in a web application is done through HTML forms.
HTML forms are a way of taking inputs from users in a web application, you can visit www.w3schools.com for more information on HTML forms.
Interaction between user and web application takes place in form of request and response object. Browser is the application which handles these request and response objects. When a user is clicking on a link or entering a URL in the browser, he/she is actually requesting something from server. Server is the environment where web applications are hosted or in simple terms it is the machine where all the resources of a web application resides. When server receives a request, it parses the request and look for the resource requested and then create a response object and return it back to browser from where the request has been raised.

Consider below example :

1. For registering on a web site, user clicks on "Sign Up" button, which raises a request for an HTML form for taking user's detail.
2. The server receives the request and responds back with HTML form requested.
3. User fill up the form and click on "Submit" button, browser form's data in request object and sends it to the server.
4. Server process the submitted data and either it creates the user or user registration gets failed. In either cases server responds back to user with proper message in response object.

How web applications are created?     
There are so many technologies available using which we can create web application components for our websites. Some of the commonly used technologies are JSP, Servlets, PHP, ASP.NET etc.
In early stages of web application developments Common Gateway Interface (CGI) were used to create web applications. CGI is a server side program which is invoked when a particular URL is loaded into the browser. CGI programs

HTTP Request and HTTP Response
The request and response object that we have talked so far are actually HTTP request and response object which are transfer back and forth using HTTP protocols.

We will now learn about creating web applications using servlets. If you have any doubts in regards to this post, please let me know through your comments I will be happy to resolve your doubts. 
Share:

Loops In Java



What is loop in programming language?
Loop in programming languages is a control flow statement, which we use to execute a set of instructions repeatedly while some condition evaluate to true.

There are three steps on which every loop works :
1. Initialization Condition : In this step we initialize a variable with a value from which we want to start our loop, we will continuously change the value of this variable in Step 2 till our terminating condition is reached.
2. Increment/Decrement of initialized variable to move the loop one step further.
3. Termination Condition : In this step we define condition, which when reached our loop will end. 
4. Body of Loop : This defines set of instructions that needs to be executed repeatedly.

There are 3 types of loop that Java provide us, they all provide similar basic functionality but they differ in syntax and the time at which terminating condition is evaluated. Let us discuss them in detail :

1. for Loop
Below is the syntax for For loop in Java :

    for(Initialization Condition;Terminating Condition;Increment/Decrement) {
     
/**
       * Body of loop
       */
   
}


Below is the sequence of execution in for loop :
1. First a variable is declared with its initial value which act as the starting condition of our loop.
2. In next step we define our terminating condition, if it is true then 3rd step is executed otherwise loop will terminate.
3. In this step body of loop will get executed which means, the statements that you want to execute repeatedly will be executed.
4. In this step value of the variable declared in first step will either increases or decreases as per the code we have written, then control will pass to 2nd step.

Let's take an example of printing 2's table  :

public TestLoop{
  public static void main(String[] args){
    for(int i=1;i<=10;i++){
      System.out.println("2 x "+i+" = "+(2*i));
    } 
  }
}

When we run above program, it will print the following output on console :


2. while Loop
Below is the general syntax for while loop in Java :

    Initialization Condition;
    while(Terminating Condition) {
      
/**
       * Body of loop
       */

       Increment/Decrement
    
}


Below is the sequence of execution in while loop :
1. First a variable is declared with its initial value which act as the starting condition for our loop.
2. In next step we define our terminating condition, if it is true then 3rd step is executed otherwise loop will terminate.
3. In this step body of loop will get executed which means, the statements that you want to execute repeatedly will be executed.
4. In this step value of the variable declared in first step will either increases or decreases as per the code we have written, then control will pass to 2nd step.

Let's take same example of printing 2's table  :

public TestLoop{
  public static void main(String[] args){
    int i=1;
    while(i<=10){
      System.out.println("2 x "+i+" = "+(2*i));
      i++;
    } 
  }
}

Output of the above program will be same as for loop.

3. do-while Loop
Below is the general syntax for while loop in Java :

    Initialization Condition;
    do {
      
/**
       * Body of loop
       */

       Increment/Decrement
    
}
while(Terminating Condition);

Below is the sequence of execution in while loop :
1. First a variable is declared with its initial value which act as the starting condition for our loop.
2. In this step body of loop will get executed which means, the statements that you want to execute repeatedly will be executed.
3. In this step value of the variable declared in first step will either increases or decreases as per the code we have written.
4. In next step we define our terminating condition, if it is true then 2nd step is executed otherwise loop will terminate.

Let's take same example of printing 2's table  :

public TestLoop{
  public static void main(String[] args){
    int i=1;
    do{
      System.out.println("2 x "+i+" = "+(2*i));
      i++;
    }while(i<=10); 
  }
}

Output of the above program will be same as for loop.

So the big question, when to use which loop? There is a principle which I personally follows while making a decision on loops :
1. If you know how many times a loop will execute then go for "for loop" otherwise for "while loop" and "do..while loop".
2. If you have to execute body of loop at least once then go for "do..while loop" otherwise go for "while loop".

There are so many questions that interviewers may ask on this topic so be well prepared for this. Also if you have any doubts you can ask in comments section.







Share:

Java JDBC - Executing Query


In this post we will discuss about executing queries using JDBC. In previous post we already have gone through a sample code for making connections and executing queries in Java using JDBC. For executing queries we had used Statement interface for executing queries, there are some other ways as well for executing queries. Below is the list of options that we have in Java JDBC for executing queries.


1. Statement Interface
We should use object of Statement interface when we want to execute static SQL query. In other words when our query do not want parameter values at runtime then we should use this interface.

2. PreparedStatment Interface
If our query wants parameter at runtime, in other words if our query is dynamic, then we should use object of PreparedStatment interface. We can set parameter values at runtime using PreparedStatement interface.

3. CallableStatement Interface
When we want to execute stored procedures in through our code then we should use object of CallableStatement interface.

Now let us discuss about these interfaces in little bit details.

Note : Examples below will be using an object of Connection for creating objects of above interfaces, so we will not see code in examples below for creating connections with databases. 

1. Statement Interface

Below is the sample code for creating Statement objects.


Statement stmt = null;
try {
   stmt = con.createStatement();
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

After creating the object of Statement interface, we can call below methods depending on our need.


ResultSet executeQuery(String sql) :
When we execute a SELECT query a result set is returned, if we want to iterate through that result set we can call executeQuery method of Statement interface which returns an object of ResultSet interface, that can be use to iterate through the result returned by query.

int executeUpdate(String sql) :
If we want to get number of rows impacted after executing a DML statement (INSERT, DELETE, UPDATE)  then we can call executeUpdate method of Statement interface. This method will return number of rows impacted by the query.

boolean execute(String sql) :
If we want to execute DDL statement (CREATE, DROP, ALTER)  then we should use this method, it returns true if ResultSet object can be retrieved after executing the query otherwise it will return false. 

When we finish our work with Statement object, it is important for us to close that object in order to save database resources. If we close Connection object first then it will automatically close the Statement object, but still I will prefer to close Statement object explicitly. 

2. PreparedStatement Interface
If we have dynamic SQL query which needs parameter at runtime then Statement interface will not be able to handle those queries, for these type of queries we use PreparedStatement interface. 
PreparedStatement interface extends Statement interface, it has added advantages and functionality over Statement interface. 

For example we want to get employee record of an employee whose id is provided at runtime, then we will use PreparedStatement as shown below :

PreparedStatement pstmt = null;
try {
   String SQL = "SELECT * From Employees WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

In our query, for parameters that we want to input at runtime is specified by ? in query.  For each ? in query we have to set values using setXXX(int index, XXX value) method of PreparedStatement object, where XXX  is data type of value you want to set and index is the position of ? for which you want to set value. Some of the examples are shown below :

setInt(int index, int value) : This method is used for setting integer values in our query.
setString(int index, String value) : This method is used for setting String values.

Here is the complete list of methods available in PreparedStatment interface.


3. CallableStatement Interface
If we want to call stored procedures and functions from our code then we should use CallableStatement interface. Similar to PreparedStatement and Statement interfaces, Connection object is used to create objects of CallableStatement interface.

Suppose we have following procedure in our MySQL database :

DELIMITER $$

DROP PROCEDURE IF EXISTS `MATH`.`sum` $$
CREATE PROCEDURE `MATH`.`sum` 
   (IN NUM1 INT,IN NUM2 INT, OUT SUM INT)
BEGIN
   SELECT NUM1+NUM2 INTO SUM   
END $$

DELIMITER ;


We can call above procedure from code as shown below :

CallableStatement pstmt = null;
try {
   String SQL = "{call sum(?,?,?)}";
   pstmt = conn.prepareCall(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

The way we are setting value for ? in PreparedStatement, we have to use same way for passing IN parameters to CallableStatement, but for OUT and INOUT parameters we have call an additional method of CallableStatement i.e. registerOutParameter(). While calling registerOutParameter() we need to make sure the data type of the variable that we are registering should be same as the procedure is expected to return.
When execution of CallableStatement is completed we can retrieve value of OUT and INOUT parameter with appropriate getXXX() method.

Note : It is very important to close resources when we are finish with them, for efficient programming. Therefore in finally block always remember to close objects of Statement, PreparedStatement and CallableStatement by calling close() method.

In subsequent topics we will discuss about functions of ResultSet, PreparedStatement and Other interfaces that help us to write an efficient program. 
Share:

Java JDBC - Steps for connecting to database

What are the steps for making connection between Java Application and Database?

Above is the question, we will be answering for in this post. In previous post we have learnt about Type of JDBC Drivers for making connection with database. In this post we will look into the programming aspects of making connection with database.

Below are the steps for making connection with database in Java application :

  1. Loading or Registering JDBC Driver
  2. Create Connection
  3. Create Statement
  4. Execute Query
  5. Close the Connection

1. Loading or Registering JDBC Driver

There are two approaches through which JDBC drivers are registered or loaded in Java Application. 

1. Class.forName() : This is the most common approach for registering or loading a JDBC driver. Through this method we load driver classes dynamically at runtime into memory. There is no need of creating object. Following is the example of using Class.forName to load MySQL driver class. 

Class.forName("com.mysql.jdbc.Driver");

2. DriverManager.registerDriver() : It's a Java inbuilt class with a static member, this method is used if we are using a non-JDK compliant JVM. Following is the example for using DriverManager.registerDriver() for registering a driver :

Driver driverObj = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driverObj);

Note : Don't forget to handle ClassNotFoundException in both cases.


2. Creating Connections

After loading driver class, we need to establish connection with database. For establishing connection we will use getConnection() of DriverManager class, below is the syntax for it's use :

Connection con = DriverManager.getConnection(url, user, password); 

con : it is a reference to Connection interface.
user : username of the database from which sql command prompt can be accessed.
password : password of the user provided.
url : it is the path through which database can be accessed. 

For our example url will be in below form :
jdbc:mysql://localhost:3306/student

jdbc:mysql:  - This specifies the type of database to which we are making connection.

localhost:3306 - This specifies the machine on which your database is installed and the port number on which your database service is listening. In our example our database is installed on local machine therefore we have used localhost if our database would have installed on remote machine then we would have used IP address of that machine instead. Default port number on which MySQL service listens is 3306.

student - This is the name of schema to which we want to make connection. 

Below is the list of some commonly used url for making connection with different databases.

RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:portNumber:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:portNumber/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname:portNumber/databaseName


3. Creating Statement

After creating connection with database, we can now create Statement object for executing SQL queries on database which we have make connection to.
createStatement(), method of Connection interface is used to create Statement object.

Below is an example for creating Statement object :

Statement stmt = con.createStatement();

4. Executing SQL Query

Next step is to execute SQL query and getting the result of query execution in ResultSet object. When we execute SQL query using Statement object created in above statement, an object of ResultSet class is returned which holds the data returned by executing query.

Below is an example of executing SQL query :

ResultSet rs = stmt.executeQuery("select * from student");


5. Printing result on console

We can loop through ResultSet object to access each row returned by query execution.

Below is an example for looping through the ResultSet object :

while(rs.next()){
     String name = rs.getString("name");
     String rollNo = rs.getString("rool_no");
     System.out.println(name+" : "+rollNo); 
}


6. Close the connection

This is the most important step, always remember to close the connection which you opens otherwise it will increase overhead on database and your application may crash. Believe me, this is one of the bad things I have seen till date which causes application server crash in production.
You can call close() method of connection class to close the connection.

Below is an example to close the connection :

con.close();

Below is a complete program :

 
 1 package TestConnection;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8 import java.util.logging.Level;
 9 import java.util.logging.Logger;
10 
11 /**
12  *
13  * @author NPSingh
14  */
15 public class TestConnection {
16 
17     public static void main(String[] args){
18         try {
19             Class.forName("com.mysql.jdbc.Driver");
20             Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
21             Statement stmt = con.createStatement();
22             ResultSet rs = stmt.executeQuery("select * from student");
23             while(rs.next()){
24                 String name = rs.getString("name");
25                 String rollNo = rs.getString("rool_no");
26                 System.out.println(name+" : "+rollNo); 
27             }
28         } catch (ClassNotFoundException | SQLException ex) {
29             Logger.getLogger(TestConnection.class.getName()).log(Level.SEVERE, null, ex);
30         }
31     }
32             
33 }

In subsequent posts on this topic, we will discuss ResultSet, Statement etc. more deeply.

Share:

Java JDBC - JDBC Drivers

JDBC Drivers helps in interacting with databases. JDBC driver manager makes sure that correct driver is used to access each data source. There are 4 types of JDBC drivers :

  1. Type 1 : JDBC-ODBC Bridge Driver
  2. Type 2 : Native API Driver (partially java driver)
  3. Type 3 : Network Protocol or Net Pure Driver (fully java driver)
  4. Type 4 : Thin Driver (100% pure java driver)
Now we will discuss all of these 4 types in detail :

Type 1 : JDBC-ODBC Bridge Driver

This driver uses ODBC driver installed on client machine to make connection to data source. In order to use this driver, we need to configure Data Source Name (DSN) on our machines which represents target database. This is the oldest driver we have and it is not much in use. Moreover, support for this driver has been stopped from Java 8.

JDBC Type 1 Driver

There are few disadvantages of using this driver :

  1. Performance of the applications gets degraded as the JDBC calls gets converted into ODBC class for executing SQL statements.
  2. ODBC driver needs to be installed on client machine.
  3. Support for this driver is ended in Java 8


Type 2 : Native API Driver

When we use this driver JDBC calls are converted into native C/C++ calls. This driver is not entirely written in Java. These drivers are used in same manner as JDBC-ODBC Bridge. These drivers are vendor specific and needs to be installed on each client machine. If we change the database then we need to change the native API library as well.

Type 2 JDBC Driver


Performance with these drivers are upgraded as compared to JDBC-ODBC Bridge. There are some disadvantages as well :

  1. These needs to be installed on each client machine.
  2. In addition to drivers vendor specific API also needs to be installed on client machine. 

Type 3 : Network Protocol or Net Pure Driver

These drivers are purely written in Java language. These drivers used a 3-tier architecture for communication with databases. Most of DB related tasks are handled by a middleware server which converts JDBC calls directly or indirectly into vendor specific database protocol.
These drivers are very flexible as compared to previous drivers because it does not require any code to be installed on client machine.

Type 3 JDBC Driver

.

Type 4 : Thin Driver (100% Pure Java Driver)

This is a pure Java-based driver, which communicates directly with vendor's database through socket connection. Performance wise this is the best driver to choose. This driver doesn't require any native database library for interaction with database. Moreover, we don't need to install any kind of special software on client or server machine.

Type 4 JDBC Driver


Which driver to should be used and when?

If we are accessing one type of database, such as Oracle, MySQL, Sybase etc. then we should use Type 4 driver.
If our Java Application is accessing multiple types of databases at same time then, we should use Type 3 driver.
If neither Type 4 nor Type 3 is available for the database used by our application then we should go for Type 2 driver.
We should not use Type 1 for deployment purpose, it should be only used for development and testing purposes only.

Share:

Java JDBC - Introduction

What is JDBC?

JDBC stands for Java Database Connectivity, it is an API for database independent connectivity between Java programs and databases. It helps in connecting wide range of databases and execute the query with the database.

The java.sql package contains classes and interfaces for working with databases. Below is the list of  commonly used classes and interfaces available in java.sql  package :

  • DriverManager class : A list of database drivers is managed by this class, which matches connection requests from java application with the proper database driver using communication sub protocol.   
  • Driver interface : Communication with database is managed by this interface but we will rarely use objects of this interface rather we will be using Objects of DriverManager class for communication with database. 
  • Connection interface : Objects of this interface represents the communication context. Methods available in this interface helps in contacting database. 
  • Statement interface : SQL statements are submitted using objects of this interface.
  • PreparedStatement interface : Parameterized SQL statements are submitted through objects of this interface.  
  • ResultSet interface : Object of this interface will hold the data returned from SQL query execution.
  • ResultSetMetaData interface : Object of this interface holds metadata information about the resultset returned from SQL query execution. 
The JDBC library includes classes and interfaces for performing below tasks :
  1. Making connection to database.
  2. Creating SQL Statements
  3. Executing SQL queries
  4. Viewing and modifying the result set. 
JDBC API uses JDBC drivers to connect with database. There are four types of drivers :
  1. JDBC-ODBC Bridge Driver
  2. Native Driver
  3. Network Protocol Driver
  4. Thin Driver
JDBC Architecture 

JDBC API supports Two-Tier and Three-Tier processing models :

Two-Tier Architecture for Data Access :

JDBC 2Tier processing
In this architecture a Java Applet or Application talks directly to data source. This requires a JDBC driver that can communicate with particular database. A user's command are delivered to the database and result of those commands are send back to the user. The database in this situation may be located on another machine to which user is connected via network. This is referred to as client/server configuration, where user's machine is client and the machine hosting database is called server. 

Three-Tier Architecture for Data Access :

3-tier JDBC Architecture

In three tier architecture commands are send to a middle tier of services which then send those commands to database server. The database server processes those commands and sends results back to middle tier, which then sends those results back to users. 
Share:

Questions on OOPs

1. What is OOPs?
Ans. OOPs stands for Object Oriented Programming specifications. It is a programming technique or paradigm in which every thing revolves around real world entities or objects. Main focus in this technique is on objects rather than actions and data rather than logic. C++, Java, C# are few examples which supports OOPs.

2. What are the core concepts of OOPs?
Ans. OOPs core concepts are :

  1. Abstraction
  2. Encapsulation
  3. Polymorphism
  4. Inheritance
  5. Composition
  6. Association
  7. Aggregation
3. How does OOPs improves software development?
Ans. The key  benefits of OOPs are :
Re-use  of previous  work: using  implementation inheritance  and  object  composition.
Real  mapping  to the  problem  domain:  Objects map to  real  world and represent  vehicles, customers, products etc.  with  encapsulation.
Modular Architecture:  Objects, systems, frameworks etc are  the building blocks of  larger systems. The  increased  quality  and  reduced  development time  are the by-products of the  key  benefits discussed above. If 90% of the  new  application consists of proven  existing  components then only  the remaining  10%  of the code have to be  tested from scratch.

4. What is the difference between Abstraction and Encapsulation?
Ans. Main differences between Abstraction and Encapsulation are :
1. Abstraction provides a general structure of a class and leaves it's implementation detail to the implementer. Encapsulation is used to restrict access to members of an object.
2. Abstraction is implemented using interfaces and abstract classes. Encapsulation is implemented using four types of access specifiers public, private, protected and default. 

5. What is abstract class in Java?
Ans. A class which defines the structure of a class without going into implementation details is known as abstract class. We can not instantiate an abstract class directly. Abstract classes can have abstract as well as non abstract methods. We have to use abstract keyword for defining abstract classes, which then can be extended using extends keyword.

6. What is interface in Java?
Ans. An interface is also used to define structure of a class with full abstraction which means unlike abstract classes interfaces would not provide any implementation of methods.

7. What is the difference between abstract classes and interfaces?
Ans. There are many differences between them, one of the major difference is interface is used to apply full abstraction where as abstract classes can be used for partial abstraction.
For more information please visit : Difference between abstract classes and interfaces

8. What is the difference between method overloading and method overriding?
Ans. In method overloading same method name is used multiple times with different set of parameters in same class whereas in method overriding implementation of method from super class is override in sub classes without changing it's set of parameters.
Another difference is overloading is resolved at compile time because class information is know at compile time but overriding is resolved at runtime because object information is required to resolve overridden methods.

9. What are the rules for method overloading?
Ans. When we are overloading methods we need to take care that their signature should be different which can be achieved either by changing number of arguments or changing type of arguments. If we are trying to overload methods by simply changing it's return type then compiler will throw an exception. 

10. What are the rules for method overriding?
Ans. When we are overriding methods in sub class then we can't change below things :
1. Signature of method can not be changed.
2. Return type of method can not be changed.
3. Overloaded method can not throw higher exception.

11. What is covariant method overriding in Java?
Ans. Consider a scenario where we have a method in a parent class which is returning a general type like List class etc. and in our sub class we have to override the same method but it would return an ArrayList instead of List. We know that return type of overridden method can not be changed, right, but in this case we can change the return type to ArrayList because it is a sub type of List. This is known as covariant method overriding.

12. What is the difference between "IS A" and "HAS A" relationship?
Ans. The "is a" relationship is expressed with inheritance whereas "has a" relationship is expressed with composition. Both techniques are used for code re-usability. Consider below example for understanding both techniques :


"is a" relationship or inheritance is uni-directional. As shown in above example, House is a Building but Building is not a House. In Java programs to establish "is a" relationship we use extends keyword.
In above example there is "has a" relationship between House and Bathroom, it is incorrect to say House is a Bathroom. In order to establish "has a" relationship we create instances of other classes inside the main class.

13. When to use inheritance and composition?
Ans. Below are the rules that we should follow while using these two techniques :
1. Don't use inheritance relationship unnecessary just for code re-use. If there is no "is a" relationship between classes then composition should be used.
2. Overuse of inheritance (using extends keyword) can break all sub classes if super class is modifed hence use it carefully.
3. Do not use inheritance just to get Polymorphism. If there is no "is a" relationship and all we want is polymorphism then we can  use interfaces with object composition.

14. What is difference between Aggregation and Composition?
Ans. Aggregation is an association in which one class belongs to a collection of classes. That class is a part of whole relationship where a part can exist without a whole, which means if whole relationship is deleted then also that class can exists.
For example : Bill of an order placed contains line items which specifies which products we have ordered. If we delete line items from that order then we do not need to delete products. This means there is weaker relationship between line items and products.

Composition is an association in which one class belongs to a collection of classes. This is a part of whole relationship where a part cannot exist without a whole. If whole is deleted then all parts are deleted.
For example : If we delete the Order then all line items in that order will get deleted, because like line items can not exist without an order. 

15. What is difference between implementation inheritance and interface inheritance?
Ans. For answer please visit : OOPs Concepts - 2

Share:

Popular Posts

Recent Posts

Followers

Total Pageviews