You are on page 1of 63

UNIT I

Java Concepts: OOPs Concepts, Inheritance in detail,


Exception handling, Packages & interfaces. JVM & .jar
file extension, Multi threading (Thread class & Runnable
Interface), SQL-DML and DDL Queries.
OOPs (Object-Oriented Programming
Concepts)
Inheritance
When one object acquires all the properties and behaviors
of a parent object, it is known as inheritance. It provides
code reusability.
Polymorphism
If one task is performed by different ways, it is known as
polymorphism. For example: to convince the customer
differently, to draw something, for example, shape,
triangle, rectangle, etc.
Object
Any entity that has state and behavior is known as an object. For example a chair, pen, table, keyboard, bike,
etc. It can be physical or logical.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.

4 L Sukanya
Abstraction
Hiding internal details and showing functionality is known as
abstraction. For example phone call, we don't know the
internal processing.
In Java, we use abstract class and interface to achieve
abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single
unit is known as encapsulation. For example capsule, it is
wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the
fully encapsulated class because all the data members are
private here.
Inheritance: Introduction
Reusability--building new components by
utilising existing components- is yet another
important aspect of OO paradigm.
It is always good/“productive” if we are able to
reuse something that is already exists rather than
creating the same all over again.
This will achieve by creating new classes, reusing
the properties of existing classes.

6 L Sukanya
Java - Inheritance
Inheritance can be defined as the process where one
class acquires the properties (methods and fields) of
another.
The class which inherits the properties of other is
known as subclass (derived class, child class) and the
class whose properties are inherited is known as
superclass (base class, parent class).  

7 L Sukanya
Inheritance: Introduction
 This mechanism of
deriving a new class from
existing/old class is called
“inheritance”.
Parent
 The old class is known as
“base” class, “super” class
Inherited
or “parent” class”; and the capability
new class is known as
“sub” class, “derived” class,
or “child” class. Child

8 L Sukanya
Inheritance Introduction
The inheritance allows subclasses to inherit all
properties (variables and methods) of their parent
classes. The different forms of inheritance are:
Single inheritance (only one super class)

Multiple inheritance (several super classes)

Hierarchical inheritance (one super class, many sub classes)

Multi-Level inheritance (derived from a derived class)

Hybrid inheritance (more than two types)

9 L Sukanya
Forms of Inheritance
A--- int a
A B A
Add()

BA
Int b C B C D
Div()

(a) Single Inheritance (b) Multiple Inheritance (c) Hierarchical Inheritance


A
A

B
B

c D
C
(a)
10 Multi-Level
L Sukanya Inheritance (b) Hybrid Inheritance
Defining a Sub class
 A subclass/child class is defined as follows:

class SubClassName extends SuperClassName


{
fields declaration;
methods declaration;
}

 The keyword “extends” signifies that the properties of


super class are extended to the subclass. That means,
subclass contains its own members as well of those of
the super class. This kind of situation occurs when we
want to enhance properties of existing class without
actually modifying it.
11 L Sukanya
class Employee{  
 float salary=40000;  
}  
class Programmer extends Employee
{   float salary=50000;  
 int bonus=10000;  
 public void main()
{  
  //Programmer p=new Programmer();  
System.out.println("Programmer salary is:"+salary);  
 System.out.println("Bonus of Programmer is:"+bonus);  } 
 
}
12 L Sukanya
Member Access and Inheritance

Although a subclass includes all of the members of


its super class, it cannot access those members of the
super class that have been declared as private.
protected access modifier
The protected access modifier is accessible within
package and outside the package but through
inheritance only.
The protected access modifier can be applied on the
data member, method and constructor. It can't be
applied on the class.

13 L Sukanya
Shadowed Variables

Subclasses defining variables with the same name as


those in the superclass, shadow them:

14 L Sukanya
Shadowed Variables - Example
public class Circle {
public float r = 100;
}

public class GraphicCircle extends Circle {


public float r = 10; // New variable
}

public class CircleTest {


public static void main(String[] args){
GraphicCircle gc = new GraphicCircle();
Circle c = new Circle();
System.out.println(“ GraphicCircleRadius= “ + gc.r); // 10
System.out.println (“ Circle Radius = “ + c.r); // 100
}
}

15 L Sukanya
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.
Derived/sub classes defining methods with same
name, return type and arguments as those in the
parent/super class, it is known as method overriding
in java.

In other words, If subclass provides the specific


implementation of the method that has been provided
by one of its parent class, it is known as method
overriding.
16 L Sukanya
Usage of Java Method Overriding
Method overriding is used to provide specific
implementation of a method that is already provided
by its super class.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
method must have same name as in the parent class
method must have same parameter as in the parent
class.
must be IS-A relationship (inheritance).

17 L Sukanya
Exception Handling in Java
What is exception
Dictionary Meaning: Exception is an abnormal condition.

In java, exception is an event that disrupts the normal flow of the

program
An exception is an abnormal condition that arises in a code sequence

at run time.
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal

flow of the application. Exception normally disrupts the normal flow


of the application that is why we use exception handling.
statement 1;  
statement 2;  
statement 3;  
statement 4;  
statement 5;//exception occurs  
statement 6;  
statement 7;  
statement 8;  
statement 9;  
statement 10; 
Suppose there are10 statements in your program and there
occurs an exception at statement 5, rest of the code will not
be executed i.e. statement 6 to 10 will not run. If we
perform exception handling, rest of the statement will be
executed. That is why we use exception handling in java.
Hierarchy of Java Exception
Types of Exception
checked and unchecked where error is considered
as unchecked exception. There are three types of
exceptions:
Checked Exception
Unchecked Exception
Error
import java.io.File;
Checked exceptions − import java.io.FileReader;
A checked exception is an public class FilenotFound_Demo
exception that occurs at the { public static void main(String args[])
compile time, these are also { File file = new File("E://file.txt");
called as compile time FileReader fr = new FileReader(file);
exceptions. These } }
exceptions cannot simply
Output
be ignored at the time of
C:\>javac FilenotFound_Demo.java
compilation, the
FilenotFound_Demo.java:8: error:
programmer should take
unreported exception
care of (handle) these FileNotFoundException; must be
exceptions. caught or declared to be thrown
FileReader fr = new FileReader(file);
^ 1 error
Unchecked exceptions − An unchecked exception
is an exception that occurs at the time of execution.
These are also called as Runtime Exceptions.
These include programming bugs, such as logic
errors or improper use of an API. Runtime
exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5
in your program, and trying to call the 6th element
of the array then
an ArrayIndexOutOfBoundsExceptionexception occu
rs.
public class Unchecked_Demo
{
 public static void main(String args[])
{ int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}}

Output
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
Exceptions.Unchecked_Demo.main(Unchecked_D
emo.java:8)
Errors − These are not exceptions at all, but
problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your
code because you can rarely do anything about an
error.
For example, if a out of memory occurs, an error
will arise. They are also ignored at the time of
compilation.
Java Exception Handling Keywords

There are 5 keywords used in java exception


handling.
1. try
2. catch
3. throw
4. Throws
5. finally
The code which should be monitor to exceptions is
placed in the try block. When an exception occurs,
that exception occurred is handled by catch block
associated with it.
try {
// Protected code
}
 catch (ExceptionName e1)
 { // Catch block }
// File Name : ExcepTest.java
public class ExcepTest
{ public static void main(String args[])
{
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]); }
catch (ArrayIndexOutOfBoundsException e)
{ System.out.println("Exception thrown :" + e); }
System.out.println("Out of the block");
}}
Output
Exception
thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multithreaded Programming
A multithreaded program contains two or more
parts that can run concurrently.
Each part of such a program is called a thread, and
each thread defines a separate path of execution.
Multithreading in java is a process of executing
multiple threads simultaneously.
Cont..
Thread is basically a lightweight sub-process, a
smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing
because threads share a common memory area.
They don't allocate separate memory area so saves
memory, and context-switching between the threads
takes less time than process.
Java Multithreading is mostly used in games, animation
etc.
Multitasking
Multitasking is a process of executing multiple tasks
simultaneously.
 We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:

1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
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.
Switching from one process to another require some time
for saving and loading registers, memory maps, updating
lists etc.
2) Multithreading
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
Multithreading enables you to write very efficient
programs that make maximum use of the CPU
Advantages of Java Multithreading
1) It doesn't block the user because threads are
independent and you can perform multiple operations
at same time.
2) You can perform many operations together so it
saves time.
3) Threads are independent so it doesn't affect other
threads if exception occur in a single thread.
4) Multithreading enables you to write very efficient
programs that make maximum use of the CPU
Life cycle of a Thread (Thread States)
A thread can be in one of the five states.
The life cycle of the thread in java is controlled by
JVM. The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Blocked
5. Terminated
t1.start();
1) New
The thread is in new state if you create an instance of Thread
class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be
the running thread.
3) Running
The thread is in running state if the thread is under execution
4) Blocked
This is the state when the thread is still alive, but is currently
not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method
exits.
How to create thread
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
Thread class
Thread class provide constructors and methods to
create and perform operations on a thread.
Thread class extends Object class and implements
Runnable interface.
public void run(): is used to perform action for a
thread.
public void start(): starts the execution of the
thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the
currently executing thread to sleep (temporarily
cease execution) for the specified number of
milliseconds.
Starting a thread
start() method of Thread class is used to start a
newly created thread. It performs following tasks:A
new thread starts(with new callstack).
The thread moves from New state to the Runnable
state.
When the thread gets a chance to execute, its target
run() method will run.
1) Java Thread Example by extending
Thread class
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
Constructors of Thread Class
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}    
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  
}  
If you are not extending the Thread class, your class object would
not be treated as a thread object. So you need to explicitely create
Thread class object. We are passing the object of your class that
implements Runnable so that your class run() method may execute.
Packages
A java package is a group of similar types of classes,
interfaces and sub-packages.
Package in java can be categorized in two form,
built-in package and user-defined package.
Advantage of Java Package
1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
4) Reusability

46 L Sukanya
How To Create Package
 Create a new folder
 EX. compile-packages-in-java.
 Create a subfolder in your new folder called 
 EX.. pack1.
 Open your text editor and create a new file that will
contain the Person class in the pack1. Be sure to create
this file in the pack1 folder. Type in the following Java
statements:
package nameofthepackage;
package pack1;
As the first statement in java file.
47 L Sukanya
How to compile & Run
Compile:
javac ./packagename/file.java
Run:
java packagename.file

48 L Sukanya
How to access package from another package?
There are three ways to access the package from
outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

49 L Sukanya
1) Using packagename.*
If you use package.* then all the classes and interfaces
of this package will be accessible.
The import keyword is used to make the classes and
interface of another package accessible to the current
package.
import pack.*;   
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  

50 L Sukanya
 Using packagename.classname
If you import package.classname then only declared
class of this package will be accessible.
EX: import pack.A; 
Using fully qualified name
If you use fully qualified name then only declared
class of this package will be accessible. Now there is
no need to import. But you need to use fully
qualified name every time when you are accessing
the class or interface.
It is generally used when two packages have same
class name e.g. java.util and java.sql packages
contain Date class.

51 L Sukanya
Access Modifiers

52 L Sukanya
Java built-in packages
There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.

53 L Sukanya
Interfaces
Interface is a conceptual entity similar to an
Abstract class.
Can contain only constants (final variables) and
abstract method (no implementation) - Different
from Abstract classes.
Use when a number of classes share a common
interface.
Each class should implement the interface.

54
Interfaces: An informal way of realising
multiple inheritance
An interface is basically a kind of class—it contains
methods and variables, but they have to be only
abstract classes and final fields/variables.
Therefore, it is the responsibility of the class that
implements an interface to supply the code for
methods.
A class can implement any number of interfaces, but
cannot extend more than one class at a time.
Therefore, interfaces are considered as an informal
way of realising multiple inheritance in Java.

55
Interfaces Definition
Syntax (appears like abstract class):
Example:
interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration – only method body
}

interface Speaker {
int a=7;
public void speak( );
}

56
Implementing Interfaces
Interfaces are used like super-classes i.e properties are
inherited by classes. This is achieved by creating a
class that implements the given interface as follows:

class ClassName implements InterfaceName [, InterfaceName2, …]


{
// Body of Class
}

57
Inheritance and Interface Implementation
 A general form of interface implementation:

class ClassName extends SuperClass implements InterfaceName [,


InterfaceName2, …]
{
// Body of Class
}

 This shows a class can extended another class while


implementing one or more interfaces. It appears like a
multiple inheritance (if we consider interfaces as special
kind of classes with certain restrictions or special features).

58
JVM (Java Virtual Machine) 

JVM (Java Virtual Machine) is an abstract machine. It is a


specification that provides runtime environment in which
java bytecode can be executed.
JVMs are available for many hardware and software
platforms (i.e. JVM is platform dependent).
What it does
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment

59 L Sukanya
JAR (Java ARchive)

A JAR (Java ARchive) is a package file format typically


used to aggregate many Java class files and associated
metadata and resources (text, images, etc.) into
one file for distribution. JAR files are archive files that
include a Java-specific manifest file.

60 L Sukanya
SQL | DDL, DML Commands

Structured Query Language(SQL) It is the database


language by the use of which we can perform certain
operations on the existing database and also we can use
this language to create a database. SQL uses certain
commands like Create, Drop, Insert etc. to carry out the
required tasks.
These SQL commands are mainly categorized as
discussed below:
1. DDL(Data Definition Language) : DDL or Data
Definition Language actually consists of the SQL
commands that can be used to define the database
schema.
61 L Sukanya
Examples of DDL commands:
• CREATE – is used to create the database or its objects
(like table, index, function, views, store procedure and
triggers).
• DROP – is used to delete objects from the database.
• ALTER-is used to alter the structure of the database.
• TRUNCATE–is used to remove all records from a table,
including all spaces allocated for the records are
removed.
• COMMENT –is used to add comments to the data
dictionary.
• RENAME –is used to rename an object existing in the
database.

62 L Sukanya
DML(Data Manipulation Language) : The SQL
commands that deals with the manipulation of data
present in database belong to DML or Data
Manipulation Language and this includes most of the
SQL statements.Examples of DML:
• SELECT – is used to retrieve data from the a
database.
• INSERT – is used to insert data into a table.
• UPDATE – is used to update existing data within a
table.
• DELETE – is used to delete records from a database
table.

63 L Sukanya

You might also like