SlideShare a Scribd company logo
1 of 84
Download to read offline
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
IT1301 - OBJECT ORIENTED
PROGRAMMING
II IT
DEPARTMENT OF INFORMATION
TECHNOLOGY
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
UNIT I
PART A
1. “JAVA is an Impure programming language” – Justify.
Java is impure object oriented programming language because it supports
primitive data type like it, byte, long etc., which are not objects.
2. “JAVA is platform independent” – Justify.
Java compilers complies the code for a machine that physically does not exist,
(i.e.) for a virtual machine. This code is Byte code. This supports the concept of
platform independent.
Java Virtual Machine that runs in the local machine, interprets the Java byte
code and converts it into platform specific machine code.
3. What is bytecode?
Java bytecode is the instruction set for the Java Virtual Machine. Java
bytecode is the machine code in the form of a .class file. With the help of java
bytecode, platform independence in java.
4. If no arguments are provided on the command line, then the string array of
Main method will be empty or null? Justify.
Java main method accepts a single argument of type String array. This is also
called as java command line arguments. JVM takes care of passing any command line
arguments as an array of strings to the main function. If there are no arguments given,
an empty array is passed - but it's still there
5. Name the types of variable.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
a. Local variable
b. Instance variable
c. Static variable
6. Tabulate the various data type with its size.
Data Type Size
byte 8
short 16
int 32
long 64
float 32
double 64
char 16
Boolean 1
7. List down the 4 access specifiers in JAVA.
a. Public
b. Private
c. Protected
d. Default
8. Define classes and objects.
Classes:
A class in Java is a blueprint which includes all your data. A class contains fields
(variables) and methods to describe the behaviour of an object.
Syntax:
<access specifier> class <ClassName> {
member variables // class body
methods
}
Objects:
An object is a major element in a class which has a state and behaviour. It is an
instance of a class which can access your data. The „new‟ keyword is used to create the
object.
9. Define constructor.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
A constructor is a block of code that initializes a newly created object. It is
similar to a method in Java but doesn‟t have any return type and its name is same as
the class name.
10. Mention the rules for creating a constructor in java.
a. Class name and Constructor name should be same
b. No return type for a constructor
c. Constructor can have n number of parameters
d. Constructors are similar to methods but it is invoked automatically during the
object creation
11. What is package?
A java package is a group of similar types of classes, interfaces and sub-
packages.
PART B
1. Discuss various features of JAVA.
Features of JAVA:
a. Simple
 Java is very easy to learn, and its syntax is simple, clean and easy to
understand.
b. Object-Oriented
 Java is an object-oriented programming language.
 Everything in Java is an object.
 Object-oriented refers to software as a combination of different types of
objects that incorporate both data and behavior.
c. Portable
 Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn't require any implementation.
d. Platform independent
 Java compilers complies the code for a machine that physically does not
exist, (i.e.) for a virtual machine. This code is Byte code. This supports
the concept of platform independent.
 Java Virtual Machine that runs in the local machine, interprets the Java
byte code and converts it into platform specific machine code.
e. Secured
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 Java is best known for its security.
 Java helps to develop virus-free systems
 Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime
Environment (JRE) which is used to load Java classes into the
Java Virtual Machine dynamically. It adds security by separating
the package for the classes of the local file system from those that
are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code
that can violate access rights to objects.
o Security Manager: It determines what resources a class can access
such as reading and writing to the local disk.
f. Robust
Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security problems.
 Java provides automatic garbage collection which runs on the Java
Virtual Machine to get rid of objects which are not being used by a
Java application anymore.
 There are exception handling and the type checking mechanism in
Java. All these points make Java robust.
g. Architecture neutral
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 Java is architecture neutral because there are no implementation dependent
features, for example, the size of primitive types is fixed.
 JAVA is Write Once Read Anywhere
h. Interpreted
 Handles the bytecode.
 Converts the bytecode to executable form.
i. High Performance
 Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code.
j. Multithreaded
 A thread is like a separate program, executing concurrently.
 Many tasks can execute at once with the help of multiple threads.
 The main advantage of multi-threading is that it doesn't occupy memory
for each thread. It shares a common memory area.
k. Distributed
 Java is distributed because it facilitates users to create distributed
applications in Java.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 RMI and EJB are used for creating distributed applications.
l. Dynamic
 Java is a dynamic language. It supports the dynamic loading of classes.
 It means classes are loaded on demand.
2. Describe the characteristics of OOPs
Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
Features:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Objects:
 An object is a major element in a class which has a state and behaviour. It is
an instance of a class which can access your data. The „new‟ keyword is used
to create the object.
 Example – Bike, Fan, Table
 A dog is an object because it has states like color, name, breed, etc. as well as
behaviours like wagging the tail, barking, eating, etc.
Classes:
 A class in Java is a blueprint which includes all your data. A class contains
fields (variables) and methods to describe the behaviour of an object.
 Syntax:
<access specifier> class <ClassName> {
member variables // class body
methods
}
Inheritance:
 Ability to inherit the properties of one class to another class
Example:
 University  College  UG Program  B.Tech Program  IT
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 Grand Parent  Parent  Child
 It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
 If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
 In Java, method overloading and method overriding are used to achieve
polymorphism.
 Another example can be to speak something; for example, a cat speaks meow,
dog barks woof, etc.
Abstraction
 Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing.
 In Java, abstract class and interface are used to achieve abstraction.
Encapsulation
 Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a 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.
3. Define constructor. Explain the various types of constructors.
 A constructor is a block of codes similar to the method.
 It is called when an instance of the class is created.
 At the time of calling constructor, memory for the object is allocated in the
memory.
 It is a special type of method which is used to initialize the object.
Rules for creating the Constructor:
 Class name and Constructor name should be same
 No return type for a constructor
 Constructor can have n number of parameters
 Constructors are similar to methods but it is invoked automatically during the
object creation
Types of Java constructors
There are two types of constructors in Java:
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 Default constructor (no-arg constructor)
 Parameterized constructor
Default Constructor
 Initialize a variable with ground (default/seed/initial) value
Syntax:
<access specifier> class ClassName{
public ClassName(){
}
}
Parameterized Constructor
 To assign a value to a instance variable
Syntax:
<access specifier> class ClassName{
public ClassName(arguments){
}
}
Example:
// To find the area of Circle
import java.util.*;
class AreaCircle
{
double area, pi, radius;
// Default Constructor
AreaCircle()
{
pi = 3.14;
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
// Parameterized Constructor
AreaCircle(int r)
{
pi = 3.14;
radius = r;
}
void area()
{
area = pi * radius * radius;
System.out.println("Area of Circle = " + area);
}
void area(int radius)
{
area = pi * radius * radius;
System.out.println("Area of Circle = " + area);
}
}
public class Main{
public static void main(String args[])
{
AreaCircle ac = new AreaCircle();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the value for radius : ");
int r = scan.nextInt();
ac.area(r);
AreaCircle ac1 = new AreaCircle(r);
ac.area();
}
}
Java Constructor Java Method
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
A constructor is used to initialize the
state of an object.
A method is used to expose the behavior of
an object.
A constructor must not have a return
type.
A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default
constructor if you don't have any
constructor in a class.
The method is not provided by the
compiler in any case.
The constructor name must be same as
the class name.
The method name may or may not be same
as the class name.
4. What are access specifiers? Explain it with the access matrix.
 The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class.
 There are two types of modifiers in Java:
o Access modifiers
o Non-access modifiers.
 There are four types of Java access modifiers:
o Private:
 The access level of a private modifier is only within the class.
It cannot be accessed from outside the class.
 private int data=40;
o Default:
 The access level of a default modifier is only within the
package.
 It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
o Protected:
 The access level of a protected modifier is within the package
and outside the package through child class.
 Example:
public class A{
protected void msg(){System.out.println("Hello");}
}
o Public:
 The access level of a public modifier is everywhere.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 It can be accessed from within the class, outside the class,
within the package and outside the package.
Access Modifier within class within package
outside package
by subclass only
outside
package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
5. What is Object class? Explain the concepts of Object Cloning and Reflection.
Object Class:
 The Object class is the parent class of all the classes in java by default.
 In other words, it is the topmost class of java.
Methods:
Method Description
public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the metadata
of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws
CloneNotSupportedException
creates and returns the exact copy (clone) of this
object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's
monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long
timeout)throws InterruptedException
causes the current thread to wait for the specified
milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait(long timeout,int
nanos)throws InterruptedException
causes the current thread to wait for the specified
milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).
public final void wait()throws
InterruptedException
causes the current thread to wait, until another
thread notifies (invokes notify() or notifyAll()
method).
protected void finalize()throws
Throwable
is invoked by the garbage collector before object is
being garbage collected.
Object Cloning:
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 The object cloning is a way to create exact copy of an object. The clone()
method of Object class is used to clone an object.
 The java.lang.Cloneable interface must be implemented by the class whose
object clone we want to create. If we don't implement Cloneable interface,
clone() method generates CloneNotSupportedException.
 The clone() method is defined in the Object class. Syntax of the clone()
method is as follows:
protected Object clone() throws CloneNotSupportedException
 The clone() method saves the extra processing task for creating the exact copy
of an object.
 If we perform it by using the new keyword, it will take a lot of processing time
to be performed that is why we use object cloning.
Object Reflection:
 Java Reflection is a process of examining or modifying the run time behavior
of a class at run time.
 The java.lang.Class class provides many methods that can be used to get
metadata, examine and change the run time behavior of a class.
 The java.lang and java.lang.reflect packages provide classes for java
reflection.
Method Description
1) public String getName() returns the class name
2) public static Class forName(String
className)throws ClassNotFoundException
loads the class and returns the reference of
Class class.
3) public Object newInstance()throws
InstantiationException,IllegalAccessException
creates new instance.
4) public boolean isInterface() checks if it is interface.
5) public boolean isArray() checks if it is array.
6) public boolean isPrimitive() checks if it is primitive.
7) public Class getSuperclass() returns the superclass class reference.
8) public Field[] getDeclaredFields()throws
SecurityException
returns the total number of fields of this
class.
9) public Method[]
getDeclaredMethods()throws
SecurityException
returns the total number of methods of this
class.
10) public Constructor[]
getDeclaredConstructors()throws
SecurityException
returns the total number of constructors of
this class.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
11) public Method getDeclaredMethod(String
name,Class[] parameterTypes)throws
NoSuchMethodException,SecurityException
returns the method class instance.
6. Discuss the user defined package creation and accessing in JAVA.
 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.
 There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
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.
Access package from another package
There are three ways to access the package from outside the package.
 import package.*;
 import package.classname;
 fully qualified name.
Creating Package:
package packageName;
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
UNIT II
PART A
1. State the use of interface in JAVA.
 Interface provides abstraction and multiple inheritance.
2. Define inheritance.
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
3. What is the various usage of static keyword?
 The static keyword in Java is mainly used for memory management.
 The static keyword in Java is used to share the same variable or method of a
given class.
 The users can apply static keywords with variables, methods, blocks, and
nested classes.
 The static keyword belongs to the class than an instance of the class.
4. Differentiate static polymorphism and dynamic polymorphism.
S.No Static (Compile Time) Polymorphism Dynamic (Run time) Polymorphism
1 The call is resolved by the compiler. The call is not resolved by the compiler.
2 It is also known as Static binding, Early
binding and overloading as well.
It is also known as Dynamic binding, Late
binding and overriding as well.
3 Method overloading is the compile-time
polymorphism where more than one
methods share the same name with
different parameters or signature and
different return type.
Method overriding is the runtime
polymorphism having same method with
same parameters or signature, but
associated in different classes.
4 It is achieved by function overloading and
operator overloading.
It is achieved by virtual functions and
pointers.
5 It provides fast execution because the
method that needs to be executed is
It provides slow execution as compare to
early binding because the method that
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
known early at the compile time. needs to be executed is known at the
runtime.
6 Compile time polymorphism is less
flexible as all things execute at compile
time.
Run time polymorphism is more flexible as
all things execute at run time.
5. Differentiate interface from abstract class.
Interface Abstract class
Interface can have only abstract methods. Since
Java 8, it can have default and static
methods also.
Abstract class can have abstract and non-
abstract methods.
Interface supports multiple inheritance. Abstract class doesn't support multiple
inheritance.
Interface has only static and final variables. Abstract class can have final, non-final, static
and non-static variables.
Interface can't provide the implementation of
abstract class.
Abstract class can provide the implementation
of interface.
The interface keyword is used to declare interface. The abstract keyword is used to declare abstract
class.
An interface can extend another Java interface
only.
An abstract class can extend another Java class
and implement multiple Java interfaces.
An interface can be implemented using keyword
"implements".
An abstract class can be extended using
keyword "extends".
Members of a Java interface are public by default. A Java abstract class can have class members
like private, protected, etc.
Example:
public interface Drawable{
void draw();
}
Example:
public abstract class Shape{
public abstract void draw();
}
6. Differentiate Class from Interface in JAVA.
Class Interface
The keyword used to create a class is
“class”
The keyword used to create an interface is
“interface”
A class can be instantiated i.e, objects of a
class can be created.
An Interface cannot be instantiated i.e, objects
cannot be created.
Classes does not support multiple
inheritance.
Interface supports multiple inheritance.
It can be inherit another class. It cannot inherit a class.
It can be inherited by another class using
the keyword „extends‟.
It can be inherited by a class by using the
keyword „implements‟ and it can be inherited
by an interface using the keyword „extends‟.
It can contain constructors. It cannot contain constructors.
It cannot contain abstract methods. It contains abstract methods only.
Variables and methods in a class can be
declared using any access specifier(public,
private, default, protected)
All variables and methods in a interface are
declared as public.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Variables in a class can be static, final or
neither.
All variables are static and final.
7. Outline the usage of Final keyword in JAVA.
 Final variable – constant – avoid the change in values of a variable
o final double pi = 3.14;
 Final method – avoid method overriding
 Final class – avoid inheritance
PART B
1. What is Inheritance? Explain the types of inheritance using suitable example.
Definition:
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
• All objects have the Object class as their top parent.
• Methods can be overridden but attributes cannot.
• To call a parent class constructor, super() is used.
Java supports 3 types of inheritance:
• Single Inheritance
• Multi-level Inheritance
• Hierarchical Inheritance
Advantage:
• Reusability of an existing class
• Derived class that has own properties along with base class properties.
Terminologies:
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
Syntax:
class SubClassName extends BaseClassName
{
Expressions;
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
}
a. Single Inheritance
In this, a class inherits the properties of a single parent class.
Syntax
Class A{
//your parent class code
}
Class B extends A {
//your child class code
}
b. Multi Level Inheritance
In multi-level inheritance, one class has more than one parent class but at different
levels of inheritance.
Syntax:
Class A{
//your parent class code
}
Class B extends A {
//your code
}
Class C extends B {
//your code
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
c. Hierarchical Inheritance
In hierarchical inheritance, one parent can have one or more child/sub/derived classes.
Syntax:
Class A{
//your parent class code
}
Class B extends A {
//your child class code
}
Class C extends A {
//your child class code
}
// Base Class
// Base Class
class A
{
void disp()
{
System.out.println(" Class A");
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
}
// Single Inheritance
class B extends A
{
void display()
{
System.out.println("Class B");
}
}
// Multilevel Inheritance
class C extends B
{
void show()
{
System.out.println("Class C");
}
}
// Hierarchal Inheritance
class D extends B
{
void print()
{
System.out.println("Class D");
}
}
class InDemo
{
public static void main(String args[])
{
C c1 = new C();
c1.disp();
c1.display();
c1.show();
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
D d1 = new D();
d1.print();
}
}
Note:
• It is enough to create the object for the child class
• Child class can access all the members in the parent class directly
• Parent class members can be accessed using child class object
Super Keyword
 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
 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.
Note:
• Super() should be written inside the derived class constructor as the first
statement
Example:
class Base{
int a, b = 100;
Base(int a){
this.a = a;
}
}
class Derived extends Base{
int b;
Derived(int c){
// Invoke base class constructor
super(a);
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
// To refer the base class instance variable
b = super.b;
}
}
2. What is the purpose of interface? Explain the concept with suitable example.
Introduction:
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
Purpose:
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
Note:
 Like abstract classes, interfaces cannot be used to create objects (in the
example above, it is not possible to create an "Animal" object in the
MyMainClass)
 Interface methods do not have a body - the body is provided by the
"implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create
objects)
Multiple Inheritance:
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Declaring Interfaces
The interface keyword is used to declare an interface.
Syntax:
interface interfacename
{
//Any number of final, static fields
//Any number of abstract method declarations
}
Variable Declaration (Constants):
Syntax:
public static final datatype variablename = value;
Method Declaration (Abstract Method):
Syntax:
public abstract returntype methodname(Argument(s));Relationship between
classes and interface:
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Example:
/* File name : Vehicle.java */
interface Vehicle {
public int modelno = 123;
public void changeGear();
public void changeSpeed();
}
Implementing Interface
A class uses the implements keyword to implement an interface.
Syntax:
class Classname implements interfacename1, intefacename2, …
{
// Method definition(s)
// Variable declaration(s)
//Abstract method definition(s)
}
Example:
/* File name : VehicleMain.java */
class VehicleImple implements Vehicle
{
int speed = 0;
int gear;
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
void changeSpeed()
{
speed++;
System.out.println(“Speed = “ +speed);
}
void changeGear()
{
if(speed < 10)
gear = 1;
else if(speed >= 10 && speed <=20)
gear = 2;
else if(speed > 20 && speed <=40)
gear = 3;
else if(speed > 40 && speed <=60)
gear = 4;
else
gear = 5;
System.out.println(“Gear = “+gear);
}
void obstacle()
{
speed--;
}
}
Class VehicleMain
{
public static void main(String args[])
{
VehicleImple vi = new VehicleImple();
vi.changeSpeed();
vi.obstacle();
vi.changeGear();
}
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Extending Interface
 An interface can extend another interface, similarly to the way that a class can
extend another class.
 The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
Syntax:
interface parentinterface
{
}
interface childinterface extends parentinterface
{
}
Example:
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
Interface Reference
Interfacename object = new classname();
Nested Interface
An interface can have another interface i.e. known as nested interface.
Example:
interface printable
{
void print();
interface MessagePrintable{
void msg();
}
}
3. Define inner class. Explain various types of inner class with suitable example.
Inner Class:
 Java inner class or nested class is a class that is declared inside the class or
interface.
 Use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
 Purpose - Hide the data and implementation
Syntax:
class OuterClassName
{
class InnerClassName
{
}
}
Types of inner class:
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
a. Member inner class
b. Anonymous inner class
c. Local inner class
b. Static inner class
a. Member inner class
A non-static class that is created inside a class but outside a method is called member
inner class. It is also known as a regular inner class.
Syntax:
class OuterClassName
{
class InnerClassName
{
}
}
Note:
1. Outer class members can be accessed directly by the inner class
2. Inner class members cannot be accessed directly in the outer class
3. To access the inner class members in outer class, object has to be created for inner
class
4. To access the inner class members outside the outer class
i. Create an object for outer class
ii. OuterClassName.InnerClassName ic = outerClassObject.new InnerClassName();
class OuterClass
{
// Instance Outer Variables
int a = 10;
class InnerClass
{
// Instance Inner class variable
int b = 20;
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
void display()
{
System.out.println("Outer A = " + a);
System.out.println("Inner B = " + b);
}
}
void show()
{
System.out.println("Inner B = " + b);
}
}
public class Main
{
public static void main(String[] args) {
OuterClass oc = new OuterClass();
OuterClass.InnerClass ic = oc.new InnerClass();
ic.display();
oc.show();
}
}
b. Anonymous Inner Class
Java anonymous inner class is an inner class without a name and for which only a
single object is created.
Example:
abstract class Test
{
abstract void display();
}
public class Main
{
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
public static void main(String args[])
{
Test t1 = new Test(){
void display()
{
System.out.println("Welcome");
}
};
t1.display();
}
}
c. Local Inner Class
 A class i.e., created inside a method, is called local inner class in java.
 Local Inner Classes are the inner classes that are defined inside a block.
 Generally, this block is a method body.
Example:
class Test
{
int a = 10;
void show()
{
class Demo
{
void display()
{
System.out.println("Local Inner Class");
}
}
Demo d1 = new Demo();
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
d1.display();
System.out.println("A = "+a);
}
}
public class Main
{
public static void main(String args[])
{
Test t1 = new Test();
t1.show();
}
}
d. Static Inner Class
 A static class is a class that is created inside a class, is called a static nested
class in Java.
 It cannot access non-static data members and methods. It can be accessed by
outer class name.
 It can access static data members of the outer class, including private.

 The static nested class cannot access non-static (instance) data members
Example:
class Test
{
static int a = 10;
static class InnerClass
{
static void show()
{
System.out.println("Static Inner Class");
System.out.println("A = "+a);
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
}
}
}
public class Main
{
public static void main(String args[])
{
Test.InnerClass.show();
}
}
4. What is abstract class? Illustrate with an example to demonstrate abstract class.
 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).
Note:
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the
body of the method.
Syntax:
abstract class classname{
}
Abstract Method:
 A method which is declared as abstract and does not have implementation
is known as an abstract method.
Syntax:
abstract class classname{
abstract returntype methodName(args);
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Example:
import java.util.Scanner;
import java.util.Date;
abstract class Shape
{
abstract void printArea();
}
class Rectangle extends Shape
{
int x,y,l,b,area;
Rectangle(int l,int b)
{
x=l;
y=b;
}
void printArea()
{
area=x*y; //calculating area of rectangle
System.out.println("Area of the Rectangle of size "+x+"*"+y+ "is"+area);
}
}
class Triangle extends Shape
{
int x,y,z,l,b,h,area;
Triangle(int l,int b,int h)
{
x=l;
y=b;
z=h;
}
void printArea()
{
area=(x*y*z)/2; //calculating area of triangle
System.out.println("Area of the Triangle of size "+x+"*"+y+"*"+z+
"is"+area);
}
}
class Circle extends Shape
{
int x,r;
double area;
Circle(int r)
{
x=r;
}
void printArea()
{
area=3.14*x*x; //calculating area of circle
System.out.println("Area of the circle of size "+x+"is"+area);
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
}
class Area
{
public static void main(String args[])
{
Scanner s1=new Scanner(System.in);
do
{
System.out.println("1.Rectangle");
System.out.println("2.Triangle");
System.out.println("3.Circle");
System.out.println("Enter your choice :");
choice=s1.nextInt();
switch(choice)
{
case 1:
System.out.println("Mention the length of the
rectangle:");
a=s1.nextInt();
System.out.println("Mention the breadth of the
rectangle:");
b=s1.nextInt();
Rectangle a1=new Rectangle(a,b);
a1.printArea();
break;
case 2:
System.out.println("Mention the length of the
triangle:");
a=s1.nextInt();
System.out.println("Mention the breadth of the
tringle:");
b=s1.nextInt();
System.out.println("Mention the height of the tringle:");
c=s1.nextInt();
Triangle b1=new Triangle(a,b,c);
b1.printArea();
break;
case 3:
System.out.println("Mention the radius of the circle:");
a=s1.nextInt();
Circle c1=new Circle(a);
c1.printArea();
break;
default:
System.out.println("Thanks for using our app");
}
}while(choice>0 && choice<4);
}
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
5. Describe the types of polymorphism with example.
Polymorphism
 Polymorphism is the ability of an object to take on many forms.
 The most common use of polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object.
 Types:
o Static polymorphism – Method Overloading – Static binding –
Compile time polymorphism
o Dynamic polymorphism – Method Overriding – Dynamic binding –
Runtime polymorphism
Static Polymorphism:
Method overloading: Same method name with different number of arguments and
return type
Syntax:
void eating(int a)
{
}
void eating(int a, int b)
{
}
void eating(String str)
{
}
// Static Polymorphism
class StaticPoly
{
// Area of Square
void area(int side)
{
int res = side * side;
System.out.println("Area of the Square is "+res);
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
// Area of Rectangle
void area(int length, int breadth)
{
int res = length * breadth;
System.out.println("Area of Rectange is "+res);
}
// Area of Circle
double area(double radius)
{
double res = 3.14 * radius * radius;
return res;
}
}
public class Main{
public static void main(String args[])
{
StaticPoly sp = new StaticPoly();
sp.area(10);
sp.area(5, 10);
System.out.println("Area of Circle is "+sp.area(3.65));
}
}
Dynamic Polymorphism
 Same method signature (method name, arguments, return type)
 Makes use of Inheritance concept
 Dynamic binding
SuperClassName object = new SubClassName();
// Dynamic Polymorphism
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
// Super Class
class DynamicPoly
{
void display()
{
System.out.println("Hello");
}
}
// Sub Class
class SubDynamicPoly extends DynamicPoly
{
void display()
{
System.out.println("Welcome");
}
}
// Sub Class
class SubDynamic extends SubDynamicPoly
{
void display()
{
System.out.println("Hai.....");
}
}
public class Main{
public static void main(String args[])
{
DynamicPoly dy;
dy = new DynamicPoly();
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
dy.display();
dy = new SubDynamicPoly();
dy.display();
dy = new SubDynamic();
dy.display();
}
}
UNIT III
1. What is lambda expression in JAVA?
 A lambda expression is a short block of code which takes in parameters and
returns a value.
 Lambda expressions are similar to methods, but they do not need a name and they
can be implemented right in the body of a method.
 Syntax:
parameter -> expression
(parameter1, parameter2) -> expression
 Example:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}
UNIT IV
PART – A
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
1. What are input and output streams?
 An I/O Stream represents an input source or an output destination.
 A stream can represent many different kinds of sources and destinations, including
disk files, devices, other programs, and memory arrays.
2. What is a byte stream in java?
 Programs use byte streams to perform input and output of 8-bit bytes.
 All byte stream classes are descended from InputStream and OutputStream.
 There are many byte stream classes. The file I/O byte streams, are
FileInputStream and FileOutputStream.
3. Define 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.
4. What is character stream?
 Character streams are used to perform input and output for 16-bit unicode.
 Though there are many classes related to character streams but the
most frequently used classes are, FileReader and FileWriter.
5. Given an example for reading data from files using FileInputStream.
import java.io.FileInputStream;
class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("input.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
6. What is AWT?
 A collection of graphical user interface (GUI) components that were implemented
using native- platform versions of the components.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 These components provide that subset of functionality which is common to all
native platforms.
 Largely supplanted by the Project Swing component set.
7. What is the relationship between an event- listener interface and an event
adapter class?
 An event-listener interface allows describing the methods which must be
implemented by one of the event handler for a specific event.
 An event-adapter allows default implementations of an event-listener interface of
a specific event.
8. Differentiate AWT from Swing.
Java AWT Java Swing
AWT components are platform-
dependent.
Java swing components are
platform-independent.
AWT components are heavyweight. Swing components are lightweight.
AWT provides less components than
Swing.
Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,tabbedpane
etc.
AWT doesn't follows MVC Swing follows MVC.
9. How Events are handled in java ?
 A source generates an Event and send it to one or more listeners registered with
the source.
 Once event is received by the listener, they process the event and then return.
Events are supported by a number of Java packages, like java.util, java.awt and
java.awt.event.
10. List the different type of drivers.
Type 1: JDBC-ODBC Bridge Driver
Type 2: JDBC-Native API
Type 3: JDBC-Net pure Java
Type 4: 100% Pure Java
11. Write a JAVA code to display “Welcome” in a dialog box.
import javax.swing.*;
class OptionPaneExample {
JFrame f;
OptionPaneExample(){
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
f=new JFrame();
JOptionPane.showMessageDialog(f,"Welcome");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
12. Mention some Event Classes and Interface
Event Classes Description Listener Interface
ActionEvent
generated when button is pressed, menu-
item is selected, list-item is double clicked
ActionListener
MouseEvent
generated when mouse is dragged,
moved,clicked,pressed or released and
also
when it enters or exit a component
MouseListener
KeyEvent
generated when input is received from
keyboard
KeyListener
ItemEvent
generated when check-box or list item is
clicked
ItemListener
TextEvent
generated when value of textarea or textfield
is changed
TextListener
MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
WindowEvent
generated when window is activated,
deactivated, deiconified, iconified, opened
or closed
WindowListener
ComponentEvent
generated when component is hidden,
moved, resized or set visible
ComponentEventListener
ContainerEvent
generated when component is added or
removed from container
ContainerListener
PART - B
1. Outline the IO stream classes with suitable example.
Introduction
 Java I/O (Input and Output) is used to process the input and produce the output
based on the input.
 Java uses the concept of stream to make I/O operation fast.
 The java.io package contains all the classes required for input and output
operations.
Stream
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 A stream is a sequence of data.
 In Java a stream is composed of bytes.
 It's called a stream because it's like a stream of water that continues to flow.
 In java, 3 streams are created for us automatically.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Example:
To print output and error message to the console.
System.out.println("simple message");
System.err.println("error message");
Types of Stream
There are two kinds of streams:
a. Byte streams
b. Character streams.
Byte Stream:
 An input stream is an object that an application can use to read a sequence of
data, and an output stream is an object that an application can use to write a
sequence of data.
 An input stream acts as a source of data, and an output stream acts as a
destination of data.
 The sub classes of byte stream are InputStream and OutputStream.
Character Stream:
 The sub classes of character stream are Reader and Writer.
 The Reader and Writer classes read and write 16-bit Unicode characters.
Unicode is an international standard character encoding that is capable of
representing most of the world's written languages.
 In Unicode, two bytes make a character. InputStream reads 8-bit bytes, while
OutputStream writes 8-bit bytes.
The java.io package contains a fairly large number of classes that deal with Java input
and output:
a. an array of bytes or characters
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
b. a file
c. a pipe
d. a network connection
Streams can be chained with filters to provide new functionality
Byte Stream
InputStream and OutputStream
a. OutputStream class
 OutputStream class is an abstract class.
 It is the superclass of all classes representing an output stream of bytes.
 An output stream accepts output bytes and sends them to some sink.
Methods:
Method Description
1) public void write(int)throws
IOException:
is used to write a byte to the current output
stream.
2) public void write(byte[])throws
IOException:
is used to write an array of byte to the current
output stream.
3) public void flush()throws
IOException:
flushes the current output stream.
4) public void close()throws
IOException:
is used to close the current output stream.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
1. ByteArrayOutputStream : Data is written to a byte array. The size of the
byte array created can be specified.
2. FileOutputStream : Data is written as bytes to a file. The file acting
as the output stream can be specified by a File object, a FileDescriptor or a String file
name.
3. FilterOutputStream : Superclass of all output stream filters. An
output filter must be chained to an underlying output stream.
4. BufferedOutputStream : A filter that buffers the bytes written to an
underlying output stream. The underlying output stream must be specified, and an
optional buffer size can be given.
5. FileInputStream and FileOutputStream (File Handling): In Java,
FileInputStream and FileOutputStream classes are used to read and write data in file.
In another words, they are used for file handling in java.
b. InputStream class
 InputStream class is an abstract class.
 It is the superclass of all classes representing an input stream of bytes.
Methods:
Method Description
1) public abstract int read()throws
IOException:
reads the next byte of data from the input stream.It
returns -1 at the end of file.
2) public int available()throws
IOException:
returns an estimate of the number of bytes that can
be read from the current input stream.
3) public void close()throws
IOException:
is used to close the current input stream.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
1. ByteArrayInputStream : Data is read from a byte array that must be
specified.
2. FileInputStream : Data is read as bytes from a file. The file acting
as the input stream can be specified by a File object, a FileDescriptor or a String file
name. FilterInputStream Superclass of all input stream filters. An input filter must be
chained to an underlying input stream.
3. BufferedInputStream : A filter that buffers the bytes read from an
underlying input stream. The underlying input stream must be specified, and an
optional buffer size can be included.
4. DataInputStream : A filter that allows the binary representation of
Java primitive values to be read from an underlying input stream. The underlying
input stream must be specified.
5. PushbackInputStream : A filter that allows bytes to be "unread" from
an underlying input stream. The number of bytes to be unread can optionally be
specified.
6. ObjectInputStream : Allows binary representations of Java objects
and Java primitive values to be read from a specified input stream.
7. PipedInputStream : Reads bytes from a PipedOutputStream
towhich it must be connected. The PipedOutputStream can optionally be specified
when creating the PipedInputStream.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
8. SequenceInputStream : Allows bytes to be read sequentially from two
or more input streams consecutively. This should be regarded as concatenating the
contents of several input streams into a single continuous input stream.
Java FileOutputStream class:
 Java FileOutputStream is an output stream for writing data to a file.
 Instead, for character-oriented data, prefer FileWriter.
Syntax:
FileOutputStream fileobject = new FileOutputStream(“filename”);
or
File object = new File(“Filename”);
FileOutputStream fileobject = new FileOutputStream(object);
Example:
/* File Name: Test.java */
import java.io.*;
class Test
{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){system.out.println(e);}
}
}
Java FileInputStream class
 Java FileInputStream class obtains input bytes from a file.
 It is used for reading streams of raw bytes such as image data.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 For reading streams of characters, consider using FileReader.
 It should be used to read byte-oriented data for example to read image, audio,
video etc.
Syntax:
FileInputStream fileobject = new FileInputStream(“filename”);
or
File object = new File(“Filename”);
FileInputStream fileobject = new FileInputStream(object);
Example:
/* File Name: SimpleRead.java */
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Example: Copy the content of one file to another file
/* File Name: C.java */
import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");
int i=0;
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}
Character Stream
Java FileWriter and FileReader
 Java FileWriter and FileReader classes are used to write and read data from
text files.
 These are character-oriented classes, used for file handling in java.
Java FileWriter class
 Java FileWriter class is used to write character-oriented data to the file.
Constructors of FileWriter class
Constructor Description
FileWriter(String file) creates a new file. It gets file name in string.
FileWriter(File file) creates a new file. It gets file name in File object.
Methods of FileWriter class
Method Description
1) public void write(String text) writes the string into FileWriter.
2) public void write(char c) writes the char into FileWriter.
3) public void write(char[] c) writes char array into FileWriter.
4) public void flush() flushes the data of FileWriter.
5) public void close() closes FileWriter.
Example:
/* File Name: Simple.java */
import java.io.*;
class Simple{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
fw.write("my name is sachin");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}
Java FileReader class
 Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class.
Constructors of FileWriter class
Constructor Description
FileReader(String file) It gets filename in string. It opens the given file in read
mode. If file doesn't exist, it throws
FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in
read mode. If file doesn't exist, it throws
FileNotFoundException.
Methods of FileReader class
Method Description
1) public int read() returns a character in ASCII form. It returns -1 at the
end of file.
2) public void close() closes FileReader.
Example:
/* File Name: Simple.java */
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
}
}
2. What is JDBC? Explain insertion, deletion and display operations on database
using JAVA code.
JDBC
 JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and
a wide range of databases
CREATING JDBC APPLICATION
There are following 5 steps involved in building a JDBC application −
 Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
 Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
 Create a connection: Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the
database.
 Create a Statement: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
 Execute the query: Requires that you use the appropriateResultSet.getXXX() method
to retrieve the data from the result set.
 Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
Example:
//STEP 1. Import required packages
import java.sql.*;
public class DBTest {
public static void main(String[] args) {
String dburl = "jdbc:mysql://localhost/emp";
String dbuser = "root";
String dbpwd = "itlab";
String dbdriver = "com.mysql.jdbc.Driver";
Connection con = null;
try
{
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
//STEP 1: Register JDBC driver
Class.forName(dbdriver);
//STEP 2: Create a connection
con = DriverManager.getConnection(dburl, dbuser, dbpwd);
//STEP 3: Create a Statement
Statement stmt = con.createStatement();
// STEP 4: Execute the query
ResultSet rs = stmt.executeQuery("select eid, ename from employee");
while(rs.next())
{
System.out.print(rs.getInt("eid"));
System.out.println(rs.getString(2));
}
//STEP 5: Clean-up environment
rs.close();
stmt.close();
}
catch(SQLException sql)
{
System.out.println(sql);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Display (select):
Step 1: Register the Driver using Class.forName() by passing the Driver class along
with its package
Step 2: Establish the connection using getConnection() method by passing the db url,
db user name, db password.
Step 3: Create an object for Statement class by assigning the result of
createStatement() method.
Step 4: Pass the sql query “select column_name from table_name” to the
executeQuery() method. This return the value that stores in ResultSet object.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Step 5: Generate a loop using ResultSet_object.next() method which reads the line by
line from the ResultSet.
i. Read the corresponding column value using getInt(), getString(),
getDouble(), etc.. method by passing the column index to the method
Step 6: Close all the objects
Insertion (insert):
Step 1: Register the Driver using Class.forName() by passing the Driver class along
with its package
Step 2: Establish the connection using getConnection() method by passing the db url,
db user name, db password.
Step 3: Create an object for PreparedStatement class by assigning the result of
prepareStatement() method and pass the sql query “insert into table_name values (?,
?)”.
Step 4: Get the input from the user and pass the ? order number and the variable to the
setInt(), setString(), setDouble(), etc.. methods.
Step 5: Use executeUpdate() method to update the values in the database
Step 6: Close all the objects
Deletion (delete):
Step 1: Register the Driver using Class.forName() by passing the Driver class along
with its package
Step 2: Establish the connection using getConnection() method by passing the db url,
db user name, db password.
Step 3: Create an object for PreparedStatement class by assigning the result of
prepareStatement() method and pass the sql query “delete from table_name where
column_name = ?”.
Step 4: Get the input from the user and pass the ? order number and the variable to the
setInt(), setString(), setDouble(), etc.. methods.
Step 5: Use executeUpdate() method to update the values in the database
Step 6: Close all the objects
Updation (update):
Step 1: Register the Driver using Class.forName() by passing the Driver class along
with its package
Step 2: Establish the connection using getConnection() method by passing the db url,
db user name, db password.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Step 3: Create an object for PreparedStatement class by assigning the result of
prepareStatement() method and pass the sql query “update table_name set
column_name = ? where column_name = ?”.
Step 4: Get the input from the user and pass the ? order number and the variable to the
setInt(), setString(), setDouble(), etc.. methods.
Step 5: Use executeUpdate() method to update the values in the database
Step 6: Close all the objects
Database Creation:
create table emp_detail(eid int not null primary key, ename varchar(10), edept varchar(10),
edesg varchar(10), esalary int);
insert into emp_detail values(100, 'arthy', 'IT', 'AP', 20000);
Coding:
import java.sql.*;
import java.util.Scanner;
/**
*
* @author arthy.r
*/
public class JDBCDemo {
String driver = "org.apache.derby.jdbc.ClientDriver";
Connection con = null;
Statement stmt = null;
PreparedStatement pstmt = null;
void select()
{
try
{
Class.forName(driver);
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee",
"arthy", "arthy");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp_detail");
System.out.println("Employee Details");
System.out.println("****************");
while(rs.next())
{
System.out.println("-------------------------------------------------------------------");
System.out.println("Employee Id : " +rs.getInt(1));
System.out.println("Employee Name : " +rs.getString(2));
System.out.println("Employee Department : " +rs.getString(3));
System.out.println("Employee Designation : " +rs.getString(4));
System.out.println("Employee Salary : " +rs.getInt(5));
System.out.println("-------------------------------------------------------------------");
}
}
catch(Exception e)
{
System.out.println("SQL Exception e");
}
}
void insert()
{
int eid, salary;
String ename, edept, edesig;
try
{
Class.forName(driver);
con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee",
"arthy", "arthy");
pstmt = con.prepareStatement("insert into emp_detail values(?,?,?,?,?)");
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
System.out.println("Employee Details");
System.out.println("****************");
Scanner s1 = new Scanner(System.in);
System.out.println("Enter the number of employee : ");
int n = s1.nextInt();
for(int i = 0; i < n; i++)
{
System.out.print("Enter the Employee ID : ");
eid = s1.nextInt();
System.out.print("Enter the Employee Name : ");
ename = s1.next();
System.out.print("Enter the Employee Department : ");
edept = s1.next();
System.out.print("Enter the Employee Designation : ");
edesig = s1.next();
System.out.print("Enter the Employee Salary : ");
salary = s1.nextInt();
pstmt.setInt(1, eid);
pstmt.setString(2, ename);
pstmt.setString(3, edept);
pstmt.setString(4, edesig);
pstmt.setInt(5, salary);
pstmt.executeUpdate();
}
}
catch(Exception e)
{
System.out.println("SQL Exception "+e);
}
}
void delete()
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
{
int eid;
try
{
Class.forName(driver);
con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee",
"arthy", "arthy");
pstmt = con.prepareStatement("delete from emp_detail where eid = ?");
System.out.println("Employee Details");
System.out.println("****************");
Scanner s1 = new Scanner(System.in);
System.out.print("Enter the employee ID : ");
eid = s1.nextInt();
pstmt.setInt(1, eid);
pstmt.executeUpdate();
}
catch(Exception e)
{
System.out.println("SQL Exception "+e);
}
}
void update()
{
int eid, salary;
try
{
Class.forName(driver);
con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee",
"arthy", "arthy");
pstmt = con.prepareStatement("update emp_detail set esalary = ? where eid = ?");
System.out.println("Employee Details");
System.out.println("****************");
Scanner s1 = new Scanner(System.in);
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
System.out.print("Enter the employee ID : ");
eid = s1.nextInt();
System.out.print("Enter the employee salary : ");
salary = s1.nextInt();
pstmt.setInt(2, eid);
pstmt.setInt(1, salary);
pstmt.executeUpdate();
}
catch(Exception e)
{
System.out.println("SQL Exception "+e);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int choice;
Scanner s1 = new Scanner(System.in);
JDBCDemo dbc = new JDBCDemo();
while(true)
{
System.out.println("DB Operations");
System.out.println("*************");
System.out.println("1. Selectionn2. Insertionn3. Deletionn4. Updationn5. Exit");
System.out.println("Enter the Choice : ");
choice = s1.nextInt();
switch(choice)
{
case 1:
dbc.select();
break;
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
case 2:
dbc.insert();
break;
case 3:
dbc.delete();
break;
case 4:
dbc.update();
break;
case 5:
System.exit(0);
}
}
}
}
3. What is JDBC? Explain the various types of drivers in JDBC.
JDBC
 JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and
a wide range of databases
JDBC Driver
 JDBC drivers implement the defined interfaces in the JDBC API, for interacting
with your database server.
 java.sql.* supports the JDBC concepts
Types
 Sun has divided the implementation types into four categories:
o Types 1, 2, 3, and 4
Type 1: JDBC-ODBC Bridge Driver
 In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on
each client machine.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 Using ODBC, requires configuring on your system a Data Source Name (DSN)
that represents the target database.
 When Java first came out, this was a useful driver because most databases only
supported ODBC access but now this type of driver is recommended only for
experimental use or when no other alternative is available.
Type 2: JDBC-Native API
 In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which
are unique to the database.
 These drivers are typically provided by the database vendors and used in the same
manner as the JDBC-ODBC Bridge.
 The vendor-specific driver must be installed on each client machine.
 Type 2 driver, eliminates ODBC's overhead.
 The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Type 3: JDBC-Net pure Java
 In a Type 3 driver, a three-tier approach is used to access databases.
 The JDBC clients use standard network sockets to communicate with a middleware
application server.
 The socket information is then translated by the middleware application server into
the call format required by the DBMS, and forwarded to the database server.
 This kind of driver is extremely flexible, since it requires no code installed on the
client and a single driver can actually provide access to multiple databases.
Type 4: 100% Pure Java
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's
database through socket connection.
 This is the highest performance driver available for the database and is usually
provided by the vendor itself.
 This kind of driver is extremely flexible, you don't need to install special software on
the client or server. Further, these drivers can be downloaded dynamically.
 MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of
their network protocols, database vendors usually supply type 4 drivers.
4. Explain in detail about Adapter class.
 Java adapter classes provide the default implementation of listener interfaces.
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Advantages of using Adapter classes:
 It assists the unrelated classes to work combinedly.
 It provides ways to use classes in different ways.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 It increases the transparency of classes.
 It provides a way to include related patterns in the class.
 It provides a pluggable kit for developing an application.
 It increases the reusability of the class.
 import javax.swing.*;
Example:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class MouseEventDemo extends MouseAdapter
{
int num = 0;
public void mousePressed(MouseEvent me)
{
System.exit(0);
}
public void mouseExited(MouseEvent me)
{
System.out.println("Welcome");
}
}
class MouseEventDemo1 extends JComponent
{
MouseEventDemo1()
{
// Creating a frame
JFrame fr1 = new JFrame();
fr1.setTitle("First Demo");
// Setting the close type
fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr1.setVisible(true);
}
public static void main(String ar[])
{
MouseEventDemo1 me = new MouseEventDemo1();
}
}
5. Explain the mouse listener with example.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 The Java MouseListener is notified whenever you change the state of mouse.
It is notified against MouseEvent.
 The MouseListener interface is found in java.awt.event package. It has five
methods.
o public abstract void mouseClicked(MouseEvent e);
o public abstract void mouseEntered(MouseEvent e);
o public abstract void mouseExited(MouseEvent e);
o public abstract void mousePressed(MouseEvent e);
o public abstract void mouseReleased(MouseEvent e);
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.imageio.*;
import javax.imageio.ImageIO;
import java.io.*;
class MouseEventDemo extends MouseAdapter
{
int num = 0;
public void mouseClicked(MouseEvent me)
{
double x = me.getX();
double y = me.getY();
System.out.println("X = "+x+"Y = "+y);
}
public void mousePressed(MouseEvent me)
{
System.exit(0);
}
public void mouseReleased(MouseEvent me)
{
int count = me.getClickCount();
System.out.println("Count = "+count);
}
public void mouseEntered(MouseEvent me)
{
Point2D po = me.getPoint();
double x = po.getX();
double y = po.getY();
System.out.println("X = "+x+"Y = "+y);
}
public void mouseExited(MouseEvent me)
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
{
System.out.println("Welcome");
}
}
class mouseevent extends JComponent
{
mouseevent()
{
MouseEventDemo e1 = new MouseEventDemo();
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
addMouseListener(e1);
}
}
class MouseEventDemo1 extends JComponent
{
MouseEventDemo1()
{
// Creating a frame
JFrame fr1 = new JFrame();
fr1.setTitle("First Demo");
// Setting the close type
fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mouseevent sft = new mouseevent();
fr1.add(sft);
fr1.setVisible(true);
}
public static void main(String ar[])
{
MouseEventDemo1 me = new MouseEventDemo1();
}
}
6. Explain various layout managements in swing program.
 The LayoutManagers are used to arrange components in a particular manner.
 The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms.
 LayoutManager is an interface that is implemented by all the classes of layout
managers.
 There are the following classes that represent the layout managers:
o java.awt.BorderLayout
o java.awt.FlowLayout
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
o java.awt.GridLayout
o java.awt.CardLayout
o java.awt.GridBagLayout
o javax.swing.BoxLayout
o javax.swing.GroupLayout
o javax.swing.ScrollPaneLayout
o javax.swing.SpringLayout etc.
Java BorderLayout
 The BorderLayout is used to arrange the components in five regions: north, south,
east, west, and center.
 Each region (area) may contain one component only. It is the default layout of a
frame or window.
 The BorderLayout provides five constants for each region:
o public static final int NORTH
o public static final int SOUTH
o public static final int EAST
o public static final int WEST
o public static final int CENTER
Example:
import javax.swing.*;
import java.awt.*;
class BorderLayoutDemo extends JFrame {
public static void main(String ar[])
{
JFrame frame = new JFrame("Layout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("Button 1");
frame.getContentPane().add(button1,BorderLayout.NORTH);
BorderLayoutDemo lo = new BorderLayoutDemo ();
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button2,BorderLayout.SOUTH);
JButton button3 = new JButton("Button 3");
frame.getContentPane().add(button3,BorderLayout.WEST);
JButton button4 = new JButton("Button 4");
frame.getContentPane().add(button4,BorderLayout.EAST);
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
JButton button5 = new JButton("Button 5");
frame.getContentPane().add(button5,BorderLayout.CENTER);
frame.setVisible(true);
}
}
FlowLayout
 The Java FlowLayout class is used to arrange the components in a line, one after
another (in a flow). It is the default layout of the applet or panel.
 Fields of FlowLayout class
o public static final int LEFT
o public static final int RIGHT
o public static final int CENTER
o public static final int LEADING
o public static final int TRAILING
Constructors of FlowLayout class
 FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
 FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
 FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Example:
import javax.swing.*;
import java.awt.*;
class FlowLayoutDemo extends JFrame
{
public static void main(String ar[])
{
JFrame frame = new JFrame("Layout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.TRAILING));
JButton button1 = new JButton("Button 1");
panel.add(button1);
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
JButton button2 = new JButton("Button 2");
panel.add(button2);
JButton button3 = new JButton("Button 3");
panel.add(button3);
JButton button4 = new JButton("Button 4");
panel.add(button4);
JButton button5 = new JButton("Exit");
panel.add(button5);
frame.add(panel,BorderLayout.CENTER);
frame.setVisible(true);
}
}
Grid Layout:
 The Java GridLayout class is used to arrange the components in a rectangular grid.
One component is displayed in each rectangle.
Constructors of GridLayout class
 GridLayout(): creates a grid layout with one column per component in a row.
 GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
 GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns along with given horizontal and vertical gaps.
Example:
import javax.swing.*;
import java.awt.*;
class GridLayoutDemo extends JFrame
{
public static void main(String ar[])
{
JFrame frame = new JFrame("Layout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2,4,5));
JButton button1 = new JButton("Button 1");
panel.add(button1);
GridLayoutDemo lo = new GridLayoutDemo();
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
JButton button2 = new JButton("Button 2");
panel.add(button2);
JButton button3 = new JButton("Button 3");
panel.add(button3);
JButton button4 = new JButton("Button 4");
panel.add(button4);
JButton button5 = new JButton("Button 5");
panel.add(button5);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
7. What is MVC? Explain MVC architecture with example.
Swing uses the Model-View-Controller architecture (MVC) as the fundamental
design behind each of its components.
 MVC breaks GUI components into 3 elements
 Each elements plays an important role in how component behaves
 Allows for Portability etc.
The Basic MVC Model
Model
-- State data for each component.
• Different for each component
• E.g. Scrollbar -- Max and minimum Values, Current Position, width of thumb
position relative to values
• E.g. Menu -- Simple List of items.
• Model data is always independent of visual representation.
View
-- How component is painted on the screen
• Can vary between platforms/look and feel
Controller
-- dictates how component interacts with events
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
MVC in Swing
Swing uses a simplified model of the MVC design: model-delegate
The MVC Swing Model
 Combines View and Controller into a single element -- the UI-delegate
 Easy to bundle graphics and event handling in Java -- AWT.
 Model delegate interaction is now Two way.
o Model -- maintains information
o UI-delegate -- Draws and reacts to events that propagate through component.
8. Explain any four swing components along with its methods
JFrame Class:
Package:
javax.swing.*
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Constructor:
 JFrame() - Constructs a new frame that is initially invisible.
 JFrame(GraphicsConfiguration gc) - Creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank title.
 JFrame(String title) - Creates a new, initially invisible Frame with the specified
title.
 JFrame(String title, GraphicsConfiguration gc) - Creates a JFrame with the
specified title and the specified GraphicsConfiguration of a screen device.
Methods:
 void setDefaultCloseOperation(int operation) - Sets the operation that will happen by
default when the user initiates a "close" on this frame.
 void setLayout(LayoutManager manager) - Sets the LayoutManager.
 setVisible(boolean aFlag): It makes the component visible or invisible.
JButton Class:
Package:
javax.swing.*
Constructors:
 JButton() - It creates a button with no text and icon.
 JButton(String s) - It creates a button with the specified text.
 JButton(Icon i) - It creates a button with the specified icon object.
Methods:
 void setText(String s) - It is used to set specified text on button
 String getText() - It is used to return the text of the button.
 void setEnabled(boolean b) - It is used to enable or disable the button.
 void setIcon(Icon b) - It is used to set the specified Icon on the button.
 Icon getIcon() - It is used to get the Icon of the button.
 void setMnemonic(int a) - It is used to set the mnemonic on the button.
 void addActionListener(ActionListener a) - It is used to add the action listener to this
object.
JTextField Class:
Package:
javax.swing.*
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Constructors:
 JTextField() - Creates a new TextField
 JTextField(String text) - Creates a new TextField initialized with the specified text.
 JTextField(String text, int columns) - Creates a new TextField initialized with the
specified text and columns.
 JTextField(int columns) - Creates a new empty TextField with the specified number
of columns.
Methods:
 void setText(String s) - It is used to set specified text on button
 String getText() - It is used to return the text of the button.
 void setEnabled(boolean b) - It is used to enable or disable the button.
 void addActionListener(ActionListener a) - It is used to add the action listener to this
object.
JLabel Class
Constructors
Constructor Description
JLabel() Creates a JLabel instance with no image and with an
empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int
horizontalAlignment)
Creates a JLabel instance with the specified text, image,
and horizontal alignment.
Methods
Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this component will
display.
void
setHorizontalAlignment(int
alignment)
It sets the alignment of the label's contents along the X
axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X
axis.
JPasswordField Class
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Constructors
Constructor Description
JPasswordField() Constructs a new JPasswordField, with a default
document, null starting text string, and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the
specified number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the
specified text.
JPasswordField(String text, int
columns)
Construct a new JPasswordField initialized with the
specified text and columns.
Methods
Method Description
isEditable() Returns a boolean value indicating whether or not a text
field is editable
setEditable() Passing True enables text to be edited, while False
disables editing. The default is True.
addActionListener() Registers an ActionListener object to receive action
events from a text field
getEchoChar() Returns the character used for echoing
getColumns() Returns the number of columns in a text field
setEchoChar() Sets the echo character for a text field
getText() Returns the text contained in the text field
setText() Sets the text for a text field
JTextArea Class
Constructors
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
JTextArea(int row, int
column)
Creates a text area with the specified number of rows and
columns that displays no text initially.
JTextArea(String s, int row,
int column)
Creates a text area with the specified number of rows and
columns that displays specified text.
Methods
Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int
position)
It is used to insert the specified text on the specified
position.
void append(String s) It is used to append the given text to the end of the
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
document.
JCheckbox Class
Constructors
Constructor Description
JCheckBox() Creates an initially unselected check box button with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text,
boolean selected)
Creates a check box with text and specifies whether or not it is
initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.
JRadioButton Class
Constructors
Constructor Description
JRadioButton() Creates an unselected radio button with no
text.
JRadioButton(String s) Creates an unselected radio button with
specified text.
JRadioButton(String s, boolean
selected)
Creates a radio button with the specified text
and selected status.
Methods
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the
button.
void addActionListener(ActionListener
a)
It is used to add the action listener to this
object.
JComboBox Class
Constructors
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the
specified array.
JComboBox(Vector<?>
items)
Creates a JComboBox that contains the elements in the
specified Vector.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Methods
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is
editable.
void
addActionListener(ActionListener a)
It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
JList
Constructors
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary>
dataModel)
Creates a JList that displays elements from the specified,
non-null, model.
Methods
Methods Description
Void
addListSelectionListener(ListSelectio
nListener listener)
It is used to add a listener to the list, to be notified
each time a change to the selection occurs.
int getSelectedIndex() It is used to return the smallest selected cell index.
ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from an
array of objects.
JOptionPane Class
Methods
Methods Description
JDialog createDialog(String title) It is used to create and return a new parentless
JDialog with the specified title.
static void showMessageDialog
(Component parentComponent, Object
message)
It is used to create an information-message
dialog titled "Message".
static void showMessageDialog
(Component parentComponent, Object
message, String title, int messageType)
It is used to create a message dialog with
given title and messageType.
static int showConfirmDialog
(Component parentComponent, Object
message)
It is used to create a dialog with the options
Yes, No and Cancel; with the title, Select an
Option.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
static String showInputDialog
(Component parentComponent, Object
message)
It is used to show a question-message dialog
requesting input from the user parented to
parentComponent.
void setInputValue(Object newValue) It is used to set the input value that was
selected or input by the user.
Menus:
 A JMenuBar instance is first created as:
JMenuBar mb = new JMenuBar();
 The JMenuBar instance is added to a frame using the setMenuBar() method of the
Frame class as follows:
setJMenuBar(mb);
 Individual menus are created (instances of the JMenu class) and added to the
menu bar with the add() method
 Add the Menu items using JMenuItem class
UNIT V
PART A
1. What is Multi-threading?
 Multithreading is a conceptual programming concept where a program(process)
is divided into two or more subprograms(process), which can be implemented at
the same time in parallel.
 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.
2. List out the methods of object class to perform inter thread communication?
 wait() – This method make the current thread to wait until another thread
invokes the notify() method.
 notify() – This method wakes up a thread that called wait() on same object.
 notifyAll() – This method wakes up all the thread that called wait() on same
object. Wakes up all threads that are waiting on this object‟s monitor.
3. What is daemon thread and which method is used to create the daemon thread?
 Daemon thread is a low priority thread which runs intermittently in the back
ground doing the garbage collection operation for the java runtime system.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
 setDaemon method is used to create a daemon thread.
 This method waits until the thread on which it is called terminates
4. Write a multithreaded program that joins two threads.
import java.io.*;
class ThreadJoining extends Thread
{
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
Thread.sleep(500);
System.out.println(“Thread 1”);
}
catch(Exception ex)
{
System.out.println("Exception”);
}
System.out.println(i);
}
}
}
class GFG
{
public static void main (String[] args)
{
// creating two threads
ThreadJoining t1 = new ThreadJoining();
ThreadJoining t2 = new ThreadJoining();
ThreadJoining t3 = new ThreadJoining();
// thread t1 starts
t1.start();
// starts second thread after when first thread t1 has died.
try
{
System.out.println("Thread 1”);
t1.join();
}
catch(Exception ex)
{
System.out.println("Exception”);
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
// t2 starts
t2.start();
// starts t3 after when thread t2 has died.
try
{
System.out.println("Thread 2”);
t2.join();
}
catch(Exception ex)
{
System.out.println("Exception”);
}
t3.start();
}
}
5. Differentiate wait() and sleep() in JAVA.
Wait() Sleep()
Wait() method belongs to Object class. Sleep() method belongs to Thread class.
Wait() method releases lock during
Synchronization.
Sleep() method does not release the lock on object
during Synchronization.
Wait() should be called only from
Synchronized context.
There is no need to call sleep() from Synchronized
context.
Wait() is not a static method. Sleep() is a static method.
Wait() Has Three Overloaded Methods:
 wait()
 wait(long timeout)
 wait(long timeout, int nanos)
Sleep() Has Two Overloaded Methods:
PART B
1. Life Cycle of Thread:
Introduction
 A process is a program in execution.
 A process may be divided into a number of independent units known as threads.
 A thread is a dispatchable unit of work.
 Threads are light-weight processes within a process.
 A process is a collection of one or more threads and associated system resources.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Thread Life Cycle
 The life cycle of threads in Java is very similar to the life cycle of processes running
in an operating system.
 During its life cycle the thread moves from one state to another depending on the
operation performed by it.
 A Java thread can be in one of the following states:
o NEW
 A thread that is just instantiated is in new state.
 When a start() method is invoked, the thread moves to the ready state
from which it is automatically moved to runnable state by the thread
scheduler.
o RUNNABLE (ready_running)
 A thread, that is ready to run is then moved to the runnable state.
 A thread executing in the JVM is in running state.
 The run() method will be invoked to make thread move to running
state.
o BLOCKED
 A thread that is blocked waiting for a monitor lock is in this state.
 This can also occur when a thread performs an I/O operation and
moves to next (runnable) state.
 The suspend() method puts the thread in the blocked state.
 The thread will be unblocked using resume() method.
o WAITING
 A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
 The wait() method puts the thread in the waiting state.
 The thread will be notified back using notify() method.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
o TIMED_WAITING (sleeping)
 A thread that is waiting for another thread to perform an action for up
to a specified waiting time is in this state.
 The sleep() method puts the thread in the timed wait state.
 After the time runs out, the thread wakes up and starts its execution
from when it has left earlier.
o TERMINATED (dead) –
 A thread reaches the termination state because of the following
reasons:
 When a thread has finished its job, then it exists or terminates
normally.
 Abnormal termination: It occurs when some unusual events
such as an unhandled exception or segmentation fault.A thread
that has exited is in this state.
2. Discuss on JAVA Archives.
 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 to
distribute application software or libraries on the Java platform.
 In simple words, a JAR file is a file that contains a compressed version of .class files,
audio files, image files, or directories.
 It is similar to a zipped file(.zip) that is created by using WinZip software.
 Even, WinZip software can be used to extract the contents of a .jar .
 So you can use them for tasks such as lossless data compression, archiving,
decompression, and archive unpacking.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
Create a JAR file
 In order to create a .jar file, we can use jar cf command
 Syntax:
o jar cf jarfilename inputfiles
View a JAR file
 Syntax:
o jar tf jarfilename
 Here, tf represents the table view of file contents.
Extracting a JAR file
 Syntax:
o jar xf jarfilename
 Here, xf represents extract files from the jar files.
Updating a JAR File
 The Jar tool provides a „u‟ option that you can use to update the contents of an
existing JAR file by modifying its manifest or by adding files.
 Syntax:
o jar uf jar-file input-file(s)
 Here „uf‟ represents the updated jar file.
Running a JAR file
 Syntax:
o C:>java -jar pack.jar
3. What is multithreading? Explain the implementation of multithreading with
suitable example.
Introduction
 A process is a program in execution.
 A process may be divided into a number of independent units known as threads.
 A thread is a dispatchable unit of work.
 Threads are light-weight processes within a process.
 A process is a collection of one or more threads and associated system resources.
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
A process containing single and multiple threads
Java supports thread-based multitasking. The advantages of thread-based multitasking
as compared to process-based multitasking are given below:
1. Threads share the same address space.
2. Context-switching between threads is normally inexpensive.
3. Communication between threads is normally inexpensive.
Creating Threads in Java
 A single process might contain multiple threads.
 All threads within a process share the same state and same memory space, and can
communicate with each other directly, because they share the same variables.
A program with master thread and children threads
Threads are objects in the Java language. They can be created by using two different
mechanisms
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
1. Create a class that extends the standard Thread class.
2. Create a class that implements the standard Runnable interface.
Creation of Threads in Java
a. Extending the Thread Class
The steps for creating a thread by using the first mechanism are:
1. Create a class by extending the Thread class and override the run() method:
class MyThread extends Thread {
public void run() {
// thread body of execution
}
}
2. Create a thread object: MyThread thr1 = new MyThread();
3. Start Execution of created thread: thr1.start();
/* A simple program creating and invoking a thread object by extending the standard Thread
class. */
class MyThread extends Thread {
public void run() {
System.out.println(“ this thread is running ... ”);
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
}
 The user needs to implement their logic associated with the thread in the run()
method, which is the body of thread.
 The objects created by instantiating the class MyThread are called threaded
objects.
 Even though the execution method of thread is called run, we do not need to
explicitly invoke this method directly.
 When the start() method of a threaded object is invoked, it sets the concurrent
execution of the object from that point onward along with the execution of its
parent thread/method.
b. Implementing the Runnable Interface
The steps for creating a thread by using the second mechanism are:
1. Create a class that implements the interface Runnable and override run() method:
class MyThread implements Runnable {
…
public void run() {
// thread body of execution
}
}
2. Creating Object: MyThread myObject = new MyThread();
3. Creating Thread Object: Thread thr1 = new Thread(myObject);
4. Start Execution: thr1.start();
/* A simple program creating and invoking a thread object by implementing Runnable
interface. */
class MyThread implements Runnable {
public void run() {
System.out.println(“ this thread is running ... ”);
}
}
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
t.start();
IT1301 – Object Oriented Programming
Prepared by, Dr. R. Arthy, AP/IT
}
}
 The class MyThread implements standard Runnable interface and overrides
the run() method and includes logic associated with the body of the thread
(step 1).
 The objects created by instantiating the class MyThread are normal objects
(unlike the fi rst mechanism) (step 2).
 Therefore, we need to create a generic Thread object and pass MyThread
object as a parameter to this generic object (step 3).
 As a result of this association, threaded object is created. In order to execute
this threaded object, we need to invoke its start() method which sets execution
of the new thread (step 4).

More Related Content

What's hot (10)

todo sobre java
todo sobre javatodo sobre java
todo sobre java
 
Java packages
Java packagesJava packages
Java packages
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
Data types in java
Data types in javaData types in java
Data types in java
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
 
Java packages
Java packagesJava packages
Java packages
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 

Similar to Qb it1301

Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
BalamuruganV28
 

Similar to Qb it1301 (20)

Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
 
Java notes jkuat it
Java notes jkuat itJava notes jkuat it
Java notes jkuat it
 
Java notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esectionJava notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esection
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
3. jvm
3. jvm3. jvm
3. jvm
 
Java notes
Java notesJava notes
Java notes
 
A seminar report on core java
A  seminar report on core javaA  seminar report on core java
A seminar report on core java
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
1_JavIntro
1_JavIntro1_JavIntro
1_JavIntro
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
Java1
Java1Java1
Java1
 
Java
Java Java
Java
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java_Interview Qns
Java_Interview QnsJava_Interview Qns
Java_Interview Qns
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 

More from ArthyR3

More from ArthyR3 (20)

Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdf
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdf
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdf
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit v
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit v
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit i
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography Workbook
 
Cns
CnsCns
Cns
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network security
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bank
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning material
 
Cyber forensics question bank
Cyber forensics   question bankCyber forensics   question bank
Cyber forensics question bank
 

Recently uploaded

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Recently uploaded (20)

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 

Qb it1301

  • 1. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT IT1301 - OBJECT ORIENTED PROGRAMMING II IT DEPARTMENT OF INFORMATION TECHNOLOGY
  • 2. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT UNIT I PART A 1. “JAVA is an Impure programming language” – Justify. Java is impure object oriented programming language because it supports primitive data type like it, byte, long etc., which are not objects. 2. “JAVA is platform independent” – Justify. Java compilers complies the code for a machine that physically does not exist, (i.e.) for a virtual machine. This code is Byte code. This supports the concept of platform independent. Java Virtual Machine that runs in the local machine, interprets the Java byte code and converts it into platform specific machine code. 3. What is bytecode? Java bytecode is the instruction set for the Java Virtual Machine. Java bytecode is the machine code in the form of a .class file. With the help of java bytecode, platform independence in java. 4. If no arguments are provided on the command line, then the string array of Main method will be empty or null? Justify. Java main method accepts a single argument of type String array. This is also called as java command line arguments. JVM takes care of passing any command line arguments as an array of strings to the main function. If there are no arguments given, an empty array is passed - but it's still there 5. Name the types of variable.
  • 3. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT a. Local variable b. Instance variable c. Static variable 6. Tabulate the various data type with its size. Data Type Size byte 8 short 16 int 32 long 64 float 32 double 64 char 16 Boolean 1 7. List down the 4 access specifiers in JAVA. a. Public b. Private c. Protected d. Default 8. Define classes and objects. Classes: A class in Java is a blueprint which includes all your data. A class contains fields (variables) and methods to describe the behaviour of an object. Syntax: <access specifier> class <ClassName> { member variables // class body methods } Objects: An object is a major element in a class which has a state and behaviour. It is an instance of a class which can access your data. The „new‟ keyword is used to create the object. 9. Define constructor.
  • 4. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT A constructor is a block of code that initializes a newly created object. It is similar to a method in Java but doesn‟t have any return type and its name is same as the class name. 10. Mention the rules for creating a constructor in java. a. Class name and Constructor name should be same b. No return type for a constructor c. Constructor can have n number of parameters d. Constructors are similar to methods but it is invoked automatically during the object creation 11. What is package? A java package is a group of similar types of classes, interfaces and sub- packages. PART B 1. Discuss various features of JAVA. Features of JAVA: a. Simple  Java is very easy to learn, and its syntax is simple, clean and easy to understand. b. Object-Oriented  Java is an object-oriented programming language.  Everything in Java is an object.  Object-oriented refers to software as a combination of different types of objects that incorporate both data and behavior. c. Portable  Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. d. Platform independent  Java compilers complies the code for a machine that physically does not exist, (i.e.) for a virtual machine. This code is Byte code. This supports the concept of platform independent.  Java Virtual Machine that runs in the local machine, interprets the Java byte code and converts it into platform specific machine code. e. Secured
  • 5. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  Java is best known for its security.  Java helps to develop virus-free systems  Java is secured because: o No explicit pointer o Java Programs run inside a virtual machine sandbox o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources. o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects. o Security Manager: It determines what resources a class can access such as reading and writing to the local disk. f. Robust Java is robust because:  It uses strong memory management.  There is a lack of pointers that avoids security problems.  Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore.  There are exception handling and the type checking mechanism in Java. All these points make Java robust. g. Architecture neutral
  • 6. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed.  JAVA is Write Once Read Anywhere h. Interpreted  Handles the bytecode.  Converts the bytecode to executable form. i. High Performance  Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. j. Multithreaded  A thread is like a separate program, executing concurrently.  Many tasks can execute at once with the help of multiple threads.  The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. k. Distributed  Java is distributed because it facilitates users to create distributed applications in Java.
  • 7. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  RMI and EJB are used for creating distributed applications. l. Dynamic  Java is a dynamic language. It supports the dynamic loading of classes.  It means classes are loaded on demand. 2. Describe the characteristics of OOPs Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. Features:  Object  Class  Inheritance  Polymorphism  Abstraction  Encapsulation Objects:  An object is a major element in a class which has a state and behaviour. It is an instance of a class which can access your data. The „new‟ keyword is used to create the object.  Example – Bike, Fan, Table  A dog is an object because it has states like color, name, breed, etc. as well as behaviours like wagging the tail, barking, eating, etc. Classes:  A class in Java is a blueprint which includes all your data. A class contains fields (variables) and methods to describe the behaviour of an object.  Syntax: <access specifier> class <ClassName> { member variables // class body methods } Inheritance:  Ability to inherit the properties of one class to another class Example:  University  College  UG Program  B.Tech Program  IT
  • 8. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  Grand Parent  Parent  Child  It provides code reusability. It is used to achieve runtime polymorphism. Polymorphism  If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc.  In Java, method overloading and method overriding are used to achieve polymorphism.  Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc. Abstraction  Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.  In Java, abstract class and interface are used to achieve abstraction. Encapsulation  Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a 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. 3. Define constructor. Explain the various types of constructors.  A constructor is a block of codes similar to the method.  It is called when an instance of the class is created.  At the time of calling constructor, memory for the object is allocated in the memory.  It is a special type of method which is used to initialize the object. Rules for creating the Constructor:  Class name and Constructor name should be same  No return type for a constructor  Constructor can have n number of parameters  Constructors are similar to methods but it is invoked automatically during the object creation Types of Java constructors There are two types of constructors in Java:
  • 9. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  Default constructor (no-arg constructor)  Parameterized constructor Default Constructor  Initialize a variable with ground (default/seed/initial) value Syntax: <access specifier> class ClassName{ public ClassName(){ } } Parameterized Constructor  To assign a value to a instance variable Syntax: <access specifier> class ClassName{ public ClassName(arguments){ } } Example: // To find the area of Circle import java.util.*; class AreaCircle { double area, pi, radius; // Default Constructor AreaCircle() { pi = 3.14; }
  • 10. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT // Parameterized Constructor AreaCircle(int r) { pi = 3.14; radius = r; } void area() { area = pi * radius * radius; System.out.println("Area of Circle = " + area); } void area(int radius) { area = pi * radius * radius; System.out.println("Area of Circle = " + area); } } public class Main{ public static void main(String args[]) { AreaCircle ac = new AreaCircle(); Scanner scan = new Scanner(System.in); System.out.println("Enter the value for radius : "); int r = scan.nextInt(); ac.area(r); AreaCircle ac1 = new AreaCircle(r); ac.area(); } } Java Constructor Java Method
  • 11. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object. A constructor must not have a return type. A method must have a return type. The constructor is invoked implicitly. The method is invoked explicitly. The Java compiler provides a default constructor if you don't have any constructor in a class. The method is not provided by the compiler in any case. The constructor name must be same as the class name. The method name may or may not be same as the class name. 4. What are access specifiers? Explain it with the access matrix.  The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.  There are two types of modifiers in Java: o Access modifiers o Non-access modifiers.  There are four types of Java access modifiers: o Private:  The access level of a private modifier is only within the class. It cannot be accessed from outside the class.  private int data=40; o Default:  The access level of a default modifier is only within the package.  It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. o Protected:  The access level of a protected modifier is within the package and outside the package through child class.  Example: public class A{ protected void msg(){System.out.println("Hello");} } o Public:  The access level of a public modifier is everywhere.
  • 12. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  It can be accessed from within the class, outside the class, within the package and outside the package. Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y 5. What is Object class? Explain the concepts of Object Cloning and Reflection. Object Class:  The Object class is the parent class of all the classes in java by default.  In other words, it is the topmost class of java. Methods: Method Description public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of this class. public int hashCode() returns the hashcode number for this object. public boolean equals(Object obj) compares the given object to this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public String toString() returns the string representation of this object. public final void notify() wakes up single thread, waiting on this object's monitor. public final void notifyAll() wakes up all the threads, waiting on this object's monitor. public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). public final void wait(long timeout,int nanos)throws InterruptedException causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method). public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method). protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected. Object Cloning:
  • 13. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object.  The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.  The clone() method is defined in the Object class. Syntax of the clone() method is as follows: protected Object clone() throws CloneNotSupportedException  The clone() method saves the extra processing task for creating the exact copy of an object.  If we perform it by using the new keyword, it will take a lot of processing time to be performed that is why we use object cloning. Object Reflection:  Java Reflection is a process of examining or modifying the run time behavior of a class at run time.  The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.  The java.lang and java.lang.reflect packages provide classes for java reflection. Method Description 1) public String getName() returns the class name 2) public static Class forName(String className)throws ClassNotFoundException loads the class and returns the reference of Class class. 3) public Object newInstance()throws InstantiationException,IllegalAccessException creates new instance. 4) public boolean isInterface() checks if it is interface. 5) public boolean isArray() checks if it is array. 6) public boolean isPrimitive() checks if it is primitive. 7) public Class getSuperclass() returns the superclass class reference. 8) public Field[] getDeclaredFields()throws SecurityException returns the total number of fields of this class. 9) public Method[] getDeclaredMethods()throws SecurityException returns the total number of methods of this class. 10) public Constructor[] getDeclaredConstructors()throws SecurityException returns the total number of constructors of this class.
  • 14. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT 11) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException returns the method class instance. 6. Discuss the user defined package creation and accessing in JAVA.  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.  There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. 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. Access package from another package There are three ways to access the package from outside the package.  import package.*;  import package.classname;  fully qualified name. Creating Package: package packageName;
  • 15. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT UNIT II PART A 1. State the use of interface in JAVA.  Interface provides abstraction and multiple inheritance. 2. Define inheritance. Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. 3. What is the various usage of static keyword?  The static keyword in Java is mainly used for memory management.  The static keyword in Java is used to share the same variable or method of a given class.  The users can apply static keywords with variables, methods, blocks, and nested classes.  The static keyword belongs to the class than an instance of the class. 4. Differentiate static polymorphism and dynamic polymorphism. S.No Static (Compile Time) Polymorphism Dynamic (Run time) Polymorphism 1 The call is resolved by the compiler. The call is not resolved by the compiler. 2 It is also known as Static binding, Early binding and overloading as well. It is also known as Dynamic binding, Late binding and overriding as well. 3 Method overloading is the compile-time polymorphism where more than one methods share the same name with different parameters or signature and different return type. Method overriding is the runtime polymorphism having same method with same parameters or signature, but associated in different classes. 4 It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers. 5 It provides fast execution because the method that needs to be executed is It provides slow execution as compare to early binding because the method that
  • 16. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT known early at the compile time. needs to be executed is known at the runtime. 6 Compile time polymorphism is less flexible as all things execute at compile time. Run time polymorphism is more flexible as all things execute at run time. 5. Differentiate interface from abstract class. Interface Abstract class Interface can have only abstract methods. Since Java 8, it can have default and static methods also. Abstract class can have abstract and non- abstract methods. Interface supports multiple inheritance. Abstract class doesn't support multiple inheritance. Interface has only static and final variables. Abstract class can have final, non-final, static and non-static variables. Interface can't provide the implementation of abstract class. Abstract class can provide the implementation of interface. The interface keyword is used to declare interface. The abstract keyword is used to declare abstract class. An interface can extend another Java interface only. An abstract class can extend another Java class and implement multiple Java interfaces. An interface can be implemented using keyword "implements". An abstract class can be extended using keyword "extends". Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc. Example: public interface Drawable{ void draw(); } Example: public abstract class Shape{ public abstract void draw(); } 6. Differentiate Class from Interface in JAVA. Class Interface The keyword used to create a class is “class” The keyword used to create an interface is “interface” A class can be instantiated i.e, objects of a class can be created. An Interface cannot be instantiated i.e, objects cannot be created. Classes does not support multiple inheritance. Interface supports multiple inheritance. It can be inherit another class. It cannot inherit a class. It can be inherited by another class using the keyword „extends‟. It can be inherited by a class by using the keyword „implements‟ and it can be inherited by an interface using the keyword „extends‟. It can contain constructors. It cannot contain constructors. It cannot contain abstract methods. It contains abstract methods only. Variables and methods in a class can be declared using any access specifier(public, private, default, protected) All variables and methods in a interface are declared as public.
  • 17. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Variables in a class can be static, final or neither. All variables are static and final. 7. Outline the usage of Final keyword in JAVA.  Final variable – constant – avoid the change in values of a variable o final double pi = 3.14;  Final method – avoid method overriding  Final class – avoid inheritance PART B 1. What is Inheritance? Explain the types of inheritance using suitable example. Definition: Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. Inheritance represents the IS-A relationship which is also known as a parent- child relationship. • All objects have the Object class as their top parent. • Methods can be overridden but attributes cannot. • To call a parent class constructor, super() is used. Java supports 3 types of inheritance: • Single Inheritance • Multi-level Inheritance • Hierarchical Inheritance Advantage: • Reusability of an existing class • Derived class that has own properties along with base class properties. Terminologies:  Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.  Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Syntax: class SubClassName extends BaseClassName { Expressions;
  • 18. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT } a. Single Inheritance In this, a class inherits the properties of a single parent class. Syntax Class A{ //your parent class code } Class B extends A { //your child class code } b. Multi Level Inheritance In multi-level inheritance, one class has more than one parent class but at different levels of inheritance. Syntax: Class A{ //your parent class code } Class B extends A { //your code } Class C extends B { //your code }
  • 19. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT c. Hierarchical Inheritance In hierarchical inheritance, one parent can have one or more child/sub/derived classes. Syntax: Class A{ //your parent class code } Class B extends A { //your child class code } Class C extends A { //your child class code } // Base Class // Base Class class A { void disp() { System.out.println(" Class A"); }
  • 20. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT } // Single Inheritance class B extends A { void display() { System.out.println("Class B"); } } // Multilevel Inheritance class C extends B { void show() { System.out.println("Class C"); } } // Hierarchal Inheritance class D extends B { void print() { System.out.println("Class D"); } } class InDemo { public static void main(String args[]) { C c1 = new C(); c1.disp(); c1.display(); c1.show();
  • 21. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT D d1 = new D(); d1.print(); } } Note: • It is enough to create the object for the child class • Child class can access all the members in the parent class directly • Parent class members can be accessed using child class object Super Keyword  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  super can be used to refer immediate parent class instance variable.  super can be used to invoke immediate parent class method.  super() can be used to invoke immediate parent class constructor. Note: • Super() should be written inside the derived class constructor as the first statement Example: class Base{ int a, b = 100; Base(int a){ this.a = a; } } class Derived extends Base{ int b; Derived(int c){ // Invoke base class constructor super(a);
  • 22. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT // To refer the base class instance variable b = super.b; } } 2. What is the purpose of interface? Explain the concept with suitable example. Introduction: An interface in Java is a blueprint of a class. It has static constants and abstract methods. Purpose:  It is used to achieve abstraction.  By interface, we can support the functionality of multiple inheritance.  It can be used to achieve loose coupling. Note:  Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass)  Interface methods do not have a body - the body is provided by the "implement" class  On implementation of an interface, you must override all of its methods  Interface methods are by default abstract and public  Interface attributes are by default public, static and final  An interface cannot contain a constructor (as it cannot be used to create objects) Multiple Inheritance:
  • 23. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Declaring Interfaces The interface keyword is used to declare an interface. Syntax: interface interfacename { //Any number of final, static fields //Any number of abstract method declarations } Variable Declaration (Constants): Syntax: public static final datatype variablename = value; Method Declaration (Abstract Method): Syntax: public abstract returntype methodname(Argument(s));Relationship between classes and interface:
  • 24. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Example: /* File name : Vehicle.java */ interface Vehicle { public int modelno = 123; public void changeGear(); public void changeSpeed(); } Implementing Interface A class uses the implements keyword to implement an interface. Syntax: class Classname implements interfacename1, intefacename2, … { // Method definition(s) // Variable declaration(s) //Abstract method definition(s) } Example: /* File name : VehicleMain.java */ class VehicleImple implements Vehicle { int speed = 0; int gear;
  • 25. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT void changeSpeed() { speed++; System.out.println(“Speed = “ +speed); } void changeGear() { if(speed < 10) gear = 1; else if(speed >= 10 && speed <=20) gear = 2; else if(speed > 20 && speed <=40) gear = 3; else if(speed > 40 && speed <=60) gear = 4; else gear = 5; System.out.println(“Gear = “+gear); } void obstacle() { speed--; } } Class VehicleMain { public static void main(String args[]) { VehicleImple vi = new VehicleImple(); vi.changeSpeed(); vi.obstacle(); vi.changeGear(); } }
  • 26. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Extending Interface  An interface can extend another interface, similarly to the way that a class can extend another class.  The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. Syntax: interface parentinterface { } interface childinterface extends parentinterface { } Example: //Filename: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } //Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } //Filename: Hockey.java public interface Hockey extends Sports { public void homeGoalScored();
  • 27. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); } Interface Reference Interfacename object = new classname(); Nested Interface An interface can have another interface i.e. known as nested interface. Example: interface printable { void print(); interface MessagePrintable{ void msg(); } } 3. Define inner class. Explain various types of inner class with suitable example. Inner Class:  Java inner class or nested class is a class that is declared inside the class or interface.  Use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.  Purpose - Hide the data and implementation Syntax: class OuterClassName { class InnerClassName { } } Types of inner class:
  • 28. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT a. Member inner class b. Anonymous inner class c. Local inner class b. Static inner class a. Member inner class A non-static class that is created inside a class but outside a method is called member inner class. It is also known as a regular inner class. Syntax: class OuterClassName { class InnerClassName { } } Note: 1. Outer class members can be accessed directly by the inner class 2. Inner class members cannot be accessed directly in the outer class 3. To access the inner class members in outer class, object has to be created for inner class 4. To access the inner class members outside the outer class i. Create an object for outer class ii. OuterClassName.InnerClassName ic = outerClassObject.new InnerClassName(); class OuterClass { // Instance Outer Variables int a = 10; class InnerClass { // Instance Inner class variable int b = 20;
  • 29. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT void display() { System.out.println("Outer A = " + a); System.out.println("Inner B = " + b); } } void show() { System.out.println("Inner B = " + b); } } public class Main { public static void main(String[] args) { OuterClass oc = new OuterClass(); OuterClass.InnerClass ic = oc.new InnerClass(); ic.display(); oc.show(); } } b. Anonymous Inner Class Java anonymous inner class is an inner class without a name and for which only a single object is created. Example: abstract class Test { abstract void display(); } public class Main {
  • 30. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT public static void main(String args[]) { Test t1 = new Test(){ void display() { System.out.println("Welcome"); } }; t1.display(); } } c. Local Inner Class  A class i.e., created inside a method, is called local inner class in java.  Local Inner Classes are the inner classes that are defined inside a block.  Generally, this block is a method body. Example: class Test { int a = 10; void show() { class Demo { void display() { System.out.println("Local Inner Class"); } } Demo d1 = new Demo();
  • 31. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT d1.display(); System.out.println("A = "+a); } } public class Main { public static void main(String args[]) { Test t1 = new Test(); t1.show(); } } d. Static Inner Class  A static class is a class that is created inside a class, is called a static nested class in Java.  It cannot access non-static data members and methods. It can be accessed by outer class name.  It can access static data members of the outer class, including private.   The static nested class cannot access non-static (instance) data members Example: class Test { static int a = 10; static class InnerClass { static void show() { System.out.println("Static Inner Class"); System.out.println("A = "+a);
  • 32. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT } } } public class Main { public static void main(String args[]) { Test.InnerClass.show(); } } 4. What is abstract class? Illustrate with an example to demonstrate abstract class.  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). Note:  An abstract class must be declared with an abstract keyword.  It can have abstract and non-abstract methods.  It cannot be instantiated.  It can have constructors and static methods also.  It can have final methods which will force the subclass not to change the body of the method. Syntax: abstract class classname{ } Abstract Method:  A method which is declared as abstract and does not have implementation is known as an abstract method. Syntax: abstract class classname{ abstract returntype methodName(args); }
  • 33. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Example: import java.util.Scanner; import java.util.Date; abstract class Shape { abstract void printArea(); } class Rectangle extends Shape { int x,y,l,b,area; Rectangle(int l,int b) { x=l; y=b; } void printArea() { area=x*y; //calculating area of rectangle System.out.println("Area of the Rectangle of size "+x+"*"+y+ "is"+area); } } class Triangle extends Shape { int x,y,z,l,b,h,area; Triangle(int l,int b,int h) { x=l; y=b; z=h; } void printArea() { area=(x*y*z)/2; //calculating area of triangle System.out.println("Area of the Triangle of size "+x+"*"+y+"*"+z+ "is"+area); } } class Circle extends Shape { int x,r; double area; Circle(int r) { x=r; } void printArea() { area=3.14*x*x; //calculating area of circle System.out.println("Area of the circle of size "+x+"is"+area); }
  • 34. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT } class Area { public static void main(String args[]) { Scanner s1=new Scanner(System.in); do { System.out.println("1.Rectangle"); System.out.println("2.Triangle"); System.out.println("3.Circle"); System.out.println("Enter your choice :"); choice=s1.nextInt(); switch(choice) { case 1: System.out.println("Mention the length of the rectangle:"); a=s1.nextInt(); System.out.println("Mention the breadth of the rectangle:"); b=s1.nextInt(); Rectangle a1=new Rectangle(a,b); a1.printArea(); break; case 2: System.out.println("Mention the length of the triangle:"); a=s1.nextInt(); System.out.println("Mention the breadth of the tringle:"); b=s1.nextInt(); System.out.println("Mention the height of the tringle:"); c=s1.nextInt(); Triangle b1=new Triangle(a,b,c); b1.printArea(); break; case 3: System.out.println("Mention the radius of the circle:"); a=s1.nextInt(); Circle c1=new Circle(a); c1.printArea(); break; default: System.out.println("Thanks for using our app"); } }while(choice>0 && choice<4); } }
  • 35. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT 5. Describe the types of polymorphism with example. Polymorphism  Polymorphism is the ability of an object to take on many forms.  The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.  Types: o Static polymorphism – Method Overloading – Static binding – Compile time polymorphism o Dynamic polymorphism – Method Overriding – Dynamic binding – Runtime polymorphism Static Polymorphism: Method overloading: Same method name with different number of arguments and return type Syntax: void eating(int a) { } void eating(int a, int b) { } void eating(String str) { } // Static Polymorphism class StaticPoly { // Area of Square void area(int side) { int res = side * side; System.out.println("Area of the Square is "+res); }
  • 36. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT // Area of Rectangle void area(int length, int breadth) { int res = length * breadth; System.out.println("Area of Rectange is "+res); } // Area of Circle double area(double radius) { double res = 3.14 * radius * radius; return res; } } public class Main{ public static void main(String args[]) { StaticPoly sp = new StaticPoly(); sp.area(10); sp.area(5, 10); System.out.println("Area of Circle is "+sp.area(3.65)); } } Dynamic Polymorphism  Same method signature (method name, arguments, return type)  Makes use of Inheritance concept  Dynamic binding SuperClassName object = new SubClassName(); // Dynamic Polymorphism
  • 37. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT // Super Class class DynamicPoly { void display() { System.out.println("Hello"); } } // Sub Class class SubDynamicPoly extends DynamicPoly { void display() { System.out.println("Welcome"); } } // Sub Class class SubDynamic extends SubDynamicPoly { void display() { System.out.println("Hai....."); } } public class Main{ public static void main(String args[]) { DynamicPoly dy; dy = new DynamicPoly();
  • 38. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT dy.display(); dy = new SubDynamicPoly(); dy.display(); dy = new SubDynamic(); dy.display(); } } UNIT III 1. What is lambda expression in JAVA?  A lambda expression is a short block of code which takes in parameters and returns a value.  Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.  Syntax: parameter -> expression (parameter1, parameter2) -> expression  Example: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(5); numbers.add(9); numbers.add(8); numbers.add(1); numbers.forEach( (n) -> { System.out.println(n); } ); } } UNIT IV PART – A
  • 39. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT 1. What are input and output streams?  An I/O Stream represents an input source or an output destination.  A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. 2. What is a byte stream in java?  Programs use byte streams to perform input and output of 8-bit bytes.  All byte stream classes are descended from InputStream and OutputStream.  There are many byte stream classes. The file I/O byte streams, are FileInputStream and FileOutputStream. 3. Define 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. 4. What is character stream?  Character streams are used to perform input and output for 16-bit unicode.  Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. 5. Given an example for reading data from files using FileInputStream. import java.io.FileInputStream; class DataStreamExample { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("input.txt"); int i=fin.read(); System.out.print((char)i); fin.close(); }catch(Exception e){System.out.println(e);} } } 6. What is AWT?  A collection of graphical user interface (GUI) components that were implemented using native- platform versions of the components.
  • 40. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  These components provide that subset of functionality which is common to all native platforms.  Largely supplanted by the Project Swing component set. 7. What is the relationship between an event- listener interface and an event adapter class?  An event-listener interface allows describing the methods which must be implemented by one of the event handler for a specific event.  An event-adapter allows default implementations of an event-listener interface of a specific event. 8. Differentiate AWT from Swing. Java AWT Java Swing AWT components are platform- dependent. Java swing components are platform-independent. AWT components are heavyweight. Swing components are lightweight. AWT provides less components than Swing. Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser,tabbedpane etc. AWT doesn't follows MVC Swing follows MVC. 9. How Events are handled in java ?  A source generates an Event and send it to one or more listeners registered with the source.  Once event is received by the listener, they process the event and then return. Events are supported by a number of Java packages, like java.util, java.awt and java.awt.event. 10. List the different type of drivers. Type 1: JDBC-ODBC Bridge Driver Type 2: JDBC-Native API Type 3: JDBC-Net pure Java Type 4: 100% Pure Java 11. Write a JAVA code to display “Welcome” in a dialog box. import javax.swing.*; class OptionPaneExample { JFrame f; OptionPaneExample(){
  • 41. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT f=new JFrame(); JOptionPane.showMessageDialog(f,"Welcome"); } public static void main(String[] args) { new OptionPaneExample(); } } 12. Mention some Event Classes and Interface Event Classes Description Listener Interface ActionEvent generated when button is pressed, menu- item is selected, list-item is double clicked ActionListener MouseEvent generated when mouse is dragged, moved,clicked,pressed or released and also when it enters or exit a component MouseListener KeyEvent generated when input is received from keyboard KeyListener ItemEvent generated when check-box or list item is clicked ItemListener TextEvent generated when value of textarea or textfield is changed TextListener MouseWheelEvent generated when mouse wheel is moved MouseWheelListener WindowEvent generated when window is activated, deactivated, deiconified, iconified, opened or closed WindowListener ComponentEvent generated when component is hidden, moved, resized or set visible ComponentEventListener ContainerEvent generated when component is added or removed from container ContainerListener PART - B 1. Outline the IO stream classes with suitable example. Introduction  Java I/O (Input and Output) is used to process the input and produce the output based on the input.  Java uses the concept of stream to make I/O operation fast.  The java.io package contains all the classes required for input and output operations. Stream
  • 42. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  A stream is a sequence of data.  In Java a stream is composed of bytes.  It's called a stream because it's like a stream of water that continues to flow.  In java, 3 streams are created for us automatically. 1) System.out: standard output stream 2) System.in: standard input stream 3) System.err: standard error stream Example: To print output and error message to the console. System.out.println("simple message"); System.err.println("error message"); Types of Stream There are two kinds of streams: a. Byte streams b. Character streams. Byte Stream:  An input stream is an object that an application can use to read a sequence of data, and an output stream is an object that an application can use to write a sequence of data.  An input stream acts as a source of data, and an output stream acts as a destination of data.  The sub classes of byte stream are InputStream and OutputStream. Character Stream:  The sub classes of character stream are Reader and Writer.  The Reader and Writer classes read and write 16-bit Unicode characters. Unicode is an international standard character encoding that is capable of representing most of the world's written languages.  In Unicode, two bytes make a character. InputStream reads 8-bit bytes, while OutputStream writes 8-bit bytes. The java.io package contains a fairly large number of classes that deal with Java input and output: a. an array of bytes or characters
  • 43. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT b. a file c. a pipe d. a network connection Streams can be chained with filters to provide new functionality Byte Stream InputStream and OutputStream a. OutputStream class  OutputStream class is an abstract class.  It is the superclass of all classes representing an output stream of bytes.  An output stream accepts output bytes and sends them to some sink. Methods: Method Description 1) public void write(int)throws IOException: is used to write a byte to the current output stream. 2) public void write(byte[])throws IOException: is used to write an array of byte to the current output stream. 3) public void flush()throws IOException: flushes the current output stream. 4) public void close()throws IOException: is used to close the current output stream.
  • 44. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT 1. ByteArrayOutputStream : Data is written to a byte array. The size of the byte array created can be specified. 2. FileOutputStream : Data is written as bytes to a file. The file acting as the output stream can be specified by a File object, a FileDescriptor or a String file name. 3. FilterOutputStream : Superclass of all output stream filters. An output filter must be chained to an underlying output stream. 4. BufferedOutputStream : A filter that buffers the bytes written to an underlying output stream. The underlying output stream must be specified, and an optional buffer size can be given. 5. FileInputStream and FileOutputStream (File Handling): In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java. b. InputStream class  InputStream class is an abstract class.  It is the superclass of all classes representing an input stream of bytes. Methods: Method Description 1) public abstract int read()throws IOException: reads the next byte of data from the input stream.It returns -1 at the end of file. 2) public int available()throws IOException: returns an estimate of the number of bytes that can be read from the current input stream. 3) public void close()throws IOException: is used to close the current input stream.
  • 45. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT 1. ByteArrayInputStream : Data is read from a byte array that must be specified. 2. FileInputStream : Data is read as bytes from a file. The file acting as the input stream can be specified by a File object, a FileDescriptor or a String file name. FilterInputStream Superclass of all input stream filters. An input filter must be chained to an underlying input stream. 3. BufferedInputStream : A filter that buffers the bytes read from an underlying input stream. The underlying input stream must be specified, and an optional buffer size can be included. 4. DataInputStream : A filter that allows the binary representation of Java primitive values to be read from an underlying input stream. The underlying input stream must be specified. 5. PushbackInputStream : A filter that allows bytes to be "unread" from an underlying input stream. The number of bytes to be unread can optionally be specified. 6. ObjectInputStream : Allows binary representations of Java objects and Java primitive values to be read from a specified input stream. 7. PipedInputStream : Reads bytes from a PipedOutputStream towhich it must be connected. The PipedOutputStream can optionally be specified when creating the PipedInputStream.
  • 46. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT 8. SequenceInputStream : Allows bytes to be read sequentially from two or more input streams consecutively. This should be regarded as concatenating the contents of several input streams into a single continuous input stream. Java FileOutputStream class:  Java FileOutputStream is an output stream for writing data to a file.  Instead, for character-oriented data, prefer FileWriter. Syntax: FileOutputStream fileobject = new FileOutputStream(“filename”); or File object = new File(“Filename”); FileOutputStream fileobject = new FileOutputStream(object); Example: /* File Name: Test.java */ import java.io.*; class Test { public static void main(String args[]){ try{ FileOutputstream fout=new FileOutputStream("abc.txt"); String s="Sachin Tendulkar is my favourite player"; byte b[]=s.getBytes();//converting string into byte array fout.write(b); fout.close(); System.out.println("success..."); }catch(Exception e){system.out.println(e);} } } Java FileInputStream class  Java FileInputStream class obtains input bytes from a file.  It is used for reading streams of raw bytes such as image data.
  • 47. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  For reading streams of characters, consider using FileReader.  It should be used to read byte-oriented data for example to read image, audio, video etc. Syntax: FileInputStream fileobject = new FileInputStream(“filename”); or File object = new File(“Filename”); FileInputStream fileobject = new FileInputStream(object); Example: /* File Name: SimpleRead.java */ import java.io.*; class SimpleRead{ public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("abc.txt"); int i=0; while((i=fin.read())!=-1){ System.out.println((char)i); } fin.close(); }catch(Exception e){system.out.println(e);} } } Example: Copy the content of one file to another file /* File Name: C.java */ import java.io.*; class C{ public static void main(String args[])throws Exception{ FileInputStream fin=new FileInputStream("C.java"); FileOutputStream fout=new FileOutputStream("M.java"); int i=0;
  • 48. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT while((i=fin.read())!=-1){ fout.write((byte)i); } fin.close(); } } Character Stream Java FileWriter and FileReader  Java FileWriter and FileReader classes are used to write and read data from text files.  These are character-oriented classes, used for file handling in java. Java FileWriter class  Java FileWriter class is used to write character-oriented data to the file. Constructors of FileWriter class Constructor Description FileWriter(String file) creates a new file. It gets file name in string. FileWriter(File file) creates a new file. It gets file name in File object. Methods of FileWriter class Method Description 1) public void write(String text) writes the string into FileWriter. 2) public void write(char c) writes the char into FileWriter. 3) public void write(char[] c) writes char array into FileWriter. 4) public void flush() flushes the data of FileWriter. 5) public void close() closes FileWriter. Example: /* File Name: Simple.java */ import java.io.*; class Simple{ public static void main(String args[]){ try{ FileWriter fw=new FileWriter("abc.txt");
  • 49. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT fw.write("my name is sachin"); fw.close(); }catch(Exception e){System.out.println(e);} System.out.println("success"); } } Java FileReader class  Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. Constructors of FileWriter class Constructor Description FileReader(String file) It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. Methods of FileReader class Method Description 1) public int read() returns a character in ASCII form. It returns -1 at the end of file. 2) public void close() closes FileReader. Example: /* File Name: Simple.java */ import java.io.*; class Simple{ public static void main(String args[])throws Exception{ FileReader fr=new FileReader("abc.txt"); int i; while((i=fr.read())!=-1) System.out.println((char)i); fr.close();
  • 50. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT } } 2. What is JDBC? Explain insertion, deletion and display operations on database using JAVA code. JDBC  JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases CREATING JDBC APPLICATION There are following 5 steps involved in building a JDBC application −  Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.  Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database.  Create a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.  Create a Statement: Requires using an object of type Statement for building and submitting an SQL statement to the database.  Execute the query: Requires that you use the appropriateResultSet.getXXX() method to retrieve the data from the result set.  Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Example: //STEP 1. Import required packages import java.sql.*; public class DBTest { public static void main(String[] args) { String dburl = "jdbc:mysql://localhost/emp"; String dbuser = "root"; String dbpwd = "itlab"; String dbdriver = "com.mysql.jdbc.Driver"; Connection con = null; try {
  • 51. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT //STEP 1: Register JDBC driver Class.forName(dbdriver); //STEP 2: Create a connection con = DriverManager.getConnection(dburl, dbuser, dbpwd); //STEP 3: Create a Statement Statement stmt = con.createStatement(); // STEP 4: Execute the query ResultSet rs = stmt.executeQuery("select eid, ename from employee"); while(rs.next()) { System.out.print(rs.getInt("eid")); System.out.println(rs.getString(2)); } //STEP 5: Clean-up environment rs.close(); stmt.close(); } catch(SQLException sql) { System.out.println(sql); } catch(Exception e) { System.out.println(e); } } } Display (select): Step 1: Register the Driver using Class.forName() by passing the Driver class along with its package Step 2: Establish the connection using getConnection() method by passing the db url, db user name, db password. Step 3: Create an object for Statement class by assigning the result of createStatement() method. Step 4: Pass the sql query “select column_name from table_name” to the executeQuery() method. This return the value that stores in ResultSet object.
  • 52. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Step 5: Generate a loop using ResultSet_object.next() method which reads the line by line from the ResultSet. i. Read the corresponding column value using getInt(), getString(), getDouble(), etc.. method by passing the column index to the method Step 6: Close all the objects Insertion (insert): Step 1: Register the Driver using Class.forName() by passing the Driver class along with its package Step 2: Establish the connection using getConnection() method by passing the db url, db user name, db password. Step 3: Create an object for PreparedStatement class by assigning the result of prepareStatement() method and pass the sql query “insert into table_name values (?, ?)”. Step 4: Get the input from the user and pass the ? order number and the variable to the setInt(), setString(), setDouble(), etc.. methods. Step 5: Use executeUpdate() method to update the values in the database Step 6: Close all the objects Deletion (delete): Step 1: Register the Driver using Class.forName() by passing the Driver class along with its package Step 2: Establish the connection using getConnection() method by passing the db url, db user name, db password. Step 3: Create an object for PreparedStatement class by assigning the result of prepareStatement() method and pass the sql query “delete from table_name where column_name = ?”. Step 4: Get the input from the user and pass the ? order number and the variable to the setInt(), setString(), setDouble(), etc.. methods. Step 5: Use executeUpdate() method to update the values in the database Step 6: Close all the objects Updation (update): Step 1: Register the Driver using Class.forName() by passing the Driver class along with its package Step 2: Establish the connection using getConnection() method by passing the db url, db user name, db password.
  • 53. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Step 3: Create an object for PreparedStatement class by assigning the result of prepareStatement() method and pass the sql query “update table_name set column_name = ? where column_name = ?”. Step 4: Get the input from the user and pass the ? order number and the variable to the setInt(), setString(), setDouble(), etc.. methods. Step 5: Use executeUpdate() method to update the values in the database Step 6: Close all the objects Database Creation: create table emp_detail(eid int not null primary key, ename varchar(10), edept varchar(10), edesg varchar(10), esalary int); insert into emp_detail values(100, 'arthy', 'IT', 'AP', 20000); Coding: import java.sql.*; import java.util.Scanner; /** * * @author arthy.r */ public class JDBCDemo { String driver = "org.apache.derby.jdbc.ClientDriver"; Connection con = null; Statement stmt = null; PreparedStatement pstmt = null; void select() { try { Class.forName(driver);
  • 54. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee", "arthy", "arthy"); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from emp_detail"); System.out.println("Employee Details"); System.out.println("****************"); while(rs.next()) { System.out.println("-------------------------------------------------------------------"); System.out.println("Employee Id : " +rs.getInt(1)); System.out.println("Employee Name : " +rs.getString(2)); System.out.println("Employee Department : " +rs.getString(3)); System.out.println("Employee Designation : " +rs.getString(4)); System.out.println("Employee Salary : " +rs.getInt(5)); System.out.println("-------------------------------------------------------------------"); } } catch(Exception e) { System.out.println("SQL Exception e"); } } void insert() { int eid, salary; String ename, edept, edesig; try { Class.forName(driver); con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee", "arthy", "arthy"); pstmt = con.prepareStatement("insert into emp_detail values(?,?,?,?,?)");
  • 55. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT System.out.println("Employee Details"); System.out.println("****************"); Scanner s1 = new Scanner(System.in); System.out.println("Enter the number of employee : "); int n = s1.nextInt(); for(int i = 0; i < n; i++) { System.out.print("Enter the Employee ID : "); eid = s1.nextInt(); System.out.print("Enter the Employee Name : "); ename = s1.next(); System.out.print("Enter the Employee Department : "); edept = s1.next(); System.out.print("Enter the Employee Designation : "); edesig = s1.next(); System.out.print("Enter the Employee Salary : "); salary = s1.nextInt(); pstmt.setInt(1, eid); pstmt.setString(2, ename); pstmt.setString(3, edept); pstmt.setString(4, edesig); pstmt.setInt(5, salary); pstmt.executeUpdate(); } } catch(Exception e) { System.out.println("SQL Exception "+e); } } void delete()
  • 56. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT { int eid; try { Class.forName(driver); con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee", "arthy", "arthy"); pstmt = con.prepareStatement("delete from emp_detail where eid = ?"); System.out.println("Employee Details"); System.out.println("****************"); Scanner s1 = new Scanner(System.in); System.out.print("Enter the employee ID : "); eid = s1.nextInt(); pstmt.setInt(1, eid); pstmt.executeUpdate(); } catch(Exception e) { System.out.println("SQL Exception "+e); } } void update() { int eid, salary; try { Class.forName(driver); con = DriverManager.getConnection("jdbc:derby://localhost:1527/employee", "arthy", "arthy"); pstmt = con.prepareStatement("update emp_detail set esalary = ? where eid = ?"); System.out.println("Employee Details"); System.out.println("****************"); Scanner s1 = new Scanner(System.in);
  • 57. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT System.out.print("Enter the employee ID : "); eid = s1.nextInt(); System.out.print("Enter the employee salary : "); salary = s1.nextInt(); pstmt.setInt(2, eid); pstmt.setInt(1, salary); pstmt.executeUpdate(); } catch(Exception e) { System.out.println("SQL Exception "+e); } } /** * @param args the command line arguments */ public static void main(String[] args) { int choice; Scanner s1 = new Scanner(System.in); JDBCDemo dbc = new JDBCDemo(); while(true) { System.out.println("DB Operations"); System.out.println("*************"); System.out.println("1. Selectionn2. Insertionn3. Deletionn4. Updationn5. Exit"); System.out.println("Enter the Choice : "); choice = s1.nextInt(); switch(choice) { case 1: dbc.select(); break;
  • 58. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT case 2: dbc.insert(); break; case 3: dbc.delete(); break; case 4: dbc.update(); break; case 5: System.exit(0); } } } } 3. What is JDBC? Explain the various types of drivers in JDBC. JDBC  JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases JDBC Driver  JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server.  java.sql.* supports the JDBC concepts Types  Sun has divided the implementation types into four categories: o Types 1, 2, 3, and 4 Type 1: JDBC-ODBC Bridge Driver  In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine.
  • 59. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target database.  When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available. Type 2: JDBC-Native API  In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the database.  These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge.  The vendor-specific driver must be installed on each client machine.  Type 2 driver, eliminates ODBC's overhead.  The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
  • 60. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Type 3: JDBC-Net pure Java  In a Type 3 driver, a three-tier approach is used to access databases.  The JDBC clients use standard network sockets to communicate with a middleware application server.  The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.  This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases. Type 4: 100% Pure Java
  • 61. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database through socket connection.  This is the highest performance driver available for the database and is usually provided by the vendor itself.  This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.  MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers. 4. Explain in detail about Adapter class.  Java adapter classes provide the default implementation of listener interfaces. Adapter class Listener interface WindowAdapter WindowListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener FocusAdapter FocusListener ComponentAdapter ComponentListener ContainerAdapter ContainerListener HierarchyBoundsAdapter HierarchyBoundsListener Advantages of using Adapter classes:  It assists the unrelated classes to work combinedly.  It provides ways to use classes in different ways.
  • 62. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  It increases the transparency of classes.  It provides a way to include related patterns in the class.  It provides a pluggable kit for developing an application.  It increases the reusability of the class.  import javax.swing.*; Example: import java.awt.*; import java.awt.event.*; import java.io.*; class MouseEventDemo extends MouseAdapter { int num = 0; public void mousePressed(MouseEvent me) { System.exit(0); } public void mouseExited(MouseEvent me) { System.out.println("Welcome"); } } class MouseEventDemo1 extends JComponent { MouseEventDemo1() { // Creating a frame JFrame fr1 = new JFrame(); fr1.setTitle("First Demo"); // Setting the close type fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fr1.setVisible(true); } public static void main(String ar[]) { MouseEventDemo1 me = new MouseEventDemo1(); } } 5. Explain the mouse listener with example.
  • 63. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent.  The MouseListener interface is found in java.awt.event package. It has five methods. o public abstract void mouseClicked(MouseEvent e); o public abstract void mouseEntered(MouseEvent e); o public abstract void mouseExited(MouseEvent e); o public abstract void mousePressed(MouseEvent e); o public abstract void mouseReleased(MouseEvent e); Example: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.imageio.*; import javax.imageio.ImageIO; import java.io.*; class MouseEventDemo extends MouseAdapter { int num = 0; public void mouseClicked(MouseEvent me) { double x = me.getX(); double y = me.getY(); System.out.println("X = "+x+"Y = "+y); } public void mousePressed(MouseEvent me) { System.exit(0); } public void mouseReleased(MouseEvent me) { int count = me.getClickCount(); System.out.println("Count = "+count); } public void mouseEntered(MouseEvent me) { Point2D po = me.getPoint(); double x = po.getX(); double y = po.getY(); System.out.println("X = "+x+"Y = "+y); } public void mouseExited(MouseEvent me)
  • 64. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT { System.out.println("Welcome"); } } class mouseevent extends JComponent { mouseevent() { MouseEventDemo e1 = new MouseEventDemo(); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); addMouseListener(e1); } } class MouseEventDemo1 extends JComponent { MouseEventDemo1() { // Creating a frame JFrame fr1 = new JFrame(); fr1.setTitle("First Demo"); // Setting the close type fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mouseevent sft = new mouseevent(); fr1.add(sft); fr1.setVisible(true); } public static void main(String ar[]) { MouseEventDemo1 me = new MouseEventDemo1(); } } 6. Explain various layout managements in swing program.  The LayoutManagers are used to arrange components in a particular manner.  The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.  LayoutManager is an interface that is implemented by all the classes of layout managers.  There are the following classes that represent the layout managers: o java.awt.BorderLayout o java.awt.FlowLayout
  • 65. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT o java.awt.GridLayout o java.awt.CardLayout o java.awt.GridBagLayout o javax.swing.BoxLayout o javax.swing.GroupLayout o javax.swing.ScrollPaneLayout o javax.swing.SpringLayout etc. Java BorderLayout  The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center.  Each region (area) may contain one component only. It is the default layout of a frame or window.  The BorderLayout provides five constants for each region: o public static final int NORTH o public static final int SOUTH o public static final int EAST o public static final int WEST o public static final int CENTER Example: import javax.swing.*; import java.awt.*; class BorderLayoutDemo extends JFrame { public static void main(String ar[]) { JFrame frame = new JFrame("Layout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button1 = new JButton("Button 1"); frame.getContentPane().add(button1,BorderLayout.NORTH); BorderLayoutDemo lo = new BorderLayoutDemo (); JButton button2 = new JButton("Button 2"); frame.getContentPane().add(button2,BorderLayout.SOUTH); JButton button3 = new JButton("Button 3"); frame.getContentPane().add(button3,BorderLayout.WEST); JButton button4 = new JButton("Button 4"); frame.getContentPane().add(button4,BorderLayout.EAST);
  • 66. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT JButton button5 = new JButton("Button 5"); frame.getContentPane().add(button5,BorderLayout.CENTER); frame.setVisible(true); } } FlowLayout  The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow). It is the default layout of the applet or panel.  Fields of FlowLayout class o public static final int LEFT o public static final int RIGHT o public static final int CENTER o public static final int LEADING o public static final int TRAILING Constructors of FlowLayout class  FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.  FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.  FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap. Example: import javax.swing.*; import java.awt.*; class FlowLayoutDemo extends JFrame { public static void main(String ar[]) { JFrame frame = new JFrame("Layout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout(FlowLayout.TRAILING)); JButton button1 = new JButton("Button 1"); panel.add(button1);
  • 67. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT JButton button2 = new JButton("Button 2"); panel.add(button2); JButton button3 = new JButton("Button 3"); panel.add(button3); JButton button4 = new JButton("Button 4"); panel.add(button4); JButton button5 = new JButton("Exit"); panel.add(button5); frame.add(panel,BorderLayout.CENTER); frame.setVisible(true); } } Grid Layout:  The Java GridLayout class is used to arrange the components in a rectangular grid. One component is displayed in each rectangle. Constructors of GridLayout class  GridLayout(): creates a grid layout with one column per component in a row.  GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components.  GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns along with given horizontal and vertical gaps. Example: import javax.swing.*; import java.awt.*; class GridLayoutDemo extends JFrame { public static void main(String ar[]) { JFrame frame = new JFrame("Layout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3,2,4,5)); JButton button1 = new JButton("Button 1"); panel.add(button1); GridLayoutDemo lo = new GridLayoutDemo();
  • 68. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT JButton button2 = new JButton("Button 2"); panel.add(button2); JButton button3 = new JButton("Button 3"); panel.add(button3); JButton button4 = new JButton("Button 4"); panel.add(button4); JButton button5 = new JButton("Button 5"); panel.add(button5); frame.getContentPane().add(panel); frame.setVisible(true); } } 7. What is MVC? Explain MVC architecture with example. Swing uses the Model-View-Controller architecture (MVC) as the fundamental design behind each of its components.  MVC breaks GUI components into 3 elements  Each elements plays an important role in how component behaves  Allows for Portability etc. The Basic MVC Model Model -- State data for each component. • Different for each component • E.g. Scrollbar -- Max and minimum Values, Current Position, width of thumb position relative to values • E.g. Menu -- Simple List of items. • Model data is always independent of visual representation. View -- How component is painted on the screen • Can vary between platforms/look and feel Controller -- dictates how component interacts with events
  • 69. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT MVC in Swing Swing uses a simplified model of the MVC design: model-delegate The MVC Swing Model  Combines View and Controller into a single element -- the UI-delegate  Easy to bundle graphics and event handling in Java -- AWT.  Model delegate interaction is now Two way. o Model -- maintains information o UI-delegate -- Draws and reacts to events that propagate through component. 8. Explain any four swing components along with its methods JFrame Class: Package: javax.swing.*
  • 70. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Constructor:  JFrame() - Constructs a new frame that is initially invisible.  JFrame(GraphicsConfiguration gc) - Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.  JFrame(String title) - Creates a new, initially invisible Frame with the specified title.  JFrame(String title, GraphicsConfiguration gc) - Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device. Methods:  void setDefaultCloseOperation(int operation) - Sets the operation that will happen by default when the user initiates a "close" on this frame.  void setLayout(LayoutManager manager) - Sets the LayoutManager.  setVisible(boolean aFlag): It makes the component visible or invisible. JButton Class: Package: javax.swing.* Constructors:  JButton() - It creates a button with no text and icon.  JButton(String s) - It creates a button with the specified text.  JButton(Icon i) - It creates a button with the specified icon object. Methods:  void setText(String s) - It is used to set specified text on button  String getText() - It is used to return the text of the button.  void setEnabled(boolean b) - It is used to enable or disable the button.  void setIcon(Icon b) - It is used to set the specified Icon on the button.  Icon getIcon() - It is used to get the Icon of the button.  void setMnemonic(int a) - It is used to set the mnemonic on the button.  void addActionListener(ActionListener a) - It is used to add the action listener to this object. JTextField Class: Package: javax.swing.*
  • 71. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Constructors:  JTextField() - Creates a new TextField  JTextField(String text) - Creates a new TextField initialized with the specified text.  JTextField(String text, int columns) - Creates a new TextField initialized with the specified text and columns.  JTextField(int columns) - Creates a new empty TextField with the specified number of columns. Methods:  void setText(String s) - It is used to set specified text on button  String getText() - It is used to return the text of the button.  void setEnabled(boolean b) - It is used to enable or disable the button.  void addActionListener(ActionListener a) - It is used to add the action listener to this object. JLabel Class Constructors Constructor Description JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(String s) Creates a JLabel instance with the specified text. JLabel(Icon i) Creates a JLabel instance with the specified image. JLabel(String s, Icon i, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. Methods Methods Description String getText() t returns the text string that a label displays. void setText(String text) It defines the single line of text this component will display. void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis. Icon getIcon() It returns the graphic image that the label displays. int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis. JPasswordField Class
  • 72. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Constructors Constructor Description JPasswordField() Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width. JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number of columns. JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text. JPasswordField(String text, int columns) Construct a new JPasswordField initialized with the specified text and columns. Methods Method Description isEditable() Returns a boolean value indicating whether or not a text field is editable setEditable() Passing True enables text to be edited, while False disables editing. The default is True. addActionListener() Registers an ActionListener object to receive action events from a text field getEchoChar() Returns the character used for echoing getColumns() Returns the number of columns in a text field setEchoChar() Sets the echo character for a text field getText() Returns the text contained in the text field setText() Sets the text for a text field JTextArea Class Constructors Constructor Description JTextArea() Creates a text area that displays no text initially. JTextArea(String s) Creates a text area that displays specified text initially. JTextArea(int row, int column) Creates a text area with the specified number of rows and columns that displays no text initially. JTextArea(String s, int row, int column) Creates a text area with the specified number of rows and columns that displays specified text. Methods Methods Description void setRows(int rows) It is used to set specified number of rows. void setColumns(int cols) It is used to set specified number of columns. void setFont(Font f) It is used to set the specified font. void insert(String s, int position) It is used to insert the specified text on the specified position. void append(String s) It is used to append the given text to the end of the
  • 73. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT document. JCheckbox Class Constructors Constructor Description JCheckBox() Creates an initially unselected check box button with no text, no icon. JChechBox(String s) Creates an initially unselected check box with text. JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected. JCheckBox(Action a) Creates a check box where properties are taken from the Action supplied. JRadioButton Class Constructors Constructor Description JRadioButton() Creates an unselected radio button with no text. JRadioButton(String s) Creates an unselected radio button with specified text. JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status. Methods Methods Description void setText(String s) It is used to set specified text on button. String getText() It is used to return the text of the button. void setEnabled(boolean b) It is used to enable or disable the button. void setIcon(Icon b) It is used to set the specified Icon on the button. Icon getIcon() It is used to get the Icon of the button. void setMnemonic(int a) It is used to set the mnemonic on the button. void addActionListener(ActionListener a) It is used to add the action listener to this object. JComboBox Class Constructors Constructor Description JComboBox() Creates a JComboBox with a default data model. JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array. JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.
  • 74. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Methods Methods Description void addItem(Object anObject) It is used to add an item to the item list. void removeItem(Object anObject) It is used to delete an item to the item list. void removeAllItems() It is used to remove all the items from the list. void setEditable(boolean b) It is used to determine whether the JComboBox is editable. void addActionListener(ActionListener a) It is used to add the ActionListener. void addItemListener(ItemListener i) It is used to add the ItemListener. JList Constructors Constructor Description JList() Creates a JList with an empty, read-only, model. JList(ary[] listData) Creates a JList that displays the elements in the specified array. JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model. Methods Methods Description Void addListSelectionListener(ListSelectio nListener listener) It is used to add a listener to the list, to be notified each time a change to the selection occurs. int getSelectedIndex() It is used to return the smallest selected cell index. ListModel getModel() It is used to return the data model that holds a list of items displayed by the JList component. void setListData(Object[] listData) It is used to create a read-only ListModel from an array of objects. JOptionPane Class Methods Methods Description JDialog createDialog(String title) It is used to create and return a new parentless JDialog with the specified title. static void showMessageDialog (Component parentComponent, Object message) It is used to create an information-message dialog titled "Message". static void showMessageDialog (Component parentComponent, Object message, String title, int messageType) It is used to create a message dialog with given title and messageType. static int showConfirmDialog (Component parentComponent, Object message) It is used to create a dialog with the options Yes, No and Cancel; with the title, Select an Option.
  • 75. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT static String showInputDialog (Component parentComponent, Object message) It is used to show a question-message dialog requesting input from the user parented to parentComponent. void setInputValue(Object newValue) It is used to set the input value that was selected or input by the user. Menus:  A JMenuBar instance is first created as: JMenuBar mb = new JMenuBar();  The JMenuBar instance is added to a frame using the setMenuBar() method of the Frame class as follows: setJMenuBar(mb);  Individual menus are created (instances of the JMenu class) and added to the menu bar with the add() method  Add the Menu items using JMenuItem class UNIT V PART A 1. What is Multi-threading?  Multithreading is a conceptual programming concept where a program(process) is divided into two or more subprograms(process), which can be implemented at the same time in parallel.  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. 2. List out the methods of object class to perform inter thread communication?  wait() – This method make the current thread to wait until another thread invokes the notify() method.  notify() – This method wakes up a thread that called wait() on same object.  notifyAll() – This method wakes up all the thread that called wait() on same object. Wakes up all threads that are waiting on this object‟s monitor. 3. What is daemon thread and which method is used to create the daemon thread?  Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.
  • 76. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT  setDaemon method is used to create a daemon thread.  This method waits until the thread on which it is called terminates 4. Write a multithreaded program that joins two threads. import java.io.*; class ThreadJoining extends Thread { public void run() { for (int i = 0; i < 2; i++) { try { Thread.sleep(500); System.out.println(“Thread 1”); } catch(Exception ex) { System.out.println("Exception”); } System.out.println(i); } } } class GFG { public static void main (String[] args) { // creating two threads ThreadJoining t1 = new ThreadJoining(); ThreadJoining t2 = new ThreadJoining(); ThreadJoining t3 = new ThreadJoining(); // thread t1 starts t1.start(); // starts second thread after when first thread t1 has died. try { System.out.println("Thread 1”); t1.join(); } catch(Exception ex) { System.out.println("Exception”); }
  • 77. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT // t2 starts t2.start(); // starts t3 after when thread t2 has died. try { System.out.println("Thread 2”); t2.join(); } catch(Exception ex) { System.out.println("Exception”); } t3.start(); } } 5. Differentiate wait() and sleep() in JAVA. Wait() Sleep() Wait() method belongs to Object class. Sleep() method belongs to Thread class. Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context. There is no need to call sleep() from Synchronized context. Wait() is not a static method. Sleep() is a static method. Wait() Has Three Overloaded Methods:  wait()  wait(long timeout)  wait(long timeout, int nanos) Sleep() Has Two Overloaded Methods: PART B 1. Life Cycle of Thread: Introduction  A process is a program in execution.  A process may be divided into a number of independent units known as threads.  A thread is a dispatchable unit of work.  Threads are light-weight processes within a process.  A process is a collection of one or more threads and associated system resources.
  • 78. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Thread Life Cycle  The life cycle of threads in Java is very similar to the life cycle of processes running in an operating system.  During its life cycle the thread moves from one state to another depending on the operation performed by it.  A Java thread can be in one of the following states: o NEW  A thread that is just instantiated is in new state.  When a start() method is invoked, the thread moves to the ready state from which it is automatically moved to runnable state by the thread scheduler. o RUNNABLE (ready_running)  A thread, that is ready to run is then moved to the runnable state.  A thread executing in the JVM is in running state.  The run() method will be invoked to make thread move to running state. o BLOCKED  A thread that is blocked waiting for a monitor lock is in this state.  This can also occur when a thread performs an I/O operation and moves to next (runnable) state.  The suspend() method puts the thread in the blocked state.  The thread will be unblocked using resume() method. o WAITING  A thread that is waiting indefinitely for another thread to perform a particular action is in this state.  The wait() method puts the thread in the waiting state.  The thread will be notified back using notify() method.
  • 79. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT o TIMED_WAITING (sleeping)  A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.  The sleep() method puts the thread in the timed wait state.  After the time runs out, the thread wakes up and starts its execution from when it has left earlier. o TERMINATED (dead) –  A thread reaches the termination state because of the following reasons:  When a thread has finished its job, then it exists or terminates normally.  Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.A thread that has exited is in this state. 2. Discuss on JAVA Archives.  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 to distribute application software or libraries on the Java platform.  In simple words, a JAR file is a file that contains a compressed version of .class files, audio files, image files, or directories.  It is similar to a zipped file(.zip) that is created by using WinZip software.  Even, WinZip software can be used to extract the contents of a .jar .  So you can use them for tasks such as lossless data compression, archiving, decompression, and archive unpacking.
  • 80. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT Create a JAR file  In order to create a .jar file, we can use jar cf command  Syntax: o jar cf jarfilename inputfiles View a JAR file  Syntax: o jar tf jarfilename  Here, tf represents the table view of file contents. Extracting a JAR file  Syntax: o jar xf jarfilename  Here, xf represents extract files from the jar files. Updating a JAR File  The Jar tool provides a „u‟ option that you can use to update the contents of an existing JAR file by modifying its manifest or by adding files.  Syntax: o jar uf jar-file input-file(s)  Here „uf‟ represents the updated jar file. Running a JAR file  Syntax: o C:>java -jar pack.jar 3. What is multithreading? Explain the implementation of multithreading with suitable example. Introduction  A process is a program in execution.  A process may be divided into a number of independent units known as threads.  A thread is a dispatchable unit of work.  Threads are light-weight processes within a process.  A process is a collection of one or more threads and associated system resources.
  • 81. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT A process containing single and multiple threads Java supports thread-based multitasking. The advantages of thread-based multitasking as compared to process-based multitasking are given below: 1. Threads share the same address space. 2. Context-switching between threads is normally inexpensive. 3. Communication between threads is normally inexpensive. Creating Threads in Java  A single process might contain multiple threads.  All threads within a process share the same state and same memory space, and can communicate with each other directly, because they share the same variables. A program with master thread and children threads Threads are objects in the Java language. They can be created by using two different mechanisms
  • 82. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT 1. Create a class that extends the standard Thread class. 2. Create a class that implements the standard Runnable interface. Creation of Threads in Java a. Extending the Thread Class The steps for creating a thread by using the first mechanism are: 1. Create a class by extending the Thread class and override the run() method: class MyThread extends Thread { public void run() { // thread body of execution } } 2. Create a thread object: MyThread thr1 = new MyThread(); 3. Start Execution of created thread: thr1.start(); /* A simple program creating and invoking a thread object by extending the standard Thread class. */ class MyThread extends Thread { public void run() { System.out.println(“ this thread is running ... ”); } } class ThreadEx1 { public static void main(String [] args ) { MyThread t = new MyThread(); t.start(); }
  • 83. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT }  The user needs to implement their logic associated with the thread in the run() method, which is the body of thread.  The objects created by instantiating the class MyThread are called threaded objects.  Even though the execution method of thread is called run, we do not need to explicitly invoke this method directly.  When the start() method of a threaded object is invoked, it sets the concurrent execution of the object from that point onward along with the execution of its parent thread/method. b. Implementing the Runnable Interface The steps for creating a thread by using the second mechanism are: 1. Create a class that implements the interface Runnable and override run() method: class MyThread implements Runnable { … public void run() { // thread body of execution } } 2. Creating Object: MyThread myObject = new MyThread(); 3. Creating Thread Object: Thread thr1 = new Thread(myObject); 4. Start Execution: thr1.start(); /* A simple program creating and invoking a thread object by implementing Runnable interface. */ class MyThread implements Runnable { public void run() { System.out.println(“ this thread is running ... ”); } } class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); t.start();
  • 84. IT1301 – Object Oriented Programming Prepared by, Dr. R. Arthy, AP/IT } }  The class MyThread implements standard Runnable interface and overrides the run() method and includes logic associated with the body of the thread (step 1).  The objects created by instantiating the class MyThread are normal objects (unlike the fi rst mechanism) (step 2).  Therefore, we need to create a generic Thread object and pass MyThread object as a parameter to this generic object (step 3).  As a result of this association, threaded object is created. In order to execute this threaded object, we need to invoke its start() method which sets execution of the new thread (step 4).