Ad Java CIE-2 Notes
Ad Java CIE-2 Notes
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and
fields in your current class also.
Example Program
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
class Animal{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
Output:
meowing...
eating...
eating...
barking...
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body
of the method.
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Note :
class B extends A
{
void m1()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Syntax:
interface <interface_name>{
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Keywor Description
d
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed
by finally block later.
finally The "finally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
System.out.println("normal flow..");
}
}
Output:
exception handled
normal flow...
TestFinallyBlock1.java
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try block");
try {
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute
the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses
JDBC drivers to connect with the database. There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
We can use JDBC API to access tabular data stored in any relational database. By the
help of JDBC API, we can save, update, delete and fetch data from the database. It is
like Open Database Connectivity (ODBC) provided by Microsoft.
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
insert, update, delete and select query execution using java program.
i). Insert
package firstprogram;
import java.sql.*;
import java.sql.DriverManager;
public class Insertdetails {
public static void main(String args[])
{
int id=2;
String name = "spanner";
int quantity=35;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory",
"root","root1234");
Statement stmt=con.createStatement();
String q1 = "insert into inventory values('" +id+ "', '" +name+ "', '" +quantity+ "')";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
ii) Update
package firstprogram;
// Updating database
String q1 = "UPDATE inventory " +
"SET name = 'nuts' WHERE id in (3)";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("name Successfully Updated");
else
System.out.println("ERROR OCCURRED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
iii). Delete
package firstprogram;
// Updating database
String q1 = "DELETE FROM inventory " +
"WHERE id = 3";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("table Successfully Updated");
else
System.out.println("ERROR OCCURRED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
iv). Select
package firstprogram;
import java.sql.*;
public class InsertDemo {
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/inventory","root","root1234");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from inventory");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
JAVA SERVLETS
Java Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the web server,
process the request, produce the response, and then send a response back to the web
server.
Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology.
We have discussed these disadvantages below.
Definition : Servlets are modules of Java code that run in a server application (hence the name
"Servlets", similar to "Applets" on the client side) to answer client requests.
Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP
and the word "Servlet" is often used in the meaning of "HTTP Servlet".
Servlets make use of the Java standard extension classes in the packages javax. servlet (the basic
Servlet framework) and javax. servlet .http
Typical uses for HTTP Servlets include:
o Processing and/or storing data submitted by an HTML form.
o Providing dynamic content, e.g. returning the results of a database query to the client.
o Managing state information on top of the stateless HTTP, e.g. for an online shopping cart
system which manages shopping carts for many concurrent customers and maps every request
to the right customer.
Servlet Life Cycle
The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When
a request is mapped to a servlet, the container performs the following steps:
1. If an instance of the servlet does not exist, the web container:
a. Loads the servlet class
b. Creates an instance of the servlet class
c. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a
Servlet
2. Invokes the service method, passing a request and response object.
3. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy
method.
1.1 A servlet example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http. *;
public class HelloClientServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html"); PrintWriter out = res.getWriter();
out.println("<HTML><HEAD><TITLE>Hello Client !</TITLE>"+
"</HEAD><BODY>Hello Client !</BODY></HTML>"); out.close();
}
public String getServletInfo()
{
return "HelloClientServlet 1.0 by Stefan Zeiger";
}
}
Servlet API
● Two packages contain the classes and interfaces that are required to build servlets. They are
javax.servlet and javax.servlet.http.
● The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All
servlets must implement the Servlet interface, which defines life cycle methods.
The servlet packages :
The javax.servlet package contains a number of classes and interfaces that describe and define the
contracts between a servlet class and the runtime environment
provided for an instance of such a class by a conforming servlet container. The Servlet interface is the
central abstraction of the servlet API.
All servlets implement this interface either directly, or more commonly, by extending a class that
implements the interface.
The two classes in the servlet API that implement the Servlet interface are GeneriISErvlet and
HttpServlet .
For most purposes, developers will extend HttpServlet to implement their servlets while
implementing web applications employing the HTTP protocol.
The basic Servlet interface defines a service method for handling client requests. This method is called
for each request that the servlet container routes to an instance of a servlet.
Handling HTTP requests and responses :
• Servlets can be used for handling both the GET Requests and the POST Requests.
• The HttpServlet class is used for handling HTTP GET Requests as it has som specialized methods
that can efficiently handle the HTTP requests. These methods are;
doGet()
doPost()
doPut()
doDelete() doOptions() doTrace() doHead()
An individual developing servlet for handling HTTP Requests needs to override one of these
methods in order to process the request and generate a response. The servlet is invoked dynamically
when an end-user submits a form.
Example:
<form name="F1" action=/servlet/ColServlet> Select the color: <select name = "col" size = "3">
<option value = "blue">Blue</option> <option value = "orange">Orange</option> </select>
<input type = "submit" value = "Submit"> </form>
Here’s the code for ColServlet.java that overrides the doGet() method to retrieve data from the HTTP
Request and it then generates a response as well.
// import the java packages that are needed for the servlet to work import java.io .*;
import javax.servlet. *;
import javax.servlet.http. *;
// defining a class
public class ColServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException
// request is an object of type HttpServletRequest and it's used to obtain information
// response is an object of type HttpServletResponse and it's used to generate a response // throws is
used to specify the exceptions than a method can throw
{
String colname = request.getParameter("col");
// getParameter() method is used to retrieve the selection made by the user
response.setContentType("text/html");
PrintWriter info = response.getWriter(); info .println("The color is: ");
info .println(col);
info.close();
}
}