Vous êtes sur la page 1sur 48

OBJECT ORIENTED PROGRAMMING

(THROUGH JAVA.)

INDEX
LESSON PLAN..................................................................................................................3
CHARACTERISTICS OF POP.........................................................................................5
DISADVANTAGE......................................................................................... ...........................6
CHARACTERISTICS OF OOP............................................................................................ ..6
ADVANTAGES................................................................................................................ .........7
 Class                                                                                                                            
 
...........................................................................................................................    
 7
Objects contain data, and code to manipulate that data. The entire set of data and 
code of an object can be made a user­defined data type with the help of a class. In 
fact objects are variables of the type class. Once a class is defined, we can create 
any number of objects belonging to that class. For example mango, apple and 
 orange are members of the class fruit.                                                                         
 
........................................................................
   
 7
 DATA ENCAPSULATION:                                                                                        
 
.......................................................................................
   
 7
 ABSTRACTION:                                                                                                        
 
.......................................................................................................   
 8
 DATA HIDING:                                                                                                          
 
.........................................................................................................    
 8
 INHERITANCE:                                                                                                         
 
........................................................................................................    
 8
 POLYMORPHISM:                                                                                                     
 
....................................................................................................
   
 8
 OVERLOADING:                                                                                                       
 
......................................................................................................   
 8
 DYNAMIC BINDING:                                                                                               
 
..............................................................................................   
 9
Note: Java is just a name and is not an acronym...........................................................10
HTML................................................................................................................................10
JAVA CODE AND JVM..................................................................................... ....................10
Object-Oriented Languages Vs Object-Based Language................................................15
 Class                                                                                                                           
 
..........................................................................................................................
    
 16
 Features of Object                                                                                                      
 
.....................................................................................................
    
 17
1.An object must combine data and behavior............................................. .........................17
It is a function of a class used to initalise the object at the time of creation. A constructor
function is called automatically when object is created. The name of the constructor
function must be equal to the class name. Constructor function will not have return data
type. Constructor function must be public type. Constructor function take value but will
not return......................................................................................................... .......................17

1
INHERITANCE................................................................................................................17
Super class:.................................................................................................. ...........................17
Sub class:....................................................................................................................... ..........17
ADVANTAGES............................................................................................................. ..........18
 Methods Overloading                                                                                                 
 
................................................................................................
    
 18
 Overriding                                                                                                                  
 
.................................................................................................................
    
 18
7)_________members of a superclass may be accessed only by methods of the superclass,
by methods of subclasses and by methods of other classes in the same package. .............20
INTRODUCTION............................................................................................................25
Swing Components...........................................................................................................26
In the delegation model, an event is an object that describes a state change in a source.
Some of the activities that cause events to be generated are pressing a button, entering a
charter..................................................................................................................................... .26
A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about the specific types of events. Second, it must implement methods to
receive and process these notifications. The methods that receive and process events are
defined in a set of interfaces found in java.awt.event. ........................................................ .27
 C                                                                                                                                
 
...............................................................................................................................
    
 35
 B                                                                                                                                
 
...............................................................................................................................
    
 35
 B                                                                                                                                
 
...............................................................................................................................
    
 35
 Need for JDBC                                                                                                          
 
.........................................................................................................
    
 39
 JDBC                                                                                                                         
 
........................................................................................................................
    
 39
Networking Introduction..................................................................................................39
Protocol.............................................................................................................................40
 Datagram                                                                                                                    
 
...................................................................................................................
    
 41
Need for Servlets........................................................................................................... ..........43

SYLLABUS
OBJECT ORIENTED PROGRAMMING. (THROUGH JAVA.)

UNIT I

2
Introduction to object oriented programming concepts- java as an object oriented
programming language - introduction to java applications and applets-control structures-
methods-arrays.
UNIT II

Object based and object oriented programming-creating packages -using overloaded


constructors-static class variables-data abstraction and information hiding-relation
between super class objects and subclass objects composition verses inheritance-
polymorphism -dynamic method binding abstract super classes and concrete super
classes-inheriting interface- use of inner classes and wrapper classes- StringTokenizer
and StringBuffer classes.
UNIT III

Role of object oriented programming in designing GUI- Graphics and Java2Doverview


of swing- event handling, adapter classes and layout managers. Advance GUI
components-JPopupMenus- JDesktopPane-advance layout managers.

UNIT IV

Exception handling and multithreading in object oriented programming. When exception


handling should be used-java exception handling-exceptions and inheritance-
multithreading in java -thread synchronization-daemon threads- Runnable interface- Files
and Streams in java.
UNIT V

Network and Database handling through object oriented programming- using JDBC -
processing queries- overview of servlets- multitier applications using JDBC from a
Servlet- introduction to networking- establishing a simple server and a client-
introduction to RMI - implementing the remote interface.

LESSON PLAN
Department: CSE
Name of the Faculty Member: M.V.Sangameswar
Subject: Object Oriented Programming (Through Java)

3
Class: II /IV B.Tech

No.of
Sno hrs UNIT TOPICS REMARKS
Introduction to object oriented
1 2 I programming concepts-
java as an object oriented programming
2 2 language
3 2 introduction to java applications
4 2 control structures
5 1 methods-arrays.
6 2 Applets
Total No of hours=11
Object based and object oriented
7 2 II programming-
8 2 creating packages
using overloaded constructors-static class
9 2 variables-
data abstraction and information hiding-
relation between super class objects and
10 2 subclass objects
composition verses inheritance-
polymorphism -dynamic method binding
abstract super classes and concrete super
11 2 classes-
-inheriting interface- use of inner classes
12 2 and wrapper classes
13 3 String classes
Total No of hours =15
Role of object oriented programming in
14 2 III designing GUI
15 2 Java2Doverview of swing
16 3 event handling, adapter classes
17 1 layout managers
18 2 Advance GUI components
Total No of hours =10
19 2 IV Exception handling
20 2 and multithreading in object oriented

4
programming
21 2 daemon threads
22 2 - Runnable interface
Files and Streams in java.
23 2
Total No of hours = 10
24 2 V Networking
25 2 JDBC
26 2 SERVLETS
27 2 RMI
Total No of hours = 8
Total no hours 54

UNIT – 1
SYNOPSIS
PROCEDURE ORIENTED PROGRMMING

Conventional programming using high-level languages such as COBAL, FORTRAN and


C is commonly known as procedure oriented programming.

Procedure –oriented programming basically consists of writing a list of instructions for


the computer to follow, and organizing these instructions into groups known as functions.
In a multi-function program, many important data items are placed as global so that they
may be accessed by all functions.

CHARACTERISTICS OF POP

5
1.Large programs are divided into smaller programs known as functions.
2.Most of the functions share global data.
3.Data move openly around the system from function to function.
4.Functions transform data from one form to another.
5.Follow TOP-DOWN approach.

DISADVANTAGE

1.Data has no security.


2.Solutions are recreated and not reused.
3.Debugging is time taking and difficult.

OBJECT ORIENTED PROGRAMMING (OOP)

OOP is a programming language that is based on the Object Oriented Orientation


methodology. The major advantages of OOP are its capabilities for creating flexible,
modular programs.

CHARACTERISTICS OF OOP

1.Programs are divided into OBJECTS.


2.Data is hidden and cannot be accessed by the external functions.
3.Objects may communicate with each other through functions
4.Follow BOTTM-Up approach.
5. Each object is an instance of a class.

CONCEPTS OF OOP:

1. Objects
2. Classes
3. Data encapsulation
4. Abstraction
5. Inheritance

6
6. Polymorphism
7. Dynamic binding

OBJECTS:
An object is a single unit, which combines both data and the functions that operate on
that data.

DISADVANTAGES:
1.It has more complexity.
2.Data available unit is the object can be accessed by only the functions units are the
objects. However object will interact with each other via functions.

ADVANTAGES
1.Data is secured.
2 Users can create his own data type.
3.Debugging is easy.
4.Reusability is possible
METHOD:
A method is a function or a procedure that access to the internal state of the object needed
to perform some operation. So, methods are functions defined inside the classes that
operate on instances of those classes.

Class

Objects contain data, and code to manipulate that data. The entire set of data and code of
an object can be made a user-defined data type with the help of a class. In fact objects are
variables of the type class. Once a class is defined, we can create any number of objects
belonging to that class. For example mango, apple and orange are members of the class
fruit.

DATA ENCAPSULATION:
The wrapping up of data and functions into a single unit is known encapsulation.

7
The data is not accessible to outside world and only those functions, which are wrapped
in the class, can access it.

ABSTRACTION:
The purpose of abstraction is to separate behavior from implementation. Abstraction
involves extracting essential details of an entity or group of entities while ignoring the
unessential details. Thus, given an entity, the process of separating only the relevant
details from the irrelevant details is called abstraction. Revealing only necessary
information to viewers.

DATA HIDING:
Selective data or processes can be hidden from public view using this feature of OOP.
This is necessary to protect certain vital data in the application.

INHERITANCE:
Inheritance is the process by which objects of one class acquire the properties of another
class. The concept of inheritance provides the idea of reusability this means we can add
additional features to an existing class without modifying it.

POLYMORPHISM:
Polymorphism, a Greek term, and means the ability to take more than one form. Using
operators or functions in different ways, depending on what they operation is called
polymorphism. For example, consider the operation of addition, for two numbers; the
operation will generate a sum. If the operands are strings, then the operation would
produce a third string by concatenation.

OVERLOADING:
A single function or an operator acting or used differently in different situations is called
operators overloading or function overloading. Overloading is a kind of polymorphism.

8
DYNAMIC BINDING:
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic means that the code associated with a given procedure call is not
known until the time of the call at runtime.

Applications of OOP

1. Simulation and modeling


2. User interface design and windowing system
3. Object Oriented Database
4. Artificial Intelligence
HISTORY OF JAVA

In 1991, Patrick Naughton and James Gosling with his co-workers started a secret project
called "Green" in Sun Micro System Company. The small project started to create a
completely new platform for software development that would solve many of the
problems in existing embedded system. Their primary aim to design a small computer
language that could be used for consumer devices like cable TV switchboxes, Microwave
ovens and remote controls. Gosling decided to call his language "oak".

In 1992, they developed and delivered product called "*7" it was an extremely intelligent
remote control. In the year 93 and 94 they rename the project as "First Person Inc" Sun
Micro System had to find ways to market their technology, but none of the consumer
electronics companies were interested.

Sun Micro System released the first version 1.0 of java in beginning of 1996. It was
followed by java 1.02 two months later. In this version it supports data base connectivity
and distributed object. Version 1.1 released in 1997, added a robust event model, awt
enhancements, jar files, internationalization, RMI and Beans. Version 1.2 released at the
end of 1998, has the feature of Swing, Java 2D, Accessibility Drag and Drop, JAVAIDL,
JNI enhancements and JVMDI, currently JDK 1.6 beta is also released and now JDK 1.2
is called Java 2 platform. The next version of Java is called 'tiger'.

9
Note: Java is just a name and is not an acronym.
HTML
HTML stands for Hyper Text Markup Language. The markup or symbols tells the web
browser how to display a web page’s words and images for the user. A java-enabled
browser is a browser that can execute a program on a computer system

JAVA CODE AND JVM


All java programs are written keeping in mind the Java VM. The Java source code and
the byte code is machine independent while JVM is machine dependent. Different
machines with different Operating system will require a JVM developed for that machine.

OBJECTIVE TYPE QUESTIONS

1) The concept of OOP's include


A) Encapsulation B) Inheritance C) Abstraction D) a, b and c

2) Java supports the following features


A) Object-Oriented B) Platform Independent C) Secure D) a, b and c

3) What is the correct syntax of main () method?

A) Public static void main([]String args) B) public static void main(String args[])
C) public Static void main (String args[]) D) public static void main (string args[])

10
4) The _________command from the java2 Software Development Kit executes a java
application.

A) javac B) java C) class D) None

5) The _________command from the java2 Software Development Kit compiles a java
application.

A) javac B) java C) class D) None


6) A java program file must end with the __________file extension.
A) .javac B) .class C) .java D) None

7) If m and n are int type variables, what will be the result of the expression?
m % n when m = 5 and n = 2
A) 0 B) 1 C) 2 D) None
8) Class ___________displays message dialogs and input dialog.
A) JOptionPane B) showMessageDialog C) showInputDialog D) None

9) The process of placing the elements of an array in order is called______an array.

A) Sorting B) Searching C) Subscript D) None

10) Determining if an array contains a certain key value is called_______the array.

A) Sorting B) Searching C) Subscript D) None

1 2 3 4 5 6 7 8 9 10
B
D D B B A C B A A

11) The JIT compilers help in faster execution of the code.


A) True B) False C) None

12) Bytecodes are instructions that are generated for a ‘virtual machine’
A) True B) False C) None

11
13) The name of the java program file must be match the name of the class with the
extension .java

A) True B) False C) None

14) The modulus operator (%) can be used only with integer operands
A) True B) False C) None

15) Method Integer.parseInt converts an integer to a String


A) True B) False C) None

16) What is the correct syntax of println() method?

A) system.out.Println(“hai”) B) system.Out.println(“hai”)
C) system.out.println(“hai”) D) System.out.println(“hai”)

17) What is the correct syntax to display message in message dialog?


A) JOPtionpane.showMessageDialog(null,”hai”)
B) JOPtionPane.showMessageDialog(null,”hai”)
C) JOptionPane.showMessageDialog(null,”hai”)
D) JOptionPane.showMessagedialog(null,”hai”)

18) An array can store many different types of values


A) True B) False C) None of the Above

19) Variable declaration can appear any where in the body of a java program.
A) True B) False C) None

20) What will be the values of x, m, and n after execution of the following
statements?

int x, m, n;

12
m = 10;
n = 15;
x = + + m + n++;

A) x = 25, m = 10, n = 15 B) x = 27, m = 10, n = 15


C) x = 26, m = 11, n = 16 D) x = 27, m = 11, n = 16

11 12 13 14 15 16 17 18 19 20
A A A B B D C B A C

DESCRIPTIVE TYPE QUESTIONS


1) Write an application that inputs three integers from the user and displays the sum,
average, product, smallest and largest of these numbers in an information message dialog.
The average calculation in this exercise should result in an integer representation of the
average. So, if the sum of the values is 7, the average will be 2 not 2.333.

2) Write an application that inputs from the user the radius of a circle and prints the
circle’s diameter, circumference and area. Use the constant value 3.14159 for π.
Use the formulas (r is the radius): diameter= 2r, circumference = 2π, area = πr2

3) Write a program to accept three numbers and check whether the three numbers
represents the sides of a right-angled triangle or not.

13
4) Write a program to get n numbers from the users and print and largest numbers?

5) Write a java program to accept any five values and display into ascending order.
(Using Bubble Sort).

6) Write a program to accept 5 elements and store them in to an array. Accept a number
and check whether the number is existing in the array or not. If existing displays the
position other wise display number not found and the number found how many times.
(Using Linear Search Method)

7) Write a program to accept 5 elements and store them in to an array. Accept a number
and check whether the number is existing in the array or not. If not existing displays
number not found. (Using Binary Search Method)

8) Write a java program to find the sum of all elements in the one-dimensional array.
(Define a class representing array with necessary data members and a method to find
the sum).

9) Write a java program to insert an element in the given array in the given position?

10) Write a java program to delete an element from a given array?

11) Write a program for multiplying two matrices?

14
UNIT-2

SYNOPSIS

Object-Oriented Languages Vs Object-Based Language


Object-oriented programming is not the right of any particular language. Like structured
programming, OOP concepts can be implemented using languages such as C and Pascal.
However, programming becomes clumsy and may generate confusion when the programs
grow large. A language that is specially designed to support the OOP concepts makes it
easier to implement them.

15
The languages should support several of the OOP concepts to claim that they are object -
oriented. Depending upon the features they support, they can be classified into the
following two categories:

• Object-based programming languages, and


• Object-oriented programming languages.

Object-based programming is the style of programming that primarily supports


encapsulation and object identity. Major features that are required for object-based
programming are:

• Data encapsulation
• Data hiding and access mechanisms
• Automatic initialization and clear-up of objects
• Operator overloading

Data Types
Data types are used to specify the type of data variable can contain. There are 2 types of
data types.
1) Primitive
2) Non-Primitive

Class
A grouping of objects that have the same properties, common behavior and common
relationships.

16
Features of Object
1. An object must combine data and behavior
2. Objects must focus on essential properties ignoring any accidental properties
3. Object must hide the implementation details from the rest of the world. It may
expose certain functionalities to other objects
4. Object must understand messages from other objects and can pass messages to
other objects.
5. An object can be reused on any future project

Constructor

It is a function of a class used to initalise the object at the time of creation. A


constructor function is called automatically when object is created. The name of the
constructor function must be equal to the class name. Constructor function will not
have return data type. Constructor function must be public type. Constructor function
take value but will not return.

INHERITANCE
Reusability is another important feature of OOP. Fortunately, java strongly supports the
concept of reusability. The java classes can be reused in several ways. Once a class has
been written and tested, it can be adapted by the other programmers, to suit their
requirements. This is basically done by creating new classes, reusing the properties of the
existing ones.

Super class:
The super class is the class from which another class inherits its behavior

Sub class:
The class that inherits the properties and methods of another class is called the subclass

17
ADVANTAGES
1. Reusability of code
2. The base class need not be changed but can be adapted to suit the requirements in
different applications. (Or ) Once a base class has been created it need not be
changed but it can be adapted to work in different situations.

Methods Overloading
Overloading is the process of declaring methods of a class having the same name but
different signatures. The signature of a method comprises of the name of the method, the
number and type of arguments. The return type of a method is not a part of the signature
and hence cannot be used as a factor for overloading.

In java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case,
the methods are said to be overloaded, and the process is referred to as method
overloading. Method overloading is one of the ways that java implements polymorphism.

Constructor overloading is a special case of method overloading. Parameterized


constructors that satisfy the rule for overloading can be used within classes.

Ex: Overloads1, overloads2

Overriding
Overriding is the process of overwriting the methods of a base class in a derived class. In
case of method overriding, the return type, name and arguments of the method in the
derived class must be same as that of the method being overridden. When an object of the
derived class invokes the overridden method, it will be the derived class implementation
that will be called.

Instance Variables and Class Variables

18
An instance variable represents a separate data item for each instance of a class, where as
a class variable represents a single data item shared by the class and all its instances.

An instance variable represents data for which each instance has its own copy. An
instance variable corresponds roughly to a field of a structure (sturct) in c or c++.

A class variable, in contrast, belongs to the class as a whole. All instances of the class
have access to the same single copy. A class variable can therefore function as a shared
resource and an indirect means of communication among the instances of the class. Class
variables are declared with the static keyword.

Class variables store values for the variables in a common memory location. Because of
this common location, all objects of the same class are affected if one object changes the
value of a class variable.

INTERFACE
There is no multiple inheritance in java. Multiple inheritance enable you to derive a class
from multiple parent class. For example A and B are base class we derive class c from
both.

OBJECTIVE TYPE QUESTIONS

1) A package is a collection of
A) Classes B) Interfaces C) Final and Abstract Classes D) Classes and Interfaces

2) Which of the following defines a legal abstract class?


A) class Vehicle { abstract void display();}
B) abstract Vehicle { abstract void display();}
C) abstract class Vehicle { abstract void display(); }

19
D) class abstract Vehicle{ abstract void display() }

3) When we implement an interface method, it should be declared as_____


A) Private B) Protected C) Public D) Abstract

4) We can overload methods with differences only in their return type


A) True B) False C) None

5) ___________members of a superclass are accessible by all the methods in the


program.

A) Private B) Protected C) Public D) Default

6) ___________members of a superclass are accessible only by methods of the


superclass.

A) Private B) Protected C) Public D) Default

7)_________members of a superclass may be accessed only by methods of the


superclass, by methods of subclasses and by methods of other classes in the same
package.
A) Private B) Protected C) Public D) Default

8) If a class contains one or more abstract method, it is an _______________class


A) Final B) Static C) Nested D) Abstract

9)Multiple Inheritances is possible in java


A)True B) Inheritance is not Possible in java C) None

10) Final methods cannot be overridden but overloaded


A) True B) False C) None
1 2 3 4 5 6 7 8 9 10

20
C C B C A B D C A
D

11)The finalize() method is called just prior to


A) an object , variable or method goes out of scope B)a variable goes out of scope
C)an object or variable goes out of scope D) before garbage collection

12) class Numbers{


public void disp(int x,int y){
JOptionPane.showMessageDialog(null,"The sum of x and is "+x+y);}
public static void main(String arg[]) {
Numbers num=new Numbers(); num.disp(4,5);}}
A) The sum of x and y is 9 B) The sum of x and y is 45
C) does not compile D) None

13) String s1=new String("Hello"); String s2=new String("Hellow");


JOptionPane.showMessageDialog(null,s1=s2);
The output of the above fraction of code is
A) Hello B) Hellow C) Does not compile D)None

14)String str=”abcde”
JOptionPane.showMessageDialog(null,” result is :”+ str.substring(1,3));

The output of the above program is


a) abc b)bcd c)ab d)bc

15)String s1="java ";


JOptionPane.showMessageDialog(null, "The index of 'k' is =" + s1.indexOf('k'));
What is the output of the above program.
a) 1 b) 0 c)-1 D)None

16)String str1=”Helloww”;

21
JOptionPane.showMessageDialog (null,” The result is =" + s1.replace ('l','w'));
a) Helloll b)Hewwoww c) Hellolw D) Hewloww

17)String s1="Hello";
JOptionPane.showMessageDialog(null,"The Result is =" + s1.insert(2,'k'));
A) hekllo B) hkello C) hello D)none

18) A___________is an environmental variable, which tells the JVM, where to find the
class libraries, including user defined class libraries.

A) Package B) Path C) Classpath D) Import Statement

19)The _______class allows an application to break a string into tokens.


A) delimiters B) white space C) , (coma operator) D) StringTokenizer

20) A class can implement many interfaces but can have only one superclass.
A) True B) False C)None

11 12 13 14 15 16 17 18 19 20
B B D C B D C D A
D
DESCRIPTIVE TYPE QUESTIONS
1) Write a program using
a) Default Constructor
b) Arguments Constructor
c) Copy Constructor
d) Acceptdata method
e) Displaydata method
To find the area of a rectangle using the following formula
Area=length * breadth

22
2) Create a class called employee with empno, name, and date of join. A Constructor with
assigns 0 in the empno, null in the name and today’s date in the date. A getdata function
accepts data and display data function, which display data. This organization has 2
categories.

1) Programmer 2) Manager

Programmers along with the above employee details should contain the language in
which you write the program. Managers along with the above employee detail the
department, which is the manager.

Write a java program, which allows entering the users programmers and managers data
and display them.

3) Write a program that will create 3 methods all bearing the same name print. These
methods should print the product (multiplication) of two integers print one string and sum
of three decimal numbers respectively.

4) Create an abstract base class called employee. It should contain a data member called
basic and a method called salary (), which returns nothing nor takes in any parameters.
Next derives a class from employee called manager, implements the salary () method
should display manager salary.

Derive another class called worker from the employee abstract base class. This time the
salary () method should display the worker salary.

Manager basic is 5000.


Workers basic is 3000
For managers da = 40% of basic
For workers da = 20 % of basic
Salary = basic + da

23
5) Create a class called details, which contains id, name as data members. A print
function displays id and name details.
Create another class called address, which contains street, city, state, zip and country as
data members. A display function displays the data. Use the details class as a composition
in address class.

6) Write a program in java. A class teacher contains two fields Name and Qualification.
Extends the class to Department it contains Dept.No and Dept.Name. An Interface named
as College it contains one field Name of the college. Using the above classes and
Interfaces get the appropriate information and display it.

7) Write a program that creates two classes under one package. One of the classes is for
calculating factorial value and the other should be power and base value.

UNIT -3

SYNOPSIS
User Interface - The User interacts with an application via its user interface
The “Program” – A set of instructions to carry out a specified task

Character Based Systems


Text is the medium of information exchange
Not very easy to use
Cannot react immediately

24
Graphical User Interface
Interface with Graphics
Easy to use
Intuitive (Natural)
Easy to learn
Attractive

Conventional programming tools suffer from the following disadvantages:


Lot of time and effort wasted in designing a good interface
Great amounts of code for interface
Repetitive coding
Conclusion:

INTRODUCTION
•A number of software platforms today provides us with a new facility called
"Foundation Class” (FC).
•These foundation classes are nothing but class libraries specifically designed for
building GUIs.
•Foundation classes simplify the designing process and reduce the time taken to code.

•A simple task like creating a menu or a dialog box involves writing lengthy and bulky
code.
•With the help of these foundation classes, the design process gets simplified and the final
product has a better look and feel.
•Microsoft Foundation Classes (MFC) and Java Foundation Classes (JFC) are two
popularly used foundation classes.

25
Swing Components
As mentioned earlier, most foundation classes provide a rich collection of classes to build
user interfaces. Swing is a set of classes under the JFC that provide lightweight visual
components and enable creation of an attractive GUI. Swing not only contains
replacement components for AWT visual components but also complex components like
trees and tables that do not have AWT equivalents. Swing components have a pluggable
look and feel so that with a single set of components you can achieve the look and feel of
any OS platform.

Swing Component Hierarchy


Swing component contains nine packages consisting of innumerable classes and
interfaces. The base class for all containers and components is ‘Jcomponent’ class of the
‘com.sun.java.swing’ package. This class is a subclass of ‘java.awt.container’; hence it
acts like both a component and a container.

Events

In the delegation model, an event is an object that describes a state change in a source.
Some of the activities that cause events to be generated are pressing a button, entering a
charter.

Events may also occur that are not directly caused by interactions with a user interface.
Ex. An event may be generated when a timer expires, counter exceeds a value.

• An event is generated whenever a user clicks a mouse, presses or releases a key


• Event Delegation Model is used to handle events
• This process allows the program to register handlers called ‘listeners’ with objects
whose events need to be captured
• Handlers are automatically called when an event takes place
• Event listeners are implemented as interfaces in Java

26
Event Listener

A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about the specific types of events. Second, it must implement methods to
receive and process these notifications. The methods that receive and process events are
defined in a set of interfaces found in java.awt.event.

Why Layout Managers are used?

1.Layout Managers are used to display the components on the target screen.

2.Java being platform independent utilize a unique way to display the

components on the screen, independent of the platform.

3.It uses the concept of Relative Position System.

4.Controlling the physical layout of GUI elements.

5.Automatically positioning the components within a container.

6.Java provides five different ways of sectioning the display area.

7.Each of these ways of displaying components on different screen sections

is handled by the Layout Manager.

Layout Managers are provided to arrange GUI components on a container for


presentation purposes. The layout managers provide basic layout capabilities that are
easier to use than determining the exact position and size of every GUI component.

Suppose you are create a button on your application. The application run on widnows 95
machine, this button will be 32 pixels wide and 21 pixels height. Pixel (Picture element)
is a small graphical unit. On a Motif platform button will be 32 pixels wide and 22 pixels
height, even though it uses the same font. Java sole the problem by using the layout
manager.

Java deifnes 5 Layout managers

27
1.Flow Layout

2.Grid Layout

3.Border Layout

4.Card Layout

5.GridBag Layout

OBJECTIVE TYPE QUESTIONS

1) The _________Layout manager arranges the components in a grid formation


with the number of rows and columns.
A) GridLayout() B) BorderLayout C) FlowLayout() D) None

2) _______________are used to arrange the components on the target screen.

A) setVisible(true) B) setVisible(false) C) LayoutManager D)None

28
3) ______________is the default layout manager for panels.
A) GidLayout() B) FlowLayout() C) BorderLayout() D)None

4) __________is the default layout manager for Window, Frame and Dialog.

A) GidLayout() B) FlowLayout() C) BorderLayout() D)None

5) ____________is a component that has no default appearance or behavior.

A) Container B) Dialog C)Canvas D) None

6) A command button generates an ________________when the user clicks the


button with the mouse.
A) ActionEvent B) PressedEvent C) ClickEvent D) None
7) __________Component is for multiple selections.
A) JRadioButton B) JCheckBox C) JComboBox D)None

8) _________Method is called when the mouse button is pressed and the mouse is
moved.
A) MouseDraggerd B)MouseClicked C) MouseReleased D) None.

9) A Jpanel cannot be added to another Jpanel.

A) True B) False C)None.

10) Scrollbar generates_______________events.

A) Action B) Item C)Adjustment D) None


1 2 3 4 5 6 7 8 9 10
C B C C A B A A C
A

11) class___________________provides methods for drawing. (Graphics)

29
12) Keyword ___________is used to indicate that a new class is a subclass of an
existing class. (Extends)
13) Every java applet should extend ___________class. (Japplet)
14) Java applet begins execution with a method called________________.(init()).
15) Java application begins execution with a method called____________.(main)

DESCRIPTIVE QUESTIONS

1) What is Layout Manager?

2) What is Swing?

3) What is Applet?

30
4) What is Listener Class?

5) What is graphics class?

6) What is adapter class?

7) What is layout managers?

8) What is swing?

9) What is component?

10) what is Swing hierarchy?

11) What is grid bag layout manager?

12) what is flow layout manager?

13) what is panel?

14) what is grid layout?

15) what is border layout?

16) what is frame window?

17) What is applet?

18) what is Jdesktop pane?

19) what is Jpopup menus?

20) Explain about JOptionpane class?

UNIT – 4

SYNOPSIS

EXCEPTION HANDLING
One of the features of the java programming language is its robustness (strength or
toughness). This means that errors are minimized and that errors should be properly

31
handled. To avoid Exceptions in a program, we should handle the exception in the
program.

An error may produce an incorrect output or may terminate the execution of the program
or even may cause the system to crash. It is therefore important to detect and manage
properly all the possible error conditions in the program so that the program will not
terminate or crash during execution.

Types of Errors

1. Compile time errors


2. Run time errors

COMPILE TIME ERRORS

All syntax errors will be detected and displayed by the java compiler and therefore
these errors are known as compile-time errors. Whenever the compiler displays an
error, it will not create the .class file.

RUNTIME ERRORS

Sometimes, a program may compile successfully creating the .class file but may not run
properly. Such programs may produce wrong results due to wrong logic or may terminate
due to errors such as stack overflow. Most common run time errors are:

MULTITHREADING

A thread is the smallest unit of executable code that performs a particular task. An
application can be divided into multiple tasks and each task can be assigned to a thread.
Two or more threads can be executed simultaneously. This is called multithreading.

32
Let us take the simple instance of a game simulator. The program plays audio sounds,
displays graphics and determines scores - all at the same time. This can be considered as
a threaded application. Each task is a thread and all threads are executed simultaneously.
Any application will have at least one thread running - the main thread. This thread is
destroyed when the program terminates.

Java supports multithreading:

Multithreading is the ability of a single program to perform more than one task at the
same time. Multithreaded applications effectively utilize processor wait time.
An application can contain multiple threads.
Each thread is specified a particular task which is executed concurrently with the other
threads. Multithreading allows you to write efficient programs that make the maximum
use of CPU, by keeping the idle time to a minimum. Each part of the program is called a
thread, and each thread defines a different path of execution. It is a specialized form of
multitasking.

OBJECTIVE TYPE QUESTIONS

1) _________________state that the processor has given its time to the thread for its
execution.
A) runnabel B) born C) running D) None

33
2)_________________state the processor time is not allotted to the thread.
A) runnabel B) born C) running D) None
3)__________________state means that the thread is ready for execution and is
waiting for the availability of the processor time.
A) runnabel B) born C) running D) None
4) In java a higher priority threads can be executed last and lower priority threads
can be executed first.
A) True B) False C)None
5) ___________is running multiple programs simultaneously, with each program
having at least one thread in it.
A) Multithreading B) Multitasking C) Multiprocessing D)None

6) To execute a thread, the thread is first created and then the ______method is
invoked on the thread.
A) start() B) init() C) run() D) None
7) A_________occurs when two threads have a circular dependency on a pair of
synchronized objects.
A) Multithreading B) Synchronization C)Deadlock D)None

8) The ThreadGroup class has three methods that allow you to modify the current state of
all the threads within that group. They are ____________, _____________ and
____________.

A) resume(), stop() and suspend() B) run(), start() and stop()


C) Wait (), notify () and run () D) sleep (), run () and resume ()
9)_____________are those exceptions that occur within the Java runtime system.
A) Compiletime Exceptions B) Runtime Exceptions C) Exception D) None
10)An_____________is a class that handles all type of Exceptions.
A) Compiletime Exceptions B) Runtime Exceptions C) Exception D) None

1 2 3 4 5 6 7 8 9 10

34
B A B B A C A B C
C

11) The package____________. Thread class consists of all the basic support for the
threads. (Java.lang)

12)__________method is used to set the priority value of a thread. (setPriority())

13)__________method is used to get the priority value of a thread. (getPriority())

14) Java is a _____________threaded language. (Multi)

DESCRIPTIVE TYPE QUESTIONS

1) What is finally?

35
2)What is InputStream?

3) What is Thread Synchronization?

4) What is Daemon Threads?

26) Write a program, which creates a window with yellow background colour and
message HOW ARE YOU?
27) Write a java program to design a border layout as shown below
Ramu
Hyd Weds Delhi
Geetha

28) Write a program for java applet, which has withdrawal form of bank?

29) Write a java program to create an applet with six buttons representing your favorite
six colours when button is clicked, the background must change to the corresponding
colour.
30) Write a program to create a child frame window from with in an applet?
31) Write a sample program to handle Mouse events and Window events?
32) Write a java program that counts the number of digits in a given number. If an
alphabet is entered instead of a number, the program should not terminate. Instead of
should display appropriate error message.
33) Write a program that checks if a given number is of byte data type. If the number
exceeds the range of a byte then raise a user-defined exception ByteSizeException and
display appropriate error message?
34) Write a program to illustrate Card Layout?

35) Write a program to illustrate Grid Bag Layout.

36) Write a java program how try, catch can be put in a loop?

36
37) Write a java program, which contains the following thread processing.
There must be one thread, which displays
1) Even Numbers up to 10 (Thread priority = 3)
2) Odd Numbers up to 10 (Thread priority = 8)
38) Write a java program to crate Synchronization?
39) Write a java program to create Deadlock condition?
40) Write a program to read input from the keyboard and echo it on the monitor using
InputStreamReader?

41) Write a program to copy the contents of one file to another file?

42) Demo on Serialization?

43) Write a program that randomly draws characters in different font sizes and colors.

44) Write a program that draws a square. As the mouse moves over the drawing area,
repaint the square with the upper left corner of the square following the exact path of the
mouse cursor.

45) a) Write a runtime polymorphism program in java using interface reference variable.

b) Write a above program using object reference variable.

46) Write a program segment that accomplishes each of the following


a) Calculate the integer part of Quotient when integer a is divided by integer b.
b) Calculate integer remainder when integer a is divided by integer b
c) Use the program pieces developed in a) and b) to write a method display
Digit that receives an integer between 1 and 99999 and prints it as a series of

37
digits, each pair of which is separated by two spaces. For example integer
4562 should be printed as 4 5 6 2.
47) Design an Editor like notepad.

UNIT – 5

SYNOPSIS
JDBC

38
1. A database contains data that is in an organized form.
2. Client/Server applications make extensive use of database programming.
3. Activities may involve opening a connection, communicating with a database,
executing SQL statements and retrieving query results.
4. Standardized APIs are available that simplify database programming. Examples of
these are ODBC and JDBC

Need for JDBC


1. ODBC uses a C interface that has lot of drawbacks
2. A literal (exact) translation of the ODBC C interface into a Java API would not be
desirable.
3. ODBC mixes simple and advanced features together and has complex options
even for simple queries.
4. A Java API like JDBC is needed in order to enable a “pure Java” solution
5. JDBC is portable
6. JDBC is a standard interface for Java programmers to access relational databases

JDBC

1. JDBC is a Java Database Connectivity API that is a part of the Java Enterprise
API
2. Defines a set of API objects and methods to interact with databases
3. JDBC is a must for all Java applications that access data stored in external data
providers like SQL Server, Oracle or Access
Networking Introduction

A Computer network is a communication system, which contents two or more computers


and peripheral devices, to allow sharing of resources, information, and services. Users in

39
a network share a common pathway to communicate with each other. Internet is a
network of networks.

Protocol

1. Communication between computers in a network or a different network requires


certain set of rules called protocol.
2. Internet is nothing but many computers communicating with each other using
protocols.
3. Protocols help in passing the information from one computer to another.

Java networking is done using TCP/ IP protocol.

Some of the different type of protocols:


HTTP (Hyper Text Transfer Protocol- enables Internet interaction)
FTP (File Transfer Protocol)
SMTP (Simple Mail Transfer Protocol - provides e-mail facility).

• Computers communicate by exchanging packets of data known as Internet


Protocol (IP)
• All the computers on the Internet communicate using IP
• The computers are identified using IP Addresses
• Internet Protocol Address is nothing but a 32-bit number

Port

A memory location that defines a communication channel or device interface. A port is


used to interface a computer to other devices
(or)
A specific communications end point within a host. It is identified by a port number

40
SOCKET

A socket is one end point of a two-way communication link between two programs
running on the network. The socket classes are used to represent the connection between
a client program and a server program.

Socket Class

Socket class has eight constructors that create sockets.


They in turn connect to the destination host and port.
The port number of the machine to which the socket is connected is obtained by the
getPort( ) method.
The local port number is obtained using the getLocalPort( ) method

Datagram

Datagrams are pack of information passed between machines. Data is transmitted across
the Internet in packets of limited size called datagrams. Each datagram contains a header
and a payload. The header contains the address, port number and some other information
to where the packet should go reliably. The payload contains the data itself.

URL Class

41
Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World
Wide Web. A resource can be something as simple as a file or a directory, or it can be a
reference to a more complicated object, such as a query to a database or to a search
engine.

Introduction

Large problems can be solved easily if it is split among two or more people. When one
person cannot handle with a large problem due to time or physical constraints the best
solution is to split the work among two or more persons.

In the world of computers, instead of investing millions on huge computers with great
computing power, it is economically wiser to split the computations among several
smaller computers.

• Distributed computing helps solve large problems by splitting them.


• The split components are kept in different computers.
• Objects on remote systems can be accessed with the same ease as those on local
systems.
Java Distributed Object Model

Various Developing Distributed Object Applications include:

1. Distributed Component Object Model (DCOM) from Microsoft


2. Common Object Request Broker Architecture (CORBA)

42
3. Remote Method Invocation (RMI) from Sun Microsystems

R M I Introduction

RMI is an acronym for Remote Method Invocation. It is the process of networking. It


means to communicate between Java-to-Java objects across platforms. That is to say, to
communicate between the distributed objects across platforms where JVM is running.

CORBA is language neutral and RMI is Java language dependent. CORBA can be written
in C, C+ +, COBOL or Java, but RMI must be written in Java only. An object is said to be
distributed, if it is made available in the network.

The java remote method invocation (RMI) application-programming interface (API)


enables client and server communications over the net. Typically, client programs send
requests to a server program, and server program responds to those requests.

Need for Servlets

1) Processing client’s request is a continual process


2)
Issues involved are multi-threading, networking, security, etc.
3) Different Java components can deal with these issues
4) Ideally one component should efficiently and dynamically handle the web server needs

Servlets

1) Servlets are platform independent, Java components


2) Servlets are server-side Applets

43
3) Servlet works behind the scene and gives the output as an HTML file
4) Servlets provide a framework for creating applications that work on
request/response architecture of the web server
Advantages of Servlets

Speed - Servlets execute faster than common scripting languages, as servlets are
compiled into java byte code.
Robust (Strong) - Servlets are almost crash proof. Since they are written in Java, the
Java virtual machine does not allow the servlet to access the memory directly. Therefore,
the possibility of invalid memory access is reduced.

Portable (moveable) - Servlet APIs are widely accepted. They are highly portable
across the platform. So, a servlet written on Windows NT platform running Java Web
Server can easily be deployed on a Unix machine running Apache Web Server.

Powerful - The full power of core Java APIs such as networking, multithreading, image
manipulation, data compression, database connectivity, internationalization, RMI and
object serialization can be exploited in servlets.

Secure - There are important features, which ensure servlet security. Firstly, servlets use
the server's security manager, since the security manager can restrict network or file
access for untrusted servlets. The security manager can give full access rights to the local
or digitally signed and trusted servlet. Secondly, servlets are secure because they can only
be invoked through the web server, and the web server is protected behind the firewall
security.

Servlets are more secure than CGI because the CGI is written in the C Language, which
is a more error-prone language than Java. (C programs can maliciously access invalid
memory locations.) However, Java does not allow the user to work with pointers.
Therefore, CGI programs are less secure than servlets.

44
OBJECTIVE TYPE QUESTIONS

1) What is Skeleton?

2) What are the advantages of servlets?

3) What is Remote Procedure Call?

4) What is Uniform Resource Locator?

5) What is the need for JDBC?

6) What is Socket?

7) What is marshalling?

8) What is webserver?

9) What is Java DataBase Connectivity?

45
10) What is servlet?

11) How many types of JDBC Drivers?

12) What is Remote Reference Layer?

13) What is protocol?

14) The collection of inter-related data is usually referred to as Database

A) Database B) Table C) Query D) None

15) Every time a server receives a request that point to a servlet, it calls that
servlet’s Service method.
A) init () B) destroy() C) service() D)None

16) Servlets usually are used on the server side True (True/False)

17) UDP is a connection less protocol True (True / False)

18) RMI is based on a similar technology for procedural programming called


RPC
19) SQL stands for Structured Query Language

20) A table in a database consists of rows and columns

46
DESCRIPTIVE QUESTIONS

1) What is JDBC?

2) What is ODBC?

3) What is servlet?

4) What is servlet container?

5) What is http servlet?

6) What is generic servlet?

7) What is rmi?

8) What is skelton?

9) What is socket?

11)what is the procedure to communicate with server socket?

12) Write a JDBC program to save records into a database?

13) what is TCP/IP protocol?

14) what is datagram?

47
1. 15) What's the difference between servlets and applets?

2. What's the advantages using servlets than using CGI?

3. What's the Servlet Interface?

4. What is the servlet life cycle?

How HTTP Servlet handles client requests?

5. what is RPC?

48

Vous aimerez peut-être aussi