You are on page 1of 170

STUDY MATERIAL

PAPER NAME: PROGRAMMING IN JAVA

SEMESTER: V

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 1


DEPARTMENT OF BCA
PROGRAMMING IN JAVA

SYLLABUS

UNIT: I

Introduction: Introduction to Java – Java and Internet – Byte codes – Features


of Java – Java Development Environment – Java Character set – Operators – Control
statements – Simple programs – Java History and Feature – Java Development Kit (JDK) –
Java Tokens – Java Statements – Arrays and Vectors – Strings and StringBuffers.

UNIT: II

Classes, Interfaces and Packages: Classes – Objects – Wrapper Classes –


Packages and Interfaces.

UNIT: III

Inheritance: Inheritance Extending classes – Abstract and Final classes –


Interfaces and Inheritance

UNIT: IV

Exception Handling: Error Handling and Exception Handling – Exception


Types and Hierarchy – Try Catch blocks – Use of Throw, Throws and Finally – Programmer
Defined Exceptions.

UNIT: V

Applets and Graphics: Fundamentals of Applets – Graphics. AWT and Event


Handling: AWT components and Event Handlers – AWT Controls and Event Handling

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 2


Types and 35 Examples – Swing- Introduction. Input and Output: Files – Streams.
Multithreading and Networking: Multiple Threads – Networking basics.

BOOK FOR STUDY Programming with Java, 4th Edition, E. Balagurusamy, Tata McGraw
Hill Pub. Ltd., New Delhi.

BOOKS FOR REFERENCE ―The Complete Reference‖ Java2, 3rd Edition, Patrick
Naughton, Herbert Schildt, Tata McGraw Hill Pub. Ltd., New Delhi.

REFERENCE WEBSITE:

Www.Wikipedia.Org

Www.Homeandlearn.Co.Uk

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 3


QUESTION PAPER PATTERN

TIME: 3 HOURS MAXIMUM: 75


MARKS

PART – A (10 x 2 = 20 Marks)


Answer all Questions
Answer to each question shall not exceed six lines
1. From Unit – I
2. From Unit – I
3. from Unit – II
4. from Unit – II
5. from Unit – III
6. from Unit – III
7. from Unit – IV
8. from Unit – IV
9. from Unit – V
10. from Unit – V
PART – B (5 x 5 = 25 Marks)
Answer all Questions
Answer to each question shall not exceed three pages
11. A. From Unit – I (OR) b. From Unit – I
12. A. From Unit – II (OR) b. From Unit – II
13. A. From Unit – III (OR) b. From Unit – III
14. A. From Unit – IV (OR) b. From Unit – IV
15. A. From Unit – V (OR) b. From Unit – V

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 4


PART – C (3 x 10 = 30 Marks)
Answer all Questions
Answer to each question shall not exceed six pages

16. A. From Unit – I (OR) b. From Unit – I


17. A. From Unit – II (OR) b. From Unit – II
18. A. From Unit – III (OR) b. From Unit – III
19. A. From Unit – IV (OR) b. From Unit – IV
20. A. From Unit – V (OR) b. From Unit – V

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 5


AVS AND SAKTHIKAILASSH GROUP OF INSTITUTIONS
DEPARTMENT OF BCA
JAVA

UNIT: I
----------------------------------------------------------------------------------------------------------------

Introduction: Introduction to Java – Java and Internet – Byte codes – Features


of Java – Java Development Environment – Java Character set – Operators – Control
statements – Simple programs – Java History and Feature – Java Development Kit (JDK) –
Java Tokens – Java Statements – Arrays and Vectors – Strings and StringBuffers.

----------------------------------------------------------------------------------------------------------------

INTRODUCTION

 Java is a high-level programming language originally developed by Sun Microsystems


and released in 1995.
 Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX. So java is platform independent.
 Language that supports oops features includes small talk, objective C, objective C++,
and object pascal.
 The latest is java a pure object oriented language.
History Of Java
 In 1990, Sun Microsystems started a project called Green.
 Objective: to develop software for consumer electronics.
 Project was assigned to James Gosling, a veteran of classic network software design.
Others included Patrick Naughton, ChrisWarth, Ed Frank, and Mike Sheridan.
 The team started writing programs in C++ for embedding into
– toasters

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 6


– washing machines
– VCR’s
 Aim was to make these appliances more “intelligent”.
 Java was “re-targeted” for the Internet
 The team was expanded to include Bill Joy (developer of Unix), Arthur van Hoff,
Jonathan Payne, Frank Yellin, Tim Lindholm etc.
 In 1994, an early web browser called WebRunner was written in Oak. WebRunner was
later renamed HotJava.
 In 1995, Oak was renamed Java.
 A common story is that the name Java relates to the place from where the development
team got its coffee. The name Java survived the trade mark search.

Types of Applications

 In IT we are developing two types of applications; they are


1. Standalone applications and
2. Distributed applications.
 A standalone application is one which runs in the context of local disk. With
standalone applications we cannot achieve the concept of data sharing. For example C,
C++, COBOL, PASCAL, etc.
 A distributed application is one which always runs in the context of Browser or
World Wide Web. All distributed applications can be accessed across the globe.
For example JAVA and DOT NET.
 Using java we can develop
1. Desktop Application à Run in single machines
2. Web Application àRun in multiple machines

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 7


JAVA AND INTERNET
 Java is strongly associated with the internet because the first application program
written in java was Hot java
 It is a web browser to run applet on internet
 Internet users can use java to create applet programs & run them locally using a “java
enabled browser” such as Hot java
 The ability of java applets to catch a ride on the information super high way has made
java a unique programming language for the internet.
 Due to this, java is popularly known as internet language.

BYTE CODES

 All language compilers translate source code into machine code.


 Java compiler produces an intermediate code known as byte code for a machine that
does not exit.
 This machine is called the java virtual machine.
 The process of compiling a java program into byte code is referred to as virtual
machine code.

Java compiler Virtual machine


Java program

SOURCE CODE BYTE CODE

 The virtual machine code is not machine specific.


 The machine specific code (machine code) is generated by the java interpreter by
acting as a intermediary between the virtual machine and the real machine.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 8


Byte code Java interpreter Machine code

VIRTUAL MACHINE REAL MACHINE

 The java object frame work acts as the intermediary between the user programs and the
virtual machine which in turn acts as the intermediary between the operating system
and the java object framework.

FEATURES OF JAVA

1. Compiled and interpreted. 6. Platform - independent and portable.


2. Object oriented 7. Robust and secure
3. Distributed 8. Familiar, simple and small
4. Multithreaded and Interactive 9. High performance
5. Dynamic and Extensible
Compiled and interpreted
 Java is a two-stage system that is both complied and interpreted language.
 First java compiler translates source code into byte code instructions.
 The byte codes are not machine instructions.
 Second stage java interpreter generates machine code that can be directly executed by

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 9


the machine that running the java program.
Platform Independent and Portable
 The most significant contribution of java over other language is its portability.
 Java programs can be easily moved from one computer system to another, anywhere
and anytime.
 Changes and Upgrades in operating systems, processors and system resources will not
force any changes in Java programs. This is the reason why java has become a popular
language for programming on Internet, which interconnects different kinds of systems
worldwide.
 We can download a java applet from a remote computer on to our local system through
Internet and execute it locally.
 Java ensures portability in two ways. First java compiler generates Byte code
instructions that can be implemented on any machine. Secondly, the sizes of the
primitive data types are machine independent.
Object Oriented:
 Java is truly object-oriented language. Almost everything in Java is an object.
 All program code and data reside within objects and classes.
 Java comes with an extensive set off classes, arranged in packages that we can
use in our programs by inheritance.
 The object model in java is simple and easy to extend.
Robust and Secure:
 Java is a robust language. It provides many safeguards to ensure reliable code. It has
strict compile time and runtime checking for data types.
 It is designed as garbage collected language relieving the programmers virtually all
memory management problems.
 Java also incorporates the concept of exception handling which captures series errors
and eliminates risk of crashing the system.
 The absence of pointers in java ensures that programs cannot gain access to memory
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 10
locations without proper authorization.
Distributed:
 Java is designed as a distributed language for creating applications on networks. It has
the ability to share both data and programs.
 Java applications can open and access remote objects on internet as easily as they can
do in a local system.
 This enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
Simple, Small and Familiar:
 Java is a small and simple language. Many features of C and C++ that are either
redundant or sources of unreliable code are not part of java.
 For example java does not use pointers, preprocessor header files, goto statement and
overloading and multiple inheritance and many others.
Multithreaded and Interactive:
 Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programs. This means that we need not wait for the application to finish
one task before beginning another.
 For example we can listen to an audio clip while scrolling a page and at the same time
download an applet from a distant computer.
 This feature greatly improves the interactive performance of graphical applications.
High performance
 Java performance is impressive for an interpreted language, mainly due to the use of
intermediate byte code. According to sun, java speed is comparable to the native C/C+
+.
 Java architecture is also designed to reduce overheads during runtime. Further, the
incorporation of multithreading enhances the overall execution speed of java programs.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 11


JAVA DEVELOPMENT ENVIRONMENT

API
 Java environment includes a large number of development tools and hundreds of
classes and methods.
 The development tools are part of the system known as Java Development Kit(JDK)
and the classes and methods are part of the Java Standard Library(JSL), also known as
the Application Programming Interface(API).
JAVA DEVELOPMENT KIT (JDK)
 Java Development Kit comes with a collection of tools used for developing and
running java programs. They are
 Applet viewer (for viewing java applets)
 Javac (java compiler)
 Java(java interpreter)
 Javap(java dissembler)
 Javab(for C header files)
 Javadoc(for creating HTML document)
 Jdb(java debugger)

APPLICATION PROGRAMMING INTERFACE (API)


 The java standard library (or API) includes hundreds of classes and methods grouped
into several functional packages. Most commonly used packages are
 Language support package: - A collection of classes and methods required for
implementing basic features of java.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 12


 Utilities package: - A collection of classes to provide utility functions such as
date and time functions.
 Input/output packages: -A collection of classes required for Input/output
manipulation.
 Networking packages: - A collection of classes for communicating with other
computers via internet.
 AWT packages: - The Abstract window Tool Kit package contains class that
implements platform independent graphical interface.
 Applet package: - This includes set of classes that allows us to create java
applets.

JAVA CHARACTER SET


 The smallest units of java language are the characters used to write java tokens.
 These characters are defined by the Unicode character set an emerging standard that
tries to create characters for a large number of scripts worldwide.
 The Unicode is a 16-bit character coding system and currently supports more than
34,000 defined characters derived from 24 languages from America, Europe, Middle
East, Africa and Asia.
OPERATORS
Introduction:
 Java supports a rich set of operators
 An operator is a symbol that is used for manipulate data and variables.
 Operators are used in programs to manipulate data and variables.
Java Operators Are Classified Into Number Of Categories.
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 13
 Increment and decrement operators
 Conditional operators
 Bitwise operators
 Special operators
ARITHMETIC OPERATORS
 Arithmetic operators are used to construct mathematical expressions as in
algebra

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo
division

Ex: a-b a+b a*b a/b a%b


 Here a and b may be variable or constants. They are also known as operands
 -, +, *, /, % are called operators.
i) Integer arithmetic
 When both the operands in a single arithmetic expression such as a + b are
integer, the expression is called an “integer expression” and the operation is
called as “integer arithmetic”.
 Integer arithmetic always gives an integer value.
E.g.: a=14, b=4

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 14


a+b=18
a-b=10
a*b=56
a/b=3(decimal part truncated)
a%b=2(reminder of integer division)
 For modulo division, the sign of the result is always the sign of the first
operand.
-14%3 = -2 14 % -3 = 2
ii) Real arithmetic

 An arithmetic operation involving only real operand is called “real arithmetic”.


 A real operand may assume values either in decimal or exponential notation.
Sample program:
import java.io. *;
class floatpoint
{
public static void main(String args[])
{
float a=20.5, b=6.4;
System .out.println("a="+a);

System.out.println("b="+b );

System.out.println("a+b="+( a-b));

System.out.println("a-b="+( a-b ));

System.out.println("a*b="+( a*b));

System.out.println("a/b="+( a/b);

System.out.println("a%b="+( a%b));
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 15
}

Mixed mode arithmetic

 When one of the operands is real and the other is an integer, the expression is
called a mixed-mode expression.
 If either operand is of the real type, then the other operand is converted to real
and the real arithmetic is performed.

E.g.: 15/10.0=1.5
15/10=1
RELATIONAL OPERATORS
 Compares two
ae-l relational operator ae-2 Operato Meaning
quantities depending on their relation.
r
 Java supports six
< Is less than
relational operators.
<= Is less than or
equal to
 A simple relational expression contains
> Is greater than
only one relational operator and is of the
>= Is greater than or
following form:
equal to
== Is equal to
ae-1 relational operator ae-2
!= is not equal to

 Where ae-1 and ae-2 are arithmetic


expressions.

Eg: Expression value

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 16


4.5<=10 True
4.5>=10 False
LOGICAL OPERATORS
 Java has three logical operators

Operator Meaning
&& Logical AND
A logical operator returns either TRUE or
|| Logical OR
FALSE values.
! Logical NOT
Truth Table

Op-1 Op-2 Op1&&op-2 Op1|| op2

True True True True

True False False True

False True False True

False False False false

 Logical operator && and || are used to check compound condition (ie for combining two
or more relations)
 When an expression combines two or more relational expressions then it is called logical
expression or a compound relational expression

Eg: if (age>55 && salary<1000)


if (mark1>40 && mark2 >40)
ASSIGNMENT OPERATORS
 Used to assign the value of an expression to a variable.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 17
 Assignment operators are usually in the form “=”
 Shorthand form:
V op=exp;

V variable

Exp expression

Op java binary operator

 The assignment statement V op = exp is equivalent to V= V op (exp);

Statement with simple Shorthand


assignment operator

a=a+1 a+=1

a=a-1 a-=1

a=a*(n+1) a*=n+1

a=a/(n+1) a/=n+1

A=a % b a%=b

Eg:

Z+=Y+1 which is equal to Z=Z+(Y+1)

Advantages:

It has 3 advantages

 Easy to write.
 Easy to read
 Efficient code.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 18


INCREMENT AND DECREMENT OPERATORS

 They are also called unary operator.

++  Increment operator, add 1 to the operand

--  Decrement operator, subtract 1 to the operand

 They may also used to increment subscripted variables

Eg. a[i++]

Sample Program:

class Incrementoperator
{
public static void main(String args[ ])
{
int m=10,n=20;
System.out. println("m=" +m);
System.out. println("n="+n);
S ystem.out. println("++m="+++m);
System.out.println("n++="+n++);
Systern.out. println("m="+m);
System .out. println("n="+n);
}
}
Output
m=10
++m=11
m=11
n=20
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 19
n++=21
n=21

CONDITIONAL OPERATORS

 The character pair ?: is used for conditional operator


 It is also called as Ternary operator.

General Form
Exp1 ? exp2: exp3
 Exp1, exp2, exp3 are expressions
 The operator ?: works as follows

 Expression1 is evaluated first, if its is true then the expression2 is evaluated.

 If expression 1 is false, expression3 is evaluated.

Eg a=10;
b=15
X= (a>b) ? a : b;
The output is X=15

BITWISE OPERATORS:

 Bitwise operators are used to manipulate data at values of bit level.


 These operators are used for testing the bits, or shifting them to the right or left.
 Bitwise operators may not to float or double.

Operator Meaning

& Bitwise AND

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 20


! Bitwise OR

^ Bitwise exclusive OR

~ One’s complement

<< Shift left

>> Shift right

>>> Shift right with zero


fill

Eg: 5 = 0000 0101


A=5
>>A // 1000 0010
<<A // 0000 1010
SPECIAL OPERATORS
 Java supports special operators
 Instance of operator
 Dot operator (or) member selection operator (.)
Instance of operator:
 Instance of operator is an object reference operator
 Allow us to determine whether the object belongs to a particular class or not.
 Return true, if the object on the left-hand side is an instance of the class given on the
right-hand side.
E.g. person instanceof students
 Is true if the object person belongs to class student; otherwise it is false.
Dot operator
 The dot operator (.) is used to access the instance variables and methods of class
objects.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 21
Person1.age // reference to the variable
Person1.salary() // reference to the method
 It is also used to access classes and sub packages from a package.
CONTROL STATEMENTS

DECISION MAKING AND BRANCHING

 When a program breaks the sequential flow and jumps to another part of
the code, it is called branching.
 When the branching is based on a particular condition, it is known as
conditional branching.
 If branching takes place without any decision, it is known as
unconditional branching.
The following statements are known as control or decision making
statements.

 If statement
 Switch statement
 Conditional operator statement
DECISION MAKING WITH IF STATEMENT

 If statement is a powerful decision making statement and is used to control the flow of
execution of statements.

General form
if (test expression)

 The expression is first evaluated.


 Depending on the value of the expression is true or false, control is transfer to a
particular statement.
 The if statement are
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 22
1. simple if statement
2. if…else statement
3. nested if…else statement
4. else if ladder
1. Simple If Statement
 If the test expression is true the statement block will be executed; otherwise
the execution will jump to the statement-x
 Statement block may be single statement or a group of statement.

General form
if (test expression)
{
statement-block;
}
Statement-x;

2. The If…Else Statement


 If the test expression is true, then the true-block statements are executed.
 Otherwise, the false block statements are executed.

General form Example


If (degree = = “BCA”)
if (test expression) {
{ points = points+500;
True block system.out.println(“Its BCA”)
statements;
}
}
Else else
{ {
False block statements; points = points+200;
} System.out.println(“Its BSC CS”);
}
….
….

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 23


3. Nested if …else statement
 Here if the condition-1 is false, the statement-3 will be executed; otherwise it
evaluates the condition-2.
 If the condition-2 is true, then statement-1 will be executed; otherwise the
statement -2 will be evaluated and then control is transferred to the
statement-x.

General Form Example


if (test condition1) if (gender == “female”)
if (test condition2) if (balance>5000)
{ {
True Bonus = 0.03 * balance;}
blockstatements-1; Else
} {
Else Bonus = 0.02 * balance;
{ }
False block Else
statement-2;
} {
Else Bonus = 0.01 * balance;
{ }
False block statements-3; Balance=balance + bonus;
}
Statement-x;
4. The ELSE IF ladder
 Else if ladder is a chain of ifs in which the statement associated with each else is
an if.
 The condition is evaluated from the top to downwards.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 24


 As soon as the condition is true, then the statements associated with it are
executed and the control is transferred to the statement -x.
 When all the n condition is false, then the final else containing the default-
statement will be executed.

General form Example


If (condition-1) If (marks>79)
Statement-1 Grade=”honors”
Else if (condition-2) Else if (marks>79)
Statement -2
Grade=”first”
Else if (condition-3)
Statement -3 Else if (marks>79)
….. Grade=”second”
…..
Else if (marks>79)
Else if (condition n)
Statement -n; Grade=”third”
Else Else
Default-statement; Grade=”fail”; // Default-stmt
Statement-x System.out.println(“grade=”+grade);

5. The Switch Statemen


 It an multiway decision statement
 The switch statement tests the value of a given variable against a list of case
values.
 When a match is found, a block of statement associated with that case is
executed.
 The expression is an integer expression or character known as case labels.
 Block1, block2 … are statements lists may contain zero or more statements.
 No need to put braces around each block
 Case labels end with a colon (:)
 The break statement at the end of each block signal the end of a particular
case and causes an exit from the switch statement, transferring the control to
the statement -x following the switch.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 25


 The default is an option case; it will be executed if the value of the expression
does not match with any of the case values.
 If not present, no action takes place when all matches fail and the control goes
to the statement -x

General form Example1


Switch(expression)
Switch(expression) {
{ case ‘1’:
case value-1: System.out.println(“Monday”);
block-1 break;
break; case ‘2’:
case value-2: System.out.println(“Tuesday”);
block-2 break;
break; case ‘3’:
case value-3:
block-3 System.out.println(“Wednesday”);
break; break;
……….. case ‘4’:
………. System.out.println(“Thursday”);
default: break;
default-block; ………………
break; ………………..
}
Statement-x; default:
System.out.println(“WRONG INPUT”);
break;
}
System.out.println(“ WELCOME TO THIS WEEK”);
…..

THE ? : OPERATOR
If (x<0)
DISCUSS ABOUT THE ?: OPERATOR. (4MARKS) Flag=0;
Else
Flag=1;
It is a two-way decision making operator
Ex1: Can be
This operator is a combination of ? and : and takes three operands. written as
This operator is popularly known as the conditional operator.
Flag = (x<0) ? 0 : 1;

Conditional expression ? Expression1 : expression2 Ex2:


AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 26
Y = (x>2) ? (2*x+1)
: (3*x+2)
DECISION MAKING AND LOOPING

 The process of repeatedly executing a block of statement is known as looping.


 The statements in the block may be executed any number of times, from zero to
infinite number.
 If a loop continues forever, it is called an infinite loop.
 A program loop consist of two segments, one known as the body of the loop and other
known as the control statements.
 The control statements test certain conditions and then direct the repeated execution of
the statements contained in the body of the loop.
 A looping process in general consists of following steps:
 Setting and initialization of a counter
 Execution of the statements in the loop
 Test for a specified condition for execution of the loop
 Incrementing the counter
 Java language provides three looping statements for loop operations.
 The while statement
 The do statement
 The for statement
THE WHILE STATEMENT
Discuss about while statement. (4marks)
 The simplest of all the looping structures in java is the while statement.
 The while is an entry-controlled loop statement.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 27


 The test condition is evaluated and if the condition is true, then the body of the loop
is executed.
 After execution of the body, the test condition is once again evaluated and if it is
true, the body is executed once again.
 The execution of the body continues, until the test condition becomes false and the
control is transfer out of the loop.
 On exit, the program continues with the statement immediately after the body of the
loop.

General form Example


Sum=0;
Initialization; N=1;
While (N<=10)
{
While (test condition) sum=sum + N;
{ N=N+1;
Body of the loop }
} System.out.println(“sum’”+sum);

Here the body of the loop is executed 10 times for n=1,2..10.

THE DO STATEMENT

 In do statement, the program proceeds to evaluate the body of the loop first.
 At the end of the loop, the test condition in the while statement is evaluated.
 If the condition is true, the program continues to evaluate the body of the loop once
again.
 The program continues to evaluate the body of the loop as long as the condition is
true.
 When the condition becomes false, the loop will be terminated and the control goes
to the statement that appears immediately after the while statement.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 28


Example
Sum=0;
General form N=1;
Initialization; do
{
do sum=sum + N;
{ N=N+1;
Body of the loop } While (N<=10)
} While (test condition) System.out.println(“sum’”+sum)

Here the body of the loop is executed 10 times for n=1,2..10.

THE FOR STATEMENT

 For loop is an entry-controlled loop.


 The execution of the for statement is as follows;

(1) Initialization of the control variables is done first, using assignment statements such
as i=1 and count=0. The variable i and count are known as loop-control variables.
(2) The value of the control variables is tested using the test condition. The test
condition is a relational expression, such as i<10 that determines when the loop will
exit.
 It the condition is true, the body of the loop is executed; otherwise the loop
is terminated and the execution continues with the statement that
immediately follows the loop.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 29


(3) When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop.

 Now the control variable is incremented using an assignment statement such as


i=i+1 and the new value of the control variable is again tested to see whether it
satisfies the loop condition.
 If the condition is satisfied, the body of the loop is again executed.
 This process continues till the value of the control variable fails to satisfy the test
condition.

General form
For (initialization; test condition;
increment)
{
Body of the loop
}

Simple example-2 Simple example-1

For (n=1; n<=10; n++) For (i=0;i<=10;i++)


{ {
sum = sum + n; System.out.println(i);
} }

Addition features of for loop valid


P=1; m=5;
For(n=0; n<17; ++n) For ( ; m!=100; )
{
Can be written as System.out.println(m);
m = m + 5;
}
 For (p=1, n=0; n<17; ++n) valid

 For (n=1, m=50; n<=m; n=n+1,m=m-1) valid

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 30


 For (i=1; i<20 && sum <100; ++i) valid

 For (m=5; m!=100; m=m+5)valid

Nesting of for loops

 A FOR loop which is present inside of another FOR loop is called nesting of for
loop.

For (i=1;i<=10;i++) For (i=1;i<=10;i++)


{
……………. {
…………….
For (j=1; j ! = 5; ++j) For (j=1; j<=10; j++)
{………….
………….. {
}
System.out.println(i,j)
…………
} }
………..
}

PRECEDENCE OF ARITHMETIC OPERATORS

 An arithmetic expression can be evaluated from left to right using the rules of
precedence of operators.
 There are two distinct priority levels:

High */%
priority

Low priority + -

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 31


JUMPS IN LOOPS

 Loops perform a set of operations repeatedly until the control variable fails to satisfy
the test condition.
 Java permits a jump from one statement to the end or beginning of a loop as well as a
jump out of a loop.

Jumping out of a loop

 Exit from a loop can be accomplished by using the break statement.


 Break can also be used within while, do and for loops.
 When break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop.
 In nested loop, the break would only exit form the loop containing it

While(…….) For (……) For(……)


{ {

{ ….. …..

…… …..
……
……. For(…….)
If (condition)
If
(condition) {
Break; ….
Break;

…… ….. …..

….. ….. If (condition)
} } Break;

……… ……. ……..
…….
 }// for second for
…..
 …..
 } // for first for

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 32


Skipping a part of a loop
 Continue statement skips a part of a loop.
 The continue statement; cause the loop to be continued with the next iteration after
skipping any statement in between.
 The continue statement tells the compiler “skip the following statements and
continue with the next iteration”.

FORMAT: EXAMPLE
continue; For(…….)
While (test condition) {
{
……
……
If (condition) If (condition)
Continue; Continue;
……. …….
……. …….
} }

LABELLED LOOPS

 A label is any valid java variable name.


 To give a label to a loop, place the label before the loop with a colon at the end.

Format1: Format 2:for block of statement

loop1 : for(…..) block1:


{
{ ……..
……… ………

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 33


……… Block2:
} {
………
}
……….
……….
}

SIMPLE JAVA PROGRAM

Simplest java program

Class SampleOne
{
Public Static void main (String args[])
{
System.Out.Println(“welcome to AVS
COLLEGE”);
}
}

Class declaration

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 34


 Class SampleOne declares a class, java is a true object-oriented language and
therefore, everything must be placed inside a class.
 class is a keyword and declares that a new class definition follows.
 SampleOne is a java identifier that specifies the name of the class to be defined.

Opening Brace

 Every class definition in java begins with an opening brace “{“ and ends with a
matching closing brace “}”.

The main line

 The third line

Public Static void main (String args[])

 The above line defines a method named main.

 This is similar to the main() function in C/C++.

 Every java application program must include the main() method. This the starting
point for the interpreter to begin the execution of the program.

 A java application can have any number of classes but only one of them must include a
main method to initiate the execution.

 The line contains a number of keywords public, static and void

 Public : the keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.

 Static : which declares this method as one that belongs to the entire class and not a part
of any object of the class. The main methods must always be declared as static since
the interpreter uses this method before any object are created.

 Void: the void states that the main method does not return any value.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 35


The output line

 The only executable statement in the program is

System.Out.println(“welcome to AVS COLLEGE”);

 This is similar to printf() statement of C or cout<< construct of C++.

 Since java is a true object oriented language, every method must be part of an object.

 The println method is a member of the Out object, which is a static data member of
System class.

 This line prints the string “java is better than C++.”

More of java

Import java.lang.math;

 The above statement instruct the interpreter to load the Math class from the package
lang.

 Math class contains the sqrt method.

An application with two classes

Class Room Class RoomArea


{ {
Float length; public Static void main(String
args[])
Float breadth; {
Void getdata(float a, float b) float area;
{ Room room1=new Room();

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 36


length=a; Room1.getdata(14,10);
breadth=b; area=room1.length *
room1.breadth;
} System.out.println(“area=” +
area);
} }
}

JAVA HISTORY AND FEATURE


JAVA HISTORY
 Java is a general purpose, object-oriented programming language by Sun Microsystems
of USA in 1991.
 Originally called Oak by james gosling, one of the inventor of the language.
 Java was designed for the development of software for consumer electronic devices
like TV, VCRS, toaster etc.
 The goal is to develop a language which is simple, portable and highly reliable.
 The java team discovered that the languages like C and C++ had limitations in terms of
both reliability and portability. They modeled their new language java on C and C++.
 The most striking feature of the language is that it is a platform neutral language. Java
is the first programming language that is not tied to any particular hardware or
operating system.
 Java is influenced by C++ it is not an enhanced version of C++.
1990 Sun Microsystems decided to develop special software for consumer
electronic devices. A team of headed by James gosling was formed to undertake this task.
1991announced a new language name “Oak”.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 37


1992application controlled a list of home appliances using hand-held device
with a tiny touch screen.
1993World Wide Web appeared, idea of developing Web applets that could
run on internet.
1994 developed web browser called “Hot java”.
1995 Oak was renamed “java”
1996java became general purpose language. Became popular and found its
home.

JAVA FEATURES

 Compiled and interpreted.  Platform - independent and


portable.
 Object oriented  Robust and secure
 Distributed  Familiar, simple and small
 Multithreaded and Interactive  High performance
 Dynamic and Extensible

JAVA DEVELOPMENT KIT(JDK)


 Dynamic and Extensible:
 Java is a Dynamic language.
 Java is capable of dynamically linking in new class libraries, methods and
objects.
 Java programs support functions written in other languages such as C and C++.
 These functions are known as native methods.
 Native methods are linked dynamically at runtime.
JAVA DEVELOPMENT KIT(JDK):

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 38


 Java environment includes a large number of development tools and hundreds of
classes and methods.
JDK development tools are part of the system known as java development
kit (JDK)
JSL the classes and methods are part of the java standard library (JSL) also
known as Application programming interface (API).

Java development kit


 JDK comes with collection of tools that are used for developing and running java
program.
They include

Tool Description

appletviewer (for viewing java Enables us to run java applets


applets)
Java interpreter, which runs applets and
java (java interpreter) applications by reading and interpreting bytecode
files.

The java compiler, which translates java


javac (java compiler)
sourcecode to bytecode files that the interpreter can
javadoc ( for creating HTML understand.
document)
Creates HTML format documentation from java
source code files.

javah( for C header files) Produces header files for use with native method.

javap (java disassembler) Java disassembler, which enables us to convert

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 39


bytecode files into a program description.

jdb ( java debugger) Java debugger, which helps us to find errors in


our programs.

JAVA TOKENS

 A java program is basically a collection of classes.


 A class is defined by a set of declaration statements and methods containing executable
statements.
 Most statements contain expression, which describe the actions carried out on data.
 Smallest individual units in a program are known as tokens.
 The compiler recognizes them for building up expressions and statements.
 In simple terms, a java program is a collection of tokens, comments and white spaces.
 Java language includes five types of tokens.
They are
 Reserved keywords
 Identifiers
 Literals
 Operators
 Separators
 Java Character set
 The smallest units of java language are the characters used to write java
tokens.
 Reserved keywords
 Java language has reserved 60 words as keywords.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 40


 These keywords combined with operators and separators according to
syntax, form definition of the java language.
 Since keywords have specific meaning in java, we cannot use them as
name for variables, classes, methods and so on. All keywords are to be
written in lowercase letters.
 Identifiers
 They are used for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.
 Rules for naming an identifier
 They can be of any length
 Uppercase and lowercase letter are distinct.
 They can have alphabets, digits, underscore and dollar sign
characters.
 They must not begin with digit.
Eg average, sum
 Literals
 Literals in java are a sequence of characters that represent constant
values to be stored in variables.
 Java language specifies five major types of literals. They are
 Integer literals
 Floating_point literals
 Character literals
 String literals
 Boolean literals
 Operators
 An operator is a symbol that takes one or more arguments and operators
on them to produce a result.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 41


 Separators
 Separators are symbols used to indicate where groups of code are divided
and arranged.

() paranthese,{} braces, [] brackets, semicolon, comma, period


JAVA STATEMENTS

 Java statements are like natural languages.


 A statement is an executable combination of tokens ending with a semicolon (;) mark.
 Statements are executed in sequence in the order in which they appear.

Java implements several types of statements, they are

 Expression statementsAssignment, pre-increment, pre-decrement, post-increment,


post-decrement, method call and Allocation Expression
 Empty statement These do nothing and are used during program development as a
place holder
 Labeled statement Any statement begin with a label, such labels must not be
keywords, already declared local variables, or previously used labels in this module.
Labels in java are used as the arguments of jump statement.
 Selection statement These select one of the several control flows. They are if, if-
else and switch
 Iteration statement these specify how and when looping will take place. They are
while, do and for.
 Jump statementjump statement pass control to the beginning or end of the current
block or to a labeled statement. They are break, continue, return and throw
 Synchronization statement these are used for handling issues with multi-threading.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 42


 Guarding statement used for safe handling of code that may cause exception.
These statements use the keywords try, catch, and finally.

ARRAYS AND VECTORS ARRAYS

Introduction

 An array is a group of contiguous or related data items that share a common name.

 A particular value in an array is indicated by writing a number called index number or


subscript in brackets after the array name

E.g. name[10] Eg: Int number[]=new int[5];

 The individual values are called elements.

One dimensional array

 A list of items can be given one variable name using only one subscript called single
subscripted variable or one dimensional array.

E.g. int value=new int [5] represent a set of five integer values.

Creating an array

 Arrays must be declared and created in the computer memory before they are used.

Creation of an array involves three steps:

 Declare the array


 Create memory locations
 Put values into the memory location.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 43


Declaration of arrays
Arrays can be declared in two forms
Form1Form2

Type arrayname[];Type[] arrayname;

Example
Int number[];Int[] number;
Float average[];Float[] average;
Creating memory locations

 After declaring an array, we need to create memory.

 Java allows creating arrays using new operator.

Arrayname = new type [size];

Eg: Number=new int[5];

Combining declaration and creation

 It is also possible to combine the two steps- declaration and creation

 Int number[]=new int[5];

Initialization of Arrays

 Putting values into the array is known as initialization.

 This process is done using the array subscript.

Arrayname [subscript]=value;

Eg: Number[0]=90;

Number[1]=100;

……….

 Arrays starts with a subscript 0 and ends with a value one less than the size specified.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 44


 Trying to access an array beyond its boundaries will generate an error message.

Initializing list of values to an array

 Values are separated by commas and surrounded by curly braces.

Type arrayname[]={ list of values};

 If size is not specified means compiler allocates enough space for all the elements
specified in the list

Eg: int number[]={23,45,56,67}

Array length

 Access the length of the array using length keyword.

Eg: int assize= a.length();

Eg: int size[][]=new int[3][10];

 Here length of size.length() 3

 Length of size[i].length() 10;

Two-dimensional array

Eg : int myarray[][];

Myarray=new int[3][4];

Or

int myarray[][]=new int[3][4]

Initializing values to two dimensional array

 Int myarray[][]={0,0,0,1,1,1} initialization done by row by row

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 45


 Int table[][]={{0,0,0},{1,1,1}}
 Int table[][]=
{

{0,0,0}

{1,1,1}

VECTORS

 Vector class contain in java.util package.

 Vector class is used to create a generic dynamic array known as vector that can hold
objects of any type and any number.

 It is heterogeneous data not homogenous.

Created like

 Vector intvect=new vector(); // declared without size

 Vector list=new vector(3); // declared with size

Advantage

 It is convenient to use vectors to store objects.

 A vector can be sued to store a list of objects that may vary in size.

 We can add and delete objects from the list as and when required.

Methods Task performed

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 46


list.addElement(item) Adds the item specified to the list at the end

list.addElement(item) Adds the item specified to the list at the end

list.elementAt(10) Gives the name of the 10th object

list.size() Gives the number of objects present.

List.removeElement(item) Removes the specified item from the list.

List.removeElementAt(n) Removes the item stored in the nth position of


the list

List.removeAllElement() removes all the elements in the list

List.copyInto(array) copies all items from list to array

List.insertElementAt(item,n inserts the item at nth position


)

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 47


Example program for vector Command line input and output are:
import java.util.*;
class LanguageVector C :\> java languagevector Ada Basic C++
{ FORTRAN Java
public static void main(String a[])
Output:
{
Vector list=new Vector(); List of languages
int length=a.length;
for (int i=0; i<length; i++) Ada
{
list.addElement(args[i]); Basic
} COBOL
List.insertElementAt(“COBOL”,2);
Int size1=list.size(); C++
String listarray[]=new String(size);
System.out.println(“list of languages”); FORTRAN
for (int i=0; i<length; i++)
Java
{
System.out.println(“listarray[i]”);
}
}// for main method
}// for class

STRINGS AND STRINGBUFFERS

 String represents a sequence of character.

 String can be represented in two ways in java

 Using character array

 Using string object or stringbuffer class

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 48


Using character array

Char carray[]=new char[4]; char arraytwo[][]= new char[3][4];


carray[0]=’j’; carray[0]=”java”;
carray[1]=’a’; carray[1]=”siva”;
carray[2]=’v’; carray[2]=”raju”
carray[3]=’a’; carray[3]=”annu”

Using string class

 In java strings are class objects and implemented using two classes; String and
StringBuffer.

General form Eg
String firstname;
String stringname; Firstname=new String(“anil”);
Stringname=new Or
String(“string”); String firstname=new String(“anil”);

To get length of the string Int m=firstname.length();

To concatenate two string String fullname=name1+name2; String


city=”new”+”delhi”;

String array

Eg : String item[]=new String[3];

 The string array item stores three strings.

Item[0]=”soap”;

Item[1]=”biscuits”;

Item[2]=”powder”;

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 49


Example program Alphabetic ordering of strings
Class Stringordering
{
static String name[]={“Madras”, “Delhi, “Ahmedabad”, “Calcutta”,” Bombay”}
public static void main(String a[]);
{
int size=name.lenght();
String temp=null;
for (int i=0; i< size; i++)
{
for (int j+1; j<size; j++)
{
if name[j].comapreTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for (int i=0; i<size; i++)
{
System.out.println(name[i]);
}
}
}

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 50


String methods

method task performed

S2=s1.toLowerCase; Converts the string s1 to all lowercase

S2=s1.toUpperCase’; Converts the string s1 to all uppercase

S2=s1.replace(‘x’,’y’); Replace all appearances of x with y

S1.equal(s2); Returns true if s1 is equal to s2

S2=s1.trim(); Remove white space at the beginning and end of the


String s1

S1.equalsIgnoreCase(s2) Returns true if s1 is equal to s2, ignoring the case of


; characters

S1.length(); Gives the length of s1.

S1.charAt(n) Gives nth character of s1

S1.concat(s2); Concatenates s1 and s2

S1.substring(n); Gives substring starting from nth character.

S1.substirng(n,m); Gives substring starting from nth character up to mth


character

String.valueOf(p); Creates a string object of the parameter p(simple type


or object)

p.toString(); Creates a string representation of object p

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 51


S1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’ in the
string s1

S1.indexOf(‘x’,’n’); Gives the position ‘x’ that occurs after nth position in
the string s1

String.valueOf(variable); Converts the parameter value to string representation.

S1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2, zero if s1


and s2 equal.

StringBuffer class

 StringBuffer class is a peer class of String.

 String creates strings of fixed_length

 StringBuffer class creates string of flexible length that can be modified in terms of both
length and content.

 In stringbuffer class we can insert characters and substrings in the middle of a string, or
append another string to the end.

Eg: StringBuffer str=new StringBuffer(“annu”);

Methods Task

S1.setChartAt(n, ‘x’); Modifies the nth character to x

S1.append(s2); Appends the string s2 to s1 at the end

S1.insert(n,s2); Inserts the string s2 at the position n of the string

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 52


s1

S1.setLength(n); Sets the length of the string s1 to n. if


n<s1.length() s1 is truncated. If n>s1.length()
zeros are added to s1.

Example program

class stringmanipulation

public static void main(String arg[])

StringBuffer str=new StringBuffer(“object language”);

System.out.println(“original string:”+ str);

// obtain string length

Systme.out.println(“length of string:” +str.lenght());

// accessing characters in a string

for (int i=0; i<str.length();i++)

int p=i+1;

System.out.println(“character at position: “+ p + “ is” + str.charAt());

// inserting a string in the middle

String astring=new String(str.toString());

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 53


int pos=astring.indeOf(“ language”);

str. Insert(pos, “oriented”);

System.out.println(“modified string: “+str);

// modifying characters

Str.setcharAt(6,’-‘);

System.out.println(“string now: ” + str);

// append a string at the end

Str.append (“improve security.”);

System.out.println(“appending string:” +str);

Unit: I

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 54


Section-A (2 Marks)

1. What is mean by java?


2. What are all the java features?
3. Explain java tokes?
4. What is mean JDK character set?
5. Explain Arrays?

Section-B (4 Marks)

1. Explain Identifier?
2. Short notes on constant and examples?
3. Explain control statements?
4. Explain looping statements?

Section–C (12 Marks)

1. Explain briefly about java features?


2. Briefly explain data types?
3. Explain java operators?

FREQUENTLY ASKED QUESTIONS(2012)

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 55


1) What is the use of jacvadoc tool? (2)

2) What is java tokens? (2)

3) Describe java character set? (5)

4) Explain difference of application program and applet program?(5)

5) Describe the all loop statements?((10)

*******************END OF UNIT I ********************

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 56


AVS AND SAKTHIKAILASSH GROUP OF INSTITUTIONS
DEPARTMENT OF BCA
JAVA

UNIT II
………………………………………………………………………………………………
Classes, Interfaces and Packages: Classes – Objects – Wrapper Classes – Packages and
Interfaces.
…………………………………………………………………………………………………
CLASSES AND OBJECTS

INTRODUCTION

 CLASS: “A class is a way of binding the data and associated methods in a single
unit”
 Any JAVA program if we want to develop then that should be developed with
respective class only i.e., without class there is no JAVA program.
 Classes create objects and object uses methods to communicate between them.
 Classes provide convenient method for packing together a group of logically related
data items and functions that work on them.

DEFINING A CLASS

 A class is a user-defined data type with a template that serves to define its properties.
 Anything in square bracket is optional.
 Classname and superclassname are valid java identifier.
 The keyword extends indicates that the properties of the superclassname class are
extended the classname class.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 57


The basic form of a class definition is Example1 Example2
Class classname [extends superclassname] Class empty Class sample
{ { { int i,j;
[Variable declaration;]
[Method declaration;] } Void getdata();
} }

ADDING VARIABLES/ FIELDS DECLARATION

 Data is encapsulated in a class by placing data fields inside the body of the class
definition.
 These variables are called instance variables because they are created whenever an
object of the class is instantiated.
 Instance variables are also know as member variables.

Example
Class Triangle
{
int length;
Int height;
}

The class triangle contains two integer type instance variable, length
and height.

ADDING METHODS/ METHOD DECLARATION

 Method declarations have four basic parts

 The name of the method (method name)


 The type of the value the method returns (type)
 A list of parameters (parameter list)
 The body of the method

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 58


The general form of the method declaration is example
Type methodname (parameter -list) Class Triangle
{ {
method-body; Int length;
} Int height;
Void getdata(int x, int y)
{
Length=x;
Height=y;
}
}

CREATING OBJECT

 OBJECT: In order to store the data for the data members of the class, we must create
an object.
 Instance (instance is a mechanism of allocating sufficient amount of memory
space for data members of a class) of a class is known as an object.
 Class variable is known as an object.

 Grouped item (grouped item is a variable which allows us to store more than
one value) is known as an object.
 Value form of a class is known as an object.
 Blue print of a class is known as an object.
 Real world entities are called as objects.

 Creating an object is also referred to as instantiating an object.


 Objects in java are created using the new operator.
 The new operator creates an object of the specified class and returns a reference to that
object.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 59


 Every time the class is instantiated, a new copy of each of them is created.
Eg:

Triangle Tri1; // declare

Tri1=new Triangle ( ) // instantiate

 The first statement declares a variable to hold the object reference


 The second one actually assigns the object reference to the variable.
 The variable tri1 is now an object of the rectangle class

Eg1: Triangle tri1 = new Triangle ( );  valid

Eg2: Triangle tri1 = new Triangle ( );  tri1 and tri2 are the objects of
Triangle class

Triangle tri2 = new Triangle ( );

Eg3: Triangle tri1 = new Triangle ( );

Triangle tri2 = tri1;

THE DIFFERENCE BETWEEN CLASS AND OBJECT

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 60


Class Object

1) A class is a way of binding the data 1) Class variable is known as an object.


and

Associated methods in a single unit.

2) Whenever we start executing a 2) After loading the class in to main


program, the class will be loaded into memory, objects can be created in n
main memory with the help of class number
loader subsystem (a part of JVM) only
once.

3) When the class id defined there is no 3) When an object is created we get the

memory space for data members of a memory space for data members of the

class. class.

ACCESSING CLASS MEMBERS

 we can access class members using DOT(.) operator

Syntax:
Accessing variables
Accessing method
Objectname. Variablename
E.g.
Objectname.methodname(parameter Tri1.length=10;
-list); Tri1.getdata (10, 20);
Tri1.height=20;

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 61


E.g. program
Class Square
{
int side;
Void getdata(int s)
{
side=s;
}
int rectarea()
{
int area=side * side;
return(area);
}
}
Class Squareaea
{
Public static void main (String arg[])
{
Square s1= new Square();
s1.getdata(5);
sqarea =s1.rectarea();
System.out.println(sqaea);
}
}

CONSTRUCTORS

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 62


 Java supports a special type of method called a constructor that enables an object to
initialize itself when object for that class is created.
 Constructors have the same name as the class name.
 They does not return any value and do not specify even void.
 Constructors are automatically called during the creation of the objects.
EXAMPLE:

Class Volume
{
Int x,y,z;
Volume() // constructor
{
x=10;
Y=10;
Z=30
}
Public int calvolume()
{
int vol=x*y*z;
Return vol;
}
}
Class Demovolume()
{
Public static void main(String arg[])
{
Volume volobj=new Volume; // creating object
Int result=volobj.calvolume(); // calling method
System.out.println(“the volume is =”+result);
}
}

ADVANTAGES of constructors:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
RULES/PROPERTIES/CHARACTERISTICS of a constructor:
1. Constructor name must be similar to name of the class.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 63


2. Constructor should not return any value even void also (if we write the return type
for the
constructor then that constructor will be treated as ordinary method).
3. Constructors should not be static since constructors will be called each and every
time
whenever an object is creating.
4. Constructor should not be private provided an object of one class is created in
another class
(constructor can be private provided an object of one class created in the same class).
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is creating.

TYPES OF CONSTRUCTORS:
 Based on creating objects in JAVA we have two types of constructors.
 They are
1. Default/parameter less/no argument constructor and
2. Parameterized constructor.
1. DEFAULT CONSTRUCTOR
 A default constructor is one which will not take any parameters.
Syntax:
E xample:
class <clsname>
{ class Test
clsname () //default constructor { {
Block of statements; int a, b;
Test ()
………………………………; {
System.out.println ("I AM FROM

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 64


………………………………; DEFAULT CONSTRUCTOR...");
} a=10;b=20;
………………………; System.out.println ("VALUE OF a = "+a);
………………………; System.out.println ("VALUE OF b = "+b);
}; }
};
class TestDemo
{
public static void main (String [] args)
{
Test t1=new Test ();
}
};

PARAMETERIZED CONSTRUCTOR
 A parameterized constructor is one which takes some parameters.
Syntax:
class <clsname>
{
…………………………;
…………………………;
<clsname> (list of parameters)
//parameterized constructor
{
Block of statements (s);
}

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 65


Example:
class Test
…………………………; {
…………………………; int a, b;
} Test (int n1, int n2)
{
System.out.println ("I AM FROM
PARAMETER CONSTRUCTOR...");
a=n1;
b=n2;
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
};
class TestDemo1
{
public static void main (String k [])
{
Test t1=new Test (10, 20);
}
};

METHOD OVERLOADING

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 66


 Methods that have the same name, but different parameter lists and different
definitions are called method overloading.
 Method overloading is used when objects are required to perform similar tasks but
using different input parameters.
 Java matches up the method name first and then the number and type of parameters to
decide which one of the definition to execute. This process is known as polymorphism.

Class Volume
{
int area()
{
int val=10*20*30;
return val;
}
int area(int m, int n)
{
int val=m*n;
return val;
}
int area(int l, int m, int n)
{
int val=l*m*n;
return val;
}
float area(float m, float n)
{
float val=m*n;
return val;
}
float area(int l, float m, int n)
{
float val=l*m*n;
return val;
}
}
Class Demovolume()
{
Public static void main(String arg[])
{
Calculatearea calarea=new calculatearea();
Int result1, result2, result3;
Float result4, result5;
result1=calarea.area();
result2=calarea.area(10,20);
AVS & SAKTHI KAILASH result3=calarea.area(100,200,300);
GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 67
result4=calarea.area(10.2,20.2);
result5=calarea.area(10,20.2,10);
System.out.println(result1,result2,result3, result4,result5);
NESTING OF METHODS

 A method can call other methods of the same class. This is known as nesting of
methods.

Example

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 68


class Nesting
{
int a, b, result;
Nesting(int x, int y)
{
a=x;
b=y;
}
Void Process()
{
result = a+b;
display();
}
Void display()
{
System.out.println(result);
}
}
class nestingtest
{
public static void main(String arg[])
{
Nesting nest=new Nesting(10,20);
nest.process();
}
}

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 69


WRAPPER CLASS

 Wrapper classes are basically used for converting the string data into fundamental data
type. Each and every wrapper class contains the following generalized parse methods.

public static Xxx parseXxx (String);

here, Xxx represents fundamental data type.

 Vectors cannot handle primitive data types like int, float, double and char.

 Primitive data types converted into object types.

 This conversion is done by using the wrapper class contains in the java.lang package

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 70


Converting primitive numbers to object numbers using constructor methods

Constructor calling Conversion action

Integer ival=new Integer(i); Primitive integer to Integer object

Float fval=new Float(r); Primitive float to Float object

Double dval=new Double(d); Primitive double to Double object

Long lval = new Long(i) Primitive long to Long object

Converting object to primitive number using typeValue() method

Method calling Conversion Action

int i= ival.intValue(); Object to primitive integer

float f = fval.floatValue(); Object to primitive float

long l= lval.longValue(); Object to primitive long

double d=dval.doubleValue(); Object to primitive double

Converting number to string using toString() method

Method Conversion Action

Str= Integer.toString(); Primitive integer to string

Str= Float.toString(); Primitive float to string

Str= Double.toString(); Primitive double to string

Str= Long.toString(); Primitive long to string

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 71


E.g. for Primitive to object

float num1=0.3F;  primitive data type

Float f1=new float (num1) changing to object

E.g. for converting string to numeric object

float num1=Float.ValueOf(in.readLine());

int val=Integer.ParseInt(in.readLine());

E.g.: object to primitive

float num1=0.3F;  primitive data type

Float f1=new float (num1) changing primitive to


object

num1=f1.floatValue(); changing object to primitive

PACKAGES AND INTERFACES

INTERFACES:

Interfaces are basically used to develop user defined data types.


 With respect to interfaces we can achieve the concept of multiple inheritances.
 With interfaces we can achieve the concept of polymorphism, dynamic binding
and hence we can improve the performance of a JAVA program in turns of
memory space and execution time.
 An interface is a construct which contains the collection of purely undefined
methods or an interface is a collection of purely abstract methods.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 72


Syntax for defining an interface:

Interface <interface
name>
Example
{  Interface is a keyword which is used for developing user
interface item
{
defined data
static types.
final int code = 1001;
Variable declaration;
void display();
 Interface
}
name represent a JAVA valid variable name and
Method declaration;
it is treated as name of the interface.
}  With respect to interface we cannot create an object
directly but we can create indirectly.

SYNTAX FOR DEFINING AN INTERFACE;

 Interface is the keyword


 Interfacename is the name of the interface.
 Variable declaration
static final type variablename = value;
 Method declaration
return-type methodname (parameter_list);

EXTENDING INTERFACE

 Interface can also be extended.


 An interface can be sub-interfaced from other interfaces.
 The new interface will inherit all the member of the super-interface.
 Interface can be extended using the keyword extends.

Example
interface name1
{
AVS & SAKTHI KAILASHvoid
GROUP OF INSTITUTIONS
display(); DEPARTMENT : BCA Page 73
}
interface name2 extends name1
{
IMPLEMENTING INTERFACES

 Implement the interface using implements keyword.

General form1 General form2


Class classname implements Class classname extends supperclass implements
interfacename interfacename
{ {
Body of class; Body of class;
} }

ACCESSING INTERFACE VARIABLES

 Interface declares a set of constant values.


 The constant values will be available to any class that implements the interface.
Example

class mainpgm
{
interface interfaceA public static void main(String s[])
{ {
final int m=10; ClassA objA=new classA();
} objA.show();
class ClassA implements interfaceA }
{ }
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 74
void show()
{
System.out.println(m);
}
}

Example 1 class InterfaceTest


interface Area
{ {
final static float pi=3.14F;
float compute (flaot x, float y); public static void main(String s[])
} {
class Rectangle implements Area Rectangle r1=new Rectangle();
{ Circle c1=new Circle();
public float compute(float x, float y) float f1,f2;
{ f1=r1.compute(10,20) ;
return (x*y); System.out.println(f1);
} f2=c1.compute(10,20) ;
} System.out.println(f2);
}
class Circle implements Area }
{
public float compute(float x, float y)
{
return (pi*x*y);}
}
}

PACKAGE

INTRODUCTION

 A package is a collection of classes, interfaces and sub-packages.


 A sub-package in turns divides into classes, interfaces, sub-sub-packages, etc.
 Learning about JAVA is nothing but learning about various packages.
 By default one predefined package is imported for each and every JAVA program and
whose name is java.lang.*.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 75


 Whenever we develop any java program, it may contain many number of user defined
classes and user defined interfaces.
 If we are not using any package name to place user defined
classes and interfaces, JVM will assume its own package called NONAME package.
In java we have two types of packages they are
I) predefined or built-in or core packages and
II) user or secondary or custom defined packages.

BENEFITS:

The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages.
 That is two classes in two different packages can have the same name.
They may be referred by their fully qualified name, comprising the package name and
the class name.
Packages provide a way to "hide" classes thus preventing other programs or packages
from accessing clases that are meant for internal use only.
Packages also provide a way for separating "design" form "coding".

JAVA API PACKAGES

Packages Contents

Java.lang Language support classes

Java.util Language utility classes such as vectors, hash tables, random


number, date etc

Java.io Input and output classes

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 76


Java.awt Set of classes for implementing graphical user interfaces

Java.net Classes for networking

Java.applet Classes for creating and implementing applets

USIGN SYSTEM PACKAGES

 Packages are organized in a hierarchical structure.


 The package named java contains the package awt, which in turns contain
various classes required for implementing graphical user interface.
There are two ways of accessing the classes stored in a package

1. Using the fully qualified class name. (Using the package name containing the
class and then appending the class name by using the dot operator.)
E.g. java.awt.Color
 Best and easiest one to access the class
 Used only once, not possible to access other classes of the package.

2. Using the import statement, appear at the top of the file. Imported package
class can be accessed any where in the program

Syntax: import packagename.classname;

 import the particular class alone.

Or

import packagename.* ;

 Imports every class contain in the package.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 77


NAMING CONVENTIONS

 Package can be named using the standard java naming rules.


 Name should be unique, duplicate name cause run-time error.
 Package begins with lowercase letter.
(To distinguish with class name, class name beings with uppercase.)
Example:

Double y = java.lang.Math.sqrt(x);

CREATING PACKAGES

 First declare the name of the package using the package keyword followed by a
package name.

 This must be the first statement in a java source file.

Steps:

 Declare the package at the beginning of a file using the form

 package packagename;

 Define the class that is to be put in the package and declare it public.

 Create a subdirectory under the directory where the main source files are stored.

 Store the listing as the classname.java file in the subdirectory created.

 Compile the file. This creates .class file in the subdirectory.

Example

package firstpackage; // package


declaration
public class FirstClass // class

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 78


definition
{
…….
……. // body of class
}

 Package name is firstpackage.


 This file is saved as a file called FirstClass.java and located in a directory name
firstpackage.
 When source file is compiled, java will create a .class file and store it in the same
directory.
 The .class file should in the directory that has the same name as the package.

Java support Package hierarchy

 Specify multiple package names in a package statement, separated by dots.

E.g.: Package firstpackage.secondpackage;

 Store the package secondpackage in a subdirectory of firstpacakge.

ACCESSING A PACKAGE

The general form of import statement is as follows

Import package1 [.package2] [.package3].classname;

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 79


 Package1 is the name of the top level package
 Package2 is the name of the package that is inside the package2 and so on.
 We can have any number of packages in a package hierarchy. Finally explicit
classname is specified.

USING A PACKAGE

 Create a classA under the package1;


 Import the classA from package1 in a program
 Compile the program
 During compilation, the compiler checks for the file ClassA.class in the package1
director for information it needs.
 During running the program the interpreter loads the program along with the code of
the ClassA.class file.

Example 1

package package1; import package1.ClassA;


public class ClassA class PackageTest1
{ {
public static void main(String args[])
public void displayA()
{
{ ClassA obj=new ClassA();
System.out.println(“class a”); obj.displayA();
} }
} }

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 80


Example 2

package package2; import package1.ClassA;


public class ClassB import package2.*;
{ class PackageTest1
{
public void displayB()
public static void main(String args[])
{ {
protected int m= 10; ClassA obj=new ClassA();
System.out.println(“class b”); ClassB objb=new ClassB();
System.out.println(“m=”+m); obj.displayA();
} obj.displayB();
} }
}

Unit: II QUESTION BANK

Section-A (2 Marks)

1. What are access packages?


2. Explain static import?
3. What is mean by interfaces?
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 81
4. What is interface definition?

Section-B (4 Marks)

1. Explain classes and objects?


2. Short notes on wrapper classes?
3. What is importing classes from other packages?
4. What is extending interfaces?

Section–C (12 Marks)

1. Explain briefly packages?


2. Briefly explain interfaces?

FREQUENTLY ASKED QUESTIONS(2012)

1. Write a general form of converting numeric string to primitive numbers?2 MARK


2. Write general form of java program?2 MARK
3. explain dirrerecne between class and interface?5 MARK
4. describe abstract class? 5 MARK
5. Explain operators and its types?10 MARK

********************* END OF UNIT II *************************************

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 82


AVS AND SAKTHIKAILASSH GROUP OF INSTITUTIONS
DEPARTMENT OF BCA
JAVA
UNIT III

…………………………………………………………………………………………………

Inheritance: Inheritance Extending classes – Abstract and Final classes – Interfaces and
Inheritance

…………………………………………………………………………………………………

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 83


INHERITANCE

INTRODUCTION

 Inheritance is the process of taking the features(data members + methods) from one
class to another class.
 The class which is giving the features is known as base/parent class.
 The class which is taking the features is known as derived/child/sub class.
 Instance is known as sub classing or derivation of extendable classes or reusability.
ADVANTAGES OF INHERITACE:
Application development time is very less.
Redundancy (repetition) of the code is reducing. Hence we can get less memory cost
and consistent results.
Instrument cost towards the project is reduced.
We can achieve the slogan write one’s reuse/run anywhere of java.
TYEPS OF INHERITANCE
 Based on taking the features from base class to the derived class, in JAVA we
have five types of inheritances. They are as follows.
1. Single inheritance
 Single class is one in which there exists single base class and single derived class

2. Multi level inheritance


 Multi level inheritance is one which there exist single base class, single derived class
and n number of intermediate base classes.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 84


 An intermediate base class is one, in one contest it acts as bass class and in another
context it acts as derived class

3. Hierarchical inheritance
 Hierarchical inheritance is one in which there exits single base class and n number of
derived classes.

4. Multiple inheritance

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 85


 Multiple inheritance is one in which there exists n number of base classes and single

derived classes.
 Multiple inheritances are one supported by JAVA through classes but it is supported by
JAVA through the concept of interfaces.

5. Hybrid inheritance
 Hybrid inheritance = combination of any available inheritances types
 In the combination , one of the combinations is multiple inheritances.
 Hybrid inheritance also will not be supported by JAVA through the concept of
classes but it is supported through the concept of interfaces.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 86


EXAMPLES FOR INHERITANCE

SINGLE INHERITANCE
 When a single sub class extends the properties of a single super class, then it is known
as single level inheritance.
 Example
class Room
int volume ()
{ {
return (Length*Breadth*Height);
int Length, Breadth;
}
Room (int x, int y) }
class inhert
{ {
public static void main (String args[])
Length=x; {
Room1 obj=new Room1(14,12,10);
Breadth=y;
int area1=obj.area ();
} int volume1=obj.volume();
System.out.println(“Area1 =”+area1);
int area () System.out.println(“Volume =”+volume1);
{ }
return (Length*Breadth);
}
}
class Room1 extends Room

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 87


{
int height;
Room1 (int x, int y, int z)
{
super (x, y);
Height=x;
}
}
MULTILEVEL INHERITANCE
 Since java supports the concept of concept of inheritance it is extensively used in
building the class library.
 Multilevel inheritance is used to build chain of classes.
Example
class Rectangle
{ class Circle extends Box
{
int L, W; circle (int i, int j, int k)
{
Rectangle (int i, int j) super (i, j, k);
{ System.out.println(“Area=”+(3.14*i*i));
}
L=i; }
class mainclass
W=j;
{
System.out.println(“Area =” +(L*W));
public static void main(String args[])
{
} Circle obj=new Circle (10, 20, 30);
}
}
}
class Box extends Rectangle
{
Box (int i, int j, int k)
{
super (i, j);
Output
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 88
Area =200

Volume=6000
System.out.println(“Volume=”+(i*j*k));
}
}

HIERARCHAL INHERITANCE
 When a finally of classes is created in hierarchal model then it is called as hierarchal
inheritance.
Example
class A
class mainclass
{ {
public static void main(String args [])
int a, b; {
A obja=new A();
void input() B objb=new B();
{ C objc=new C();
obja.input1();
a=10; objb.a=10;
objb.b=20;
b=20; objb.addtion();
objc.a=10;
System.out.println(“a=”+a+”b=”+b); objc.b=20;
objc.product();
}
}
} }

class B extends A
{
void addition ()
{
System.out.println(“a+b=”+(a+b));
}
}
class C extends A
{ void product ()
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 89
{
System.out.println(“a*b=”+(a*b));
}
}
ABSTRACT AND FINAL CLASSES

ABSTRACT CLASS

In JAVA we have two types of classes.


They are
1. concrete classes and
2. abstract classes.
A concrete class is one which contains fully defined methods. Defined methods are also
known as implemented or concrete methods. With respect to concrete class, we can create
an object of that class directly.
An abstract class is one which contains some defined methods and some undefined
methods. Undefined methods are also known as unimplemented or abstract methods. Abstract
method is one which does not contain any definition. To make the method as abstract we
have to use a keyword called abstract before the function declaration.

Syntax for ABSTRACT CLASS:

abstract class <clsname>


{
Abstract return_type method_name (method parameters if
any);
};

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 90


For example:
abstract class Op

ABSTRACT METHODS {

 When a method is defined as final than that method is not re- abstract void sum ();

defined in a subclass. };

 Java allows a method to be re-defined in a sub class and those


methods are called abstract methods.
 When a class contains one or more abstract methods, then it should be declared as abstract
class.
 When a class is defined as abstract class, it must satisfy following conditions
 We can’t use abstract classes to instantiate objects directly. For example
 The abstract methods of an abstract class must be defined in its sub class.
 We can’t declare abstract constructors or abstract static methods.
 Final allows the methods not redefine in the subclass.
 Abstract method must always be redefined in a subclass, thus making overriding
compulsory.
 This is done using the modifier keyword abstract in the method definition.
 When a class contains one or more abstract methods, it should also be declared
abstract.
Example
abstract class shape
{
………..
…………
abstract void draw();
…………
………..
}

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 91


RULES:
 We cannot use abstract classes to instantiate objects directly.
 The abstract methods of an abstract class must be defined in its subclass.
 We cannot declare abstract constructors or abstract static method.
FINAL CLASS
USING FINAL WITH INHERITANCE
1. Using final to prevent overriding
 To disallow a method from being overridden, specify final as a modifier at the state of
its declaration.
 Methods declared as final can’t be overridden.
 Example
class A
class B extends A
{ {
void meth () //error can’t override
final void meth () {
{ System.oput.println(“illegal”);
}
System.out.println(“this is a final method”); }
}
}

 When a final method is called, java compiler can copy the byte code for the subroutine
directly inline with the compiled code of the calling method, thus eliminating the
overhead of the method call.
2. Using final to prevent inheritance
 When we want to prevent a class from being inherited, then the class can be declared
as final.
 When a class is declared as final then it implicitly declared all of its methods as final.
 It is illegal to declare a class a both abstract and final since an abstract class is in
complete by itself and relies upon its sub classes to provide complete implementations.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 92
FINAL VARIABLES AND METHODS
 It prevents the subclasses form overriding the member of the superclass.
 Final variables and methods are declared as final using the keyword final as a
modifier.
 Making a method final ensures that the functionality defined in that method will never
be altered in any way.
 The value of a final variable can never be changed.
Final classes
 A class that cannot be sub-classed is called a final class.
 It prevents a class being further sub-classed for security reasons.
 Any attempt to inherit these classes will cause an error.

final class Aclass final int size =100;


{ final void showstatus()
} {…….
Final class Bclass extend someclass ……
{ }
}

FINALIZER METHODS
 Initializationà constructor method is used to initialize an object when it is declared.
This process is called initialization.
 Finalizationàfinalizer method is just opposite to initialization, it automatically frees
up the memory resources used by the objects. This process is known as finalization.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 93


 It acts like a destructor.
 The method can be added to any class.
The finalizer method à finalize()

METHOD OVERRIDING
 A method defined in a super class is inherited by its sub class and is used by the objects
created by the sub class.
 There may be occasions when we want an object to respond to the same method is called.
 This is possible by defining a method in the sub class that has the same name, same
arguments and same return type as a method in the super class.
 When the methods are called, the method defined in the sub class is invoked and executed
instead of the one in the super class. This is known as overriding.\
 Example
class Super
{ int x; void display ()
Super (int x) {
System.out.println(“Super x=”+x);
{ System.out.println(“Sub y=”+y);
this.x; } }
class overridetest
} {
void display () public static void main (String args[])
{
{ Sub S1=new Sub (100, 200);
System.out.println(“x=”+x); S1.display ();
}
} }
}
class Sub extends Super
{ int y;
Sub (int x, int y)
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 94
super (x);
this.y=y;
}
}
METHODS WITH VARARGS
 Varargs represents variable length arguments in methods.
 It makes that java code simple and flexible.

General form
<access specifier> <static> void method-name (object …
arguments)
{
}

 In the above syntax The method contains an argument called varargs in which
 Object is the type of an argument
 Ellipsis (…) is the key to varargs
 Argument is the name of the variable.

For eg: Public void sample(String username, String password, String mail)
Can be written as Public void sample (String …var_name)
Here var_name is the variable name that specifies that we can pass any number of
String arguments to the sample method.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 95


Example program
Class exampleprg
{
Exampleprg(String… person)
{
for (String name: person)
{
System.out.println(“hello” + name);
}
}
Public static void main(String s[])
{
exampleprg (“ram”, “siva”, “suriya”);
}
}

INTERFACES AND INHERITANCE


 Java does not support multiple inheritances. (I.e. java cannot have more than one
superclass.)

class A extends classA extends classB // not possible to use like


this
{
………..
}
 Java provides an alternate approach known as interfaces to support the concept of
multiple inheritances.
 Java can implement more than one interface.

Unit: III QUESTION BANK

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 96


Section-A (2 Marks)

1. What is Inheritance?
2. What is Public Access?
3. Defining Interfaces?
4. What is Extending Interfaces?

Section-B (4 Marks)

1. Explain single Inheritance?


2. What are all the Inheritance rules?
3. Shot notes on abstract method and classes?

Section–C (12 Marks)

1. Explain briefly Inheritance?


2. Briefly explain about public, Friendly, Protected and Private protected access?
3. Explain briefly Interfaces?
FREQUENTLY ASKED QUESTIONS(2012)

5. Write a types of expressions? 2 MARK


6. What is the use of dot operator?2 MARK
7. explain arrays?5 MARK
8. explain strings in java?5 MARK
9. Explain applet life cycle?10 MARK

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 97


*******************END OF UNIT III**********************************

AVS AND SAKTHIKAILASSH GROUP OF INSTITUTIONS

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 98


DEPARTMENT OF BCA
JAVA

UNIT: IV
----------------------------------------------------------------------------------------------------------------
Exception Handling: Error Handling and Exception Handling – Exception
Types and Hierarchy – Try Catch blocks – Use of Throw, Throws and Finally – Programmer
Defined Exceptions.

---------------------------------------------------------------------------------------------------------------

EXCEPTION HANDLING

INTRODUCTION

 DEFINITION: Exceptional handling is a mechanism of converting system


error messages into user friendly messages.
 Run time errors in JAVA are known as exceptions.
 System error messages are those which are unable to understand by end user or
client.
 User friendly messages are those which are understandable by end user or client.

ERROR HANDLING AND EXCEPTION HANDLING


 An exception is an abnormal condition that arises in a code sequence at run time. In
other words, an exception is a run-time error.
 In computer languages that do not support exception handling, errors must be
checked and handled manually-typically through the use of error codes, and so on.
 This approach is an cumbersome as it is troublesome.
 Java’s exception handling avoids these problems and, in the process, brings run-time
error management into the object-oriented world.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 99


TYPES OF ERRORS
 Errors are of two types. They are compile time errors and run time errors.

 Compile time errors are those which are occurring because of poor
understanding of the language.
 Run time errors are those which are occurring in a program when the user
inputs invalid data.
 The run time errors must be always converted by the JAVA programmer into
user friendly messages by using the concept of exceptional handling.

COMPILE-TIME ERRORS
 All syntax errors will be detected and displayed by the Java compiler and therefore
these errors are known as compile-time errors.
 Whenever the compiler displays an error, it will not create the .class file.
 It is therefore necessary that we fix all the errors before we can successfully compile
ad run the program.
 Most of the compile-time errors due too typing mistakes. Typographical errors are
hard to find.
 We may have to check the code word by word, or even character by character.
 The most common problems are:

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 100
Missing semicolons
Missing brackets in classes and methods
Misspelling of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables.
Incompatible types in assignments/initialization
Bad references to objects
Use of = in place of = = operator

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

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 101
 Dividing an integer by zero
 Accessing an element that is out of bounds of an array
 Trying to store a value into an array of an incompatible
class or type
 Trying to cast an instance of a class to one of its subclasses.
 Passing a parameter that is not in a valid range or value for
a method.
 Trying to illegally change the state of a thread
 Attempting to use a negative size for an array
 Using a null object reference as a legitimate object reference
to access a method or a variable.
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string
Example

class Example
{
public static void main(String
args[])
{
int d=0;
int a = 42/d;
}
}

When the Java run-time system detects the attempt to divide by zero, it constructs
a new exception object and then throws this exception. This causes the execution of
example to stop, because once an exception has been thrown, it must be caught by an

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 102
exception handler and dealt with immediately. In this example, we haven’t supplied any
exception handlers of our own, so the exception is caught by the default handler provided
by the Java run-time system.

EXCEPTIONS TYPES AND HIERARCHY


EXCEPTION TYPES

 Java exception is an object that describes an exceptional (that is error) condition that
has occurred in a piece of code.
 When an exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error. Either way, at some point, the
exception is caught and processed.
 Exception can be generated by the Java run-time system, or they can be manually
generated by your code.
 If we want the program to continue with the execution of the remaining code, then we
should try to catch the exception object thrown by the error condition and then display
an appropriate message for taking corrective actions. This is known as exception
handling.
 In JAVA we have two types of exceptions they are custom defined exceptions
 User Defined Exceptions.
 Predefined Exceptions.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 103
 Predefined exceptions are those which are developed by SUN micro system and
supplied as a part of JDK to deal with universal problems. Some of the universal
problems are divide by zero, invalid format of the number, invalid bounce of the
array
 Predefined exceptions are divided into two types.
 synchronous exceptions.
 Asynchronous exceptions.
Asynchronous exceptions.
 Asynchronous exceptions are those which are always deals with hardware
problems. In order to deal with asynchronous exceptions java.lang.Error class
is the super class for all
synchronous exceptions

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 104
 Synchronous exceptions are one which always deals with programmatic errors.
In order to deal with synchronous exceptions we must predefine the class called
java.lang.exception
 Synchronous exceptions are of two types
 They are checked exceptions
i. A checked exception is one whichfound and interface not found.
ii. Unchecked exceptions are those which are always deals with
programmatic run time errors such as ArithmeticException,
NumberFormatException, ArrayIndexOutOfBoundsExcept An exception is an
object which occurs at run time which describes the nature of the message.

HIERARCHY CHART OF EXCEPTION HANDLING


 java.class.Object _ super class for all JAVA class’

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 105
 The purpose of exception handling mechanism is to provide a means to detect and
report an “exceptional circumstance” so that appropriate action can be taken.
 The mechanism suggests incorporation of a separate error handling code that performs
the following tasks:

1. Find the problem ( Hit the exception )


2. Inform that an error has occurred ( Throw the exception )
3. Receive the error information ( Catch the exception )
4. Take corrective actions ( Handle the exceptions )
 When writing programs, we must always be an the lookout for places in the program
where an exception could be generated.
 Some come exceptions that we must watch out for catching are listed in table.

EXCEPTION TYPE CAUSE OF EXCEPTION

ArithmeticException Caused by math errors such as division by


zero

ArrayIndexOutOfBoundsException Caused by bad array indexed

ArrayStoreException Caused when a program tries to store the


wrong type data in an array.

FileNotFoundException Caused by an attempt to access a


nonexistent file

IOException Caused by general I/O failures, such as


inability to read from a file.

NullPointerException Caused by referencing a null object

NumberFormatException Caused when a conversion between strings

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 106
and number fails.

OutOfMemoryException Caused when there’s not enough memory


to allocate a new object.

SecurityException Caused when an applet tries to perform an


action not allowed by the browser’s
security settings.

StackOverflowException Caused when the system runs out of stack


space.

StringIndexOutOfBoundsExceptio Caused when a program attempts to access


n a nonexistent character position in a string.

TRY CATCH BLOCKS

SYNTAX FOR EXCEPTPIONAL HANDLING

 In order to handle he exceptions in java we must use the fallowing key words. They are
try,
catch, finally, throws and throw.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 107
try
{
Block of statements which are to be monitored by JVM at run time (or
problematic errors);
}
catch (Type_of_exception1 object1)
{
Block of statements which provides user friendly messages;
}
catch (Type_of_exception2 object2)
{
Block of statements which provides user friendly messages;
}
.
.
.
catch (Type_of_exception3 object3)
{
Block of statements which provides user friendly messages;
}
finally
{
Block of statements which releases the resources;
}

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 108
 The basic concept of exception handling are throwing an exception and catching it.

try block
Exception object Creator

catch block

 Java exception handling is managed via keywords: try, catch,throw, throws and
finally.
 Program statements that you want to monitor for exceptions are contained within a try
block.
 If an exception occurs within the try block, it is thrown. Your code can catch this
exception and handle it in some rational manner.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be specified as such by a throws
clause.
 Any code that absolutely must be executed before a method returns is put in a finally
block.

Try block:
 This is the block in which we write the block of statements which are to be
monitored by JVM atrun time i.e., try block must contain those statements which
causes problems at run time.
 If any exception is taking place the control will be jumped automatically to
appropriate catch block.
 If any exception is taking place in try block execution will be terminated and the rest
of the statements in try block will not be executed at all and the control will go to
catch block.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 109
 For every try block we must have at least one catch block. It is highly recommended
to write ‘n’number of catch’s for ‘n’ number of problematic statements.

Catch block:
 This is used for providing user friendly messages by catching system error messages.
 In the catch we must declare an object of the appropriate execution class and it will
be internally referenced JVM whenever the appropriate situation taking place.
 If we write ‘n’ number of catch’s as a part of JAVA program then only one catch
will be executing at any point.
 After executing appropriate catch block even if we use return statement in the catch
block the control never goes to try block.

Finally block:
 This is the block which is executing compulsory whether the exception is taking place
or not.
 This block contains same statements which releases the resources which are obtained
in try
block (resources are opening files, opening databases, etc.).
 Writing the finally block is optional.

Example

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 110
class Example OUT PUT

{ Division by zero

public static void main(String args[]) D=5

{
try
{
int d=0;
int a = 42/d;
}
catch( ArithmeticException e)
{
System.out.println(“Division by
zero”);
}
d=5;
System.out.println(“d=”+d);
}
}

MULTIPLE CATCH STATEMENTS


 In some cases, more than one exception could be raised by a single piece of code.
 To handle this type of situation, you can specify two or more catch clause, each
catching a different type of exception.
Example

class Multicatch
{

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 111
public static void main(String[] args)
{
try
{
int a=args.length;
System.out.println(“a=”+a);
int b= 42/a;
int c[]={1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.println(“Divide by zero:”+e);
}

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index Out Of Bound:”+e);
}
System.out.println(“After try/catch block.”);
}
}
 This program will cause division by zero exception if is started with no command-line
parameters, since a will equal zero.
 It will survive the division if you provide a command-line argument, setting a to
something larger than zero.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 112
 But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a
length of 1, yet the program attempts to assign a value to c[42].

USE OF THROW, THROWS AND FINALLY

THROWS

 There may be times when we would like to throw our own exceptions. We can do this
by using the keyword throws as follows:

throw new Throwable_subclass;

 The following example declares a new subclass to signal an error condition in a


method. It overrides the toString( ) method, allowing the description of the exception
to be displayed using println( ).

// This program creates a custom exception type.


class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail=a;
}
public String toString( )
{
return “MyException[“+detail+”]”;
}
}

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 113
class ExceptionDemo
{
static void compute( int a ) throws MyException
{
System.out.println(“Called compute(“+a+”)”);
if (a > 10 )throws new MyException(a);
System.out.println(“Normal Exit”);
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch(MyException e)
{
System.out.println(“Caught”+e);
}
}
}

 The ExceptionDemo class defines a method named compute( ) that throws a


MyException object. The exception is thrown when compute( )’s integer parameter is
greater than 10. Here is the result:

Called compute(1)

Normal Exit

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 114
Called compute(20)

Caught MyException[20]

 If a method is capable of causing an exception that it does not handle, it must specify
this behaviour so that callers of the method can guard themselves against the
exception.
 You do this by including a throws clause in the method’s declaration.

FINALLY

 Java supports another statement known as finally statement that can be used to handle
an exception that is not caught by any of the previous statement.
 finally block can be used to handle any exception generated within a try block.

 It may be added immediately after the try block or after the last catch block shown as
follows.

try try
{ {
--- ---
--- ---
} }
finally
catch( )
{ {
--- -----
} --- --
}
….
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 115
….
finally
{
---
---
}

 when a finally block is defined, this is guaranteed to execute, regardless of whether or


not an exception is thrown.
 As a result, we can use it to perform certain house-keeping operations such as closing
files and releasing system resources.

Example

class FinallyDemo
Output
{ inside procA
procA’s finally
static void proA( )
{
try
{
System.out.println(“Inside ProcA”);
}
finally
{
System.out.println(“ProA’s finally”);
}
}
public static void main( String args[] )
{

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 116
procA( );
}
}
PROGRAMMER DEFINED EXCEPTIONS

 User defined exceptions are those which are developed by JAVA programmer as a part
of
application development for dealing with specific problems such as negative salaries,
negative ages,
etc.
Guide lines for developing user defined exceptions:
 Choose the appropriate package name.
 Choose the appropriate user defined class.
 Every user defined class which we have choose in step 2 must extends either
java.lang.Exception or java.lang.RunTimeException class.
 Every user defined sub-class Exception must contain a parameterized
Constructor by taking string as a parameter.
 Every user defined sub-class exception parameterized Constructor must called
parameterized Constructor of either java.lang.Exception or
java.lang.RunTimeException class by using super(string parameter always).
For example:
package na; // step1
public class Nage extends Exception // step2 & step3
{
public Nage (String s) // step4
{
super (s);// step5
}

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 117
};
NOTE: Main method should not throw any exception since the main method is called by
JVM and JVM cannot provide user friendly message.

QUESTION BANK
UNIT 4

1. Explain in briefly about exception handling (10)


2. Write a short notes on error handling and exception handling(5)
3. What is mean by exception(2)
4. What is mean by try (2)
5. Explain briefly about the try catch blocks(10)
6. Discussing the multiple catch statements(5)
7. Discussing in detailed about use of throw , throws and finally(10)
8. Write a short notes on throws(5)
9. Write a short notes on finally(5)

FREQUENTLY ASKED QUESTIONS(2012)


6) Define: wrapper class?2 MARK
7) Define: applet?2 MARK

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 118
8) Describe string buffer class?5 MARK
9) Explain the operators in java? 5 MARK
10) Explain multithreaded programming?10 MARK

**********************END OF UNIT IV***********************************

AVS AND SAKTHIKAILASSH GROUP OF INSTITUTIONS


DEPARTMENT OF BCA
JAVA

UNIT: V
----------------------------------------------------------------------------------------------------------------

Applets and Graphics: Fundamentals of Applets – Graphics. AWT and Event Handling:
AWT components and Event Handlers – AWT Controls and Event Handling Types and 35
Examples – Swing- Introduction. Input and Output: Files – Streams. Multithreading and
Networking: Multiple Threads – Networking basics.
----------------------------------------------------------------------------------------------------------------

APPLETS AND GRAPHICS


INTRODUCTION:
 In JAVA we write two types of programs or applications.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 119
 They are standalone applications and distributed applications.
 A standalone application is one which runs in the context of local disk
and whose result is not sharable. Every standalone application runs from
command prompt and it contains main method along with
System.out.println statements.
 A distributed application is one which runs in the context of browser or
World Wide Web and it can be accessed across the globe. Any
technology which runs in the browser will have ‘n’ number of life cycle
methods and it does not contain main methods and
System.out.printlnstatements.
In JAVA, SUN micro initially has developed a concept called applets which runs in
the context of browser. “An applet is a JAVA program which runs in the context of
browser or World Wide Web”.
In order to deal with applets we must import a package called java.applet.*. This
package contains only one class Applet whose fully qualified name is
java.applet.Applet. Since applets are running in the browser, the class Applet contains
the life cycle methods.Life cycle methods are also called as loop back methods.

FUNDAMENTALS OF APPLETS
 Applets are small java program that are primarily used in internet computing. They can
be transferred over the internet from one computer to another and run using the applet
viewer or any web browser that support the java program.
 An applet can perform arithmetic operations, play sounds, display graphics, accept user
input, create animation and play interactive games.
 Java applications are generally run from a command-line prompt using JDK. Applets are
run on any browser supporting Java. For an applet to run it must be included in a web
page using HTML pages.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 120
 When a browser loads a web page including an applet, the browser downloads the applet
from the web server and runs it on the web owner’s system. Java interpreter is not
required specifically for doing so it is already built-in the browser.

LOCAL APPLET
 An applet developed locally and stored in a local system called as local applet.
 They doesn’t require internet connection It searches the directories in the local system
and locates and loads specified applet.
REMOTE APPLET
 It is stored on a remote computer which is connected to the net. If connected with the net,
we can download the remote applet onto our system. We can utilize it via the internet.
URL
 Uniform Resource Locator. It specifies the applets address.
 Applet code uses the service of two classes namely, Applet and Graphics from the Java
library.
 The applet class is contained in the java. Applet package provides life and
behavior to the applet through its methods such as init(), start(), and paint().
The Applet class maintains the lifecycle of an applet.
 The paint() method of the applet class actually displays the result of the applet
code on the screen.
APPLET LIFE CYCLE
 Every java applet inherit a set a default behavior from the Applet class. As the result
applet is loaded, it undergoes a series of changes in its state as shown in the above figure
the applet states will be
 Born or initialization state
 Running state
 Idle state
 Dead or destroyed state
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 121
 In java.applet.Applet we have four life cycle methods.
 They are public void init (), public void start (), public void stop () and public void
destroy ()
1. Public void init ():
 This is the method which is called by the browser only one time after loading the
applet.
 In this method we write some block of statements which will perform one time
operations, such as, obtaining the resources like opening the files, obtaining the
database connection, initializing the parameters, etc.
 It is achieved by calling init() method of the applet class.
Syntax:
Public void init()
{
……..
}
2. Public void start ():
 After calling the init() method, the next method which is from second request to
sub-sequent requests the start method only will be called i.e., short method will be
called each and every time.
 In this method we write the block of statement which provides business logic.

Syntax:
Public void start()
{
………
}

3. Public void stop ():


AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 122
 This id the method which is called by the browser when we minimize the window.
 In this method we write the block of statements which will temporarily releases the
resources which are obtained in init method.
Syntax:
public void stop()
{
………….
}

4. Public void destroy ()


 An applet is said to be dead or destroyed when it is removed from the memory.
 This is the method which will be called by the browser when we close the window
button or when we terminate the applet application.
 In this method we write same block of statements which will releases the resources
permanently which are obtained in init
Syntax:
public void destroy()
{
.....
......
}
5. Public void display()
 Applet moves to the display state whenever it has to perform some output operation
on the screen. This happens immediately after the applet enters into the running
state.The paint() method is called to accomplish this task. Almost every applet will
have a paint() method like other method in the life cycle.
Syntax: public void paint(Graphics s)
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 123
//ACTIONS
}

STEPS for developing APPLET PROGRAM:


1. Import java.applet.Applet package.
2. Choose the user defined class that must extends java.applet.Applet class and ensure
the
modifier of the class must be public.
3. Overwrite the life cycle methods of the applet if require.
4. Save the program and compile.

5. Run the applet: To run the applet we have two ways. They are using HTML
program and using applet viewer tool.
 Using HTML program: In order to run the applet through HTML program we must use
the following tag.

Syntax:

<applet code =”.class file of the applet” height = height value width =
widthvalue>
</applet>

For example:
File name: MyApp.html

<HTML>

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 124
<HEAD>
<TITLE> My applet example </TITLE>
</HEAD>
<BODY>
<APPLET code="MyApp" height=100
width=150>
</APPLET>
</BODY>
</HTML>

Usingappletviewer:
 Appletviewer is a tool supplied by SUN micro system to run the applet programs from
the command prompt (in the case of browser is not supporting).

Syntax: appletviewer filename.java

For example:
appletviewer MyApp.java

 When we use appletviewer to run the above applet, MyApp.java program must
contain the
following tag within the multi line comment.

/*<applet code= “MyApp” height=300 width=300>

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 125
</applet>*/

EXAMPLE:
An applet program which displays “WELCOME TO AVS COLLEGE”
Program:

/*<applet code= “MyApp” height=300 width=300> </applet>*/


import java.applet.Applet;
public class MyApp extends Applet
{
public void paint(java.awt.Graphics g)
{
g.drawString ("WELCOME TO AVS
COLLEGE", 20, 15); }
};

GRAPHICS

GRAPHICS

 One of the most important features of Java is its ability to draw graphics .
 Java’s graphics class includes methods for drawing many different types of shapes.
 To draw a shape on the screen , we may call one of the methods available in the
graphics class.
 The following are the most commonly used methods in graphics class.

Creating Lines and rectangles:

Methods:

 drawLine()

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 126
 drawRect()
 fillRect()
 drawRoundRect()
 fillRoundRect()
Ex:

Import java.awt.*;
Import java.applet.*;
/*<Applet code = “line.class” height=100 width=200>
</Applet>*/
Public class line extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.fillRect(60,10,30,80);
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(20,100,70,30,5,5);
}
}
Circles and Ellipses:
It is achieved by using
 drawOval()
 fillOval()
Ex:

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 127
Import java.awt.*;
Import java.applet.*;
/*<Applet code = “cir.class” height=100
width=200>
</Applet>*/
Public class cir extends Applet
{
public void paint(Graphics g)
{
g.drawOval(20,20,200,120);
g.setColor(color.Green);
g.fillOval(70,30,100,100);
}
Arcs:

It is achieved by using
 drawArc()
 drawOval()
Ex:
Import java.awt.*;
Import java.applet.*;
/*<Applet code = “larc.class” height=100
width=200>
</Applet>*/
Public class larc extends Applet
{
public void paint(Graphics g)
{

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 128
g.drawOval(40,40,120,150);
g.fillOval(68,81,10,10)
g.fillArc(60,125,80,40,180,180);
}
}
Polygons:

 They are the shapes with many sides.


 It is a set of lines interconnected together. Thus the end of the first line will be the
beginning of the second line …..
 It is achieved by using the drawPolygon() method.

Syntax:
Void drawPolygon(int x[], int y[], int
numpoints)
AWT (abstract window
toolkit)

 In JAVA we can develop to types of GUI (Graphic User Interface) applications.


 They are standalone GUI applications and distributed GUI applications.
 As a part of GUI applications we use to create two types of components.
 They are passive components and active components
 A passive component is one where there is no interaction from the user.
For example label.
 An active component is one where there is an interaction from the user.
For example button, check box, scroll bar, etc.
 The active and passive components in JAVA are available in terms of classes.
 In order to deal with any GUI applications we must import a package called

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 129
java.awt.* (contains various classes and interfaces for creating GUI components) and
java.awt.event.* (contains various classes and interfaces which will provide functionality to
GUI components).
 Except Object class and Applet class all the classes in the above hierarchy chart are
belongs
to java.awt.* package.
A JAVA program which creates Window and Frame

import java.awt.*;
class myf extends Frame class FDemo
{ {
Myf () Public static void main
(String [] args)
{ {
setText (“AVS COLLEGE BCA”); Myf mo=new myf ();
setSize (100, 100); }
LABEL setBackground (Color, cyan); }:
CLASS: setForeground (Color, red);
setVisible (true);
}
};

 Label is a class which is used for creating label as a part of windows application.
 The component label comes under passive component.
 Labels always improve the functionality and readability of active components.
 Creating a label is nothing but creating an object of label.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 130
Label class API:
Data members:
public static final int LEFT (0)
public static final int CENTER (1)
public static final int RIGHT (2)
//The above three statements are called alignment parameters or modifiers.
Constructors:
Label ()
Label (String)
Label (String label name, int alignment modifier)
Instance methods:
public void setText (String);
public String getText ();
public void setAlignment (int);
public int getAlignment ();
BUTTON CLASS:
Button is an active component which is used to perform some operations such as
saving thedetails into the database, deleting the details from the database, etc.
Creating a button is nothing but creating an object of Button class.
Button API:
Constructors:
Button ();
Button (String);
Instance methods:
public void add ActionListener (ActionListener);
public void remove ActionListener (ActionListener);
CHOICE:
 Choice is the GUI component which allows us to add ‘n’ number of items.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 131
 This component allows selecting a single item at a time.
 Creating a choice component is nothing but creating an object of Choice class.
Choice API:
Constructors:
choice ();

Instance methods:
public void add (String);
public void addItem (String);
public void add (int pos, String);
public void addItem (int pos, String);
public void remove (String);
public void remove (int);
public void removeAll ();
CHECKBOX:
 Checkbox is basically used for maintaining checklist purpose checkbox is an
interactive component which contains a square symbol and a label.
 Creating a checkbox is nothing but creating an object of checkbox class

Checkbox API:
Constructors:
checkbox ();
checkbox (String);
checkbox (String, boolean);
Instance methods:
public void setLabel (String);

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 132
public String getLabel ();
public void setState (boolean);
public boolean getState ();
public void addItemListener (ItemListener);
public void removeItemListener (ItemListener);
RADIO BUTTONS:
 In java.awt we are not having a special class for radio buttons but we can create
radio
button from Checkbox class.
 In java.awt we have a predefined class called CheckboxGroup through which we
can add all
the checkboxes to the object of CheckboxGroup class.
Steps for converting checkboxes into radio button:
1. Create objects of CheckboxGroup class.
For example:
CheckboxGroup cbg1=new CheckboxGroup ();
CheckboxGroup cbg2=new CheckboxGroup ();
 CheckboxGroup object allows to select a single checkbox among ‘n’ number of
checkboxes.
2. Create ‘n’ number of objects of Checkbox class
For example:

Checkbox b1, b2;


b1=new Checkbox (“C”);
b2=new Checkbox (“Cpp”);
3. Decide which checkboxes are adding to which CheckboxGroup object.
In order to add the checkboxes to the CheckboxGroup object, in Checkbox class we have
the following method:

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 133
public void setCheckboxGroup (CheckboxGroup);
For example:
cb1.setCheckboxGroup (cbg1);
cb2.setCheckboxGroup (cbg2);
4. Register the events of checkbox with ItemListener by using the following method:
public void addItemListener (ItemListener);

NOTE: Instead of using a setCheckboxGroup method we can also used the following
Constructor which is present in Checkbox class.

Checkbox (String, CheckboxGroup, boolean);


Checkbox (String, boolean, CheckboxGroup);
For example:
Checkbox cb1=new Checkbox (“C”, cbg1, false);
Checkbox cb2=new Checkbox (“Cpp”, cbg2, false);
TEXT FIELD:
 TextField is GUI interactive component which allows entering the data in single
line.
 Whatever the data, we enter to text field, by default that data will be treated as
string.
 If we are able to read the data of text field then that text field is known as editable
or normal text field.
 If we are unable to read the data of the text field then that text field is known as
echo text
field and the character which is available is known as echo character. Creating a text box is
nothing but creating an object of TextField class.
Text Field API:
Constructors:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 134
TextField ();
TextField (int);// int represents size of the text field
TextField (String);// data in the text field
TextField (String, int);
Instance methods:
public void setSize (int);
public int getSize ();
public void setText (String);
public String getText ();

LIST:
 List is the GUI interactive component which allows to select either single or
multiple items at a time.
 Creating List component is nothing but creating an object of List class.
List API:
Constructors:
List ();
List (int size);
List (int size, boolean mode);
Instance methods:
public void setSize (int size);
public int getSize ();
public void add (String);
public void addItem (String);
public void add (int, String);

EVENT HANDLING TYPES

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 135
 Whenever we want to develop any windows applications one must deal with event
delegation model.
 Event delegation model contains four properties.
 They are: In order to process any active components, we must know either name or
caption or label or reference of the component (object).
 Whenever we interact any active component, the corresponding active component will
have one predefined Event class, whose object will be created and that object contains
two details:
1. Name of the component.
2. Reference of the component.
 The general form of every Event class is xxx event.
For example:

Component name Event name


Print java.awt.event.ActionEvent
Choice java.awt.event.ItemEvent
TextField java.awt.event.TextEvent
TextArea java.awt.event.TextEvent
Scrollbar
java.awt.event.AdjustmentEvent

 In order to perform any action or operation when an interactive component is


interacted we must write some set of statements into the appropriate methods.
 These methods are not defined or developed by SUN micro system, but they have
supplied those methods with no definition i.e., undefined methods.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 136
 In JAVA purely undefined methods are abstract methods present in interfaces.
 Interfaces in awt are called listeners. Hence, every interactive component must have a
predefined listener whose general notation is xxx listener
For example:

Component name Listener name


Button
java.awt.event.ActionListener
Choice

SWINGS java.awt.event.ItemListener
TextField java.awt.event.TextListener
TextArea java.awt.event.TextListener
Scrollbar
java.awt.event.AdjustmentListener

INTRODUCTION
 In the earlier days SUN micro system; we have a concept called awt.
 AWTis used for creating GUI components.
 All AWT components are written in ‘C’ language and those components appearance is
changing from one operating system to another operating system. Since, ‘C’ language is
the platform dependent language.
 In later stages SUN micro system has developed a concept called swings.
 Swings are used for developing GUI components and all swing components are developed
in java language.
 Swing components never change their appearance from one operating system to another
operating system. Since, they have developed in platform independent language.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 137
AWT SWING
1. awt components are developed in ‘C’ 1. Swing components are developed in java
language. language.
2. All awt components are platform 2. All swing components are platform
dependent. independent.
3. All awt components are heavy weight 3. All swing components are light weight
components, since whose processing time components, since its processing time and
and main memory space is more. main memory space is less.

FOR EXAMPLE:
JButton JB=new JButton (“ok”);
 All components of swings are treated as classes and they are belongs to a package
called javax.swing.*
 In swings, we have two types of components. They are
 auxiliary components and
 logical components.
Auxiliary components are those which we can touch and feel. For example, mouse,
keyboard, etc.
Logical components are those which we can feel only.
Logical components are divided into two types. They are
 passive or inactive components and
 active or interactive components.]

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 138
HIERARCHY CHART IN SWINGS:

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 139
INPUT AND OUTPUT

FILES
 It is defined as the collection of records. Further the records are classified as a
collection of fields.
 We can store and manage files which creates file, updates file. We can perform both
reading and writing operation on files.
 The process of reading and writing objects are called as Object Serialization Java.io
package includes a class called File Class which provides support for creating files
and directories. It includes several constructors for instantiating the file objects.
Creation of Files:
 A file name is a unique string of characters that helps identify a file on disk.
It consists of two parts:
(a) Primary Part:
(b) Extension Part
Ex:
Test.dat unit.doc stud.txt

File Initialization:
It can be done in two ways.
(a) Direct Method
(b) Indirect Method
(1) Direct Method:
Here we explicitly specify the name of the file.
Ex:
FileInputStream fis; //defining a file stream object
try
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 140
fis=new FileInputStream(“test.dat”)
………
}
Catch (IOException e)
……
(2) Indirect Method:
Here we can implicitly specify the file
Ex:
…..
File infile;
infile = new File(“test.dat”);
FileInputStream fis;
try
{
fis = new FileInputStream(infile);
…….
}
Catch( ….)

RANDOM ACCESS FILES


 It allows us to create files that can be used for reading and writing data with random access.
Open Mode Options:
r  for reading option
w  for both read and write
rw  for performing updation on existing file
File Pointer:
 We can move the arbitrary positions in the file prior for reading and writing.
 It is done by means of seek()
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 141
import java.io.*;
class rac
Ex:
{
File = new RandomAccessFile (“rand.dat”,”rw”)
public static void main(String args[])
{
EXAMPLE PROGRAM FOR RANDOM
RandomAccessFile file=null;
ACCES FILES
try
{
file=new
STREAMS
RandomAccessFile("rand.dat","rw");
 It represents an ordered sequence of data. It is
//writing to the file
uniform, easy-to-use, an object-oriented
file.writeChar('R');
interface between the program and the I/O
file.writeInt(255);
devices. It requires a source field and the
file.writeDouble(323.45);
destination field.
file.seek(0);//go to the begining of the
file
Types of Stream:
System.out.println(file.readChar());
1. Input Stream
System.out.println(file.readInt());
2. Output Stream
System.out.println(file.readDouble());
1. Input Stream:
file.seek(2);//go to end of the file and
it is used to extract the data from the source file
append
and sends it to the program for further processing.
file.writeBoolean(false);
2. Output Stream:
file.seek(4);//go to fourth item
it takes the data from the program and sends it to
System.out.println(file.readBoolean());
the destination file.
file.close();
Stream Classes:
}
All the stream class are done by using java.io.*;
catch(IOException e)
package.
{
}
}
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 142
}
It contains a large number of stream classes that provide capabilities for processing
all types of
data.
Categories:
1. Handling I/O operations  ByteStream Class
2. Managing I/O Operations  CharacterStream Class

ByteStream Class:
 It creates and manipulates streams and files for reading and writing bytes.It is
unidirectional in nature, that means it transmit the byte in only one direction.
1. InputStream:
 It reads 8 bit bytes including a superclassIt includes a number of subclasses
for supporting various related functions.
 It is an abstract class.No instance of the class is created.
Functions:
Reading bytes
Closing streams
Marking positions
Skipping ahead
Finding number of bytes
2. OutputStream:
It is derived from the base class output stream.
It is also an abstract class.
Functions:
Writing bytes
Closing streams
Flushing streams

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 143
EXAMPLE PROGRAM

import java.io.*;
class rwb
{
public static void main(String args[])
{
FileInputStream infile=null;
int b;
try
{
infile=new FileInputStream("in.Doc");
while((b=infile.read())!=-1)
{
System.out.print((char)b);
}
infile.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}

OTHER STREAMS:
1. Object Streams:

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 144
 We can perform input–output operations on objects.
 The object streams are created using ObjectInputStream and
ObjectOutputStream
 This process is called as object serialization
2. Piped Streams:
 They provide the functionality for the threads to communicate and exchange the data
between them.
 The objects used are PipedInputStream and PipedOutputStream.
3. Pushback Streams:
 It is used to push a single byte or character back into the input stream so that it
can be reread.
 This is used with parsers.

4. Filtered Streams:
 It provides two abstract classes FilterInputStream and FilterOutputStream, which
create i/o streams for filtering io operations.
 They are called as filters.

MULTITHREADING AND NETWORKING


THREAD:
 A flow of control is known as thread.
 If a program contains multiple flow of controls for achieving concurrent execution
then that program is known as multi threaded program.
 A program is said to be a multi threaded program if and only if in which there exist
‘n’ number of sub-programs there exist a separate flow of control.
 All such flow of controls are executing concurrently such flow of controls are known
as threads and such type of applications or programs is called multi threaded
programs.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 145
Switching Switching

CREATING THREADS

 Creating threads in Java is simple.


 Threads are implemented in the form of objects that contain a method called run( ).
 The run( ) method is the heart and soul of any thread. It makes up the entire body of
the thread and is the only method in which the thread’s behavior can be implemented.
 A typical run( ) would appear as follows:

public void run( )

---- ( Statements for implementing thread )

----
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 146
}

 The run( ) method should be invoked by an object of the concerned thread. This can be
achieved by creating the thread and initiating it with the help of another thread method
called start( ).

A NEW THREAD CAN BE CREATED IN TWO WAYS.

1. By creating a thread class : Define a class that extends thread class and override its
run( ) method with the code required by the thread.

2. By converting a class to a thread: Define a class that implements Runnable interface.


The Runnable interface has only one method, run( ) , that is to be defined in the
method with the code to be executed by the thread.

 The approach to be used depends on what the class we are creating requires.
 If it requires to extend another class, then we have no choice but to implement the
Runnable interface, since Java classes cannot have two superclasses.

EXTENDING THE THREAD CLASS

 We can make our class Runnable as a thread by extending the class java.lang.Thread.
This gives us access to all the thread methods directly. It includes the following steps:

1. Declare the class as extending the Thread class

2. Implement the run( ) method that is responsible for executing the sequence of code that
the thread will execute.

3. Create a thread object and call the start( ) method to initiate the thread execution.

Declaring the class

The thread class can be extended as follows:

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 147
class MyThread extends Thread
{
……..
……..
}
Now we have a new type of thread MyThread.

Implementing the run( ) method

 The run( ) method has been inherited by the class MyThread.


 We have to override this method in order to implement the code to be executed by our
thread.
 The basic implementation of run( ) will look like this:

public void run( )


{
……..
…….. // Thread code here
}
 when we start the new thread, Java calls the thread’s run( ) method, so it is the run( )
where all the action takes place.

STARTING NEW THREAD

 To actually create and run on instance of the thread class, we must write the following

MyThread aThread = new MyThread( );

aThread.start ( ); //invokes run( ) method

 The second line calls the start( ) method causing the thread to move into the runnable
state.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 148
 Then the Java runtime will schedule the thread to run by invoking its run( ) method.
Now, the thread is said to be in the running state.

An example of using the Thread class

class A extends Thread


{
public void run( )
{
for ( int i=1;i<=3;i++)
{
System.out.println(“\t From thread A:i=”+i);
}
System.out.println( “ Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
for ( int i=1;i<=3;i++)
{
System.out.println(“\t From thread B:i=”+i);
}
System.out.println( “ Exit from B”);
}
}
class ThreadTest
{

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 149
public static void main(String[] args)
{
new A( ).start( );
new B( ).start( );
}
}
Output
From thread A:i=1
From thread A:i=2
From thread B:i=1
From thread B:i=2
From thread A:i=3
Exit from A
From thread B:i=3
Exit from B
 The main thread dies at the end of its main method. However, before it dies, it creates
and starts all the two threads A and B. Note that the output from the threads are not
specially sequential.

STOPPING AND BLOCKING THE THREAD

Stopping A thread

 Whenever we want to stop a thread from running further, we may do so by calling its
stop( ) method, like:

AThread.stop( );

 This statement causes the thread to move to the dead state. The stop( ) method may be
used when the premature death of a thread is desired.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 150
Blocking a Thread

 A thread can also be temporarily suspended or blocked from entering into the runnable
and subsequently running state by using either of the following thread methods:

sleep( ) // blocked for a specified time

suspend( ) //blocked until further orders

wait( ) //blocked until certain condition

 The thread will return to the runnable state when the specified time is elapsed in the
case of sleep( ), the resume( ) method is invoked in the case of suspend( ) and the
notify( ) method is called in the case of wait( ).

LIFE CYCLE OF A THREAD


 During the life time of a thread, there are many states it can enters. They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state(Terminated)

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 151
STATE TRANSITION DIAGRAM OF A THREAD

NEWBORN STATE

 When we create a thread object, the thread is born and is said to be in newborn state.
The thread is not yet scheduled for running. At this state, we can do only one of the
following things with it:

 Schedule it for running using start( ) method


 Kill it using stop( ) method
 If scheduled, it moves to the runnable state. If we attemps to use any other method at
this stage, an exception will be thrown.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 152
SCHEDULING A NEW BORN THREAD

RUNNABLE STATE
 The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution.
 If all threads have equal priority, then they are given time slots for execution in round
robin fashion, i.e., first-come, first-serve manner.
 This process of assigning time to threads is known as time-slicing.
 However, if we want a thread to relinquish control to another thread of equal priority
before its turn comes, we can do so by using the yield( ) method.

RUNNING STATE
 Running means that the processor has given its time to the thread for its execution.
 The thread runs until it relinquish control on its own or it is preempted by a higher
priority thread.
 A running thread may relinquish its control in one of the following situations.

1 .It has been suspended using suspend( ) method. A suspended thread can be revived by
using the resume( ) method. This approach is useful when we want to suspend a thread for
some time due to certain reason, but do not want to kill it.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 153
Relinquishing control using suspend( ) method

2.
It

has been made to sleep. We can put a thread to sleep for a specified time period using the
method sleep( time) where time is in milliseconds. This means that the thread is out of queue
during this time period. The thread re-enters the runnable state as soon as this time period is
elapsed.

3.It has been told to wait until some event occurs. This is done using the wait( ) method. The
thread can be scheduled to run again using the notify( ) method.

BLOCKED STATE
 The thread is said to be blocked when it is prevented from entering into the runnable
state and subsequently the running state.
 This happens when the thread is suspended, sleeping, or waiting in order to satisfy
certain requirements. A blocked thread is considered “ not runnable” but not dead and
therefore qualified to run again.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 154
DEAD STATE
 Every thread has a life cycle.
 A running thread ends its life when it has completed executing its run( ) method.
 It is a natural death. However, we can kill it by sending the stop message to it at any
state thus causing premature death to it.
 A thread can be killed as soon as it is born, or while it is running, or even when it is in
“ not runnable “ condition.

Example
class A extends Thread
{
public void run( )
{
for(int i=1; i< 3;i++)
{
if (i == 1 ) yield( );
System.out.println(“\n From thread A:I=”+i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
for(int j=1 ;j<=5;j++)
{
System.out.println(“\n From thread B:j=”+j);

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 155
if (j==3 )
stop( );
}
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run( )
{
for(int k=1; k<=3;k++)
{
System.out.println(“\t From thread c:k=”+k);
if (k === 1 )
try
{
sleep(1000);
}

catch( Exception e)
{
}
}
System.out.println(“Exit from C”);
}
}
class ThreadMethods
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 156
public static void main(String[] args)
{
A threadA =new threadA( );
B threadB =new threadB( );
C threadC =new threadC( );
System.out.println(“Start thread A”);
ThreadA.start( );
System.out.println(“Start thread B”);
ThreadB.start( );
System.out.println(“Start thread C”);
ThreadC.start( );
System.out.println(“End of main thread”);
}
}
Output
Start thread A
Start thread B
Start thread C
From Thread B:j=1
From Thread B:j=2
From Thread A:i=1
From Thread A:i=2
End of main thread
From Thread C:k=1
From Thread B:j=3
From Thread A:i=3
Exit from A
From Thread C:k=2
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 157
From Thread C:k=3
Exit from C

THREAD EXCEPTIONS
 Note that the call to sleep( ) method is enclosed in a try block and followed by a catch
block. This is necessary because the sleep( ) method throws an exception, which
should be caught.
 If we fail to catch the exception, program will not compile.
 Java run system will throw IllegalThreadStateException whenever we attempt to
invoke a method that a thread cannot handle in the given state.
 For example, a sleeping thread cannot deal with the resume( ) method because a
sleeping thread cannot receive any instructions. The same is true with the suspend( )
method when it is used on a blocked ( not runnable ) thread.
 Whenever we call a thread method that is likely to throw an exception, we have to
supply an appropriate exception handler to catch it.

THREAD PRIORITY
 In Java, each thread is assigned a priority, which affects the order in which it is
scheduled for running.
 The threads of the same priority are given equal treatment by the Java scheduler and,
therefore they share the processor on a first-come,first-serve basis. Java permits us to
set the priority of a thread using the setPriority( ) method as follows:
ThreadName.setPriority( int number );
 The number is an integer value to which the thread’s priority is set. The thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY=5
MAX_PRIORITY = 10
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 158
 The number may assume one of these constants or any value between 1 and 10. Note
that the default setting is NORM_PRIORITY.
 By assigning priorities to threads, we can ensure that they are given the attention they
deserve. Whenever multiple threads are ready for execution, the Java system chooses
the highest priority thread and execute it.
 Remember that the highest priority thread always preempts any lower priority threads.
Example
class A extends Thread
{
public void run( )
{
System.out.println(“Thread` A Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread A:i=”+i);
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
System.out.println(“Thread B Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread B:j=”+j);
System.out.println(“Exit from B”);
}
}

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 159
class C extends Thread
{
public void run( )
{
System.out.println(“Thread C Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread C:i=”+i);
System.out.println(“Exit from C”);
}
}
class ThreadPriority
{
public static void main(String args[])
{
A threadA = new A( );
B threadB = new B( );
C threadC = new C( );
threadC.setPriority( Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority( )+1);
threadC.setPriority( Thread.MIN_PRIORITY);
System.out.println(“Start thread A”);
threadA.start( );
System.out.println(“Start thread B”);
threadB.start( );
System.out.println(“Start thread C”);
threadC.start( );
System.out.println(“End of main thread”);
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 160
}
}
Output
Start thread A
Start thread B
Start thread C
Thread B Started
From thread B:j=1
From thread B:j=2
Thread C Started
From thread C:k=1
From thread C:k=2
From thread C:k=3
Exit from C
End of main thread
From thread B:j=3
Exit from B
Thread A Started
From thread A:i=1
From thread A:i=2
From thread A:i=3
Exit from A
SYNCHRONIZATION
 In the above examples, we have seen threads that use their own data and methods
provided inside their run( ) method.
 What happens when they try to use data and methods outside themselves. On such
occasions, they may compete for the same resources and may lead to serious problems.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 161
 For example, one thread may try to send a record from a file while another is still
writing to the same file.
 Depending on the situation, we may get strange results. Java enables us to overcome
this problem using a technique known as synchronization.
 In case of Java, the keyword synchronized helps to solve such problems by keeping a
watch an such locations. For example, the method that will read information from a file
and the method that will update the same file may be declared as synchronized.
Example
synchronized void update( )
{
---- // code here is synchronized
----
}
 When we declare a method synchronized, Java creates a “monitor” and hands it over to
the thread that calls the method first time.
 As long as the thread holds the monitor, no other thread can enter the synchronized
section of code.
 A monitor is like a key and the thread that holds the key can only open the lock.
 It is also possible to mark a block of code as synchronized as shown below:
synchronized ( lock-object )
{
---- // code here is synchronized
----
}
 Whenever a thread has completed its work by using synchronized method, it will hand
over the monitor to the next thread that is ready to use the same resource.
 An interesting situation may occur when two or more threads are waiting to gain
control of a resource.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 162
 Due to some reason, the condition on which the waiting threads rely on gain control
does not happen.
 This result in what is known as deadlock. For example, assume that the thread A must
access method1 before it can release method2, but the threadB cannot release method1
until it gets hold on method2.
 Because these are mutually exclusive conditions, a deadlock occurs. The code below
illustrate this:
ThreadA
synchronized method2( )
{
synchronized method1( )
{
}
}
ThreadB
synchronized method1( )
{
synchronized method2( )
{
}
}
IMPLEMENTING THE RUNNABLE INTERFACE
 To create thread using the Runnable interface, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated from this “runnable” class as
the target of the thread.
4. Call the thread’s start( ) method to run the thread.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 163
 If the direct reference to the thread threadX is not required, then we may use a shortcut
as shown below:
new Thread( new X( ) ).start( );
Example
class X implements Runnable
{
public void run( )
{
for(int i=1;i<3;i++)
System.out.println(“\t ThreadX:”+ i);
System.out.println(“End of thread X”);
}
}
class RunnableTest
{
public static void main(String[] args)
{
X runnable = new X( );
Thread threadX = new Thread( runnable );
threadX.start( );
System.out.println(“End of main thread”);
}
}
Output
End of main Thread
ThreadX:1
ThreadX:2
End of ThreadX
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 164
NETWORKING BASICS

Collection of interconnected autonomous or non-autonomous computers is known as


network.
 Autonomous represents independent processing power whereas non-autonomous
represents dependent processing.
Aims of networking:
1. Fastest and reliable communication can be achieved.
2. Communication cost is so less.
3. Data can be shared either locally (centralized application) or globally (distributed
application).
 As a part of networking we write two types of programs. They are client side
programming
and server side programming.

1. A client side programming is one which always makes a request to get the service
from the server side program.
2. A server side programming is one which receives client request, process the request
and gives response back to the client.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 165
 In order to exchange the data between the client and server we must have a protocol. A
protocol is the set of rules which exchange the data between client and server
programs.
 When we are developing any client and server application we must follow certain steps
at client client side and server side.

Steps to be performed at client side

1. Connect to the server side program. To connect to the server the client side program must

pass server name or domain naming services or IP address

2. Make a request by passing data.

3. After performing some operations at server side, the client side program must receive the
response from the server side.

4. Read the response data which is sent by the server.

Steps to be performed at server side

1. Every server side program must run at certain port number (a port number is a logical
numerical ID at which logical execution of the program is taking place)

2. Every server must have a physical name to access the services or programs which are

running. Server can be access in two ways.

On name(local host by defacult) called DNS and

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 166
on IP address (127.0.0.1 default)

3. Every server side program must receive client request.

4. Every server side program must read request data (request parameter).

5. Process the data or request.

6. Send the response back to the client.

Socket: In order to develop the program at client side we must use the class Socket.

Socket API:

Constructor:

Socket (String hname, int Portno) throws UnknownHostException,


IOException

Instance methods:

public OutputStream getOutputStream ();

public InputStream getInputStream ();

public void close (); _3

DISADVANTAGES OF NETWORKING:

1. We are able to develop only one-one communication or half-duplex or walky


talky applications only.

2. We are able to get only language dependency (client side and server side we
must write only

java programs).

3. There is no support of predefined protocol called http.


AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 167
4. There is no internal support of third party servers such as tomcat, weblogic, etc.

5. We are able to develop only intranet applications but not internet applications.

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 168
QUESTION BANK

UNIT 5

1. Briefly discussing about applets and graphics (10)


2. Explain fundamentals of applets(2)
3. Write a notes on applets(5)
4. Explain the URL(5)
5. Write a notes on applet life cycle(10)
6. How to creating an executable applet(2)
7. Write a coding to designing a web page(5)
8. Explain the structure of the applet tag(5)
9. Write a notes on passing parameter to applet(5)
10.Explain the listing of html tags(5)
11.Briefly explain about the graphics(10)
12.Write a notes on input and output files(10)
13.Explain briefly about multithreading and networking(10)
14.Write a short notes on extending the thread class(5)
15.Write a shot notes on staring new thread(5)
16.Explain the life cycle of a thread(5)
17.Explain about the thread priority(5)
18.Write a short notes on synchronization(5)
19.Explain the implementing the run able interface(5)

FREQUENTLY ASKED QUESTIONS (2012)


11) When will you apply final class?2 MARK
12) Define hiding classes?2 MARK

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 169
13) what are the steps for create applet ? 5 MARK
14) how to accessing interface variable?5 MARK
15) Explain the exception types with an example?10 MARK

*****************************END OF UNIT V******************************

ALL THE BEST

AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 170

You might also like