Java Bcom

Page 1

PROGRAMMING IN JAVA

IIIBCOM-5Semester SYLLABUS

Unit-1:

Fundamentals of Object Oriented Basic concepts of OOP.

Overview

of Java Language:

Machine-Java versus C++. Unit-2:

Programming: Introduction.

Object

Introduction. Java features. Java program structu

ldentifiers-Literals: Integer literals-character literals-Floating point

m.

iet C.

d*

literals-String

Lterdis.

perators:

Arithmetic operators, Relational operators, Assignment operators. Conditional operators- Variables, Keywords, Data types.

Unit-3: Java Statements: Input and Output Statements, Control Structures: If.. else statement- Switch statement While statement- Do . While statement-For loop- Continue statement-Break

statement.

Unit-4: Classes, Objects & Methods: Introduction, Defining a Class. Adding Variables. Adding Methods, Creating ObjecS, Accessing Class members, ConstructOTS, Method Overloadng. Static members, Nesting of methods.

UnitArrays: Arrays, One-dimensional arrays, Creating an array, Two-dimensional arrays, Creating a two-dimensional array.

Threads: Introduction, Creating Threads, Extending the Threads, Stopping and Blocking Thread, Life Cycle of a Thread.

a

Prescribed Textbook: Programming with Java by E.Balagurusamy. Reference Books: Programming in Java by Sachin Malhotra, OXFORD University Press. 2. Java Complete Reference by Herbert Schildt. 3. John R.Hubbard. Programming with Java, Second Edition, Schaum's outline series 1.

TATA McGraw-Hill Company.


UNIT-11 FUNDAMENTALSOFOBJECTT-ORIENTED PROGRAMMING Introduction to OOP Object-Oriented Programming approach was introduced to overcome the drawbacks o Procedure-Oriented Programming (POP) approach. OOP treats data as a important element i the program development. Ii lies dala more closely to the functions and protects

fro

moditications by outside funetions.

Object-oriented paradigm: OOP was developed to overcome the drawbacks of POP. 2. O0P 1reats data as a eritical clemcnt in the program development. 1.

and does not allow i to tlow freely around the system. 3. In Object oriented programming. programs are divided into a number of entities called objects. 4.

In OOP, Data and Methods are combined together in to a single unit is called Object. Method

Method

Data

Method

Method

5. Everything is represented in the form of object in OOPs. 6. Data is hidden and cannot be accessed by external

methods.

7.

Objects may communicate with each other through the methods. 8. 0OPs provide security to the data. 9 In OOPs, newdata and methods cambe easily 10.

addedwhenevernecessary.

OOPs follow bottom-up approach in the program design. OBJECTA

OBJECT B

DATA

DATA

FUNCTIONS

FUNCTIONS

FUNCTIONS

DATA

OBJECT C


Fmphasis

is

on data rather than

fnctons Programs are divided into sub parts called Objccts. 3Functions and data are tired togcther vithin the ebject 4 Data is hidden and cannot he access by

5. 6.

externa fimctins.

Objects may communicate with each other through functtons. New data and functions can be easily added whenever necessary OOPs follow Boitom-lp approach in program design

S.

OOPs give secunty to data.

Disadvantages of OOPs:

.

2.

OOPs source code is too bigger. hence it requires huge memory. Bottom-Up approach gives a little bit of confusion to the programmer.

3.

Due to the dynanmic binding, the executions of Object Oriented programs are slower

than Procedure Oriented Programs.

Applications of 0OP 2.

Artificial intelligence and expert systems. Simulation and modeling studies.

3.

Object oriented data base systems.

1.

Object 5.

orientedoperating syustems..

Real time systems.

6. Decision support and office automation systems. 7.

CAD(Computer Aided Design)/CAM(Computer Aided Manufacturing) systems.

8.

Multimedia applications graphical user interface.

9.

Computer based training educations.

10.GULbased applieations such as windows applieations 11.

Data recovery systems & Image processing tools.

12.

Distributed systems.

13.

Neural networks and parallel programming. Audio and video manipulation tools.

14.

Benefits of OOP and the user. The OOP offers several benefits to both the programming designer following are the advantages of oopsI. Through inheritance we can eliminate repeated code & extend use of existence class. programs. 2. Data hiding helps the programmer to build secure objects. 3. It is easy to partition the work in to number of to large sy stem 4 Object oriented systems can be casily upgraded lrom small the objects 5. Message passing techniques are uselul for communicatjon between

Nettu Xerox


8.

nheriiance uses to create new data types.

User defined data types can be easily created. 10. Better reliable and portable.

9.

I1. Dynamic linking is available.

Basic Concepts of 00Ps

(or)Basic Features of O0Ps (or)Key concepts of OOPs(or)

00P Characteristics:

The following are the basic concepts of object oriented programming language. 1. Objects 2. Class 3. Data Abstraction 4. Encapsulation 5. Inheritance

6. Polymorphism

. Dynamic binding

8. Message passing

1.Obiects:

Objects are the basic run time entities in an object oriented programming. Objects may represent a person, a place, a bank account or any item. Object takes memory space and has an addresSs. Objects are the variables and classes are data types.

Each object contains data and methods. By using methods, we can manipulate data. ways of representating

Two

Object:

an object

Student

STUDENT|

DATAT

TAL

Name

Date of Birth Marks

COurse Functions

AVERAGE

Total Average

DISPLAY

DISplay (A)

(B)

2. Classes:

Classes are the basic buitding btocks of oops A class is a kind of blueprint or template or internal structure of an object.

a

The

entire set of data and code of an object can be made with the help of class. .Once a class has been defined, we create number of objects belonging to that class.

Class

is a data type and object is a variable

Class |

3. Data

of that class.

Objects

Fruit

Mango.banana,apple

Bike

Hero,Yamaha, Honda

Abstraction:

Removing data

of unnecessary information and representing necessary information is called


dat.i abstTaction.

use the concept of abstraction. and are defined with (variables) and methods (finctions) Casses

a list of

data ilems

Eneapsulation:

4.

Data

Cncapsulation

is

most important feature of class.

process of combining data and methods (functions) Encapsulation.

The

The

.By 5.

in a single unit is known as

data of a class is aecessed by only the methods of same class. using encapsulation. we can accomplish data hiding.

Inheritance:

The process of ereating a new class from old class is called inheritance. Inheritance is very useful to add additional features to an existing class without moditying it,.

.The new class will have the combined features of new class and old class. orz .New class is called derived class or sub class and old class is called super class baseclass. Bird

Feathers eggs

Non-Flying

Flying

Robln

6. Polvmorphism:

Crow

Kiwi

a

to take more than one form with single name. "morphism" comes from the "Greek' word. "Poly" means "many" and

Polymorphism means the ability

"Polymorphism"

means "forms". i.e., many forms. in two more purposes. It's a quality that allows one name to be used data. An action is depends on the type of the Shape polymorphisms. There are two types of Draw() 1. Compile-time polymorphism. 2.

Run time polymorphism. Circle object

Box object

Triangle object

Draw(circle)

Draw(box)

Draw (Triangle)


7.

Dynamic binding Dynamic is

lt 8.

binding means inking

associated

wvith

Uhe

code at the tme of executing the progran.

polymorphism and inheritance

Message passing

A

message for an object

is

nothing but request lo execute

a

procedure.

passing specifies name ol the object, naine of the method (message) and information to be sen.

Message

th

(name)j

Employe

$olary

Objoct

mossago

information

Features of Java Java. The following are most important features of 1.

Compiled and Interpreted.

8.

High Performance.

2.

Platform-Independent and Portable.

9.

Dynamic and Extensible.

3.

Object Oriented

10. Ease of

4. Robust and Secure.

11. Scalability and Performance

5. Distributed.

12. Monitoring and manageability

6-Simple Smalland Pamiliar. 7. 1.

Development

13

Desktop Client-

Multithreaded and Interactive.

interpreted. But Java is both compiled and interpreted language. The Java compiler translates "source code" into "Byte code", and the java interpreter translates "Byte code" into "Machine

Compiled and interpreted: Usually, a computer language

is either complied or

code". 2.

Platform independent and portable: The most important feature of Java language is Portable i.e.,Java programs can easily moved from_one_computer to another, anywhere-

and anytime. Byte code instructions of java programs are executed in any platform using JVM, hence java is platform independent. 3. Object oriented: Java is purely object oriented programming language. Because, all the program code and data must resides with in the class. 4.

Robust and Secure: Java is the Robust and Secure language. Because,

It has strict compile time and runtime checking for errors. Java also supports exception handling to handle

runtime errors. 5.

Distributed: Java

is designed as a distributed

language to create network based applications

(Client/Server applications). 6.

Familiar, Simple and Small: Java is simple and small language. Because, many fearures of c&care reduced in java. All over the world, many no.ol persons are using Java. So that. Java is a familiar language.

7.


III BCOM 5th Sem Java is pertoTmance a Java pertormance: high language. due to the use of Byte codeB 8. High Ising "Byte code .Java increases overal! excctien speed ot pragram

9. Dynamie and exICnsible: Java is a dynamic language. because if is capahie of dyrumie linking. Java supports native methods to extend the programs, devetoped in C arnd C*

JavaHistory Java

8

A

generai

purpose object oTriented programming

Microsysiems of USA in 1991 Origimally java was called OAK"

James Gosling.

by

language devetopcd by sun onc

of

the

inventors of

java

languag2c

as developed lor consumer eicctronic devices like TVs. VCR s arnd such oner Java electronic machines. The main goal of java team is developing of simple. portable and highly re iable language.

Java Milestones: Development

Year

er Sun Microsystems decided to develop special software to manipulate consum clectronie devices. Most popular OOPs language Oak was introduced. new language Green Project team by sun, demonstrated the application of their

1990 1991

1992 1993

1994

tocontrola list of home appliances. on the Internet and transformed the text-based

World Wide Web appeared internet nto a graphical rich environment. A Web browser called "Hot Java" was development.

1995

Oak was renamed as Java.

1996

Sun releases Java Development Kit 1.0 (JDK 1.0) Sun releases Java Development Kit 1.1 (JDK 1.1) Development kit 1.2 (SDK Sun releases Java2 with version 1.2 of the Software

1997 1998

1999 2000 2002

2004

1.2) (J2SE) and Enterprise Edition Sun releases Java 2 Platform, Standard Edition

|

J2EE

J2SE with SDK 1.3 was released.

J2SE with SDK

1.4 was

released.

released. J2SE with JDK 5.0 (J2SE 5.0) was

Structure of Java Program

programming language developed by Sunobjecl-oriented purpose general is a Java Micro Systems in 1991.

is dependent on any particular Hardware Java is the first programming language that not can be executed on any system. or Sofiware. Programs developed in java

A

as shown in the folloM ing program Java program may contain one or more secions

-


cuentation Package

bection Statement

import Statenernts

Stuggested phonal

Optuonai

Intorface Statoments

Optional

Class Detnition

Optional

man) Method elass maint) method detnition

Essenttal

Java Program Structure 1.

Documentation Section: The documentation section contains set of comment

lines

Comment lines are non-executable statements that are ignored by the compiler. The documentation section contains - the name of the program, author and other details. Java supports 2 types of comment lines. They are a) Single line comment //

.*/ b) Multiple line comment /*. 2. Package Statements: The first statement in a Java program is the package statement. This statement declares the package, and informs the compiler that the classes defined here belongs to this package. The package statement is optional. Example: package student; 3. Import Statements: An import statement is similar to Hinclude statement in C or C++ language. The import statement instructs the interpreter, to allocate memory for the

specified classes. Ex: import java.lang.System; Import java.util.*; 4. Interface Statenments: An interface is like a class, which includes a group of abstract methods. This section is used to declare an interface. This is used only when we want to implement multiple inheritance in a java program. are the primary and 5. Class Definition: A Java program can contain multiple classes. Classes on the number of essential elements ofa program. The complexity of the program depends

classes used in the program. a main() method. The main() method 6. maint0 method Class: Every java program contains creates objects of various classes and establishes communication between them.


1.Java Compiie

produces

does not eXist. This machine

an intermediate code known as Bvte code for

called Java Virtual Machine (JVM) and computer memory. is

Java program

it

machine tha

exists only inside the

Virtual machine

Java compiler

Source code 3.

à

Byte code

The Byte code is Machine Independent. The machine code is generated by Java

Interpreter by acting as an intermediary between the virtual machine and real machine.

Byte code

Machine code

Java Interpreter

Virtual machine

Real machine

Functions of JVM: Collecting classes from API (Application Program Interface). 2. Allocating memory to the ohjects 3. Calling methods, Calling I/0 resources. 4. Producing output. 5. Submitting machine code to the processor. 6. Removing memory allocated to the objects. 1.

Comparing java with

C++

IS

C+:

C+ partially

Java object

oriented Java is truly object oriented programming

programming language 21C++ supports operator overloading

B_C++ supports global variables. 41C++ usespointers

C++

supports destructor method.

6C++ uses headerfiles.

C+uses

only compiler. 8 and methods declared outside Variables

language Java does not support operator overloading

Javadoes not supports global variables Javadoes not uses pointers Java uses

finalize()

method

in

place

of

destructo. Java uses import statements in place of header files.

Java uses both conpiler and interpreter. Variables and methods must be declared inside


Java

C++is the superset of

9

is

rnether a superset

neT a

subset ot

ori

C is plattom dependent language multithreading 11C++ does not support

C+

10

Java ts plattorm tndependent language Java supports multithreading.

UNIT-2 JAYATOKENS in the program is called token. Java supports The smallest individual elemeN

5

types

of

lokens. They are . Keywords (Pre-Delined Words) ldentifiers (User-defined Words) 2.

3. Literals

(Constants)

4. Separators

Operators

5. 1.

Kevwords

System or language defined

words are called Keywords.

Reserved words. Keywords are also called Pre-defined words or language. in There are 50 keywords used Java that-purpese-will-pet-be-ehanged-by Key*ordshave-a-speeifie meaning-andpHFpOse, the programmer. keywords in Java language The following are the list of |

abstract

assert

boolean

import

class else double for float instanceOI_ int

New

package

private

static

strictip

throw

throws

catch

Do

finally

short

This

char

Const

byte Continuee

enum

extendS

break

Case

default final implements

goto

if

intertace

long

native

protected Switch try

return_ Synchronized

public

super transient

void

volatile while 2.

Identifiers:

An identifier is a name, given to names, aray names and so on.

Rules for an identilier:

.

a

program element such as variables, constants. functin

digits and underscore only. An identifier must contain combination of alphabets, 2. The first letter must be an alphabet. 3. The length of an idenlilier can be upto 3l clharacler>. 4. Comnmas are not allowed 5. Spaces are not allowed 6 Special sy mbols other than underscore are not allowed


8. An identifier must

not be repeated in

a

program.

Exanmples: a

1otal

stud_no.

3.Literals:Constants): Literals arOgram. The

are constants. They cannot

change their values during the execution of the

following are various types of Literals. LITERALS CHARACTER

NUMBER

LInteger 4.

Floating Point Single Character

String

score are divided Separators: Separators are the symbols used to indicate where groups of and arrange. 1)

Parenthesis

2) Braces

3) Brackets 4) Comma

5 Period 6) Semi colon

5.Operatoors operation. The following operator is a symbol that performs an Arithmetic or logical are the Operators available in JavaAn

Arithmetie operators 2. Relational operators 3. Logical operators 4. Assignment operators 1.

5. Increment and decrement operators

Conditional operators 7. Bitwise operators 8. Special operator 6.

Literals: (Constants); during the execution of the are constants. They cannot change their values program. The following are various types of Literals. Literals


LITERALS

CHARACTER

NUMBER

Floating Point

Integer

Single Character

String

Integer Literalsi

Literal. lractional part{decimal point) is called an Integer Any number without digits (0...9) and sign (+ or -). The integer numbers can contain must not contain commas and spaces. Integer Literal

An

Example: 8

2500

25

-9

Floating Point (Real) Literals:

part(decimal point) is called floating point Literal. fractional with number Any exponen= digits (0...9), a decimal point and/or A floating point number can contain The letter E' or 'e' represents the exponent.

Eg-1: 45.0

6520.2587

Eg-2:-65ES er 6-5E+5

-6847.000 means 6-5x10-

means 6.5x10

6.5E-5

Single Character Literals:

single quotes is known as single characte= within enclosed character single Any Literal. may contain any alphabet, digit or special symbol.

It

It

fo can be used in arithmetic operations using its ASCIL (American Standard Cade Information Interchange) value.

Example

m

n'

9

&

String Literals: one or more characters enclosed within double quotes .A sequence of

is known a

string Literal.

It can contain alphabets, digits or special symbols. It cannot be used in arithmeo

operations.

"A

Ex:

SYSTEM" "SMART CITY"

5. Operators An

operator is

a

symbol that pertorms an Arithmetic or Logical operation.


Operator Binary Operator:

II

an operato acts on Iwo arables

then

it

is

Operator

Ternary Operator:

1i an

operator acts on three variables then

it is

called

Binary

calied Ternar

Operator The following are the Operators available in Java 1.

2.

3. 4.

Arithmetic operators Relational operators Logical operators Assignment operators

5. Increment and decrement operators

6.

Conditional operators

Bitwise operators 8. Special operator 7.

1Arithmetic Operators Arithmetic Operators are use to perform arithmetic calculations. The following are the arithmetic operators.

Meaning

Operator

Addition Subtraction Multiplication Division

vfoduto Division

(Remainder) and operators will work exactly as in mathematics. a=15. b=10 and c=2.5 then

The+-

*

|

Expresion_

Result

at+bc

40.0

a+b-c

a/b_ %b

a

15/4.5 4.55

15

%

If a and b are two integers.

22.5

1(decimal part truncated)

5(remainder)= 3.3333333 1.3

2 Relational Operators: The relational operators are used to compare two values and to give either true or false. These are used to form simple conditions. All the relational operators are applied on any type of data. The following are the relational operators.

Operator | Meaning Is Lessthan_or Is Lessthan equalto Is Greater than Is Grcater than or equalto_ Is Equal to ls notequal to


Expression

Tue 10

False False

13

Tnue

Irue

A

ch ch

False

3,Logical Operators: true

two or more conditions and gives the result cith These operators are used to combine are called compound conditions. or false. These conditions

Operator |Meaning && Logical AND LogicalOR TLogical NOT

otherwis operator gives true if all the conditions are true Logical AND (&&) Operator: This operator is as follows: it gives false. The truth table for &&

Condition1 Condition2 Condition1 && Condition2 TRUE TRUE | TRUE

FALSEE

TRUE

FALSE

FALSE_TRUE FALSE FALSE

| FALSE | FALSE conditions are false otherwise Logical OR ( ) Operator: This operator gives false if all the gives true. The truth table for operator is as follows: Condition1 | Condition2 Condition1 Condition2

TRUE

TRUE

TRUE

|FALSE

TRUE

FALSE

TRUE

FALSE

|FALSE

TRUE |

| TRUE

FALSE

It meanLogical NOT (1) Operator: This operator negates(opposite) the result of a condition. trut if the condition is true then it gives false. If the condition is false then it returns true. The 1able for! operator is as followS:

ConditionCondition) TRUE FALSE FALSE TRUE Example: Let a=15, b=20 then

Expression

a=15b==20

a>15&&b>=20

a=15&&b<=20 !(a==

15)

Result True False True | False

4. Assignment Operators:

The assignment operators are used to assign (store) a value to a variable. An assignnme operator always consists of a variable on leil hand side and expression constant variable e right hand side. There are two types ol assignment operators. Ihey are /

Simple Assignment Operator


The general format

perator

ofthis operator Expression Constant Variable

Variable

above syntax. the value of Expression Variable on the lett hand side of= sign. In the

Eg:

N

y

S5;

is as follows:

/

Variable is assignezi to the

Constant

a =b=S0;

a+b*c;

) Compound Assignment Operators: The general form of compound assignment operators Variable

Compound operator

is as

follows

Expression Constant Variable

In the above syntax, the operator can be either +5,,

*=,

/=or %

Operator | Example Meaning at=b

a=atb

a=b

a-a-b

a=b

a-a*b

a/=b

a=a/b

a%=b

aa%b

5. Inerement and Decrement Operators Increment Operator (++): The increment operator

is a

unary operator. It is used to increase the value of an

The incrementoperator +thas-differentoperand by 1 The operand-must be a_variable in two ways. They is position it is used. It means this operator used meaning depending on the are pre-increment and post-increment.

Pre-increment: it is called "Pre increment". In this If the ++ operator precedes the operand then value of variable tirst and then the new method, the pre-increment operator increments the

value is used in the expression.

means

For example:

aat C

a:

In operator succeeds the operand then it is called "Post increment". and then it is incremented. this method. the old value of the variable is used in expression

Post-increment: If the

+-


Decrement Operator (

Is used to decrease the value of The decrement operator is a unary operator t The decrement operator has differe a operand by i. The operand must be variabie. ways. Th 11scd. Ii mcans this operator is Used in twO it meaning depending on the position is are pre-decremen and post-decrement.

Pre-dccrement:

called "Pre decrement". In th f the value of variable first and then the ne method. ihe pre-dcerement operator decrements value is used in the expressio. mcans C a, a-1 For example:

the

operator precedes the operand then

it is

a

Ca

Post-decrement:

operator succeeds the operand then it is called "Post decrement". lf the-' expression and then it is decremented. method. the old value of the variable is used in means Ca For example: Ca--

a

Initial Values Expression B

a-

In th

1;

Final Values A

a++b ab++

B 8 8

a--b la=b-

6. Conditional Operator:

This operator performs condition based execution. This operator operates on thres operands. Hence it is also known as Ternary Operator. This operator simplifies "if...else control statement. The general form of conditional operator is as follows:

Syntax:

var

(condition) ? Statementl : Statement2;

Example:import java.io.*;

class Largest

public static void main(String args[]) throws 1OException int a,b,large;

DatalnputStream d=new DatalnputStream(System.in);

System.out.print("Enter First Number"),

a=Integer.parselnt(d.readLine(): System.out.print("Enter Second Number"):

b Interer parselnt(d.readLine()


above exanmple, if a-b then the value of variable is assigned to the variable 'large In the

of b

'a' is assigned otfherwise the value

VARIABILES

variable is an identilier that denotes a storage location, usegd to store a data value. variable may take diflferent values at dilferent times during the execution of the program. A

Example:

average

total

A

y

V'ariable names may consists of alphabets, digits, underscorc and dollar characters.

for Variable Names:

Rules 1)

They must not bcgin with a digit.

2) Uppercase and Lowercase are distinct. This means

Total

is not

same as TOTAL.

3) It should not be a keyword.

4) Blank space is not allowed. 5) Variable names can be of any length.

Declaration of Variables: we must Variables are the names of storage locations. After designing variable names, declare them to the compiler. Declaration does three things. 1)

It tells the compiler what the variable name is.

2) It specifies what type of data the variable will hold. 3) The place

of declaration decides the scope of the variable.

for declaration of a A variable must be declared before it is used in the program. Syntax variable is as follows.

Datatype

Syntax: Eg

int

variablel, variable2, variable3.

float

Count,

*******"****

X, Y;

double

.variablen;

pl;

Giving values to variables: and betore it is used in an A variable must be given a value after it has been declared expression. This can be achieved in two ways. ) By using an assignment statement. 2) By using a read statement. to a variable is through Assignment Assignment Statement A simple method of giving value

statement.

Syntax

Variablename = value;

Ex: initialvalue = 0; finalvalue = 100:

yes=X; We can also string assignment expression.


X =y =7=0; It is also possible to assign a vaue to a variable at the time process of giving initial values to variables is known as "initialization".

Syntax:

Datatype variablename

=

oi

ts declaration.

T

value;

Ex: int inalvalue = 100: double total = 75.36:

Read Statement We may also give values to variables interactively through the keyboard using readLine()" method. Ex: DatalnputStream ds = new DatalnputStream(System.in);

intx=Integer.parselnt(ds.readLine()):

The readLine () method reads the input from the keyboard as a string

Scope of a Variable: Scope is nothing but life time of a variable. It tells where the variables are available and wher the variables are not available.

Java variables are 3 types. They are1. Instance Variables 2. Class Variables 1.

3LocatVariabtes Instance Variables: The variables that are declared inside the class are called "Instance variables".

These variables are created when the objects are instantiated. They can take different values and different memory location for every object. 2. Class Variables:

The variables that are declared inside the class with static keyword are called "clas variables"

These variables are created, when the program starts the execution. variables are directly accessed by using a class name without creating an Class object. 3. Local Variables:

variables that are declared and used inside the method are called "Local variables".

The

These

These

variables are created,

henever we call the method. variables are not accessible outside the method.

Example: Class A int

x.

nstance variables


RAO'S

static int a.b; 2 class variables void getl)ata() int m.n:

7Local

variables

DATA TYPES Every variable in Java has a data type. The data type specilies the size and type of data

to

variable. The Java supports the following data types. Data Types in java are classified into Primitive and non-Primitive. is stored in the

DATA TYPES IN JAVA

Non-Primitive

Primitive

Non-Numeric

Numeric

Floating Point

Integer

JCharacte

Class

ArTay

Interface

Boolean

nteger- Integer types can hold whole numbers such as 78,45 etc. The size of the value is depends on the type of the integer data type. Java supports 4 types of integer data types. They are

Integer byte

short

int

long

Sizeand Range of Integer types:

Type byte

short int

long

Eloating point:

Size Tbyte 2 bytes 4 bytes 8 bytes

Minimum Value 128

-32,768

Maximum Value 127

2,147,483,648

32,767 2,147,483,647

-9,223,372,036,8555

19,223,372,036,854

loating point types holds the number containing fractional parts such as 45.9. 9.8 etc. Java Supports 2 types of floating point data types.


vap

Floating

oat

doubie

Size and Range of floating point types: Type

loat double

Size

Minimum Value

4byte 8bytes

34c-038 1.7e-308

Maximum Value 34c-038 1.7e+308

Character:

Java provides a character data type called "char". The char type can hold one charace li occupies 2 1Bytes of memory.

Boolean:

Boolean data 1ype is used, when we want to store the result of the condition. Boole data type is defîned by using the keyword "Boolean" and uses I bit of memory. Here I bi nothing bur either 0(false) or (true). 1

UNIT-3

INPUT AND OUTPUT STATEMENTS A stream is the way (path) to transfèr data from source to destination. Both source

destination are either physical devices or programs.

Stream Source LL----*

Destination

Stream classes: The java.io package contains a large number of stream classes to handle input output stream operations on all types of data. There are two categories

Java Stream

Byte

Character

Streamn

Streamn


Byte Stream classes are designed tor creating and manipulating streams by reading and writing bytes. Java proVIdes tiwo Kinds of byte stream classes.

Byte Stream

Input Stream

Output Stream

(a). Input Stream Classes: All the Input Stream classes are derived from the base class InputStream. The InputStream class is an abstract class. therefore we cannot create object to it. The InputStream

class provides several sub classes to perform various input operations.

Object

InputStream

SequencelnputStrea

FilelnputStream

PipelnputStream

ObjectlnputStrea

ByteArraylnputStrea

InputStream class Methods: Method )

1.

read(

2.

read(byte b[ ])

Description Read a byte from the InputStream

Reads an array of bytes

3. available()

Returns the no.of bytes available in the InputStream

4. skip(n)

Skips n bytes from the stream

S.resetl 6. close()

Return back to the beginning of the stream

Closes the InputStream


Streann Casses: derived from the use class OutputStream Al ihe Outpuu Stream classes re to it class, therclore we canot creatc objecl The OutpuiStrcam class is av1 abstract operations. sub classes to perlorm variotus Output The OutputStreanm class provides several

().

Dutut

Objet

OutputStrcam

SequenceoutputStrea

PileoutputStream

ObjectOutputStrea

PipcOutputStream

BytcArrayOutputStream

OutputStream.class.Methods: Method

.Writel) 2. Write(byte b[ })

3.close()

4. flush (11).

)

Description Write a byte from the OutputStream

Writes an array of bytes to the OutputStream

Close the OutputStream

Flushes the OutputStream

Character Stream classeS:

Character Stream classes are designed for creating and manipulating streams by readi and writing characters. Java provides two kinds of Character Stream classes.

Character Stream Classes

Reader

Writer


he

Readler class

designed to rend characters Irom the iles (or) streams Rcader ciass class tor all Rcader Stream classes The the functionalhty of Reader Stream classes rs similar to the nput Sream classes. eNcept Input streams uses bytes while the Reader sUems usCs characters, is

ase

Object

Reader

BuflcredReader

InputstreamReader CharArrayRecader

StringReader

(a). Writer Classes:

The Writer class is designed to write characters from the files (or) streams. Writer class is the base class for all Writer Stream classes. The functionality of Writer Stream classes is very

similar to the.Ouput Stream classes, except Oulput streams-uses.bytes while the Wriier streams uses characters.

Object

Writer

OutputStreamReader

BufferedWriter

CharArrayWriter

StringWriter

CONTROL STATEMENTS (or) CONTROL STRUCTURES Generally Control

any high level program will be executed in sequential manner. With the

statements. the sequential flow of execution will be altered. The follow ing are dirteren available in Java.


n Jaa. t/ht

coirol statenses

Stth nditinhel iprerge

Conditional Control Statements statemer are also known as Decision Making Statecments Control Conditional The statemer= programmer to select one particular group of the allow statements The conditional typthe given condition. There are mainly three on depending groups available several from

are of conditional statements. They 1.

if or if...clse statenment

2.

switch statement

3.

Conditional Operator Statement.

Decision Making with if statement: different-forms depending on the complexity= statement maybe implemented.in

Theif

conditions to be tested. Simple if statement If...else statement 3. Nested if...else statement. 4. Else if ladder. 1.

Simpleifstatement;

statement that The if statement is a conditional control based on the executes the specilied set of instructions condition. The general form of simple if stalement is

if

Condition

Flow Chart Onaitun

True

Statement - block; Statemeit-tu

- block may be

single statement or a in the group of statements. I1 there is only a single statenent statement block, there is necessity of curly braces (). The statement

a

Xerc


Flowchar

if ondition Statement

e

t

als condienal

-

blockl

clse

Statcment- block2 t

i (n°%2==0)

Ex

ttesment.Ps8

System.out.printin("lven Number"):

clse

System.oum.printn("Odd Number"

Nested

if...clse statement: When the 'if.clse' statement

nested if

another if...clse statement then statement. The general format is as follows: is used witlhin

Syntax:

if (condition1)

if(condition2) statement-block1: clse

statement-block2; else

if (condition3) statement-block3; else

statement-block4;

L

In the above syntaxi.

i. ii.

is

executed

lf conditionl' and 'condition2' are irueisthen stament-blockl stament-block2 is exeeuled If conditionl' is true and 'condition2" is false then then stament-block3 is executed false and 'condition3' true is conditionl' and 'condition3' are lalse then stament-block4 executed

If 'condition1' is

V.If

Cond-I

nd2

Stateent.bick

ateiment nlk

it is

called


Ex:

Class Nesting public static void main(String args|)

a=10.b-20.c=40: Sytem.out.print("Larget value int

if

is

:

"):

a>b)

ifa>c) System.out.prmln(a): else

System.out.printn(b): else

if (b>c) System.out.println(b); else System.out.println(c);

Switch Statement:

The 'switch' statement is a multiple condition statement. It can be used to make, decision from the number of choices. It is an extension of if...else' statenment. The gener

fomat of switch statement is as follows: Syntax: switch (op)

v:

statement-block1; [break;] case V2:statement-block2; case

Thras]

|case Switch (op)

Case

vnstatement-block-n;

[break;] statement-block-d;]

V

Statement-block

In Case V:

Statement-block2

op Stateiicnl-biock-n

the above syntax, 'op' is an integer character. Vi V2 constants that represent the value hese are the constants of eih integer or character type.

Vare

.


Program Class

Weeks

Dublic statie void

mani String args|

])

int op S, Switch (op)

case

1:

System.out.printn"Sunday"): break:

case 2: System.out.printn("Monday"); break: case 3: Systiem.out.printn( "Tuesday") brcak; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday'"): break: System.out.println("Friday"): case 6: break: case 7: System.out.println("Saturday"); break: default:System.out.printin("Wrong Value");

Repetitive (Or) Looping (Or) Iterative Control Structures The repetitive control statements are used to execute a group of statements repeatedly (or) for a specified number of times. The repetitive control statements are also called lterative Looping control statements. In Java, there are

3

types of repetitive control structures. They are

-

While Statement 2. Do..while Statement 1.

3. For Statement

Any looping statement statement involves following

Initialization 2. Condition checking 3. Statements execulion

stepsS

1.

4. Incrementation

condition

Stalenent-block


loop ,wle is saement

pecified condition

used satisfied.

is

is

Syntax:

tO It

as long a execute one or Inore statement5 repeatcdiy is an entry control loop structure.

while (condition)

statement-block:

Ce In the above syntax.

be enclosed within parenthesis. The condition' is a relational expression that must statements. When there is more than 2. The statement-block specifies one or more statement, they must be enclosed in braces ({}).

.

wTite

Program:

to

class Nums

Uv lo0

faanwhietoPrint loop

nuwbw Youn

inq

public statie void main(String args[

]})

int i=1;

while(i=100) System.out.print(i); ++i;

Output:

1234.......100 Do...While' Statement: This statement is_used to execute one or more statements repeatedly as long as specified condition is satisfied. It is an exit control loop structure. The do..while struetu executes the statement part at least one time either the condition is true or false. Syntax: Do

statement-block;

while (condition);

Programn: class Dums public static void main( String args[ ]) int


Svstemm.Out.printii}:

++1

whileti<100):

Je

Output:

For Statement This statement condition is

satistied.

is

used to execute a set of statements repeatedly as long as the specitied n entry control loop structure.

It is

Syntax:

tor(initialisation:condition; increment/decrement) statement-block;

It evaluates the initialization part first and then

it checks the condition. If the condition it is true then executes all the statements in the statement-block. After executing all the statements. increment'decrement part is executed. This looping process is continued as long as condition is true. When the condition becomes false. the loop is terminated.

ProyTaMS: class Fnums

public static void main(String args[ }) int i;

fori=1: is=100:it+) System.out.print(i);_

Output:

T234......I00 Unconditional Control Structures The unconditional control statements are used to change the execution sequence of a program by transferring the control from one plac to another place within a program without using any condition. The following are the unconditional control structures used in Java language.

.

Break Continue

Retun

Break Statement: he break statement can be used in three ways


II BCOM 5th Sem Java

RAO'S DEGREE COLLEGE

used inside a loop to come out of it of ihe block 2) break is used inside the switch statemeni to Ceme oul 3) break is used in nested blocks to go to the end of the block is

A)break

Syntax: Break;

(or) Break label; f6x imperct iog

Jaa plam

Example:

in a

ap

class Btvwo

classBone public static void main(String args| int

bea

statencnt

public static void main(String args | )

D

int i. j

1

outer for(i=1:i<=100;i++)

for(i-1:is=100:i++) System.out.print(

i

Inner: for (j=1:j<=100: j++)

):

ifi=50)

System.out.print( j

break:

);

ifj-50) break outer:

output:

1234......50

Continue Statement:

Continue statement is used inside a loop to repeat the next iteration of the loop. Whe continue statement is executed, the next statements in the loop are not executed and control « execution goes back to the next repetition of the loop

Syntax:

Continue; (or) continue label;

Example class Ctone

|

public static void main(String args [)

class Ctwo public static void main(String args [})

inti for(i-1: i<=10; i++)

outer: for(i=1; i<=10; i++)

if(i-4

Inner:

||

i--7)

continue; System.out.print( i );

int i, j3

for (j=1;j<=10; j++)

if4

||

j=7)

continue outer; System.out.print( 1);

Ouiput:


retun statemenl statement

is often

is

used in

used in

method the methods. a

to

come

oul

of

it to the

calling method. return

Examples return (x+y): {/calculates x+y and return that value return -5; il return -5 to the calling method. :

oRdam

Jo

class Deino

toue

etuxn

gtatemert

public static void main( String args | |) int res=Demo.square(10):

System.out.println("Result ="

+

res):

static int square(int num)

return( num

*

num:

utput: Result= 100

Demo.square ( 10)

I.write a Java program for finding the sum

return num

of two numbers

import java.util.Scanner; class Adds

public static void main(String argsH}int x,y,z,

System.out.println("Enter two integers to calculate their sum"); Scanner in=new Scanner(System.in); x=in.nextInt();

yin.nextInt(); Z-Xty; System.out.println("Sum of the entered integers=" +z);

OUTPUT:

er }9

two integers to calculate their sum

*

num


RAO'S DEGREE COLLEGE

90

Sum

ot entered

integers

O0

the numbor in descending ori rder display to loop for Write a Java program using

.

class Descends

public static void main(String args|]) int n=10:

System.out.printn("Descending order from 10°) for(int i=n;i>=0;i--) System.out.println(1); }

OUTPUT: 10 9

8

0

3,Write- a-Java program-to-display even-numbers from1to_100class Numl

public static void main (String args[]) int n;

for(n-2n<=100;n=n+2) System.out.println(n);


RAO'S DEGREE

III BCOM 5th Sem Java

OUTPUT

100

4.Write a Java program to find the sum of the following series

1+2+3+4+5+.

+100

Program: class Snums

public static void main (String args[]) int n,sum=0;

for(n=l;n=100;n++) {sum=sumtn; System.out.println("sum of numbers"+sum);

QUTPUT: Sum of numbers: 50500


UNIT-4 Classes, Obiects & Miethods

Class: e

class is a collection of telated objects that share cammen properties and methed Classes arc uscd to pack a group ot data iterns and tuncticoTTi in java The data items arc called "licids and iunctions are callcd "methods A

Defining a Class: Classes are delined using the keyword "Class" once a ciass is defined. we can create an number of objects bclong into that class. In java these variable called "instances of classes" A

class is

a

user-defined data lype.

The

class variables are known as objects.

Syntax: class classname

Ficlds declaration Variable Declaration Mcthods deelaration

Ficlds Declaration /\Variable Declaration: variables ar The variables which are declare inside a class are called "ficlds" These the class is instantiated also called instance variables they are created when ever an object of

Example: class Rectangle int length; int width

no memory space The class rectangle contains two integer type instance variables

reserved for these instance variables.

Merhods TDeclaration a Methods are necessary for manipulating the data containing that class. Methods thhe class immediately atter the declaration of instme declared and defined inside the body of variable.

Syntax:

returntype methodname (Parameters list) Method body Method declarations have 4 basic parts . The name of the method ( method nanme) 2. lhe ype of the value that the nmethod returns (return type) 3 A list of parameters( parameters ist) 4The body of the method ( Method body )


RAO'S

iII

DEGREE

Example class Reclangle int length. Width:

Void getlData (int s, int y)

lengh=x width y:

Obiects:

An object is a block of memory that contains space to store all the instance variables.

Creating objects: Creating an object is also referred as instantiating an objcct In java objects are created using the operator new The new operator creates an object of the specified class and returns

a

reference to

the object

Class name obj

Syntax 1:

Obj

F

//

new class name

ClassName obj Rectangle r

Syntax 2: Ex

;

new Rectangle ();

=

(

declares the object Insatiate the object ); /

new className

( );

INow r' is a reference to rectangle object

Accessing Class Members: We can not access the instance variables and methods directly from outside the class. To access them from outside the class we must use the concerned object and the dot operator ( .)

objectname.variable = value; Objectname.methodName(parameters List); Here object name is the name of the object method name is the name of the method that we

Syntax:

wish-te-callProgram: Java program to define Rectangle class and calculate area. class Rectangle int length, width

void getData( int x , int y)

length = x; width = y int area (O

Return length

*

width:


class RectArea public statie void main (String args ) int areal. area2: Rectangle rl = new Rectangle Rectangle r2 new Rectangle rl. length -20: |

=

rl.width 10: areal =rl.length

(

):

(

):

=

*

rl.width:

r2.getData (20.40): area2=12.area( ): System.out.println (" areal System.out.println ("* area2

Output: Area 1 Area 2

=

200

=

800

= =

*+area): *+ area);

Constructors A

w used to initialize the instance variable constructor is special member function. It is

object is created.

characteristicsThe constructor has the following sarme as that of its tiass Tiame Constructor amE Must be 2.

It is declared with no return type

3.

constructor A class can have more than one

when the objects are instantiated. 4. Constructor is called automatically and executed variables to receive may or may not have parameters. Parameters are the

d-

A constructor

constructors. They are from outside. Java supports two types of 1.

Default Constructors

2. Parameterized Constructors.

1. Default Constructors:

II Default constructor is the constructor which does not accept any parameters. dela constructors are defined for a class, the java system automatically generates the

constructor.

Syntax:

Ex

ConstructorName (() Constructor body

Rectangle() length =0

WidthU: Net4u Xer


2.Parameterized Constructors: Parameterized constructor is the constructor which accept at least one parameter.

ConstruciorName (Parameters list)

Syntax:

Constructor body

Rectangle

Ex:

(

int x. int y)

length = *: width = y:

Constructor Overloading This is An interesting feature of the constructor is that a class can have "multiple constructors". to its called constructor over loading. All the constructors have the same name as corresponding

arguments (or) data class name. But they defer only in terms of their signature. As number of types (or) order.

Program: Class Rectangle int length, width;

Rectangle(O_ length =0; width =0;

Rectangle ( int x, int y) // parameterized constructor length =x; width = y; void area () {

width; System.out.println (" srea of rectangle =+a); int a= length

*

Class Rareas public static void main (String args[})

Rectanglerl

=

Rectangle 12

=

rl.arca r2.area(

(

): ):

new Rectangle ();// calling default constructor new Rectangle (5,10); ll calling parameterized constructor


Output: Area of rectangle= 50

Method Overloading in

java

it is

possibie to ereate methods that have the same

nanie

bul With dillerenn param amele

overloading. lists and dilierent detinitions. This is called Method w overloaded methods we have to provide dilferent ncthod delinition be is number of arguments ( the same name with difterent parameter list. The dilference may be uniquc. type of arguments. That is each parameter list should To create and

perfornm similar tasks but usi Method overloading is used when objects are required to in an object. java searches tor the meth different input parameters when we call a method

decide which method to execute name tirst and then the number and type of parameters to

t-

process is known as polymorphism.

Example:

Class Arithm int add

(

int x,int y)

Return(x+y); float add (float x, float y)

return (x+y);

Class Movload

publiestatie-void-main-fString-args{}Arith a =new Arithnm ( ): int m= a. add(3,4);// calling method float n=a. add(4.5,3.6); // calling method2 System.out.println ("integer Addition=* +m): System.out.println (" float addition=" +n):

Output:

Integer addition =7 Floating addition =8.1

38

Net4u

Xez


Static Members Static Members:

1.

The members ihat are declared as static are called static members methods

ol a claSs

can be declared as

Botih vartanies

and

static

are associated with the elass rather than objects

2.

These members

3.

Static variables and methods are referTed as class variables and class

methods

Static Variables:

.

The variables

that are declarcd inside

a

class with the keyword "static

are

calied

staii

variables. 2.

Static variables are used when we want

a

variable that is common to all object

oI tne

class. 3.

Static variables can be used with out creating an object.

Syntax:

Syntax:

static datatype variablename; name directly Static variables can be accessed by using the class

ClassName. StaticVariableName; Ex: Math. Pl;

Staticmethods: 1.

"Static the keyword static are called with class a inside declared The methods that are

methods". static access only static variables and 2. A static method can members of the class. 3. It can't access non static name (parameter list) static return type method Syntax:

methods.

Method body directly using the class name by accessed be Static methods can (parameters list); StaticMethodName class name. Syntax: Ex: Math.pow (2,3);

Ex:

class Arithms x, int y) public static int max (int

int i

i= (x>y) ? x:y; return

i:

class Slarge 39

Nettu Xerox


publie static void main (String args|

m

})

.

Arithms .max(2.10):

Sy stem.oul.println "Maximum

Output:

Maxium

=10

NETSTING OF METIIODS by an object of that class (or class itself, A method of class can be called only operator. ofstatie nethods) using the 'dot'

in the c

same class. by another method of And a method can be called by using its name This is known as 'nesting of methods"'.


UNIT-5 ARRAYS AND THREADS Array 1.

An array is

a groupof

memory locations that share same name and data type 2. The elements of an array are stored in continuous memory locations. 3. Elements of an array can be accessed through a number called "Inder. 4. The index of a first element is 0' and the index of the last element is 'size-1".

Types of Arrays: 1. One -dimensional arrays 2. Two-dimensional arrays 3. Variable size arrays 1.

One-dimensional array:

When an array is declared with only one-dimension (subscript) then it is called as one dimensional array.

Creating

an array:

Creating an array involves 3 steps. 1. Declaring an array 2. Creating memory 3. Assigning values

1.Declaring thearray Arrays in java may be declared in two methods. They are Method 1: datatype arrayName[ l:

Eg int

al

Method 2:

datatypelI arrayname;

Eg: int[ ] ax 2. Creation of arrays: -Like elas5-ebjects, +memery-is-altecated fer-arrays-using-the-keyword-called new

Sntax:

arrayname=new datatype|size]; Eg: a =new int[10];

3.Assigning values: The final step is assigning the values into the array. This is possible by using index of the array elements.

Syntax: arrayname[index]=value; Eg: al4]=10; a[3]-20; It is possible to

combine array declaration and memory allocation in a single line by using the lollowing syntax.

Syntax: datatype arayname J=new dataty pejsize Eg int ajnew

int|10}:


III BCOM 5th Sen Ja

RAO'S DEGREE cOLLEGE new float[5: tloat b[ }

Initializing an array Tne proCCsS

Ol

assigning \alues

lo an anay

nitializng an arro

Syntax:datatype aray name[sizel Eg: int alS| 10,15.20.25.30:

Arraylength: ln java,

We can

al the

tme

oi

dcciaration

is 1s

cal

{valuel.valhue.

ealculate array size by using

a

special variable called length.

it retu rr.

size of the array as Integer.

Syntax: arrayname.length; Eg: int x = a.length: Program: Java program to initialize and display array elements import java.lang.System; import java.lang.String; class Array1

public static void main(String args[]) int al -{45,10,22,33,65

System.out.println(Array elements are"); for(int i=0;i<a.length;i++) System.out.println(a[i]l):

Output: Array elements are 45

10 22 33 65

2. Multi-dimensional arrays; An array that contains two or more subscripts then it is called "Multi-dimense array". Multi dimensional arrays are classified as tw0-dimensional, three-dimensional. I dimensional and so on.

Two-dimensional array: An array that contains two subscripts then it is called *Two-dimensional array. kinds of arrays are used to represent data in the forms

of rows and columns.


Row

Row

(0,0)

(0,1

(0.2)

(0,3)

(1,0)

(1,1)

(1,2)

(1,3)

(2,0)

(2,1)

(2,2)

(2,3)

(3,0)

(3,1)

(3,2)

(3,3)

1

2

Row 3 Row 4

Columnhl

Column2 Column3

Column4

Declaration of fiv0 dimensional arrays: Two dimensional arrays are declared

in two

methods

as follows.

Method1: datatype array Name[ J0: Eg int a[ JU Method2: datatype[U0 arrayName; Eg int [ I a: Memory-llecation: 1

Spntax: arrayName= new datatype[ rows||columns Eg: a new int[3]14]:

J;

Initializinga two dimensional array: Syntax: datatype arrayname[row size][column size]

=

{{rowl values}, {row2 values}, ..., }:

Eg

inta[2]13)={{4,6, 8),{1,3,5};

are combined in a single line using the Both declaration and memory allocation

following syntax.

Syntax: datatype arrayname[ Eg: intal 1[

]==

}|

J= new datatype|row size|lcolumn size|;

new int[3]|B];

Example Program: two-dimensional array. Java program to demonstrate a class Array2

public static void main(String args|})


int a ilnew

intjsI1S}

tori0.i

tori 0,is

alJlil itj

Sy

stem.out printh"Amay clements are"}

fori t)iri) fori 0 ci) System.out print(ali}i): System.out printn(" "):

Output: Array clements are

2

3

3 4

S6 S6

4567

7

S

Thread: 1. A Thread is a process thathas a single flow ofcontrol. Theprograns which have o one flow of control are called as "Single- Threaded Programs" 2. A unique property of java is its support for multithreading. Executing

threads simultaneously threading".

by a single computer

is known

Main Thread Main Thread

Program

start()

Thread

Switchin A

Thread

B

switchin

Creating Threads: There are two methods to create threads in java 1. Extending Thread class 2. Implementing Runnable Interface

Thread CC

two or

as

*

:

m


includes

the following si eps. . Define the class thal cxtending the Thread class. Override the run() mcthod, by placing the code of the process. Create u Thread class object Call the start() method to invoke

run{) mcthod.

Program: i.mport

java.lang.String

i mport java.

lang.System; java. fmport i lang.Thread; A extends Class Thread Public

void

run(

)

for (int i=2; i<=10; i++) System.out. println (""Even=

class

B

extends

Public void

"+1);

Thread run()

{

for (int j=2; System.out.println

j<=10;

j=j+2) ("Odd=

"+j) ;

Toddeven

Class

public

A obj=new B

void

static

objl=new

obj.start(

obj1.start

A() B(

main (String

args[

Output: Even

=

2

Odd= Even = 4 Odd = 3 Even = 6 Odd 5

Even =8 Odd 77 Even = 10

)

) (()

Odd

9

2. Implementing Runnable Interface: a class that implements Runnable interface. Define the run{) method. Implement Create a Thread class object and pass newly created implementation object as a parameter. Call the start() method to invoke run{) method.

class

Program: 1mport import npor

L

java.

lang.String;

java.

ang.Systen

Va.

ang.

nIead;

45

Net4u Xerox


RAO'S DEGREE

iuPlement s

Class

for1rt System.

1

out rt.

EYern

run

void

for(int

T1

Runnable

Iemen Pubi iC

urihat.

j-2;

j<10;

System. out.printIn

jj'1) ("Odd

OutputE

"+j)

Even =2

Odd

Thtwo

Class

A

void

static

public

main (String

argsl

obj=new A()

objl=new B() Thread tl=new Thread (obj) Thread t2=new Thread (obj1); ); t1.start B

i

Even = 4 Odd 3 Even = 6

Odd = 5 Even=8 Odd 7

Even

10

Odd 9

(

t2.start(

)i

STOPPING AND BLOCKING A THREAD Stopping

a Thread:

we may do by ca Whenever we want to stop a thread from running further, its stop() method.

Example: obj.stop( Here objis a Thread object. A thread will This statement causes the thread to move to the Dead state. move to the dead state automatically when it reaches the end of its method. before stop() method may be used when the thread is to be stopped

completion. Blocking A

a thread:

thread can also be temporarily

suspended

(or) blocked from entering

runnable and running state by using the following thread methods. 1. sleep() //blocked for a specified time. 2. suspend 3

waiU)

()

}

blocked until further order

// blocked until certain condition occurs

into


The thread

will retuirn to the

sleep(

),

notify(

)

runnable state when the specilicd time the resume ( ) method is invoked in the case method is called in the case of wait( ) method.

is

of

clapscd

in

suspend(

the case ol ). and

the

THREAD LIFE CYCLE

The thread enters into following five states during its life tinne 1.

New Born state

2. Runinable state 3. Running state 4. Blocked state 5. Dead state

New Born

Start()

Stop()

Stop)

Active Thread

Runnable

eld

Dead

Running

Suspend()

resume()

Steeptt

notifyo-

Killed Thread

-Stop}-

wait()

Blocked

Born state: When we create a Thread object, then thread is in New born state. At this state, we can do only one of the following things. Scheduled it for running using.start() method.

1. New

Kill it

using stop() method.


NeW

stop() start)

Dead

Runnab

execu

2.

Runnable stat

cution, d is Wai is ready for thrcad the ned the quec has joined In this state 1s, the thread

availability of the Ior the

processor. That

threads. Yield() ( ***

Runnin

3.

Runnable Threads

given itetin the processor has that means state bu nar Running state: RunningThe running thread may stop it's execution ca execution. the thread for me= following methods. using the Suspend) any one of the suspended The Thread has been a) Suspend: method. with Resume() starts again and Suspend0

Running

Resume() Blocked Runnable

for a specified time using sleep been has Thread b) Sleep(): The after the specified time. method, and execution continues

Sle

Suspend(0

After Running

c

Runnable

Blocked

ing has been wait for occurring of some events us method, and again starts with the Notifyl) method.

WaitL: The Thread I

48

NerHu


Runnng

Notily(

Runnable

Blocked

A Thread is suid to be Blocked state, 4. Blocked state: suspendecd or sleeping or waiting.

5.

state:

A

whetier

the Thread

Thrcad is said to be Dead state, when it's Runf completes the execution or by calling Stop() mcthod.

Dead

) method

is


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.