Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Ad Java CIE-2 Notes

Inheritance in Java allows one class to inherit properties and behaviors from another, facilitating code reuse and extension. There are various types of inheritance, including single, multilevel, and hierarchical, each demonstrating different relationships between classes. Additionally, concepts such as the super keyword, method overriding, abstract classes, and interfaces are essential for understanding Java's object-oriented programming capabilities.

Uploaded by

nahcolnt.78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Ad Java CIE-2 Notes

Inheritance in Java allows one class to inherit properties and behaviors from another, facilitating code reuse and extension. There are various types of inheritance, including single, multilevel, and hierarchical, each demonstrating different relationships between classes. Additionally, concepts such as the super keyword, method overriding, abstract classes, and interfaces are essential for understanding Java's object-oriented programming capabilities.

Uploaded by

nahcolnt.78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Inheritance in Java

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.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

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);
}
}

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
In java programming, multiple and hybrid inheritance is supported.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

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...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can
see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal class,
so there is hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class
instance variable.
We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Output:
black
white

2) super can be used to invoke parent class


method
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method
is overridden.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:

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

Creating a Multilevel Inheritance Hierarchy in Java

Inheritance involves an object acquiring the properties and behaviour of


another object. So basically, using inheritance can extend the functionality of
the class by creating a new class that builds on the previous class by
inheriting it.

Multilevel inheritance is when a class inherits a class which inherits another


class. An example of this is class C inherits class B and class B in turn
inherits class A.

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();
}
}

Method Overriding in Java


if subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.

o Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message deliver

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.

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.

Example of abstract class


abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as
an abstract method.
abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract


method
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Understanding the real scenario of Abstract class
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., g
etShape() method
s.draw();
}
}

Using final with inheritance


During inheritance, we must declare methods with the final keyword for
which we are required to follow the same implementation throughout all
the derived classes. Note that it is not necessary to declare final methods
in the initial stage of inheritance(base class always). We can declare a final
method in any subclass for which we want that if any other class extends
this subclass, then it must follow the same implementation of the method
as in that subclass.

Using final to Prevent Inheritance


When a class is declared as final then it cannot be subclassed i.e. no other
class can extend it. This is particularly useful, for example, when creating
an immutable class like the predefined String class. The following
fragment illustrates the final keyword with a class:

final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}

Note :

● Declaring a class as final implicitly declares all of its methods as


final, too.
● It is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its
subclasses to provide complete implementations. For more on
abstract classes, refer abstract classes in java

Using final to Prevent Overriding


When a method is declared as final then it cannot be overridden by
subclasses. The Object class does this—a number of its methods are final.
The following fragment illustrates the finalkeyword with a method:
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}

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.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table
describes each.

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.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will
not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw an exception
}finally{}

Java catch block


Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block
with a single try block.

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to
be nested.
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....

Java Nested try Example


Example 1
Let's see an example where we place a try block within another try block for two
different exceptions.
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are checked
at the compile time instead of runtime and we can create custom exceptions making
the code recovery and debugging easier.

Java throw keyword


The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related to
user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is
mainly used to throw a custom exception. We will discuss custom exceptions later in
this section.
We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a number
by another number. Here, we just need to set the condition and throw exception using
throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
1. throw new exception_class("error message");
Let's see the example of throw IOException.
1. throw new IOException("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually
extend the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer as
a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.
TestThrow1.java
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to
provide the exception handling code so that the normal flow of the program can be
maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as NullPointerException, it is programmers' fault that he
is not checking the code before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name
2. {
3. //method code
4. }

Which exception should be declared?


Ans: Checked exception only, because:
o unchecked exception: under our control so we can correct our code.
o error: beyond our control. For example, we are unable to do anything if there
occurs VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.

Java throws Example


Let's see the example of Java throws clause which describes that checked exceptions
can be propagated by throws keyword.
Testthrows1.javaimport java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Output:

exception handled
normal flow...

Java finally block


Java finally block is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.
The finally block follows the try-catch block.
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.

Usage of Java finally


Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur


Let's see the below example where the Java program does not throw any exception,
and the finally block is executed after the try block.
TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}

Case 2: When an exception occurr but not handled by the


catch block
Let's see the the fillowing example. Here, the code throws an exception however the
catch block cannot handle it. Despite this, the finally block is executed after the try
block and then the program terminates abnormally.

TestFinallyBlock1.java
public class TestFinallyBlock1{
public static void main(String args[]){

try {
System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

Case 3: When an exception occurs and is handled by the


catch block
Example:
Let's see the following example where the Java code throws an exception and the
catch block handles the exception. Later the finally block is executed after the try-catch
block. Further, the rest of the code is also executed normally.
TestFinallyBlock2.java
public class TestFinallyBlock2{
public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

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.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dyna
the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database

Syntax of getConnection() method


1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of
responsible to execute queries with the database.

Syntax of createStatement() method


public Statement createStatement()throws SQLException

Example to create the statement object


Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database.
returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


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

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close(
Connection interface is used to close the connection.

Syntax of close() method


public void close()throws SQLException

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object


con.close();

}catch(Exception e){ System.out.println(e);}

}
}

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;

// Java program to illustrate


// updating the Database
import java.sql.*;

public class update1


{
public static void main(String[] args)
{
int id=3;
String name = "name";
String newname="bolt";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/inventory","root","root1234");
Statement stmt = con.createStatement();

// 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;

// Java program to illustrate


// updating the Database
import java.sql.*;

public class Delete1


{
public static void main(String[] args)
{
int id=3;
String name = "name";
String newname="nuts";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory","root","root1234")
;
Statement stmt = con.createStatement();

// 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.

Properties of Java Servlet

The properties of Servlets are as follows:

Servlets work on the server side.


Servlets are capable of handling complex requests obtained from 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();
}
}

You might also like