View
152
Download
5
Embed Size (px)
Citation preview
Subject : Advance Java
Class : SYMCA
Subject Teacher : Dr. V. V Shaga
Unit-IObject Oriented Terminologies
Prepared By : Dr. V.V Shaga
Contents
• Classes & Objects• Methods & Overloading Methods• Constructors & Overloading Constructors• Using Object as Parameter• Returning Object• Static Variables & Methods• Command Line Arguments
Prepared By : Dr. V.V Shaga
What is a Class?
• A class is a blueprint/templates of objects.
Prepared By : Dr. V.V Shaga
•An object holds values for the variables defines in the class.•An object is called an instance of the Class•Everything in Java is an object• Real world Entity
Object life cycle:CreationUsageDestruction
What is an Object?
Prepared By : Dr. V.V Shaga
Object Creation
A variable s is declared to refer to the objects of type/class String:
String s;The value of s is null ; it does not yet refer to any object. A new String object is created in memory with initial “abc” value:
String s = new String(“abc”);Now s contains the address of this new object
Prepared By : Dr. V.V Shaga
Object Usage
Four usage scenarios: one variable, one object two variables, one object two variables, two objects one variable, two objects
Prepared By : Dr. V.V Shaga
Object Usageone variable, one object
String s = new String(“abc”);What can you do with the object addressed by s ?Example :
print the length: System.out.println(s.length() );
Prepared By : Dr. V.V Shaga
Object Usage
Two variable, one object
String s1 = new String(“abc”);String s2;Assignment copies the address, not value:
s2 = s1;Now s1 and s2 both refer to one object. After s1 = null; s2 still points to this object
Prepared By : Dr. V.V Shaga
Object Usage
Two variable, Two object
String s1 = new String(“abc”);String s2 = new String(“abc”);s1 and s2 objects have initially the same values:
s1.equals(s2) == trueBut they are not the same objects:
(s1 == s2) == falseThey can be changed independently of each other.
Prepared By : Dr. V.V Shaga
Object Usage
One variable, Two object
String s = new String(“abc”);s = new String(“xyz”);
The “abc” object is no longer accessible through any variable.
Prepared By : Dr. V.V Shaga
Example : Class & Object
A class with three variable members:class Box {
double width;double height;double depth;
}A new Box object is created and a new value assigned to its width variable:
Box myBox= new Box();myBox.width= 100;
Prepared By : Dr. V.V Shaga
Assignment
Create a Class Shape with attributes length,breadth,radius.Create objects rectangle and circle and set the values for the above attributes and display the area of both the shapes.
Prepared By : Dr. V.V Shaga
MethodsGeneral form of a method definition:
type name(parameter-list) {…return value; …}
Components:1) type : type of values returned by the method. If a method
does not return any value, its return type must be void.2)name : is the name of the method 3)parameter-list : is a sequence of type-identifier lists separated by commas4) return value indicates what value is returned by the method
Prepared By : Dr. V.V Shaga
Example for calling methodsWithin a class, we can refer directly to its member variables:
class Box { double width, height, depth; //Member variables void volume() //Member function or method { System.out.println(“Volume is :” + width* height * depth); }}
Prepared By : Dr. V.V Shaga
Example for calling methodsWhen an instance variable is accessed by code that is not part of the class in which that variable is defined, access must be done through an object:class BoxDemo{
public static void main(String args[]) {
Box mybox1 = new Box(); //creating instance of Boxmybox1.width = 10;mybox1.height = 20;mybox1.depth = 15; mybox1.volume(); //calling method of class
}}
Prepared By : Dr. V.V Shaga
Method Overloading
•It is legal for a class to have two or more methods with the same name.•However, Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments.•Therefore the same-named methods must be distinguished:
1) by the number of arguments, or2) by the types of arguments
Note : Overloading and inheritance are two ways to implement polymorphism
Prepared By : Dr. V.V Shaga
Constructors• A constructor initializes the instance variables of an object.• It is called immediately after the object is created but before
the new operator completes.– it is syntactically similar to a method– it has the same name as the name of its class– it is written without return type; the default return type of
a class constructor is the same class• When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.
Prepared By : Dr. V.V Shaga
Using Object as Parameter
void display(Test t) {
System.out.println("A="+t.a);System.out.println("B="+t.b);System.out.println("C="+t.c);
}public static void main(String args[])
{Test obj=new Test(2,3,4); obj.display(obj); // passing object as parameter
}
Prepared By : Dr. V.V Shaga
Returning Object
Test displayDetails(int a,int b,int c){ Test t=new Test();
t.a=a;t.b=b;t.c=c;return(t); //Returning Object ‘t’ in ‘newobj’
} public static void main(String args[])
{ Test obj=new Test(2,3,4); Test newobj;
newobj=obj.displayDetails(23,32,33);System.out.println(newobj.a + newobj.b +newobj.c);
}
Prepared By : Dr. V.V Shaga
Static Variables • It is a variable which belongs to the class and not to
object(instance)• Static variables are initialized only once , at the start
of the execution . • A single copy to be shared by all instances of the class• A static variable can be accessed directly by the class
name and doesn’t need any objectSyntax : <class-name>.<variable-name>
Prepared By : Dr. V.V Shaga
Static Methods
• It is a variable which belongs to the class and not to object(instance)
• A static method can access only static data. It can not access non-static data (instance variables)
• A static method can call only other static methods and can not call a non-static method from it.
• A static variable can be accessed directly by the class name and doesn’t need any object
Syntax : <class-name>.<method-name>
Prepared By : Dr. V.V Shaga
Command Line Arguments
• Command Line Arguments can be used to specify configuration information while launching your application.
• There is no restriction on the number of command line arguments. You can specify any number of arguments
• Information is passed as Strings.• They are captured into the String argument of
your main method
Prepared By : Dr. V.V Shaga
Command Line Argumentsclass Test{
public static void main(String b[]){System.out.println("Argument one = "+b[0]);System.out.println("Argument two = "+b[1]);}
}On Command Prompt:C:\>javac Test.javaC:\>java Test MCA STUDENTS
Prepared By : Dr. V.V Shaga
What is Inheritance?
• the ability of one class or object to possess characteristics and functionality of another class or object
• Advantages–Less duplication.–More generic code.–More robust design due to code reusability
Prepared By : Dr. V.V Shaga
Class Employee //Base or Parent or Super Class{string name;double wage;void incrementWage(){…}}
//Derived or Child or Sub class Class Manager extends Employee {string managedUnit;void changeUnit(){…}}
Manager m = new Manager(); //Creating instance of derived classm.incrementWage(); // inherited
Example
Prepared By : Dr. V.V Shaga
‘Super’ Keyword
“super” is a reference to the parent class or to access the members of the super class.Two Important uses:1) to access the hidden data variables of the
super class hidden by the sub class.2) is to call super class constructor in the
subclass
Prepared By : Dr. V.V Shaga
Accessing Variable of Super Classclass A{
int a; float b; void Show(){ System.out.println("b in super class: " + b); }}
class B extends A{ int a; float b; B( int p, float q){ a = p; super.b = q; // assigning value to super class variable } void Show(){ super.Show(); //calling super class method in derived class System.out.println("b in super class: " + super.b); System.out.println("a in sub class: " + a); } public static void main(String[] args){ B subobj = new B(1, 5); subobj.Show();}}
Prepared By : Dr. V.V Shaga
Calling Super Class Constructorclass A{
int a,b,c; A(int p, int q, int r){ a=p; b=q; c=r; } }
class B extends A{ int d; B(int l, int m, int n, int o){ super(l,m,n); // calling super class constructor d=o; } void Show(){ System.out.println("a = " + a + "b = " + b + "c = " + c + "d = " + d); } public static void main(String args[])
{ B b = new B(4,3,8,7); b.Show(); }
}
Prepared By : Dr. V.V Shaga
Method Overriding
• When method in a subclass has same name & type signature as method in its super class, then method in subclass is said to override the method in the super class.
• Overridden methods allow Java to support run-time polymorphism
Prepared By : Dr. V.V Shaga
Example
class ORDemo //Base Class{ int i,j; ORDemo(int x,int y) { i=x; j=y; } void show() //overridden method { System.out.println("super class values i & j=" + i + " " + j); }}
Cont…
Prepared By : Dr. V.V Shaga
Example
class MORDemo extends ORDemo{ int k; MORDemo(int x,int y,int z) { super(x,y); k=z; } void show() { //overriding method super.show(); System.out.println("derived class values k=" + k); } public static void main(String args[]) { MORDemo m=new MORDemo(1,2,3); m.show(); //this will call method of derived class } }
Prepared By : Dr. V.V Shaga
Assignment
• Write a program that creates a super class Figure that stores the dimensions of various two-dimensional objects. It also defines a method called area() that computes the area of an object. The program derives two subclasses from Figure. The first is Rectangle & the second is Triangle. Each of these subclasses overrides area() so that it returns the area of a Rectangle & a Triangle.
Prepared By : Dr. V.V Shaga
Rules for method overriding
1. The argument list should be exactly the same as that of the overridden method.
2. The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
3. The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overriding method in the sub class cannot be private . However the access level can be less restrictive than the overridden method's access level.
4. A method declared final cannot be overridden.
Cont…
Prepared By : Dr. V.V Shaga
6. A method declared static cannot be overridden but can be re-declared.
7. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
8. A subclass in a different package can only override the non-final methods declared public or protected.
9. Constructors cannot be overridden.10. The overriding method can throw narrower or fewer
exceptions than the overridden method.
Rules for method overriding
Prepared By : Dr. V.V Shaga
Abstract class & methods
• super class cannot have any instance and such of classes are called abstract classes.
• Abstract classes usually contain abstract methods. Abstract method is a method signature (declaration) without implementation.
Prepared By : Dr. V.V Shaga
Example
public abstract class Player // class is abstract { private String name; public Player(String vname) { name=vname; } public String getName() // regular method { return (name); } public abstract void Play(); // abstract method: no implementation }
NOTE : Subclasses must override the method & provide its implementation If all the abstract methods of super class are not defined in this new class this class also will
become abstract
Prepared By : Dr. V.V Shaga
‘final’ Keyword
In Java programming the final key word is used for three purposes:
a. Making constants b. Preventing method to be overridden c. Preventing a class to be inherited
Prepared By : Dr. V.V Shaga
• The final keyword is a way of marking a variable as "read-only". Its value is set once and then cannot be changed.
For example, if year is declared as final int year = 2005; Variable year will be containing value 2005
and cannot take any other value after words.
‘final’ Keyword
Prepared By : Dr. V.V Shaga
‘final’ Keyword
• Prevents a method from being overridden• Example:
class A { final void show(){…. } }class B extends A{void show(){… // Compile time ERROR ! Can’t override}}
Prepared By : Dr. V.V Shaga
‘final’ Keyword
• Prevents a class from being inherited• Example:
final class A { //implicitly declares all of its methods as final
} }class B extends A{// ERROR ! Can’t inherit}
Prepared By : Dr. V.V Shaga
Packages
• A package is a collection of related classes and interfaces providing access protection and namespace management.
Prepared By : Dr. V.V Shaga
Types of Packages
• Pre-defined – java.lang.*(for achieving language functionalities)– java.io.*(for file handling operations)– java.applet.* (for browser oriented applications)– java.sql.* (for operations on databases)– java.text.*(for formatting date & time)– java.net.* (for client server applications)
Prepared By : Dr. V.V Shaga
Types of Packages
• User-defined : one which is developed by java Programmers
Syntax: keyword
package pack1[.pack2[.pack3….[.pack n…]];
Example:package P1;package P1.P2;
Prepared By : Dr. V.V Shaga
Steps for Developing Packages
1. Choose appropriate package name & package statement must be first executable statement
2. Choose appropriate class name whose modifier must be public
3. The modifier of Constructors & methods of a class must be public
4. Give the filename as class name with extension .java
Prepared By : Dr. V.V Shaga
Examplepackage tp; //package statement with package name tppublic class Test // class modifier public{ public Test() // constructor modifier public { System.out.println("Test - Default Constructor"); } public void show() // function modifier public { System.out.println("Test - Show function"); }}Note : for compiling packages use following on command prompt:
javac - d . Test.java This will create a .class file in ‘tp’ package.
Prepared By : Dr. V.V Shaga
Using package classes
import tp.Test; // import keyword for accessing classesclass PackDemo{ public static void main(String args[]) { Test t1=new Test(); t1.show(); }}
Prepared By : Dr. V.V Shaga
Interfaces
• An interface is like a class with nothing but abstract methods and final, static fields.
• All methods and fields of an interface must be public.
• As Java does not support multiple inheritance, interfaces are seen as the alternative of multiple inheritance, because of the feature that multiple interfaces can be implemented by a class.
Prepared By : Dr. V.V Shaga
Interface Declaration
interface Calculate { float pi=3.14f; //final and static by default double calculateArea(int r); }
Prepared By : Dr. V.V Shaga
Implementing Interface
class InterfaceDemo implements Calculate{ public double calculateArea(int r) { return (3.14*r*r); } public static void main(String args[]) { Calculate d= new InterfaceDemo(); System.out.println("Area is:"+d.calculateArea(4)); }}
Unit-1Exception Handling
Prepared By : Dr. V.V Shaga
Contents
• Exceptions• Exception Hierarchy• Types of Exception• Java Exception Handling• Using Try-Catch• Multiple Catch Blocks• Finally• throw and throws • User Defined (Custom) Exceptions
Prepared By : Dr. V.V Shaga
Exceptions
• An exception is an abnormal condition that arises in a code sequence at run time.
• In other words, an exception is a run-time error
• A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code
Prepared By : Dr. V.V Shaga
Exceptions
• When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error
Prepared By : Dr. V.V Shaga
Exception HierarchyObject
Throwable
Exception
IOException
SQLException
RuntimeExceptio
nArithmeticException
NullPointerExceptio
nNumberFormatExceptio
n
Error
Prepared By : Dr. V.V Shaga
Types of Exceptions
Checked
• Extends Throwable Class except RuntimeExceptions and Errors
• Eg. IOException , SQLException
• Checked at Compile-time
Unchecked
• Extends RuntimeExceptions
• Eg. ArithematicException,NullPointerException,ArrayIndexOutOfBoundException
• Checked at runtime
Error
• Error is Irrecoverable• Eg.
OutOfMemoryError, VirtualMachineError etc
Prepared By : Dr. V.V Shaga
Examples of Exceptions1. int a=50/0; //ArithmeticException
2. String s=null; System.out.println(s.length());//NullPointerException
3. String s="abc"; int i=Integer.parseInt(s);//NumberFormatException
4. int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
5. int num = s.nextInt(); Enter an Integer: abc // InputMismatchException
Prepared By : Dr. V.V Shaga
Java Exception Handling Keywords
There are 5 keywords used in java exception handling:– try– catch– finally– throw– throws
Prepared By : Dr. V.V Shaga
Using Try and Catch
Try•Java try block is used to enclose the code that might throw an exception. •It must be used within the method.•must be followed by either catch or finally block.
Catch•Java catch block is used to handle the Exception. •You can use multiple catch block with a single try.
Prepared By : Dr. V.V Shaga
Using Try and Catchpublic class TestTryCatch { public static void main(String args[]){ try{ int data=50/0; //throws exception }
catch(ArithmeticException e){System.out.println(e);}
} }
Prepared By : Dr. V.V Shaga
Internal working of Try-catch
Prepared By : Dr. V.V Shaga
Multiple catch blocks:
• You can have any number of catch blocks after a single try block.
• If an exception occurs in the guarded code the exception is passed to the first catch block in the list.
• If the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed down to the next catch block.
• This continue until the exception is caught or falls through all catches.
Prepared By : Dr. V.V Shaga
Multiple catch blocks:public class TestMultipleCatchBlock {public static void main(String[] args) {
try {int a[] = new int[5];a[6] = 30 / 3;
}catch (ArithmeticException e) {
System.out.println("ArithmeticException");} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException");}
System.out.println("Rest of the code...");} }
1
2
Prepared By : Dr. V.V Shaga
finally block
• Java finally block is a block that is used to execute important code such as closing connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block must be followed by try or catch block.
Prepared By : Dr. V.V Shaga
finally blockclass TestFinallyBlock{ public static void main(String args[]){
try{ int data=25/5;
System.out.println(data); } catch(NullPointerException e) {
System.out.println(e);} finally {
System.out.println("finally block is always executed");}
System.out.println(“Rest of the code..."); } }
Prepared By : Dr. V.V Shaga
finally block
Prepared By : Dr. V.V Shaga
‘throw’ keyword
• The Java throw keyword is used to explicitly throw an exception.
• We can throw either checked or unchecked exception in java by throw keyword.
• The throw keyword is mainly used to throw custom exception.
Prepared By : Dr. V.V Shaga
‘throw’ keywordpublic class TestThrow1{ static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); } }
Prepared By : Dr. V.V Shaga
‘throws’ keyword• Any method capable of causing exceptions
must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about
which exceptions to handle. • A method can do so by using the throws
keyword.
Prepared By : Dr. V.V Shaga
‘throws’ keywordclass Test {
static void check() throws ArithmeticException { System.out.println("Inside check function");
throw new ArithmeticException("demo"); }
public static void main(String args[]) {
try{ check(); } catch(ArithmeticException e) {
System.out.println("caught" + e); }
}}
Prepared By : Dr. V.V Shaga
User Defined Exceptions (Custom Exceptions)
• We can also create your own exception sub class simply by extending java Exception class.
• We can define a constructor for your Exception sub class (not compulsory) and you can override the toString() function to display your customized message on catch.
Prepared By : Dr. V.V Shaga
User Defined Exceptions (Custom Exceptions)
class MyException extends Exception{ String str1; MyException(String str2) { str1=str2; } public String toString(){ return ("Output String = "+str1) ; }}
Prepared By : Dr. V.V Shaga
User Defined Exceptions (Custom Exceptions)
class TestMultipleCatchBlock{ public static void main(String args[]){ try{ throw new MyException("My CustomException"); } catch(MyException exp){ System.out.println(exp) ; } }}
Unit – I
Serialization
Prepared By : Dr. V.V Shaga
Contents
• Serializable Keyword• Object Serialization
Prepared By : Dr. V.V Shaga
Serialization• Serialization is a process of converting an
object into a sequence of bytes which can be persisted to a disk or database or can be sent through streams.
• The reverse process of creating object from sequence of bytes is called deserialization.
• A class must implement Serializable interface present in java.io package in order to serialize its object successfully.
Prepared By : Dr. V.V Shaga
Serialization
• Serializable is a marker interface (has no data member and method) that adds serializable behaviour to the class implementing it.
• Java provides Serializable API encapsulated under java.io package :– java.io.Serializable– java.io.Externalizable– ObjectInputStream– and ObjectOutputStream etc.
Prepared By : Dr. V.V Shaga
Object Serialization
• Object serialization is a mechanism where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
• After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
Prepared By : Dr. V.V Shaga
Object Serialization
Prepared By : Dr. V.V Shaga
Object Serialization• The entire process is JVM independent, meaning
an object can be serialized on one platform and deserialized on an entirely different platform.
• Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
NOTE : Static members are never serialized because they are
connected to class not object of class.
Prepared By : Dr. V.V Shaga
Serializing ObjectStudentInfo.java
import java.io.*;public class StudentInfo implements
Serializable {
int roll;String name;
StudentInfo(int r,String n){this.roll=r;this.name=n;
}}
Prepared By : Dr. V.V Shaga
Serializing ObjectTestStudentInfo.java
import java.io.*;
public class TestStudentInfo {public static void main(String[] args) {
StudentInfo obj=new StudentInfo(10,"Vikrant");try{FileOutputStream fos=new FileOutputStream("Viks.txt");ObjectOutputStream oos=new ObjectOutputStream(fos);oos.writeObject(obj); // writing object to fileoos.close();fos.close();}catch(Exception ex){System.out.println(ex);}
}
Prepared By : Dr. V.V Shaga
Deserialization of ObjectTestStudentInfo.javaimport java.io.*;public class TestStudentInfo {public static void main(String[] args) {
StudentInfo si=null ; try { FileInputStream fis = new FileInputStream("Viks.txt"); ObjectInputStream ois = new ObjectInputStream(fis);
si = (StudentInfo)ois.readObject(); // Deserialization of Object } catch (Exception e) { System.out.println(e); } System.out.println(si.roll); System.out. println(si.name);}
Prepared By : Dr. V.V Shaga
Why to Serialize?
The Objects can be Serialized to achieve following : To save objects into file at the time of execution To read and write later in the same application Transmit object over a network To support persistence in java objects Maintain the java objects type and safety properties in
serialized form To communicate via sockets or Remote Method
Invocation (RMI) To implement java beans
Prepared By : Dr. V.V Shaga
Questions1. What is Serialization ? What we can achieve by
Serializing the Object?2. What is object stream? Explain different types of
object streams.3. List out the different methods of
ObjectOutputStream.4. What are the steps involved in serialization?5. WAP to serialize the object employee whose instance
variable are emp_code and emp_name . There are atleast 5 records of employee are expected. In the same program deserialize the object.
Prepared By : Dr. V.V Shaga
References
• http://www.studytonight.com• http://www.javatpoint.com• https://www.tutorialspoint.com/
Prepared By : Dr. V.V Shaga
Fill in the blanks
A) The path travelled by data in a program is known as __________________
B) The ability of an object to record its state so that it can be reproduced in future is called___________________
C) The class which is responsible for reading objects from stream is __________________
Unit – I
JDBC(Java Database Connectivity)
Prepared By : Dr. V.V Shaga
Contents
• Introduction to JDBC• JDBC Architecture• JDBC Drivers• Steps to Create JDBC Application• Operations– Insert– Update– Delete– Select
Prepared By : Dr. V.V Shaga
JDBC (Java Database Connectivity)
• JDBC is Java application programming interface (API) that allows the Java programmers to access database management system from Java code
• defines interfaces and classes for writing database applications in Java by making database connections.
• executing SQL statements and supports basic SQL functionality.
• It provides RDBMS access by allowing you to embed SQL inside Java code.
Prepared By : Dr. V.V Shaga
JDBC Architecture
Application JDBC Driver
• Java code calls JDBC library• JDBC loads a driver • Driver talks to a particular database• Can have more than one driver -> more than one
database• Ideal: can change database engines without changing
any application code
Prepared By : Dr. V.V Shaga
JDBC Drivers
JDBC
Type I“Bridge”
Type II“Native”
Type III“Middleware”
Type IV“Pure”
ODBC ODBCDriver
CLI (.lib)
MiddlewareServer
Prepared By : Dr. V.V Shaga
Type I Drivers
• Use bridging technology• Requires installation/configuration on client
machines• Not good for Web• e.g. ODBC Bridge
Prepared By : Dr. V.V Shaga
Type II Drivers
• Native API drivers• Requires installation/configuration on client
machines• Used to leverage existing libraries• Usually not thread-safe• Mostly out-dated now• e.g. Intersolv Oracle Driver, WebLogic drivers
Prepared By : Dr. V.V Shaga
Type III Drivers
• Calls middleware server, usually on database host
• Very flexible -- allows access to multiple databases using one driver
• Only need to download one driver• But it’s another server application to install
and maintain• e.g. Symantec DBAnywhere
Prepared By : Dr. V.V Shaga
Type IV Drivers
• 100% Pure Java• Use Java networking libraries to talk directly
to database engines• Only disadvantage: need to download a
new driver for each database engine• e.g. Oracle, mySQL
Prepared By : Dr. V.V Shaga
Steps for Creating JDBC Application
1.Establish a Connection2.Create JDBC Statements3.Execute SQL Statements4.GET ResultSet 5.Close connections
Prepared By : Dr. V.V Shaga
1. Establish a connection
• import java.sql.*;• Load the vendor specific driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");// Dynamically loads a driver class for databases
• Make the connection Connection con = DriverManager.getConnection(“jdbc:odbc:DSNName”,
"","");// Establishes connection to database by obtaining
a Connection object
Prepared By : Dr. V.V Shaga
2. Create JDBC statement(s)
Three kinds of Statements:
Statement: Execute simple sql queries without parameters.Statement st= con.createStatement() ; Creates an SQL Statement object.
Prepared Statement: Execute precompiled SQL queries with or without parameters.PreparedStatement objects are precompiled SQL statements.Ex:PreparedStatement ps=con.prepareStatement("insert into Student values(?,?,?,?)")
Callable Statement: Execute a call to a database stored procedure.CallableStatement cs=con.prepareCall(String sql)returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements.
Prepared By : Dr. V.V Shaga
3)Executing SQL Statements
String insertStud = "Insert into Student values (1,’Vikrant’,’Pune’)";
st.executeUpdate(insertStud );
Prepared By : Dr. V.V Shaga
4) Get ResultSet
String query = "select * from Student";
ResultSet rs = st.executeQuery(query);
while ( rs.next() ){
System.out.println(rs.getInt(1) + " " + rs.getString(2)+ “ ” + rs.getString(3));}
Prepared By : Dr. V.V Shaga
5) Close connection
st.close();con.close();
Prepared By : Dr. V.V Shaga
Sample JDBC Program// for insertion of recordsimport java.sql.*;public class Employee {
static Connection con=null;static PreparedStatement pst=null;static String username="postgres";static String pwd="root";static String
connURL="jdbc:postgresql://localhost:5433/postgres";public static void main(String[] args) {try{//loading the driversClass.forName("org.postgresql.Driver");
//Establish the connection
con=DriverManager.getConnection(connURL,username,pwd);pst=con.prepareStatement("insert into employee
values(?,?)");
Prepared By : Dr. V.V Shaga
Sample JDBC Program
pst.setInt(1, 1009);pst.setString(2, "G.D Agrawal");//Executing the SQL statementint x=pst.executeUpdate();System.out.println( x +" Record inserted..");//Close the Connectionscon.close();
}catch(Exception ex) {
System.out.println(ex);}
}}
Unit-1Collections
Prepared By : Dr. V.V Shaga
Contents
• Collections• Collection Interface• Types of Collections– Set– List– Queue
Prepared By : Dr. V.V Shaga
Collections
• Collections is a group of objects which could be homogenous or heterogeneous with some size.
• Collections in Java are data-structures primarily defined through a set of classes and interface
• It is also refer to as a container which contains the group of multiple elements into a single unit.
Prepared By : Dr. V.V Shaga
Collections
• Collections are used :– To generalize the array concept– To store multiple types of objects– Resizable– To define set of interfaces for storing java objects
• So collection is a group of classes which gives the functionality of managing : Vectors, ArrayList, HashMap, LinkedList, Stack and Hashtable.
Prepared By : Dr. V.V Shaga
Collection Interface • Collection Interface uses following methods :– add() – to add element in collection– remove()- to remove element from collection– toArray() - convert collection into array of elements– contains() - to check if a specified element is in the
collection respectively.• Collection Interface is a sub-interface of Iterator
Interface. The Iterator interface provides the iterator() method that goes through all of the elements in the collection.
Prepared By : Dr. V.V Shaga
Types of CollectionsTypes of Collection
Sets
HashSet
TreeSet
LinkedHashSet
Lists
ArrayList
LinkedList
Vector
Queue
Prepared By : Dr. V.V Shaga
Set Interface
Types of Collections
Extends collection interface• Doesn’t allow duplicate elements• Supports all methods present in collection
interface Method Description
boolean add(Object element) It returns false if element already present in Set
boolean addAll(Collection c) If all the elements of specified collection are part of set, it returns false
Prepared By : Dr. V.V Shaga
Set Interface
Types of Collections
Set Interface:
HashSet class
•Implemented using a hash table•No ordering of elements.•add, remove, and contains methods constant time complexity O(c)
TreeSet class•Implemented using a tree structure.•Guarantees ordering of elements.•add, remove, and contains methods logarithmic time complexity O(log (n)), where n is the number of elements in the set.
Prepared By : Dr. V.V Shaga
Set InterfaceTypes of Collections
LinkedHashSet class
•Subclass of HashSet•Maintains Doubly linked list of the entries in the set•Fixed order but not sorted manner•Both HashSet and LinkedHashSet have the same constructor
Prepared By : Dr. V.V Shaga
Set InterfaceTypes of Collections
import java.util.*;public class TestHashSet {public static void main(String[] args) {
HashSet obj=new HashSet();obj.add("A");obj.add("B");obj.add("C");obj.add("A");System.out.println(obj+"\n");System.out.println("Size :" + obj.size());}}
OUTPUT:
[A, B, C]
Size :3
Prepared By : Dr. V.V Shaga
Types of Collections
List Interface: ( List is ordered collection called as sequence ) .
• ArrayList and LinkedList are implementation classes of List interface.
• Extends collection interface• May have duplicate elements• Elements in list Indexed from 0 to list.size• Elements added at the end of list.• After removing nth element , all next elements shifted
one position up
Prepared By : Dr. V.V Shaga
Types of Collections Method Description
boolean add(Object element)void add (int index,Object element)
Ensures collection contains the specified element. If index given then element added at specified index otherwise at the end of list
boolean addAll(Collection c)boolean addAll(int index , Collection c)
Inserts all the elements from specified collection into this collection. If index is supplied , then position is selected for insertion. Else at the end inserted
List Interface
Prepared By : Dr. V.V Shaga
Types of Collections Method Description
boolean get(int index) Return the indexth entry in the list
boolean remove(Object element)Object remove(int index)
Removes element from collection. We can remove element of specified index number. First method with Boolean returntype returns the value indicating whether element was removed or not
List Interface
Prepared By : Dr. V.V Shaga
Types of Collections
List Interface
ArrayList class•ArrayList is an array based implementation where elements can be accessed directly via the get and set methods.•Can be dynamically increase or decrease•Three Constructors:•ArrayList() , •ArrayList(Collection C),•ArrayList(int initialcapacity)
LinkedList class
•Gives better performance on add and remove compared to ArrayList.•Gives poorer performance on get and set methods compared to ArrayList .
Prepared By : Dr. V.V Shaga
Types of Collections
Queue Interface:• Queue is a collection used to hold multiple
elements prior to processing. • Besides basic Collection operations, a Queue
provides additional insertion, extraction, and inspection operations.
• Order elements in a FIFO (first-in, first-out) manner
• In a FIFO queue, all new elements are inserted at the tail of the queue.
Prepared By : Dr. V.V Shaga
Collection Framework
• Collection Framework is the unified architecture that represent and manipulate collections.
• The collection framework provides a standard common programming interface to many of the most common abstraction without burdening the programmer with many procedures and interfaces.
• It provides a system for organizing and handling collections.
Prepared By : Dr. V.V Shaga
Collection Framework
This framework is based on:– Interfaces that categorize common collection
types.– Classes which proves implementations of the
Interfaces.– Algorithms which proves data and behaviors need
when using collections i.e. search, sort, iterate etc.
Prepared By : Dr. V.V Shaga
Hierarchical representation of Interfaces in Collection
Framework
Collection
List Set
SortedSet
Map
SortedMap