You are on page 1of 51

1

Core Java Training

2
Objectives
• Abstract classes
• Interface
• Exception Handling
• Collection Framework
• File IO Basics
• Multithreading Basics
• JDBC

3
Abstract Class
• Abstract class is which doesn’t have any existence. So we can’t
instantiate abstract class.
• If any method within a class is abstract then the class should be
abstract.
• Abstract class can contain abstract method as well as concrete
method.
• The class which inherits abstract class should implement all the
abstract methods, if not then we have to make child class as
abstract class.
• Don’t use abstract & final combination

4
Example :

abstract class Shape{


abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}
class TestAbstraction{
public static void main(String args[]){
Shape s=new Circle();
s.draw();
} } 5
Interface
interface Printable{ public void print(); }

• Why Interface ? To implement multiple interfaces. For


loose coupling, interface is not tightly coupled with any
specific hierarchy.
• Interface contains only abstract methods.
• Variables declared within the interface are by default
public, static and final
• Method declared within the interface are public and
abstract
• In implementation class provide implementation of
abstract method else make the class as abstract.
• We cannot instantiate interface.
6
Interface
interface printable{
void print();
}

class DemoImpl implements printable{


public void print()
{
System.out.println("Hello");
}

public static void main(String args[]){


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

7
Interface
• Valid Combination:
• Class extends Class
• Class implements interface
• Interface extends interface

8
String Class
• It’s a built in class from java.lang package.
• It is a first class object (This doesn’t require
new keyword).
String s =“Hello”;
• It is immutable (can’t modify the content of
the existing string)

9
String Buffer
• It’s a built in class from java.lang package.
• String buffer class is mutable
• It is synchronized.

• StringBuffer sb=new StringBuffer(“Hello”);


String s1=”India”;
System.out.println(sb.append(s1));

10
Wrapper Classes
• Wrapper class in java provides the mechanism to convert
primitive into object and object into primitive.
Primitive Type Wrapper class
boolean Boolean
int Integer
long Long
double Double

• We require wrapper classes for parsing the value


Integer .ParseInt() - > It will convert String into int type
• We require wrapper classes for collection

11
Auto Boxing & Auto Unboxing
• Auto Boxing:
int i = 10;
// Integer obj = new Integer(i); ->Before java 1.5
Integer obj = i; ->From java 1.5

• Auto UnBoxing:
//Integer obj = new Integer(10);
//int i = obj.intValue(); -> Before java 1.5
Int i = obj; From 1.5 (Auto Unwrapping)

12
Exception Handling
• The exception handling in java is one of the
powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained..

Ex:
• Number format exception
• Array Index out of bound exception
• Arithmetic exception
• Null pointer exception
• Custom Exception

13
Exception Hierarchy

14
Exception Hierarchy
• Throwable (super class)

• Errors (Errors occurred because of internal problem. Ex:


Memory issues, system issues etc.. We can’t handles errors)

• Exceptions (We can handle exceptions)


- Unchecked (Unchecked exception which we don’t need to
handle. JVM handles this)

- Checked (Checked exception which we need to handle, else


compile time error)

15
Five keywords:
• try
• catch
• finally
• throw
• throws

16
try {
// The code which may generate exception put that
code in try block
}
catch (Exception e) {
// To handle those exception we need catch block
}
finally{
//Finally block get executed always
}

• Notes: Try must require CATCH or FINALLY.


17
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e1){
System.out.println(e1);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println(e2);
}
catch(Exception e3){
System.out.println(e3);
}
finally{
System.out.println( ” in finally block”);
}
} 18
}
• throw Keyword
To throw exception explicitly.

public class TestThrow{


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);
System.out.println("rest of the code...");
}
}
19
• throws Keyword
Throws exception indicates that the method is not capable to handle that
exception. The caller needs to handle that exception.

import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
}
} 20
User Defined Exception
• If you are creating your own Exception that is
known as custom exception or user-defined
exception.
• Java custom exceptions are used to customize
the exception according to user need.
• E.g
EmployeeNotFoundException
InvalidAgeException
21
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m)
{ System.out.println("Exception occured: "+m);} 22
}}
Collection
• Collection is a data structure which store and
manipulate the group of objects (It doesn’t
store primitive data type).

• All the operations that you perform on a data


such as searching, sorting, insertion,
manipulation, deletion etc. can be performed
by Java Collections.

23
Collection Hierarchy

24
List
Features of List
• May contain duplicate element
• It is an ordered collection
• Implementation classes are Linked List, Vector &
Array List

• Difference between Vector & ArrayList


Vector is synchronized & ArrayList is not
synchronized

25
List
• Linked List
• To add the value
list.addFirst(), list.addLast (), list.add(1, 33)
• To retrieve the value
list.getFirst(), list.getLast() , list.get(1)
• To remove the value
list.removeFirst(), list.removeLast(), list.remove(1))

26
Set
• Features of Set
• Can’t contain duplicate element
• It is an unordered collection
• Implementation classes are HashSet and
TreeSet

27
Map
• Features of Map
• Map contains key and value pairs
• Key must be unique
• value can be different
• Implementation classes are HashTable,
LinkedHash Map, & Tree Map

• Difference between HashTable & HashMap


Hash Table is synchronized and HashMap is not
synchronized
28
Generic
• Generic provides type safety for collections.
It’s a compile time checking.

List <String> myList = new ArrayList<String>();


myList.add(“Fred”); //OK
myList.add(new Dog()); // Compile time
error, it can hold only String type

29
Files and I/O
• The java.io package contains nearly every class you might
ever need to perform input and output (I/O) in Java.
• Stream
A stream can be defined as a sequence of data.
There are two kinds of Streams
• InPutStream: The InputStream is used to read data from a
source.
• OutPutStream: the OutputStream is used for writing data
to a destination.

30
Byte Streams
• Java byte streams are used to perform input
and output of 8-bit bytes.
• FileInputStream and FileOutputStream.

FileInputStream and FileOutputStream classes


are used to read and write data in file.

31
import java.io.*;
class Demo1{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");

int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}
32
Character Streams
• Java Character streams are used to perform
input and output for 16-bit unicode.
• FileReader and FileWriter.

FileWriter and FileReader classes are used to


write and read data from text files.

33
Multithreading
• Multitasking
• Multitasking is a process of executing multiple tasks simultaneously.

Multitasking can be achieved by two ways:

1) Process-based Multitasking (Multiprocessing)


- Each process have its own address in memory i.e. each process
allocates separate memory area.
- Process is heavyweight.
-Cost of communication between the process is high.

2) Thread-based Multitasking (Multithreading)


Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
34
Multithreading in Java
• Multithreading applications are platform dependent because each
OS is having its own scheduling (Memory allocation) algorithm.

• In Java there are two ways to create Threads:


1) Class Demo implements Ruunable{
Public void run(){

}
}
2) Class Demo extends Thread{
Public void run(){

}
}

35
Thread Lifecycle

36
Thread Lifecycle
• start(): Ready to Run

• run(): We have to override run method and we need to


provide business logic in run method

• sleep(): We have to provide sleep time. It will pause


execution. When sleep time expires it will automatically go to
Ready to Run i.e Start method

• stop(): Dead state (Deprecated now)

• States of thread
• Born -> Ready to Start - > Running - > Sleep - > Dead state

37
class TestSleepMethod extends Thread{

public void run(){


for(int i=1;i<5;i++){
try{Thread.sleep(500);}
catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod t1=new TestSleepMethod();
TestSleepMethod t2=new TestSleepMethod();
t1.start();
t2.start();
}
} 38
Synchronization
• Synchronization ensures that only one thread
can access common object at a time
• To avoid race condition
• There are two ways to synchronize:
Synchronize method or synchronize block

39
• //example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
} } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5); } } 40
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
41
}
Inter thread Communication
• Inter-thread communication is all about allowing
synchronized threads to communicate with each other.

• It is implemented by following methods of Object class:

wait()
notify()
notifyAll()

42
Inter thread Communication
• wait():wait will pause the execution until
another threads gives notification.
• notify(): notify will give notification to single
thread
• notifyAll():notify will give notification to all
the threads which are in wait condition

43
JDBC (Java Database Connectivity)
• Java JDBC is a java API to connect and execute
query with the database.
• JDBC API uses jdbc drivers to connect with the
database.

44
JDBC Drivers
• Type I (JDBC –ODBC bridge)
• Type II (Native API Driver)
• Type III ( Network Protocol Driver )
• Type IV (Thin Driver – Pure Java Driver)

45
Thin driver
• The thin driver converts JDBC calls directly into the
vendor-specific database protocol.
• That is why it is known as thin driver.
• It is fully written in Java language.

Advantage: Better performance than all other drivers. 46


JDBC API
• Class
DriverManager : to get connection with database
• Interfaces:
Statement – For simple select query
Preparedstatement – For parameterized query
Callablestatement – To call stored procedure
Connection – Represent connection
Resultset – Represent resultset
47
JDBC Steps
• Load Driver
• Establish connection
• Create object of statement / Prepare
statement / callable statement
• Fire queries
• Get the result set
• Process result set
• Close connection

48
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);}
} 49
}
50
51

You might also like