java programming - kopykitab · 2018-10-01 · java programming an iso 9001:2008 certified company...

16
JAVA PROGRAMMING An ISO 9001:2008 Certified Company An ISO 9001:2008 Certified Company An ISO 9001:2008 Certified Company An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh Rana Assistant Professor Department of Computer Science Galgotia College of Engineering and Technology Greater Noida (Uttar Pradesh)

Upload: others

Post on 20-May-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

JAVA

PROGRAMMING

An IS O 90 01: 20 08 Cert if i ed Compan y An IS O 90 01: 20 08 Cert if i ed Compan y An IS O 90 01: 20 08 Cert if i ed Compan y An IS O 90 01: 20 08 Cert if i ed Compan y

Vayu Education of India2/25, Ansari Road, Darya Ganj, New Delhi-110 002

Kamlesh RanaAssistant Professor

Department of Computer Science

Galgotia College of Engineering and Technology

Greater Noida (Uttar Pradesh)

Page 2: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Java Programming

Copyright ©VAYU EDUCATION OF INDIA

ISBN: 978-93-83137-22-0

First Edition: 2013

Price: 180/-

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or

transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or

otherwise, without the prior permission of the Authors and Publisher.

Printed & bounded in India

Published by:

(An ISO 9001:2008 Cer tif ied C ompany )(An ISO 9001:2008 Cer tif ied C ompany )(An ISO 9001:2008 Cer tif ied C ompany )(An ISO 9001:2008 Cer tif ied C ompany )

VAYU EDUCATION OF INDIA2/25, Ansari Road, Darya Ganj, New Delhi-110 002

Ph.: 91-11-43526600, 41564445

Fax: 91-11-41564440

E-mail: [email protected]

Web: www.veiindia.com

Page 3: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

BLOCK - I

1. INTRODUCTION TO OOPS AND JAVA .......................................................................................... 1

1.1 Introduction ................................................................................................................. 3

1.2 Principles of Object – Oriented Programming............................................................ 4

1.2.1 Objects ........................................................................................................... 4

1.2.2 Classes ........................................................................................................... 5

1.2.3 Data Abstraction and Encapsulation ............................................................... 7

1.2.4 Inheritance ...................................................................................................... 8

1.2.5 Polymorphism ............................................................................................... 10

1.3 Benefits of OOPs ..................................................................................................... 11

Exercise .................................................................................................................. 12

2. HISTORY OF JAVA ................................................................................................................. 13

2.1 History of JAVA ....................................................................................................... 13

2.2 JAVA Features .......................................................................................................... 13

2.3 Java Program Structure ............................................................................................ 18

2.4 Difference between Java and C++ .......................................................................... 20

2.5 Compile Java Program.............................................................................................. 21

2.6 Run Java Program .................................................................................................... 21

Exercise .................................................................................................................. 22

3. TYPES OF JAVA PROGRAM ...................................................................................................23

3.1 Types of JAVA Program ........................................................................................... 23

3.1.1 Applet .......................................................................................................... 23

3.1.2 Servlet ........................................................................................................... 29

Exercise .................................................................................................................. 33

CCCCONTENTSONTENTSONTENTSONTENTS

Page 4: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

4. JAVA ELEMENTS ................................................................................................................. 34

4.1 JAVA Elements ......................................................................................................... 34

4.1.1 Comments ..................................................................................................... 35

4.1.2 Variables and data types ............................................................................... 35

4.1.3 Literals .......................................................................................................... 35

4.1.4 Operators ...................................................................................................... 35

4.1.5 Basic I/O statements .................................................................................... 35

Exercise .................................................................................................................. 44

BLOCK - II

1. DECISION MAKING ............................................................................................................... 45

1.1 Decisin Making ......................................................................................................... 47

4.1.1 Simple If-else Construct .............................................................................. 47

4.1.2 Nested if ....................................................................................................... 49

4.1.3 if-else-if Ladder ............................................................................................ 51

Exercise .................................................................................................................. 56

2. LOOP CONTROL STRUCTURE.................................................................................................57

2.1 Loop Control Structure ............................................................................................. 57

2.1.1 For loop ..................................................................................................................... 57

2.1.2 While loop ................................................................................................................. 57

2.1.3 do-while loop. ............................................................................................................ 57

Exercise .................................................................................................................. 66

3. ARRAY ................................................................................................................................. 67

3.1 Arrays ....................................................................................................................... 67

3.2 Creating an array ...................................................................................................... 68

3.4 The size of an array .................................................................................................. 71

3.5 Multi-dimensional arrays ........................................................................................... 72

3.6 Initializing multi-dimensional arrays........................................................................... 74

Exercise .................................................................................................................. 77

4. STRING ............................................................................................................................... 78

4.1 Strings ....................................................................................................................... 78

4.2 String Handling ......................................................................................................... 79

Page 5: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

BLOCK - III

1. CLASS ................................................................................................................................. 87

1.1 Classes ...................................................................................................................... 89

1.2 General Form of a Class ........................................................................................... 89

1.3 Reusing Class ........................................................................................................... 92

Exercises ................................................................................................................ 98

2. OBJECT................................................................................................................................ 99

2.1 Object ....................................................................................................................... 99

Exercise ................................................................................................................ 108

3. INHERITANCE .................................................................................................................... 109

3.1 INHERITANCE ..................................................................................................... 109

3.2 Class Hierarchy ...................................................................................................... 112

3.4 Single and Multiple Inheritance ............................................................................... 113

3.5 Interfaces and Packages ........................................................................................ 114

3.6 Implementation of Inheritance ................................................................................ 115

Exercises .............................................................................................................. 116

4. PACKAGE ........................................................................................................................... 1 1 8

4.1 Packages ................................................................................................................ 118

4.2 Small Programming ................................................................................................. 119

4.3 Hiding Classes ........................................................................................................ 121

4.4 Interfaces ................................................................................................................ 122

Exercise ................................................................................................................ 125

BLOCK - IV

1. APPLETS ............................................................................................................................ 129

1.1 Applet ..................................................................................................................... 131

1.2 Applet Life Cycle ................................................................................................... 134

1.3 Custom Applets ....................................................................................................... 136

1.4 Applet Characteristics ............................................................................................ 137

1.5 Applets applications ................................................................................................ 139

1.6 Painting ................................................................................................................... 139

Exercise ................................................................................................................ 141

Page 6: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Java Programmingviii

2. AWT COMPONENT ................................................................................................................ 142

2.1 Abstract Window Tool Kit (AWT) ......................................................................... 142

2.2 Window construction components .......................................................................... 143

2.3 The Basic User Interface Components .................................................................. 144

2.4 Labels ..................................................................................................................... 145

2.5 Buttons .................................................................................................................... 146

2.6 Checkboxes ............................................................................................................ 146

2.7 Radio Buttons ......................................................................................................... 147

2.8 Choice Menus ......................................................................................................... 148

2.9 Create the Panel Layout ......................................................................................... 149

Exercise ................................................................................................................ 151

3. EVENT HANDLER ................................................................................................................. 152

3.1 Event ....................................................................................................................... 152

3.1.1 Mouse Evenet ............................................................................................. 152

3.1.2 Mouse Clicks .............................................................................................. 153

3.1.3 Keyboard Event .......................................................................................... 157

Exercise ................................................................................................................ 162

4. EXCEPTION HANDLING ....................................................................................................... 163

4.1 Exception Handling ................................................................................................. 163

4.2 Constructs and Exception Semantics in Java .......................................................... 164

4.3 Defining Exception Objects .................................................................................... 164

4.4 Defining Exception Handlers .................................................................................. 164

4.5 Raising Exceptions .................................................................................................. 165

4.6 Nested Exception Handlers .................................................................................... 169

4.7 Multiple Handlers .................................................................................................... 170

BLOCK - V

1. MULTITHREDING ............................................................................................................... 173

1.1 Threads ................................................................................................................... 175

1.2 Creating and Using Threads ................................................................................... 176

1.3 The Runnable Interface .......................................................................................... 177

1.4 When a Thread has stopped ................................................................................... 178

Page 7: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Contents ix

1.5 Thread Scheduling .................................................................................................. 179

1.6 PriorityThreadTester ............................................................................................... 180

1.7 Thread Creation Using the Thread Class ............................................................... 182

1.8 Thread Creation Using the Runnable Interface ...................................................... 183

Exercises .............................................................................................................. 184

2. I/O STREAM ....................................................................................................................... 186

2.1 Stream..................................................................................................................... 186

2.1.1 Input Stream ............................................................................................... 187

2.1.2 Output Streams ........................................................................................... 194

Exercise ................................................................................................................ 196

3. NETWORKING ..................................................................................................................... 197

3.1 Networking ............................................................................................................. 197

3.2 Sockets in Java ....................................................................................................... 199

3.3 Listener Sockets in Java ......................................................................................... 200

3.4 Creating Links Inside Applets ................................................................................. 200

3.5 Opening Web Connections...................................................................................... 202

3.6 The URLconnection Class ...................................................................................... 203

3.7 Communicating Between Applets ........................................................................... 205

Exercise ................................................................................................................ 206

4. JDBC .................................................................................................................................. 207

4.1 Introduction ............................................................................................................. 207

4.2 Java Database Connectivity ................................................................................... 207

4.3 JDBC Architecture ................................................................................................. 208

4.4 JDBC Drivers ......................................................................................................... 208

4.5 Types of Drivers ..................................................................................................... 208

4.6 JDBC APIs ............................................................................................................. 212

4.7 Data Definition Language (DDL) with JDBC ....................................................... 215

4.7.1 Creating a Table ......................................................................................... 215

4.8 Data Manipulation Language (DML) with JDBC .................................................. 216

4.8.1 Creating (Inserting) Records Using JDBC................................................. 217

4.8.2 Deleting Records Using JDBC................................................................... 217

4.8.3 Retrieving Records Using JDBC................................................................ 217

7.9 Query SQL Statements ........................................................................................... 218

Exercises .............................................................................................................. 219

Index ............................................................................................................. 221-222

Page 8: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

BLOCK-I

1. Introduction to OOPS and JAVA

2. History of JAVA

3. Types of JAVA Program

4. JAVA Elements

Page 9: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

1.1 INTRODUCTION

Object-Oriented Programming is a programming paradigm that uses abstraction to create models based

on the real world. It uses several techniques from previously established paradigms, including modularity,

polymorphism, and encapsulation. Today, many popular programming languages such as Java,

JavaScript, C#, C++, Python, PHP, Ruby and Objective-C support object-oriented programming (OOP).

Object-oriented programming (OOP) is a technique for writing computer software. The term

object oriented refers to the methodology of developing software in which the emphasis is on the data,

while the procedure or program flow is de-emphasized. That is, when designing an OOP program, you

do not concentrate on the order of the steps that the program performs. Instead, you concentrate on

the data in the program and on the operations that you perform on that data.

Advocates of object-oriented programming claim that applications that are developed using an

object-oriented approach

(i) are easier to understand because the underlying code maps directly to real-world concepts that

they seek to model

(ii) are easier to modify and maintain because changes tend to involve individual objects and not the

entire system

(iii) promote software reuse because of modular design and low interdependence among modules

(iv) offer improved quality because they are constructed from stable intermediate classes

(v) provides better scalability for creating large, complex systems.

In Object Oriented Programming objects are data elements in your application that perform some

function for you. Objects can be visual objects that you place on the frame—for example, icons, push

buttons, or radio boxes. Visual objects are called controls; they display information or accept user

input.

BLOCK-I

Introduction to OOPS

and JAVA

1

Page 10: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Java Programming4

Objects can also be non-visual objects that manage the application behind the scenes; for example,an object that enables you to interact with SAS data sets may not have a visual representation but still

provides you with the functionality to perform actions on a SAS data set such as accessing variables,adding data, or deleting data. An object or component is derived from, or is an instance of, a class. Theterms object, component, and instance are interchangeable. Software objects are self-contained entities

that possess three basic characteristics:

behavior a collection of operations that an object can perform on itself or on other objects.Methods define the operations that an object can perform. For example, you can use the _onGeneric

method in sashelp.classes.programHalt.class to trap all generic errors.

state a collection of attributes and their current values. Two of the programHalt component’sattributes are stopExecution (which determines whether the program continues to execute after the

program halt occurs) and dump (which contains the program-halt information). You can set thesevalues through SCL.

identity a unique value that distinguishes one object from another. This identifier is referred to as

its object identifier. The object identifier is created by SCL when you instantiate an object with the_NEW_ operator. This identifier is also used as the first-level qualifier in SCL dot notation.

An object-oriented program usually contains different types of objects, each corresponding to a

particular kind of complex data to manage, or perhaps to a real-world object or concept such as a bankaccount, a hockey player, or a bulldozer. A program might contain multiple copies of each type ofobject, one for each of the real-world objects the program deals with. For instance, there could be onebank account object for each real-world account at a particular bank. Each copy of the bank account

object would be alike in the methods it offers for manipulating or reading its data, but the data insideeach object would differ reflecting the different history of each account.

Objects can be thought of as encapsulating their data within a set of functions designed to ensure

that the data are used appropriately, and to assist in that use.

1.2 PRINCIPLES OF OBJECT – ORIENTED PROGRAMMING

It is necessary to understand some of the concepts used extensively in object – orientedprogramming. These include:

1.2.1 Objects

1.2.2 Classes

1.2.3 Data abstraction and encapsulation

1.2.4 Inheritance

1.2.5 Polymorphism

1.2.1 Objects

Objects are the basic run time entities in an object – oriented system. They may represent a person,a place, a bank account, a table of data or any item that the program has to handle. They may alsorepresent user – defined data such as vectors, time and lists. Programming problem is analyzed in

terms of objects and the nature of communication between them. Program objects should be chosensuch that they match closely with the real – world objects. Objects take up space in the memory andhave an associated address like a record in Pascal or a structure in C.

Page 11: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Introduction to OOPS and JAVA 5

OBJECT

DATA

FNCTIONS

Student

Name

Date of Birth

Marks

Total

Average

Display

Figure 1.1 Representation of an Object

When a program is executed, the objects interact by sending messages to each other. For example,

if “customer” and “account” are two objects in a program, then the customer object may send a

message to account object requesting for the bank balance. Each object contains data and code to

manipulate the data. Objects can interact without having to know each others data or code. It is

sufficient to know the type of messages accepted, and the type of response returned by the objects.

1.2.2 Classes

The class is at the core of Java. It is the logical construct upon which the entire Java language is

built because it defines the shape and nature of an object. As such, the class forms the basis for object-

oriented programming in Java. Any concept you wish to implement in a Java program must be encapsulated

within a class. Because the class is so fundamental to Java, this and the next few chapters will be

devoted to it. Here, you will be introduced to the basic elements of a class and learn how a class can be

used to create objects. You will also learn about methods, constructors, and this keyword.

Page 12: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Java Programming6

General Form of a Class

When we define a class, we declare its exact form and nature. We do this by specifying the data

that it contains and the code that operates on that data. While very simple classes may contain only

code or only data, most real-world classes contain both. As we will see, a class’ code defines the

interface to its data.

A class can be declared by using the class keyword. The classes that have been used up to this

point are actually very limited examples of its complete form. The classes can (and usually do) get

much more complex. The general form of a class definition is shown here:

class Class_Name

{

Type instance_variable1;

Type instance_variable2;

……………………. ...

……………………….

……………………….

Type instance_variableN;

Type methodname1(parameter-list)

{

// body of method

}

Type methodname2(parameter-list)

{

// body of method

}

// ...

Type methodnameN(parameter-list)

{

// body of method

}

}

The data, or variables, defined within a class are called instance variables. The code is contained

within methods. Collectively, the methods and variables defined within a class are called members of

the class. In most classes, the instance variables are acted upon and accessed by the methods defined

for that class. Thus, it is the methods that determine how a class’ data can be used.

Page 13: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Introduction to OOPS and JAVA 7

Variables defined within a class are called instance variables because each instance of the class

(that is, each object of the class) contains its own copy of these variables. Thus, the data for one object

is separate and unique from the data for another. We will come back to this point shortly, but it is an

important concept to learn early.

All methods have the same general form as main( ), which we have been using thus far. However,

most methods will not be specified as static or public. Notice that the general form of a class does not

specify a main( ) method. Java classes do not need to have a main( ) method. You only specify one if

that class is the starting point for your program. Further, applets don’t require a main( ) method at all.

Example

Suppose, here is a class called Room that defines three instance variables: width, height, and

length. Currently, class Room does not contain any methods

class Box {

double width;

double height;

double length;

}

1.2.3 Data Abstraction and Encapsulation

The wrapping up of data and functions into a single unit (called class) is known as encapsulation.

Data encapsulation is the most striking feature of a class. The data is not accessible to the outside

world, and only those functions which are wrapped in the class can access it. These functions provide

the interface between the object’s data and the program. This insulation of the data from direct access

by the program is called data hiding or information hiding.

Abstraction refers to the act of representing essential features without including the background

details or explanations. Classes use the concept of abstraction and are defined as a list of abstract

attributes such as size, weight and cost, and functions to operate on these attributes. They encapsulate

all the essential properties of the objects that are to be created. The attributes are sometimes called data

members because they hold information. The functions that operate on these data are sometimes called

methods or member functions. Since the classes use the concept of data abstraction, they are known

as Abstract Data types (ADT).

Suppose, for example, that you’re interested in the Faucet object being developed for the program

that models water use and you want to incorporate it in another program you’re writing. Once the

interface to the object is decided, you don’t have to be concerned as others work on it, fix bugs, and

find better ways to implement it. You’ll get the benefit of these improvements, but none of them will

affect what you do in your program. Because you’re depending solely on the interface, nothing they do

can break your code. Your program is insulated from the object’s implementation.

Page 14: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Java Programming8

1.2.4 Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects of

another class. It supports the concept of hierarchical classification. For example, the bird ‘robin’ is a

part of the class ‘flying bird’ which is again a part of the class ‘bird’. The principle behind this sort of

division is that each derived class shares common characteristics with the class from which it is

derived as illustrated in fig 1.2.

In OOP, the concept of inheritance provides the idea of reusability. This means that we can add

additional features to an existing class without modifying it. This is possible by deriving a new class

from the existing one. The new class will have the combined features of both the classes. The real

appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that is

almost, but not exactly, what he wants, and to tailor the class in such a way that it does not introduce

any undesirable side-effects into the rest of the classes. Note that each sub-class defines only those

features that are unique to it. Without the use of classification, each class would explicitly include all its

features.

BIRD

………………

Attributes, Feathers

Lay, Eggs

Non_Flying Bird

…………………

Attributes

Flying Bird

…………………

Attributes

Penguin

………………

Attributes

………………

Swallow

………………

Attributes

………………

Robin

….……………

Attributes

……………..

Figure 1.2 Property of Inheritance

To inherit a class, you simply incorporate the definition of one class into another by using the

extends keyword. To see how, let’s begin with a short example. The following program creates a

superclass called X and a subclass called Y. Notice how the keyword extends is used to create a

subclass of X.

// A simple example of inheritance.

// Create a superclass.

class x

{

int i, j;

Page 15: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Introduction to OOPS and JAVA 9

void showij()

{

System.out.println(“i and j: “ + i + “ “ + j);

}

}

// Create a subclass by extending class X.

class Y extends X

{

int k;

void showk()

{

System.out.println(“k: “ + k);

}

void sum()

{

System.out.println(“i+j+k: “ + (i+j+k));

}

}

class SimpleInheritance

{

public static void main(String args[])

{

X superOb = new X();

Y subOb = new Y();

// The superclass may be used by itself.

superOb.i = 10;

superOb.j = 20;

System.out.println(“Contents of superOb: “);

superOb.showij();

System.out.println();

/* The subclass has access to all public members of its superclass. */

subOb.i = 7;

Page 16: JAVA PROGRAMMING - KopyKitab · 2018-10-01 · JAVA PROGRAMMING An ISO 9001:2008 Certified Company Vayu Education of India 2/25, Ansari Road, Darya Ganj, New Delhi-110 002 Kamlesh

Java Programming By Kamlesh Rana

Publisher : Vayu Education ISBN : 9789383137220 Author : Kamlesh Rana

Type the URL : http://www.kopykitab.com/product/3234

Get this eBook