0% found this document useful (0 votes)
3 views

JAVA-ALL

The document provides an overview of Java programming, focusing on object-oriented programming fundamentals, including concepts like classes, objects, encapsulation, inheritance, and polymorphism. It outlines the benefits of Java, its applications, differences from C and C++, and details about the Java Development Kit (JDK) and Java Runtime Environment (JRE). Additionally, it explains the structure of a Java program, including tokens, keywords, identifiers, literals, variables, and constants.

Uploaded by

jaydipsinh7285
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JAVA-ALL

The document provides an overview of Java programming, focusing on object-oriented programming fundamentals, including concepts like classes, objects, encapsulation, inheritance, and polymorphism. It outlines the benefits of Java, its applications, differences from C and C++, and details about the Java Development Kit (JDK) and Java Runtime Environment (JRE). Additionally, it explains the structure of a Java program, including tokens, keywords, identifiers, literals, variables, and constants.

Uploaded by

jaydipsinh7285
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 110

[CCMS VADU] BCA-501-JAVA PROGRAMMING

Unit-1
Fundamentals of object oriented programming: -
Object oriented paradigm: -
OOP supports to inheritance, overloading of operator.
Emphasis on data rather than procedure.
Programs are divided into objects.
Functions that operate on the data of an object.
Data is hidden and can not be accessed by external functions.
Objects may pass the data to each other by using functions. It
is easy to add new data and function in the class.
It is use the bottom-top approach in the program.

Basic concept of object oriented programming: -


Objects: - Objects are the basic run time entities in an object oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program has to
handle.
Classes: - Class that contain data, and code to manipulate that data. The entire set of data and
code of an object can be made a user-defined data type with the help of class.
Encapsulation: - The wrapping up of data and functions into a single unit (class) is known as
encapsulation. The data is not accessible to the out side of the class.
Data abstraction: - Data abstraction refers to the act of representing essential feature without
including the background detail.
Inheritance: - Inheritance is the process in which the property of one class can be reused in
another class. The concept of inheritance provides the idea of reusability.
Polymorphism: - Polymorphism means the ability to take more then one form. That is also known
as overloading.
Dynamic binding: - Binding refers to the linking of a procedure call to the code to be executed in
response to the call. It is also known as late binding.
Message passing: - Objects communicate with one another by sending and receiving information.
A message for an object is a request for execution of procedure, and therefore will invoke the
function.

Benefits (Buzzwords or futures) of OOP (JAVA): -


Benefits of OOP are as under.
1. Compiled and Interpreted: Java is both compiled and interpreted language.
2. Platform-Independent and portable: Java programs can be easily moved from one
computer system to another, anywhere & anytime.
3. Object- oriented: All program code and data reside within objects and classes. So JAVA is a
true OOP.
4. Robust & secure: Java is a robust language. It provides many safeguards to ensure reliable
code. Security becomes an important issue for a language that is used for programming on
Internet.
5. Distributed: Java is design as a distributed language for creating application on network. It has
ability to share both data & programs. Java applications can open and access remote objects on
Internet as easily as they can do in local system.
6. Simple, Small & Familiar: Java is a small & simple language. Many features of C & C++ that
are used in JAVA. For example, Java dose not support Pointer, pre-processor Header Files, go-to
statement, operator overloading, multiple inheritance and many others.

[BY. VIPUL PRAJAPATI] Page 1


[CCMS VADU] BCA-501-JAVA PROGRAMMING

7. Multithreading: JAVA can handle multiple tasks simultaneously. This future is known as
multithreading.
8. High performance: Java performance is impressive for an interpreted language, mainly due to
the use of intermediate byte-code.
9. Dynamic & Extensible: Java is capable of dynamic linking in new class libraries, method and
objects.

Application of JAVA: -
The programming areas of application of JAVA include:
1. Real time systems.
2. Simulation and modelling.
3. Object oriented database.
4. Hypertext and hypermedia.
5. AI and expert system.
6. Neural network and parallel programming.
7. Decision support and office automation system.

Difference between C and JAVA: -


Java does not include the C unique statement keywords sizeof and typedef.
Java does not contain the data type structure and union.
Java does not define the type modifier keywords auto, extern, register, signed and unsigned.
Java does not support an explicit pointer type.
Java adds new operators such as instance-of and >>>.
Java adds labelled break & continue statement.

Difference between C++ and JAVA: -


Java does not support operator overloading.
Java does not have template classes as in C++.
Java does not support pointer.
Java has replaced the destructor function with a finalize () function.
There are no header files in Java.
Java does not support goto statement.

JAVA development kit (JDK): -


The java development kit comes with a collection of tools that are used for developing and running
programs.

Tools Description

appletviewer (for Enables us to run Java applet (without actually using a java-
viewing java applet) compatible browser)

Java (java interpreter ) Java interpreter, which runs applet and application by reading
and interpreting byte code file.

Javac (java compiler ) The Java compiler, which translate Java source code to byte
code files that the interpreter understand.

Javadoc (for creating Create HTML – format documentation from java source code
HTML document) files.

Javah (for C header Produce header files for use with native methods.
files )

Javap (java Java disassembler, which enables us to convert byte-code files


disassembler) into a program description.

Jdb(java debugger) Java debugger, which helps us to fine errors in our program.

[BY. VIPUL PRAJAPATI] Page 2


[CCMS VADU] BCA-501-JAVA PROGRAMMING
The way these tools are applied to build and run application programs is illustrate in figure.
Create a JAVA program; we need to create a source code file using a text editor.
The source code is then compiled using the Java compiler javac and executed using the JAVA
interpreter java.
The java debugger jbd is used to find errors, if any, in the source code.
A compiled Java program can be converted in to source code with the help of Java disassembles
javap.

Application program interface (API): -


The java standard library includes hundreds of classes & methods grouped into several functional
packages.
Language support package: - A collection of classes & methods required for implementing basic
features of Java.
Utilities packages: - A collection of classes to provide utility function such as date & time
function.
Input/Output packages: - A collection of classes required for input / output manipulation.
Network packages: - A collection of classes for communicating with other computer via Internet.
AWT packages: - The abstract window toolkit package contains classes that implement platform
independent graphical user interface.
Applet package: - This is includes a set of classes that allow us to create Java Applet.

JAVA run time environment (JRE): -


The JRE facilities the execution of program development in Java.
Java Virtual Machine (JVM): - It is a program that interprets the intermediate Java Byte code and
generates the desire output. It is because of byte code and JVM concept that programs written in
java are high portable.
Runtime class Libraries: -These are a set of core class libraries that are required for the
execution of Java program.
User interface toolkits: - AWT and Swing are example of Toolkits that support varied input
methods for the users to interact with the application program.
Development technologies: -
1. Java plug-in: Enables the execution of a Java applet on the browser.
2. Java Web Start: - Enables remote- deployment of an application. With the help of Web Start,
users can launch an application directly from the Web browsers without going through the
installation procedure.

[BY. VIPUL PRAJAPATI] Page 3


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Basic structure of JAVA program: -
A java Program may contain many classes of which only one class define a main Method.
Classes contain data members and methods that operate on the data members of the class.
Methods may contain data type declarations and executable statements.

Documentation section [Suggested ]


Package statement [Optional]
Import statements [Optional]
Interface statements [Optional]
Class definitions [Optional]
Main Method class [Essential]
{
Main Method Definition
}

Documentation Section: -
1. The documentation section comprises a set of Comment lines giving the name of the program,
the author and other details, which the programmer would like to refer to at later stage.
2. Comments must explain why and what of classes & how of algorithms. This would greatly help
maintaining the program.
Package statement: -
1. The first statement allowed in java file is Package statement.
2. This statement declares a Package name and informs the compiler that the classes defined here
belong to this package.

package student;

3. The package statement optional means our classes do not have to be a part of package.
Import Statements: -
1. This is similar to the #include statement in C.

import student.test;

2. This statement instructs the interpreter to load the test classes contained on the package
student.
Interface statements: -
1. An interface is like a class but includes a group of method declarations.
2. This is also an optional section and is used only when we wish to implement the multiple
inheritance features in the program.
Class Definition: -
1. A java program may contain multiple class definition.
2. Classes are the primary and essential elements of a Java Program.
3. The number of classes used depends on the complexity of the program.
Main Method Class: -
1. Since every java Stand-alone program required a Main method as its starting point, this class is
the essential part of a Java program.
2. A simple java program may contain only this part.
3. The Main method creates objects of various & establishes communication between them.
4. Public: - Public is an access specifier that declares the main method as unprotected &
therefore making it accessible to all other classes.
5. Static: - Static is a keyword which can be called & executed without creating the object, so
when we want to call main() method without using an object, we should declare main() method
as Static.
6. Void: - A method can return some result. If we want the method to return the result in form of
an integer then we should write int before the method name.
o If a method is not meant to return any value, then we should write void before the
method’s name. Void means no value.
7. Main: - This is the starting point for interpreter to begin the execution of the program.

8. String args[]: - An args[] is the array name & it is of String type. This means that it can be
store a group of strings. This array can also store a group of number but in the form string only.

[BY. VIPUL PRAJAPATI] Page 4


[CCMS VADU] BCA-501-JAVA PROGRAMMING

System.out.println (“Hello”)
System is the class name & out is a static variable in system class.
Out is called a field in system class. (Out is an object of system class).
When we call this field, a Printstream class object will be created internally, so we can call the
print() method.

Sample program: -
Following JAVA program find the area of circle.

class area
{
public static void main(String args[])
{
double pi, r, a;
pi = 3.1416;
r = 5;
a = pi * r * r;
System.out.println (“This is the area of Circle” +a);
}
}

JAVA tokens: -
Java program is basically a collection of class.
A class define by set of declaration statements and methods containing executable
statements. Most statements contain expression, which describe the action carried out on
data.
Smallest individual unit in a program are known as tokens.
The compiler recognizes them for building up expression and statement.
Java program has collection of Tokens.
o Reserved Keywords
o Identifiers
o Literals
o Operators
o Separation
Keywords: -
Keywords are an essential part of a language definition.
Java language has reserved 50 words as keywords.
These keywords combine with operators & separators according to syntax, form definition of the
java language.
Every JAVA word is classified as a keyword.
All keyword have fixed meanings.
These meaning cannot be changed.
All keywords are to be written in lower-case letters.

abstract do extends for import long


byte private short switch throws volatile
class boolean catch continue double final
void instanceof native protected static while
finally if int new public this
try Break char default enum float
implements interface package return super throw

Identifiers: -
Identifier refers to the mane of variables, functions and array name, structure name.
These names are defined by user, so they are known as user-define names.
Identifier consists of letters and digits.
Both uppercase and lowercase are permitted.
Rules of Identifiers: -
1. First character must be an alphabet or underscore.
2. Must consist of only letters, digits and underscore.
3. The JAVA variable of any size.
4. We can not use keyword as identifiers.
5. White spaces are not allowed in identifiers.

[BY. VIPUL PRAJAPATI] Page 5


[CCMS VADU] BCA-501-JAVA PROGRAMMING

Literals: -
Literals in java a sequence of character (digits, letters and other characters) that represent
constant values to be stored in variable.
Constants refer as fixed value in JAVA that does not change during the execution of a program.
Five major types of literals
1. Integer literals
2. Floating point Literals
3. Character literals
4. String literals
5. Boolean literals
Integer Constants refer to a sequence of digit like 1056.
Real (Float) constants refer a fractional (point) part like 17.76. Such numbers are called real or
floating point constants.
A single character constant contains only a single character. They are enclosed within single quote
mark. Ex. – ‘g’, K’, ‘l’ etc…
A string constant is sequence of character enclosed within double quote mark. Ex. – “Well Done”,
“Hello Word”, etc…

Separator: -
Separators are symbols used to indicate where groups of code are divided and arranged.
() Parentheses: - Used to enclose parameter in method definition and invocation also used for
defining precedence in expression.
{} Braces: - Used to contain the values of automatically initialize array and to define a block of
code classes, methods & local scopes.
[] Brackets: - Used to declare an array types.
; Semicolon: - Used to separate the statements.
, Comma: - Used to separate variables, in for loop etc…
. Period: - Used to separate package names, also used to separate variable or method from a
reference variable.

Variables: -
A variable is a data name that may be used to store a data value.
Variables may take different values at different time during execution.
A variable name can be chosen by the programmer.
Ex.- Average, height, Total, Counter_1, class_strenght etc….
Rules For Variable: -
1. They must begin with letter.
2. The JAVA variable of any size.
3. Uppercase and lowercase are significant.
4. It should not be a keyword.
5. White space is not allowed.
Some valid example of variable.
John, Value, T_raise, Delhi, x1, ph_value, mark, sum2, sum_5 etc….

Constants: -
Constants refer as fixed value in JAVA that does not change during the execution of a program.
JAVA supports several types of constants.

Constants

Numerical Constants Non Numerical Constants

Integer Constants Real (Float) Constants Character Constants String Constants

Integer Constants refer to a sequence of digit like 1056.


Real (Float) constants refer a fractional (point) part like 17.76. Such numbers are called real or
floating point constants.
A single character constant contains only a single character. They are enclosed within single quote
mark. Ex. – ‘g’, K’, ‘l’ etc…
A string constant is sequence of character enclosed within double quote mark. Ex. – “Well Done”,
“Hello Word”, etc…

[BY. VIPUL PRAJAPATI] Page 6


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Data Types: -
JAVA language is very rich in data types.
The varieties of data types are available in JAVA.
JAVA supports two types of data types,
1. Primitive (Intrinsic) data type
2. Non primitive (derived) data type.
All JAVA compilers support five types of primitive data types.
Integer (int), character (char), floating point (float), double floating point (double), null (void) and
Boolean.
Integers are whole numbers with the range of values and define by keyword int.
Floating point numbers are defining in JAVA by the keyword float, double and long double.
A single character can be defined as a char data type.
The void type has no values. This is usually used to specify the type of function.
JAVA data types are classified as under.

Size and range of primitive data types are mentioned as under.

Data type Size Minimum Maximum


byte 1 bytes -128 127
short 2 bytes -32,768 32767
int 4 bytes -2,147,483,648 2,147,483,647
long 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807
float 4 bytes 3.4 e—038 1.7 e+38
double 8 bytes 3.4 e—038 1.7 e+308

Character Type: - In order to store character constant in memory, JAVA provides a character data
type called char. The character type assumes a size of 2 bytes but, it can hold only a single
character.

Boolean type: - Boolean type is used when we want to test particular condition during the
execution of the program. There are only two values that a Boolean type can take: true or false.

[BY. VIPUL PRAJAPATI] Page 7


[CCMS VADU] BCA-501-JAVA PROGRAMMING

Scope of variable: -
An area of the program where the variable is accessible is called Scope.
JAVA supports three types of variables.
1. Instance variables.
2. Class variables.
3. Local variable.
Instance variable: -
1. Instance variable declare in class.
2. Instance variable are created when the object are instantiated and therefore they are
associated with objects.
3. They take different value for each object.
Class variable: -
1. Class variable are global to a class and belong to entire set of objects that class created.
2. Only one memory location is created for each class variable.
Local variable: -
1. Local variable is declare and used in methods.
2. They are called so because they are not available for use outside the method definition.
3. Local variable is also declared in program blocks defined between an {open & close braces}.
4. This variable is visible only from the beginning of its program block to end of the program block.

Type casting: -
There is a need to store a value of one type in to variable of another type.
Syntax:
type variable1= (type) variable2;

The process of converting one data type to another is called casting.


Example:

int m = 50;
byte n = (byte) m;
long count= (long) m;

Casting is often necessary when a method returns a type different than the one we require.
Casting in to smaller type may result in a loss of data.
Like, he float & double can be cast to any other type expect Boolean.
Casts that Results in NO LOSS OF Information

From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int Long, float, double
long Float, double
float Double

Standard Default Value: -

Type of Variable Default value


Byte zero: (byte)0
Short zero: (short)0
Int zero: 0
Long zero : 0l
Float 0.0f
double 0.0d
Char null char
boolean False
reference Null

Automatic Conversion: -
1. It is possible to assign a value of one type to a variable of different type without a cast.
2. Java does the conversion of the assigned value automatically.
3. This is known as automatic type conversion.

[BY. VIPUL PRAJAPATI] Page 8


[CCMS VADU] BCA-501-JAVA PROGRAMMING
4. Automatic type conversion is possible only if the destination type has enough precession to
store the source.

byte b = 75;
int a = b;

5. The process of assigning a smaller type to large one is known as winding or Promotion.
6. Larger to smaller one is known as Narrowing.

Operators: -
JAVA supports several kinds of operators.
An operator is a symbol that tell to computer that to perform mathematical or logical operation.
An operator is used in program to perform the operation on variable or data values.
JAVA operator can be classified as under.
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
5. Increment and Decrement operator
6. Conditional operator
7. Special operator
8. Bitwise operator

Arithmetic operator: -
JAVA provides all the basic arithmetic operators.
The operators +, -, *, /, % all work the same way as they do in other language.
These can operate on any basic data type.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
For example, here a and b are variable and known as a operand.
a + b : variable a is added to b
a - b : variable a is subtract from b
a * b : variable a is multiply by b
a / b : variable a is divided by b and integer division truncate the fractional part.
a % b : variable a is divided by b and produce the reminder of an integer division.
Note: - Modulo division (%) operator can not be used with floating point data.

Relational operator: -
JAVA provides all the basic relational operators.
These operators are used to compare two more values with each other to get relation.
These kinds of comparisons can be done with the help of relational operators.
The value of expression is either one or zero.
The value is one if the relational expression is true.
The value is zero if the relational expression is false.
JAVA supports six relational operators.
These operators and meaning are shown as under.

Relational operator Meaning


< Is less then
<= Is less then or equal to
> Is greater then
>= Is greater then or equal to
== Is equal to
!= Is not equal to

For example here a and b are integer type of variables.


a<b a>b
a<=b b>=a
b==a a!=b

[BY. VIPUL PRAJAPATI] Page 9


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Among the six relational operators, each one is complement of another operator.
> is complement of <=
< is complement of >=
== is complement of !=
We can simplify an expression the not and the less then operators using complement as shown as:
!(x<y)x>=y
!(x>y)x<=y
!(x!=y)x==y
!(x<=y)x>y
!(x<y)x>=y

Logical operator: -
JAVA has following logical operators.

Logical operator Meaning


& Logical AND
| Logical OR
! Logical NOT
The logical operator && and || are used when we want to test more then one condition and take
decision. An example is :
a>b && x == 10
This kind of expression, which is combination of two or more relational expression, is known as
logical expression or compound expression.
Like the simple relational expression, logical expressions also provide a value one for true
expression and zero for false expression.
Some examples of logical expression.
1. if (age > 55 && salary < 1000)
2. if (number < 0 || number >=1000)

Assignment operator: -
Assignment operators are used to assign the result of an expression.
Also JAVA has short hand assignment operators.
Syntax is:
variable op = expression , where op is a operators.
The assignment statement
V op = exp;
Is equal to
V = v op (exp);
Ex:-
X + = y+1;
Is equal to
X = x+(y+1);
Some of common shorthand assignment operators are shown as under.

Statement with simple assignment operator Statement with shorthand 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

The use of shorthand assignment operator has three advantages.


1. What appears on the left-hand side need not be repeated and therefore it becomes easier to
write.
2. The statement is easier to read.
3. The statement is more efficient.

Increment and Decrement operator: -


JAVA has two very useful operators. These two operator not found in other language.
These operator are Increment (++) and Decrement (--) operators.
The operator ++ adds 1 to operand.
The operator – subtracts 1 from operand.
For example:

[BY. VIPUL PRAJAPATI] Page 10


[CCMS VADU] BCA-501-JAVA PROGRAMMING

We use the increment and decrement operator in for loop, while loop and do while loop.
There are two types of increment and decrement operators. Prefix and postfix operators.
A prefix operator first adds 1 to the operand and then result is assign to the variable.
A postfix operator first assigns the value to the variable and then increments the operand.

Conditional (Ternary) operator:-


Conditional operator is also known as a ternary operator.
A conditional operator pair “ ? : “ is available in JAVA.
A conditional operator is used to create conditional expression.
Syntax is :
exp1 ? exp2 : exp3;
In this syntax exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated
and become the value of expression.
If exp1 is false, exp3 is evaluated and its value becomes the value of the expression.
Note that only one of the expressions either exp2 or exp3 is evaluated.
For example:
int a=10;
int b=15;
int x;
x = (a<b) ? a : b ;
In this example, x will be assigning the value of b.

Precedence of arithmetic operators: -


An arithmetic expression without parentheses will be evaluated from left to right using the rules of
precedence of operator.
There are two levels of arithmetic operators in JAVA.
High priority : * / %
Low priority : + -
Consider the following statement that has been used.

X = a-b/3+c*2-1
When a = 9, b = 12, and c = 3 then the statement become

X=9-12/3+3*2-1

First pass:
Step-1: x=9-4+3*2-1
Step-2: x=9-4+6-1

Second Pass:
Step-3: x=5+6-1
Step-4: x=11-1
Step-5: x=10

Simple IF statement: -
The if statement is powerful decision making statement.
The if statement is used to control the flow of execution of statement.
It is two-way decision statements and is used to conjunction with expression.
General form of if statement is:

if(test condition)
{
block-statement;
}
statement-x;

The ‘block-statement’ may be a single statement or a group of statements.


If the test condition is true, the block statement will be executed.
Otherwise the block-statement will be skipped and execution will be jumped to the statement-x.
Consider the following example.

if(category == sports)

[BY. VIPUL PRAJAPATI] Page 11


[CCMS VADU] BCA-501-JAVA PROGRAMMING
{
marks = marks + bonus_marks;
}
System.out.println (“marks = ” + marks);
…………..

The if…..else statement: -


The if…..else statement is a extension of simple is statement.
The general form of if…..else statement is as under.

if (test condition)
{
true block statement;
}
else
{
false block statement;
}
statement-x;

If the test condition is true, then the true block statement is executed. If
the test condition is false, then the false block statement is executed. In
either case, either true block or false block will be executed, not both. In
the both cases, the control is transferred subsequently to statement-x.
Let us consider an example of counting the number of boys and girls in class.
We use the code 1 for boys and code 2 for girls.
……..
if(code == 1)
{
boy = boy + 1;
}
else
{
girl = girl + 1;
}
……..
………

Nesting of if…..else statement: -


When a series of decision are involved, we may have to use more then one if….else statement in
nested from as shown below.

if(test condition-1)
{
if(test condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;

If the condition-1 is true then test condition-2 is executed.


If condition-2 is true then statement-1 is executed.
If condition-2 is false then statement-2 is executed.

But if the condition-1 is false then control is transfer to the statement-3. In this case statement-1
and statement-2 is not executed.

[BY. VIPUL PRAJAPATI] Page 12


[CCMS VADU] BCA-501-JAVA PROGRAMMING
In both case control is transfer to the statement-x.
For example:
……….
if(s = ‘f’)
{
if(balance >= 5000)
{
bonus = 0.05 * balance;
}
else
{
bonus = 0.02 * balance;
}
}
else
{
bonus = 0.02 * balance;
}
balance = balance + bonus;
………

The else if ladder: -


There is another way of putting ifs together when multi path decisions are involved.
A multi path decision is a chain of ifs in which the statement associated with each else is an if.
General form of else if ladder is:

if (condition-1)
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;
else if (condition-n)
statement-n
else
default-statement;
statement-x;

This construct is known as the else if ladder.


The conditions are evaluated from the top (of ladder) downwards.
As soon as a true condition is found, the statement associated with it is executed and the control is
transferred to the statement-x.
When all the conditions become false, then the final else containing the default-statement will be
executed.
Let us consider the following example.
………
if (code == 1)
colour = “red”;
else if (code == 2)
colour = “green”;
else if (code == 3)
colour = “white”;
else
colour = “yellow”;
……..
……..

The switch statement: -


The switch statement is another decision making and branching statement.
We have seen that when one of many alternatives is to be selected, we can use an if statement to
control the selection.
When the numbers of alternatives are increased at that time we have to use switch statement.
JAVA has built-in multi way decision statement known as a switch.
The switch statement tests the value of a given variable (or expression) against a list of case values
and when a match is found, a block of statement associated with that case is executed.
The general form of the switch statement is shown below:

[BY. VIPUL PRAJAPATI] Page 13


[CCMS VADU] BCA-501-JAVA PROGRAMMING

switch (expression)
{
case value-1:
statement-1;
break;

case value-2:
statement-2;
break;

case value-3:
statement-3;
break;

………
……..
default :
default statement;
break;
}
statement-x;

The switch expression must be either integer or character type.


Case labels must be integer or character.
Case labels must be unique. No two labels can have the same values.
Case labels must end with semicolon.
The break statement transfers the control out of the switch statement.
The break statement is optional. That is, two or more case labels may belong to the same
statement.
The default label is optional. If present, it will be executed when the expression does not find a
matching case labels.
There can be at most one default labels.
The default may be placed anywhere but usually placed at the end.
It is permitted to nest switch statements.

The ? : operator: -
Conditional operator is also known as a ternary operator.
A conditional operator pair “ ? : “ is available in C.
A conditional operator is used to create conditional expression.
Syntax is :
exp1 ? exp2 : exp3;

In this syntax exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated
and become the value of expression.
If exp1 is false, exp3 is evaluated and its value becomes the value of the expression.
Note that only one of the expressions either exp2 or exp3 is evaluated.
For example:
int a=10;
int b=15;
int x;

x = (a<b) ? a : b ;
In this example, x will be assigning the value of b.

The while statement: -


The simplest of all the looping structure in java is the while loop.
The basic format of the while statement is:

Initialization;
while (test condition)
{
body of the loop;
}

[BY. VIPUL PRAJAPATI] Page 14


[CCMS VADU] BCA-501-JAVA PROGRAMMING
statement-x;

The while is an entry controlled loop statement.


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 process of repeated execution of the body continues until the test-condition finally becomes
false and the control is transferred out of the loop.
On exit, the program continues with the statements immediately after the body of the loop.
Let us consider the following example.

sum =0;
n=1;
while(n<=10)
{
sum = sum + n * n ;
n = n + 1;
}
System.out.println(“Sum= “ + sum);
……………….

The do…while statement: -


On some time it is required to execute the body of the loop before the test condition is checked.
This kind of situation can be handle with help of the do while statement.
The do while statement is also known as exit control or post tested loop.
General form of do while statement is :

Initialization;
do
{
body of the loop;
}
while (test condition);
statement-x;

On reaching the do statement, the program proceeds to evaluate the body of the loop first.
At the end of loop, the test condition in the while statement is executed.
If the condition is true then control is further transfer to body of the loop.
But if the condition is false control is transfer to statement-x.
The do while loop create an exit control loop and therefore body of the loop is always executed at
least once.
A simple example of do while loop is :

number = 0;
do
{system.out.println (“input a number”);
number = number + 1 ;
} while (number>0 && number < 100);

The for statement: -


The for loop is another entry control or pre tested loop.
The general form of for loop is:

for (initialization ; test condition ; increment or decrement)


{
body of the loop;
}
statement-x;
There are three part in a for loop.
Initialization, test condition and increment or decrement.
Initialization done first. Initialization portion is executed only one time.
Then control is transfer to test condition. If the condition becomes true then control is transfer to
body of the loop.
After the execution of body of the loop control is goes to increment or decrement portion.
After the execution of increment or decrement part control is goes to test condition.
[BY. VIPUL PRAJAPATI] Page 15
[CCMS VADU] BCA-501-JAVA PROGRAMMING
If condition becomes false then control is transfer to statement-x.
Consider the following example:

…………
for (x=0; x<=10 ; x++)
{
System.out.println (“x = ” + x);
}
System.out.println (“\n”);
………….

Nesting of for loop: -


Nesting of for loops, that is, one for statement within another for statement.
For example consider the following :

for(row = 1; row <= romax; row++)


{
for (column =1; column <= colmax; ++column)
{
y = row * column;
system.out.println (+ y);
}
System.out.println (“\n”);
}

The nesting may continue up to any desired level.

Jumping in loops: -
Loops perform the set of operations repeatedly until the control variable fails to satisfy the test
condition.
But sometimes, when executing a loop it becomes desirable to skip a part of loop or to leave the
loop as soon as a certain condition is occurs.
At that time we have to use a break statement. When the break statement is encountered inside
the loop, the loop is immediately exited and the program continues with the statement immediately
following the loop.

Skipping a part of loop:-


During the loop operation, it may necessary to skip a part of the body of the loop under certain
conditions.
Like the break statement, C supports another similar statement called continue statement.
The continue statement tells the compiler that “SKIP THE FOLLOWING STATEMENTS AND CONTINUE
WITH THE NEXT STATEMENT.”
We can use the continue statement with for loop, while loop, do while loop, and goto statement.
For example : -

while(test condition)
{………..
if( condition)
continue;
………….
}
Rough work

[BY. VIPUL PRAJAPATI] Page 16


[CCMS VADU] BCA-501-JAVA PROGRAMMING

Unit-2

Class: -
Class is a collection of data and method to manipulate that data are combines together and
become user defined data type is known as class.
Class is a user-defined data type.
Class create an object and object use methods to communicate between them.
Classes provide a convenient method for packing together a group of logically related data items
and functions that work on them.
In JAVA the data items are called fields and functions are called methods.

Defining a class: -
Class that contain data, and code to manipulate that data. The entire set of data and code of an
object can be made a user-defined data type with the help of class.
A class specification has two parts. (1) Class declaration (2) Class method definition.
The general form of a class declaration is:

class class_name
{
[BY. VIPUL PRAJAPATI] Page 17
[CCMS VADU] BCA-501-JAVA PROGRAMMING
field declarations;
method declarations;
}

Once class has been defined, we can create an object of class type using declaration that is similar
to the basic type declaration.
In JAVA this objects are known as instance of a class.
Every thing in side braces is optional.
The field variables and methods are collectively called class members.

Field declaration: -
We can create a data field (variable) inside class body.
These variables are called instance variables because they are created whenever an object of the
class is created.
Example: -

class prog1
{
int length;
float width;
}

Remember that here both variables are only declared and therefore no storage space has been
created in the memory.
Instance variable is also known as member variable.

Method declaration: -
Without method, field variable has no life.
We must add methods that are necessary for manipulating the data.
Methods are declared inside the body of class after the declaration of field variables.
The general form of method declaration is: -

………………….
return_type method_name (argument list)
{
method body;
}
…………………

Method declaration has four basic parts.


1. Return type of the method.
2. The name of the method.
3. A list of argument.
4. The body of method (executable statement).

The method actually describes the operations to be perform on data.


Let us consider the following example.
class rectangle
{
int length;
int width;

void getdata (int x, int y)


{
length = x;
width = y;
}

int rect_area (void)


{
int area = length * width;
return(area);
}
}

[BY. VIPUL PRAJAPATI] Page 18


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Now our class rectangle contains two instance (field) variables and two methods.
We can add more variables and methods, if required.
Note: - Most of times when we use the classes, we have many methods and variables within the
class. Instance variables and methods in class can be accessible by all other method in class. But
method can not access the variable of other method.

class access
{
int x;

void method1 ()
{
int y;
x = 10; // legal
y = 20; // legal
}

void method2 ()
{
int z;
x = 5; // legal
z = 20; // legal

y = 40 // Illegal because it is variable of method1()


}
}

Creating an object: -
An object in JAVA is essentially a block of memory that contains space to store all the instance
variables.
We can create an object in JAVA by using new operator.
The new operator creates an object for the particular class and returns a reference to that object.
We can create an object by using following statement.

Class_name obj_name = new class_ constructor_name();

For example: -
rectangular rect1 = new rectangular();

Whenever objects are created every time memory space is allocated to the field variables for
particular object.

Accessing class members: -


Each object containing its own set of variable.
We should assign values to these variables in order to use them in our program.
All variable must be assigned before they are used.
Out side the class we are not able to access data member and methods directly.
For accessing a method we must use the object of the same class and dot operator.
Syntax: -
objectname. variablename = value ;
objectname.methodname(argument list) ;

Here object name is the name of object.


The variablename is the name of the instance variable inside the object that we want to access.
The methodname is name of method that we want to call.
And parameter list is a comma separated list of “actual values” (or expressions) that must match in
the type and number with the parameter list of the method name declared in the class.
Consider the following example.

rect1.length = 15;
rect1.width = 10;
rect2.length = 20;

[BY. VIPUL PRAJAPATI] Page 19


[CCMS VADU] BCA-501-JAVA PROGRAMMING
rect2.width = 12;

Note that the two objects rect1 and rect2 store different values.
To access methods consider the following example.

rect1.getdata (15, 10);

Note that here rect1 is object and getdata() is a method of class.

Constructors: -
We know that all objects that are created must be given initial values.
We have earlier using two approaches.
1. Uses the dot operator (.) to access the instance variable & then assign values to them individually.
2. Use of the method to initialize each object.
Java allows objects to initialize themselves when they are created. This automatic initialization is
performed through the use of a constructor.
A constructor is a special method that initializes a newly instantiated object.
A constructor initializes an object immediately upon creation. It has the same name as the class in
which it resides and is syntactically similar to a method.
Once defined, the constructor is automatically called immediately after the object is created, before
the new operator completes.
Constructors look a little strange because they have no return type, not even void.
It is the constructor's job to initialize the internal state of an object so that the code creating an
instance will have a fully initialized, usable object immediately.

Simple Constructor: -

/* Here, Box uses a constructor to initialize the dimensions of a box.*/


class Box
{
double width;
double height;
double depth;
/ This is the constructor for Box.
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
/ compute and return volume
double volume()
return width * height * depth;
}
}
class BoxDemo6
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Parameterized Constructor: -

[BY. VIPUL PRAJAPATI] Page 20


[CCMS VADU] BCA-501-JAVA PROGRAMMING
In parameterized Constructor is used to define a value of instance variable when a object is created.

/* Here, Box uses a parameterized constructor to initialize the dimensions of a box.*/


class Box
{
double width;
double height;
double depth;
/ This is the constructor for Box.
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
/ compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
/ declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
/ get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
/ get volume of second box vol =
mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Method Overloading:-
Overloading a method means to use the same method name for more than one method.
In Java it is possible to define two or more methods within the same class that share the same name,
as long as their parameter declarations are different.

When this is the case, the methods are said to be overloaded, and the process is referred to as method
overloading.
Method overloading is one of the ways that Java implements polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to
determine which version of the overloaded method to actually call.
Thus, overloaded methods must differ in the type and/or number of their parameters.
While overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method.
When Java encounters a call to an overloaded method, it simply executes the version of the method
whose parameters match the arguments used in the call.
Example
/ Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
/ Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
/ Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}

[BY. VIPUL PRAJAPATI] Page 21


[CCMS VADU] BCA-501-JAVA PROGRAMMING
/ overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
/ call all versions of test()
ob.test();
ob.test(10); ob.test(10,
20); result =
ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}

This program generates the following output:

No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob.test(123.2): 15178.2

As you can see, test( ) is overloaded four times.


The first version takes no parameters,the second takes one integer parameter, the third takes two
integer parameters, and the fourth takes one double parameter.
The fact that the fourth version of test( ) also returns a value is of no consequence relative to
overloading, since return types do not play a role in overload resolution.
When an overloaded method is called, Java looks for a match between the arguments used
to call the method and the method's parameters.

Automatic type conversions in Overloading: -

/ // Automatic type conversions apply to overloading.


class OverloadDemo {
void test() {

System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}

This program generates the following output:

[BY. VIPUL PRAJAPATI] Page 22


[CCMS VADU] BCA-501-JAVA PROGRAMMING
No parameters
a and b: 10 20
Inside test(double) a: 88

Static Members:-
Normally a class member must be accessed only with an object of its class.
It is possible to create a class member that can be used by itself, without reference to a specific
instance or object.
To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object.
You can declare both methods and variables to be static.
The most common example of a static member is main( ). main( ) is declared as static because it
must be called before any objects exist.
Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.

Example
/ Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x)
{ System.out.println("x = " +
x); System.out.println("a = " +
a); System.out.println("b = " +
b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{ meth(42);
}
}

Output:-
Static block initialized.
x = 42
a=3
b = 12

As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3, then
the static block executes (printing a message), and finally, b is initialized to a * 4 or 12. Then main( )
is called, which calls meth( ), passing 42 to x. The three println( ) statements refer to the two static
variables a and b, as well as to the local variable x.

Nesting of Methods:-
A method can be called by using only its name by another method of the same class. This is known as
Nesting of Methods

/ Program for Nesting method program which find largest value.//


class Nesting
{
int m,n;
Nesting(int x,int y) //Constructor method
{
m=x;
n=y;
}
int largest()
{
if(m>=n)
[BY. VIPUL PRAJAPATI] Page 23
[CCMS VADU] BCA-501-JAVA PROGRAMMING
return m;
else
return n;
}
void display()
{
int large=largest(); // call method and store result in variable
System.out.println("Largest value is ==>"+large);
}
}
class Nestingtest
{
public static void main(String args[])
{
Nesting nest=new Nesting(14,20);
nest.display();
}
}

Inheritance:-
It is always nice if we could reuse something that already exists rather than creating the same all over
again.
This is basically done by creating new class, reusing the properties of existing one, the deriving a new
class from an old is called inheritance.
The old class is known as base class or super class or Parent class and the new one is called the
subclass or derived class or child class.
The inheritance allows subclasses to inherit all the variable and methods of their parent class.
Inheritance may take different form.
Single inheritance (only one super class)
Multiple inheritance (several super class)
Hierarchical inheritance (one super class, many subclasses)
Multilevel inheritance (derived from a derived classes)

Rules of inheritance: -
There are certain rules for inheritance which are define as under:
1. Private members of base class can not be inherited.
2. When a base class is privately inherited by derived class, “public members of base class
become private members of derived class.” And therefore they are only accessed by
members of derived class. They are not accessible to the object of derived class.
3. When a base class is publicly inherited by derived class, “public members of base class
become public members of derived class.” And therefore they are accessible to the object of
derived class.

[BY. VIPUL PRAJAPATI] Page 24


[CCMS VADU] BCA-501-JAVA PROGRAMMING

Java dose not directly implement multiple inheritance. However, this concept is implemented using a
secondary inheritance path in the form of interface.

Defining a Sub Class:-


Class subclassname extends superclassname
{
Variable declaration;
Methods declaration;
}

The keywords extends signifies that the properties of the superclassname are extended to the
subclassname.
The subclass will now contain its own variable and methods as well those of the superclass.
This kind of situation occurs when we want to add some more properties to an extending class without
actually modifying it.
Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of
hierarchical classifications.

Making a private member inheritable: -


A private member of base class is not inheritable in derived class.
But in some situations we need to inherit private members in derived class.
JAVA provides a third visibility mode, protected.
A member declares as protected is accessible by the member function within the class and also by
derived class.
Rules for making a private member inheritable:
1. When a protected member is inherited in public mode, it becomes protected in the derived
class. And therefore they are accessible by the member function of derived class. And they are
also ready for further inheritance.
2. When a protected member is inherited in private mode, it becomes private in the derived class.
And therefore it is available only for member of the derived class. They are not inherited
further.
3. When a protected member is inherited in protected mode, it becomes protected in derived
class. And therefore they are accessible by the member function of derived class. And they are
also ready for further inheritance.

Consider the following table for inheritance:

Base class visibility Derivation mode Derived class visibility


Private Not inherited Not inherited
Public Private Private
Public Public Public
Protected Private Private
Protected Public Protected
Protected Protected Protected

Single Inheritance: -
The derived class is derived from single base class that is known as single inheritance.

/ A simple example of inheritance.


/ Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
/ Create a subclass by extending class A.
class B extends A {
int k;
void showk() { System.out.println("k:
" + k);

[BY. VIPUL PRAJAPATI] Page 25


[CCMS VADU] BCA-501-JAVA PROGRAMMING
}
void sum() { System.out.println("i+j+k: " +
(i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[])
{ A superOb = new A();
B subOb = new B();
/ The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20; System.out.println("Contents
of superOb: "); superOb.showij();
System.out.println();

/* The subclass has access to all public members of


its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System. out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System. out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Output :-
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

Multiple Inheritance: -
The derived class is derived from multiple base class is known as multiple inheritance.
Multiple inheritance allows us to combine a feature of several existing classes in single class.

/ A simple example of inheritance.


/ Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
/ Create a subclass by extending class A.
class B extends A {
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class c extends A
{
int l;

[BY. VIPUL PRAJAPATI] Page 26


[CCMS VADU] BCA-501-JAVA PROGRAMMING
void showl()
{
System.out.println("l:" +l);
}
void mul()
{
System.out.println("i*j*l: "+(i*j*l));
}
}
class MultipleInheritance {
public static void main(String args[])
{ A superOb = new A();
B subOb = new B();
c submul= new c();
/ The supercl ass may be used by itself.
superOb.i = 10;
superOb.j = 20; System.out.println("Contents
of superOb: "); superOb.showij();
System.out.println();

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


subOb.i = 7;
subOb.j = 8; subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();

subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();

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


submul.i = 5;
submul.j = 5;
submul.l = 5;
System.out.println("Contents of subOb: ");
submul.showij();
submul.showl();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
submul.mul();

}
}

Super Keywords:-
A subclass constructor is used to construct the instance variables of both the subclass and the super
class.
The subclass constructor uses the keyword super to invoke the constructor method of the super class.
The super keyword is used subject to the following condition.
1. Super may only be used with in a sub class constructor method.
2. The call to super class constructor must appear as the first statement with in the subclass
constructor.
3. The parameters in the super call must match the order and type of the instance variable declared
in the superclass.

/ A simple example of inheritance with SUPER Key


words. class A
{
int i, j;
A(int x, int y)
{
i=x;
j=y;
}

[BY. VIPUL PRAJAPATI] Page 27


[CCMS VADU] BCA-501-JAVA PROGRAMMING
int add()
{
return (i+j);
}
}
class B extends A
{
int k;
B(int x,int y,int z)
{
super(x,y);
k=z;
}
int sum()
{
return(i+j+k);
}
}
class super_keywords
{
public static void main(String args[])
{
B b=new B(2,3,4);
int add1=b.add();
int add2=b.sum();
System.out.println("This is addition::-->"+add1);
System.out.println("This is sum::-->"+add2);
}
}

The this Keywords:-


Sometimes a method will need to refer to the object that invoked it. To allow this , Java defines the
this keywords.
this can be used inside any method to refer to the current object.
this is always a reference to the object on which the method was invoked.
//Represent working of this keywords //
class abc
{
int a;
abc(int a)
{
this.a=a;
}
void display()
{
System.out.println("Value of a::-->"+a);
}
}
class use_this
{
public static void main(String args[])
{
abc b=new abc(10);
b.display();
}
}

Method Overriding:-
When a method in a subclass has the same name and type signature as a method in its superclass,
then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the version of that
method defined by the subclass.
The version of the method defined by the superclass will be hidden.
Example

[BY. VIPUL PRAJAPATI] Page 28


[CCMS VADU] BCA-501-JAVA PROGRAMMING
/ Method
overriding. class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
/ display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
/ display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Output:-
k: 3

Garbage Collection:-
Since objects are dynamically allocated by using new operator, you might be wondering how such
objects are destroyed and their Memory released for later reallocation.
Java handles de-allocation for you automatically. The technique that accomplishes this is called
Garbage collection.

Finalize Method:-
We have seen that a Constructor method is used to initialize an object when it is declare. This process
is known as Initialization.
Similarly, Java support a concept called Finalization, which is just opposite to Initialization.
Java provides automatically free memory allocation used by object, but objects may hold other non-
object resources such as file handle or window character font.
The garbage collector can not free these resources. To free this kind of resource we can use finalize()
method.
The finalize() method has this general form:

Protected void finalize()


{
//finalize code here
}

Final keyword:-
All method & variable can be overridden by default in subclass.
If we wish to prevent the subclasses from overriding the members of the superclass, we can declare
them as final using the keyword final.
Sometimes we may like to prevent a class being further subclasses for security reason; a class that
cannot be subclassed is called a final class.

Abstract keywords:-

[BY. VIPUL PRAJAPATI] Page 29


[CCMS VADU] BCA-501-JAVA PROGRAMMING
We have seen that by making a method final we ensure that the method is not redefined in a
subclass. That is, the method can never be subclassed.
Java allows us to do something that is exactly opposite to this.
We can indicates that a method must always be redefined in a subclass, thus making overriding
compulsory.
This is done by abstract keywords.
While using abstract classes, we must satisfy the following condition
1. We can not use abstract classes to instantiate objects directly.
2. The abstract methods of an abstract class must be defined in its subclass.
3. We can not declare abstract constructors or abstract static methods.

/ demonstration of abstract keywords//


abstract class A
{
abstract void callme();
/ methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is concrete method");
}
}
class B extends A
{
void callme()
{
System.out.println("B's implementation of call me");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b=new B();
b.callme();
b.callmetoo();
}
}

Dynamic Method dispatch:-


Dynamic methods dispatch is an important mechanism in Java that is used to implement runtime
polymorphism.
In this mechanism, method overriding is resolved at runtime instead of compile time.
That means the choice of the version of the overridden method to be executed in response to method
call is done at runtime.

// Demo of Dynamic Method Dispatch //


class Super
{
void method()
{
System.out.println("Method super");
}
}

class Sub extends Super


{
void method()
{
System.out.println("Method sub");
}
}

class dynamic_dispatch
{
public static void main(String args[])

[BY. VIPUL PRAJAPATI] Page 30


[CCMS VADU] BCA-501-JAVA PROGRAMMING
{
Super A=new Sub(); // Sub's object refrence assign super type refrence variable
A.method();
}
}

Arrays: -
Definition: - “Array is sequence collection of related data item that share same name and same
data type, but store a different value.”
C supports a derived data type known as array that can be used for many applications.
Three type of array is available in C :
1. One dimensional array.
2. Two dimensional arrays.
3. Multidimensional arrays.

One dimensional array: -


Definition: - “Array is sequence collection of related data item that share same name and same
data type, but store a different value.”
A list of items can be given one variable name using only one subscript and such a variable is
called a one–dimensional array.
Like any other variable, arrays must be declared before they are used.
The general form of array declaration is:

data-type variable-name [ ] = new data-type [ size ];

The data-type specifies the data type of array.


Variable is a name of variable which is declared by user.
The new is dynamic memory allocation operator which provides the memory.
Size indicates the maximum number of elements that can be stored inside the array.

For example, if we want to represent a set of five number, say (35,40,20,57,19), by an array
variable number, then we may declare the variable number as follows:

int number[ ] = new int [ 5 ];


The computer provides five storage locations as shown below:

number[0]
number[1]
number[2]
number[3]
number[4]
The values to the array elements can be assigned as follows:

number[0] = 35;
number[1] = 40;
number[2] = 20;
number[3] = 57;
number[4] = 19;

This would cause the array number to store the values as shown below:

35 number[0]
40 number[1]
20 number[2]
57 number[3]
19 number[4]

These elements may be used in programs just like any other C variable.
For example, the following are valid statements:

a = number[0] + 10;
number[4] = number[0] + number [2];
number[2] = x[8] + y [10];

[BY. VIPUL PRAJAPATI] Page 31


[CCMS VADU] BCA-501-JAVA PROGRAMMING
When the compiler sees the character array sting, it terminates it with additional null character.
The null character of the character is determined by ‘\0’.
When declaring character array, we must allow one extra element space for the null terminator.

Initialisation of array: -
Initialisation means to store the values to an array element.
An array can be initialized at two ways.
1. At compile time.
2. At run time.

Compile time initialisation: -


We can initialisation the elements of arrays in the same way as the simple variables when they are
declared.
The general form of initialisation of arrays is:
data-type array-name[size] = {list of values};
The values in the list are separated by commas.
For example int num[3] = {10, 23, 43};
If the number of elements are greater then number of assigned value at that time only that
elements will be initialised. The remaining elements will be initialised with zero.
For example int num[5] = {2, 4, 5};

2 num[0]
4 num[1]
5 num[2]
0 num[3]
0 num[4]

In some case the size of array will be omitted.


In such case, the compiler allocates enough space for all initialized elements.

For example int num[ ] = {10, 49, 54, 43};


In this statement the size of array will be four.
Character array may be initialized in same way.
For example char name[ ] = {‘d’, ’o’, ’c’, ’t’, ’o’, ’r’};
char city[ ] = “idar”;

Run time initialisation: -


An array can be initialised at run time.
Run time initialisation is used with large array.
Consider the following example.
int i;
int num[50];
for( i = 0; i<=49; i++)
{
scanf(“%d”, & num[i]);
}
The 50 elements are initialised with values which are provided by user from keyboard at runtime.

STRINGS: -
String manipulation is the most common part of many JAVA programs.
String represents a sequence of characters.
The easiest way to represent a sequence of characters in JAVA is by using a character array.
For example:
char chararray [ ] = new char [4];
chararray[0] = ‘ j ’ ;
chararray[1] = ‘ a ’ ;
chararray[2] = ‘ v ’ ;
chararray[3] = ‘ a ’ ;

In JAVA, strings are class objects and implements using String and StringBuffer class.
A JAVA string is an instantiated object of string class.
A JAVA string is not a character array and is not NULL terminated.
The string may be declared and created as follows.
String String_name;
String_name = new String (“string”);
[BY. VIPUL PRAJAPATI] Page 32
[CCMS VADU] BCA-501-JAVA PROGRAMMING

For example:
String first_name;
first_name = new String (“Anil”);

These two statements are combined as follows.


String first_name = new String (“Anil”);

Like arrays, it is possible to get the length of string using length method of the string class.
int m = first_name.length( );

Note the use of parentheses here. JAVA string can be concatenated using the + operator.
String fullName = name1 + name2;
String city1 = “New” + “Delhi”;

String Methods: -
The string class defines a number of methods that allow us to accomplish a variety of string
manipulation task.
Some most commonly used string methods.

Method Call 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
S2=s1.trim() Remove white spaces at the beginning and end of the string s1
S1.equals(s2) Returns ‘true’ if s1 is equal to s2
S1.equalsIgnoreCase(s2) Returns ‘true’ if s1=s2, ignoring the case of character

S1.length() Gives the length of s1


S1.CharAt(n) Gives the nth character of s1
S1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2, and zero if s1 is equal to s2
S1.concat(s2) Concatenates s1 and s2
S1.substring(n) Gives substring starting from nth character
S1.substring(n, m) Gives substring starting from nth character up to mth
String.Valueof(p) Creates a string object of the parameter p
p.toString() Creates a string representation of the object p
S1.indexof(‘x’) Gives the position of the occurrences of ‘x’ in the string s1
S1.indexof(‘x’, n) Gives the position of ‘x’ that occurs after nth position in the string s1
String.Valueof(Variable) Converts the parameters value to string representation

String Buffer Class: -


String Buffer class is a peer class of String. While String creates strings of fixed_length, String
Buffer creates strings of flexible length that can be modified in terms of both length and content.
We can insert characters and substring in the middle o a string, or append another string to the
end.
Commonly used string buffer methods.
Methods Task
S1.setCharAt(n , Modifies the nth character to x
‘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 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.

Vector Class:-
The Vector class is one of the most important in all of the Java Class
libraries. Recall that you can not expands the size of a static array.
You may think of a vector as a dynamic array that automatically expands as more elements are
added to it.
All vectors are created with some initial capacity.
When space is needed to accommodate more elements, the capacity is automatically increased
. It is for this reason that vector are commonly used in Java Programming.
The class supports the following constructor:-
[BY. VIPUL PRAJAPATI] Page 33
[CCMS VADU] BCA-501-JAVA PROGRAMMING

Vector()
Vector(int n)
Vector(int n,int delta)

The first form creates a vector with initial capacity of ten Element.
The second forms create a vector with an initial capacity of n element.
The third forms create a vector with an initial capacity of n elements that increase by Delta elements
each time it needs to expand.
The instance methods provided by this class.

SN Method_Name Description
1 Void addElement(Object Adds Obj to the vector.
obj)
2 int capacity() Returns the capacity.
3 Object clone() Returns a duplicated of the current Object.
4 Boolean contains(Object Returns True if Obj is contained by the vector.
obj) Otherwise returns False.
5 void copyInto(Object Copies the element s of the current object to array.
array[])
6 Object elementAt(int Returns the element at index.
index)
7 Enumeration elements() Returns an enumeration of the elements.
8 Void ensureCapacity(int Set the minimum capacity to minimum.
minimum)
9 Object firstElement() Returns the first element.

10 int indexOf(Object obj) Search for the first occurrence of Obj. Returns its
index or -1 if Obj is not in the vector.
11 int indexOf(Object obj,int Searches for the first occurrence of Obj beginning at
start) index start. Returns its index or -1 if Obj is not in the
vector.
12 Void Adds Obj to the vector at index.
insertElementAt(Object
obj,int index)

13 boolean isEmpty() Returns true if the vector is empty.otherwise return


false.
14 Object lastElement() Returns the last element.
15 int lastIndexOf(Object Searches for the last occurrence of Obj, before index
obj,int start) start. Returns its index or -1 if Obj is not in the
vector.
16 Void Removes the element at Index.
removeAllElementsAt(int
index)
17 Void setElementAt(Object Assigns Obj to the element at index.
obj,int index)
18 void setSize() Set the number of the elements to size, Element
beyond size are discarded.
19 int size() Returns the number of the elements currently in the
vector.
20 String toString() Returns the string equivalent of the vector.
21 void trimToSize() Set the capacity to the number of elements currently
in the vector.

The Enumeration interface allows you to iterate through a set of object.


Its define two methods shown here:

boolean hasMoreElements()
Object nextElement()

[BY. VIPUL PRAJAPATI] Page 34


[CCMS VADU] BCA-501-JAVA PROGRAMMING

The first method returns true if more elements are available, otherwise, it returns false.
The second method returns the next available element.
This interface is implemented by Vector class.

Example: - Illustrates the basic of working with Vector.


import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
//create a Vector and its element
Vector vector=new Vector();
vector.addElement(new Integer(5));
vector.addElement(new Float(-14.14f));
vector.addElement(new String("hello"));
vector.addElement(new Long(1200000));
vector.addElement(new Double(-23.45e-11));

//Display the Vector Element


System.out.println(vector);

//Insert an element in to vector


String s=new String("String to be inserted");
vector.insertElementAt(s,1);
System.out.println(vector);

//Remove an element from the vector


vector.removeElementAt(3);

System.out.println(vector);
}
}

Example:- Illustrates the basic working with the Enumeration Interface.


import java.util.*;
class EnumerationDemo
{
public static void main(String args[])
{
//create a Vector and its element Vector
vector=new Vector(); vector.addElement(new
Integer(5)); vector.addElement(new Float(-
14.14f)); vector.addElement(new
String("hello")); vector.addElement(new
Long(1200000)); vector.addElement(new
Double(-23.45e-11));

//Display the elements of the vector


Enumeration e=vector.elements();
while(e.hasMoreElements())
{
Object obj=e.nextElement();
System.out.println(obj);
}
}
}

Wrapper classes: -
As we know that vector class does not handle primitive data types like int, float, long, char and double.
Primitive data types may be converted into object types by using the wrapper class provided by JAVA.
Wrapper classes for converting simple types.

Simple Type Wrapper class

[BY. VIPUL PRAJAPATI] Page 35


[CCMS VADU] BCA-501-JAVA PROGRAMMING

boolean Boolean
char Character
double Double
float Float
int Integer
long Long

The wrapper class have a number of unique methods for handling primitive data types and object.
Converting primitive numbers to object number using constructor methods.

Constructor calling Conversion actions


Integer IntVal = new Integer(i) Primitive integer to integer object
Float FloatVal = new Float(f) Primitive float to float object
Double DoubleVal = new Double(d) Primitive double to double object
Long LongVal = new Long(l) Primitive long to long object

Converting object number to primitive numbers using typeValue() method.

Method Calling Conversion Action


int i = IntVal.intValue() Object to primitive integer
float f = FloatVal.floatValue() Object to primitive float
long l = LongVal.longValue() Object to primitive long
double d = DoubleVal.doubleValue() Object to primitive double

Converting numbers to string using to String() method.

Method Calling Conversion action


Str = Integer.toString(i) Primitive integer to string
Str = Float.toString(f) Primitive float to string
Str = Double.toString(d) Primitive double to string
Str = Long.toString(l) Primitive long to string

Converting string objects to numeric objects using the static method ValueOf().

Method Calling Conversion action


DoubleVal = Double.Valueof(str) Converts string to double object
FloatVal = Float.Valueof(str) Converts string to float object
IntVal = Integer.Valueof(str) Converts string to integer object
LongVal = Long.Valueof(str) Converts string to long object

Converting numeric strings to primitive numbers using parsing methods.

Method Calling Conversion Action


int i = Integer.parseInt(str) Converts string to primitive integer
long i = Long.parseLong(str) Converts string to primitive long

The parseInt() and parseLong() methods throw a Number Format Exception if the value of the str does
not represent an integer.

Interface: -
Interface defines only abstract methods & final fields.
This means that interface do no specify any code to implement these methods and data fields contains
only constants.
An interface contains only abstract methods which are all incomplete methods, so it is not possible to
create an object to an interface.
In this case, we can create separate classes where we can implement all the methods of the interface.
These classes are known as implementation classes will have all the methods with body.
It is possible to create object of implementation class.

[BY. VIPUL PRAJAPATI] Page 36


[CCMS VADU] BCA-501-JAVA PROGRAMMING
An interface defines the contract between service provider and the client without highlighting internal
implementation.
Like Interface describes the services, what service provider provides and what client get.

The main Advantage of interface are:-


1. We never highlight our implementation to the outside world; we can achieve security for our
implementation.
2. With out effecting outside world, we can enhance our internal implementation. Interface is
considered as 100% pure abstract class because we never keep implementation inside interface.
And hence all the methods present inside an interface are abstract methods.
For the service provider point of view an interface defines the services provided by that person.
From the client point of view an interface describes what services he required.

Syntax:- interface interfacename


{
Variable name;
Method name;
}

interface is the keyword & interfacename is valid Java variable(just like class name)

static final type variable name=value;

Note that all variable declare as constants.


Method declaration will contain only a list of methods without any body statement.
return type methodname (parameter list);

Implementing Interface:-
Interfaces are used as “Superclass” whose properties are inherited by classes.

Class classname implements interfacename


{
Body of class name
}

Class classname extends superclass implements interface1,


interface2 {
Body of class name
}

This shows that a class can extend another class while implementing interface.
When a class implementation more than one interfaces, they are separated by comma.
Example:-
interface Area // interface define
{
final static float pi=3.14F;
float compute (float x,float y);
}
class Rectangle implements Area //interface implemented
{
public float compute(float x,float y)
{
return (x*y);
}
}
class circle implements Area // interface implemented
{

[BY. VIPUL PRAJAPATI] Page 37


[CCMS VADU] BCA-501-JAVA PROGRAMMING
public float compute(float x,float y)
{
return (pi*x*x);
}
}
class interfacedemo
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
circle cir=new circle();
Area area; // interface object
area=rect; // area refers to rect object
System.out.println("This is area of rectangle:-->"+area.compute(10,20));
area=cir; // area refers to circle object System.out.println("This is area
of circle:-->"+area.compute(10,20));
}
}

Interfaces Can Be Extended: -


One interface can inherit another by use of the keyword extends.
The syntax is the same as for inheriting classes.
When a class implements an interface that inherits another interface, it must provide implementations
for all methods defined within the interface inheritance chain.

Example:-
/ One interface can extend another.

interface A {
void meth1();
void meth2();
}
/ B now includes meth1() and meth2() — it adds meth3().
interface B extends A {
void meth3();
}
/ This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

Multiple Inheritances using Interface:-


If two super classes have same names for their members (variable & Methods) then which member is
inherited into the sub class is the main confusion in multiple Inheritance.
This is the reason; Java does not support the concept of multiple inheritances.
This confusion is reducing by using multiple interfaces to achieve multiple inheritances.
Example:

// Multiple inheritance using interface

[BY. VIPUL PRAJAPATI] Page 38


[CCMS VADU] BCA-501-JAVA PROGRAMMING

interface A
{
float HT=6.2F;
void height();
}
interface B
{
float HT=5.8F;
void height();
}
class C implements A,B
{
public void height()
{
float ht=(A.HT+B.HT)/2;
System.out.println("C's height--->"+ht);

}
}
class multiple
{
public static void main(String args[])
{
C c=new C();
c.height();
}
}

Class Interface
The member of a class can be constants or The member of an interfaces are always
variable declare as constants, i.e their values are
final.
The class definition can contain the code The methods in an interface are abstract in
for each of its methods. That is the nature, i.e., there is no code associated
methods can be abstract or non-abstract. with them. It is later defined by the class
that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare object. It can
only be inherited by a class.
It can be various access specifier like It can only use the public access specifier.
public, private, or protected.

Packages: Putting classes together: -


Packages: -
We have repeatedly stated that one of the main futures of OOP is its ability to reuse the code already
created.
One way to achieving this by extending the classes and implementing the interface we had created.
Another way of achieving the reusability in JAVA, therefore, is use packages.
Packages are Java’s way of grouping a variety of classes and/or interfaces together.
The grouping usually done according to functionally.
In fact, packages act as ‘container’ for classes.
JAVA packages are classified into two categories. [1] API (System) packages [2] User defined
packages.

Benefits of packages: -
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 packages and the class name.
Packages provide a way to ‘hide’ classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.

[BY. VIPUL PRAJAPATI] Page 39


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Package also provides a way for separating ‘design’ form ‘coding’. First we can design a class and
decide their relationships, and then we can implement the JAVA code needed for particular method.

JAVA API packages: -


A JAVA API package provides a large number of classes grouped under different packages according
to his functionality.
Most of time we use the packages available with the JAVA API.
Consider the following figure.

Following are the JAVA system packages and their classes.

Packages Contents
Name
java.lang Language support classes. These are classes that JAVA compiler itself used and
therefore they are automatically imported. They include classes for primitive types,
string, math functions, thread and exceptions.
java.util Language utility classes such as vector, hash table, random number, date, etc…
java.io Input/output support classes. They provide facilities for the input and output of
data.
java.awt Set of classes for implementing graphical user interface. They include classes for
windows, buttons, list, menus, and so on.
java.net Classes for networking. They include classes for communicating with local
computers as well as with internet servers.
java.applet Classes for creating and implementing applets.

Naming conventions: -
Packages can be named using the standard JAVA naming rules.
By convention, however, packages begin with lowercase letters. This may make it easy for user to
distinguish packages name from class name.
Look at the following example.

[BY. VIPUL PRAJAPATI] Page 40


[CCMS VADU] BCA-501-JAVA PROGRAMMING

This statement uses a fully qualified class name Math to invoke the method sqrt(). Note that
methods begin with lowercase letters.
Consider the following example.

java.awt.Point pts[]

This statement declares an array of Point type object using the fully qualified class name.
Every package name must be unique to make the best use of package. Duplicate name will create
run time errors.
Since multiple user work on internet, duplicate package names are unavoidable. JAVA designers
have recognised this problem and therefore suggested a package naming convention that ensures
uniqueness.

Creating package: -
We first declare the name of the package using the package keyword followed by the package
name.
This must be the first statement in the JAVA source file while creating a
package. Then we define the class.
Consider the following example.

package first_package ;

public class first_class


{
…………………….
……………………. (Body of class)
…………………….
}

Here the package name is first_class. The first_class is now considered as a part of this
package.

This listing would be saved as a file called first_class.java, and located in a directory named
first_package.
When the source file is compiled, JAVA will create a .class file and store it in the same directory.
While creating our own package it involves the following steps.
1. Declare the package at the beginning of the file using the form package packagename:
2. Define the class that is to be put in the package and declare in public.
3. Create subdirectory under the directory where the main source files are stored.
4. Store the listing as the classname.java file in the subdirectory created.
5. Compile the file. This create .class file in the directory.

Accessing a package: -
The JAVA system packages can be accessed either using a fully qualified class name or using a
shortcut approach through the import statement.
We use the import statement when there many references to particular package or the package
name.
The same approaches can be used to access the further-defined packages as well.
The import statement can be used to search a list of packages for particular class.
Consider the following example.

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

Here package1 is the name of the top level package; package2 is the name of package that is
inside the package1 and so on.
Note that the statement must end with a semicolon (;). Multiple import statements are allowed.
We can also use another approach as follows;

import packagename.* ;

[BY. VIPUL PRAJAPATI] Page 41


[CCMS VADU] BCA-501-JAVA PROGRAMMING

Here, package name may denote a single package or hierarchy of packages.

Using a package: -
Let us now consider the some simple programs that will use the classes from other package.
The listing below shows a package named package1 containing a single class Class1.

package package1 ;
public class ClassA
{
public void displayA()
{
System.out.printline(“Class A”);
}
}

This source file should be named ClassA.java and stored in the subdirectory package1.
Now compile this JAVA file. The resultant ClassA.class will be stored in the same subdirectory.
Now consider the following listing shown below.

inport package1.ClassA ;
class packagetest1
{
public static void main (String args[ ])
{
ClassA objA = new ClassA( );
objA.display( );
}
}

Above example shows a simple program that imports the class ClassA from the package
package1.

-------
JAVA util package classes: -
The Random Class:-
The Random Class allows you to generate random double, float, int or long numbers.
You may also generate numbers that have a Gaussian distribution.
This can be valuable if you are building a simulation of real-world system.
Input data frequently followed such a distribution.
This class provides the following Constructor
Random()
Random(long seed)
Here, seed is a value to initialize the random number generator. The first form uses the current time as
the seed.
Some instance Methods define by this class.

SN Method Name Description


1 void nextBytes(byte buffer[]) Fills buffer with random number.
2 Double nextDouble() Returns a random double value.
3 float nextFloat() Returns a random float value.
4 int nextInt() Returns a random int value.
5 long getLong() Returns a random Long value.
6 void setSeed(long seed) Seeds the random number generator with seed.

Example: - To generate 10 Random Integer by Random class.


import java.util.*;
class randomInt
{
public static void main(String args[])
{

[BY. VIPUL PRAJAPATI] Page 42


[CCMS VADU] BCA-501-JAVA PROGRAMMING
//create random number Ganerator
Random generator=new Random();

//Generate and dispaly 10 random integers

for(int i=0;i<10;i++)
{
System.out.println(generator.nextInt());
}
}
}

The Date Class:-


The Date class encapsulates information about a specific date and time.
It provides the following constructor.
Date()
Date(long msec)
The first form returns an object that represent the current date & time
The second form returns an object that represent the date and time msec milliseconds after epoch.
The epoch is defined as midnight on January 1,1970 GMT(GreenWich Mean Time).
Some instance Methods define by this class.

SN Method_Name Description
1 Boolean after(Date d) Returns true if d is after the current date.
Otherwise returns false.
2 Boolean before(Date d) Returns true if d is before the current date.
Otherwise return false.
3 Boolean equals(Date d) Returns true if d has the same value as the
current date. Otherwise return false.
4 long getTime() Return the number of milliseconds since the
epoch.
5 Void setTime(long msec) Set the date and time of the current object
to represent msec milliseconds since the
epoch.
6 String toString() Returns the string equivalent of the date.
------
Example:- Display current date with Date object with default constructor.

import java.util.*;

class dateDemo
{
public static void main(String args[])

//Go date object initilized to current date & Time

Date currentDate=new Date();

//Display current date

[BY. VIPUL PRAJAPATI] Page 43


[CCMS VADU] BCA-501-JAVA PROGRAMMING
System.out.println(currentDate);

//get date object initialize to the epoch(Jan 1 1970)

Date epoch=new Date();

//display epoch date

System.out.println(epoch);

The Calendar & Gregorian Calendar Classes:-


The abstract calendar class allows you to interpreter date and time information.
This class defines several int constants that are used when you get or set components of the calendar.
These are listed here :-
AM AM_PM APRIL
AUGUST DATE DAY_OF_MONTH
DAY_OF_WEEK DAY_OF_WEEK_IN_MONTH DAY_OF_YEAR
DECEMBER DST_OFFSET ERA
FEBRUARY FIELD_COUNT FRIDAY
HOUR HOUR_OF_DAY JANUARY
JULY JUNE MARCH
MAY MILLISECOND MINUTE
OCTOMBER PM SATURADAY
SECOND SEPTEMBER SUNDAY
THRUSDAY TUESDAY UNDECIMBER
WEDNESDAY WEEK_OF_MONTH WEEK_OF_YEAR
YEAR ZONE_OFFSET

The Calendar class doses not have public constructors.


Instead, you may use the static getInstance() method to obtain a calendar.

Method_Name Description
abstract boolean after(Object Returns true if the invoking Calendar object contains a date
calendarObj) later than the one specified by calendarObj, it returns false.

abstract boolean before(Object Returns true if the invoking Calendar object contains a date
calendarObj) earlier than the one specified by calendarObj, it returns false.
abstract boolean equals(Object Returns true if the invoking Calender object contains a date
calendarObj) equals to the one specified by calendarObj, it returns false.
final int get(int calendarField) Returns the value of one component of the invoking object.
The component is indicated by Calendar Field. Some Example
of the component that can be requested are
Calendar.YEAR,Calendar.MONTH,Calnender.MINUTE and
so forth
static Calender getInstance() Returns a Calender object for the default locale and time
zone.
final Date getTime() Returns a Date object equivalent to the time of the invoking
object.
final void set(int year,int month Set various date and time component of the invoking object.

[BY. VIPUL PRAJAPATI] Page 44


[CCMS VADU] BCA-501-JAVA PROGRAMMING
,int date,int hour,int minute,int
second)
final void setTime(Date d) Set various date and time component of the invoking object.
This information is obtained form the Date object d.

Initialized to the current date and time. One of its forms is shown here:-
Calendar getInstance()
Some Instance methods provided by this class.

The GregorianCalendar class is a concrete subclass of Calendar.


It provides the logic to manage date and time information according to the rule of Gregorian calendar.
This is the calendar that numbers years starting at the birth of Christ.
Its provides several constructor ,some of these are shown here:

1. GregorianCalendar()
2. GregorianCalender(int year,int month,int date)
3. GregorianCalender(int year,int month,int date,int hour,int minute,int sec)
4. GregorianCalender(int year,int month,int date,int hour,int minute,int minute)

The first form creates an object initialize with the current date and time.
The other forms allow you to specify how various date and time component s are initialized.
The class provides all of the methods defined by Calendar and also adds the isLeapYear() method
shown here:
boolean isLeapYear()

This method returns true, if the current year is a leap year. Otherwise, it returns false.

Example: - This program illustrate how to use some methods provide by Calendar class.

import java.util.*;
class CalendarDemo
{
public static void main(String args[])
{
Calendar calendar=Calendar.getInstance();
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.HOUR));
System.out.println(calendar.get(Calendar.DATE));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
System.out.println(calendar.get(Calendar.MINUTE));
}
}

Stack Class:-
The Stack Class extends Vector and provides a LIFO (last-in, First-out) stack.
Here is an excellent example of the power of object-oriented programming.
The Vector class provides the functionality of a dynamic array.
This capacity is also needed to implement the Stack class.

The stack class reuses this implementation and also provides methods to push, pop, and otherwise
manipulate the stack.
You will see that class inheritance is commonly used throughout the Java Class libraries to achieve
maximum code reuse.

SN Method_Name Description
1 Boolean empty() Returns True if the stack is empty. otherwise , returns
False.
2 Object peek() Returns the object at the top of the stack but dose not
throws remove it from the stack.
EmptyStackException
3 Object pop() throws Returns the object at the top of the stack and remove
EmptyStackException it from the stack.
4 Object push(Object Pushes Obj onto the stack and also return obj.
obj)

[BY. VIPUL PRAJAPATI] Page 45


[CCMS VADU] BCA-501-JAVA PROGRAMMING
5 int search(Object Search the stack for obj.if not found, returns -1 .
obj) otherwise returns the index at which obj located. The
top of the stack is index 1.

Example: - Program which use Stack Classes.


import java.util.*;
class pushpop
{
public static void main(String args[])
{
//create stack
Stack stack=new Stack();

//push elements onto stack


for(int i=0;i<args.length;i++)
stack.push(new Integer(args[i]));

//pop elements from stack and display


while(!stack.empty())
{
Object obj=stack.pop();
System.out.println(obj);
}
}
}

Hash table Classes:-


Hash tables are commonly used in Java Programming. They allow you to easily store and retrieve
object.
Each entry in a hash table contains a key and a value.
Both the key and the value are objects. The keys must be unique; the values need not be.
You do not retrieve elements from a hash table by index.
Instead, a key is used to obtain the corresponding value. Another name for this type of data structure
is associative array.
The Hashtable class allows you to create and use hash tables.
The following are some of its constructors

Hashtable()
Hashtable(int n)
Hashtable(int n,float lf)

Here, n is the initial capacity of hash table and if is its load factor.
The latter is a number between 0 & 1.
The size of Hash table is automatically increased when the number of entries in the hash table exceeds
the product of the capacity and load factor.
Instance method of this class

SN Method_Name Description
1 boolean contains(Object Returns TRUE if the hash table contains v as one of its
v)throws NullPointerException values. Otherwise, return FALSE. The method throws a
NullPointerException if v is null.
2 boolean containsKey(Object k) Returns true if the hash table contains k as one of its keys.
Otherwise, returns false.
3 boolean containsValue(Object Returns true if the hash table contains v as one of its
v) values. Otherwise returns false.
4 Enumeration elements() Returns an enumeration of the value.
5 Object get(Object k) Returns the value associated with the key k.
6 boolean isEmpty() Returns true if the hash table is empty. Otherwise, returns
false.
7 Enumeration keys() Returns an enumeration of the key.
8 Object put(Object k, Object v) Puts a key/value pair into the hash table. The key is k and
throws NullPointerException the value is v. The method throws a
[BY. VIPUL PRAJAPATI] Page 46
[CCMS VADU] BCA-501-JAVA PROGRAMMING
NullPointerException if k or v is null.
9 Object remove(Object k) Remove the key/value pair whose key is k.
10 Int size() Returns the number of key.
11 String toString() Returns the string equivalent of this hash table.

Example: - Program which illustrate the basic working of Hash Table.

import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
//create hash table and populate it
Hashtable hash=new Hashtable();
hash.put("pen","red");
hash.put("pencil","blue");
hash.put("book","green");
hash.put("kit","yellow");

//display the elements of the hash table


Enumeration e = hash.keys();
while(e.hasMoreElements())
{
Object k=e.nextElement();
Object v=hash.get(k);
System.out.println("key= "+ k +"; value= " +v);
}
//Display the value for pen
System.out.println("\n The color of an pen is:- ");
Object v=hash.get("pen");
System.out.println(v);
}
}

String Tokenizer Class:-


The StringTokenizer class allows you to parse a string in to token.
The characters that act as delimiters between tokens can be
specified. This functionality can be very useful in some types of
application.
For Example, you may need to build a program that processes formatted data from a file.
Compiler and interpreters it also require the ability to examine a string and segment it into tokens
according to a set of rules.
This class provides the following Constructors.

StringTokenizer(String str)
StringTokenizer(String str,String delimiter)
StringTokenizer(String str,String delimiter,Boolean delimiterAreTokens)

-------
Here, str is the String to be parsed & delimiters contains the character that separate tokens.
If delimitersAreTokens is true, the tokenizer returns the delimiters as tokens. Otherwise, the delimiters
are not returned from the tokenizer.
Instance method which are use by String Tokenizer

SN Method_Name Description
1 int countTokens() Returns the number of tokens in the string.
2 boolean hasMoreToken() Returns true if there are more tokens. Otherwise ,
returns false.
3 String nextToken() Returns the next token.
4 String nextToken(String Returns the next token and defines delimiters as
delimiters) the set of the delimiter characters.

[BY. VIPUL PRAJAPATI] Page 47


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Example: - Program which illustrate the basic working of String Tokenizer.
import java.util.*;
class StringToken
{
public static void main(String args[])
{
String str="123/45.45/23/34/000/67";
StringTokenizer st=new StringTokenizer(str,"/");
while(st.hasMoreTokens())
{
String s=st.nextToken();
System.out.println(s);
}
}
}
ROUGH WORK

Unit-3
Threads: -
Java provides built-in support for multithreaded programming. A multithreaded program contains
two or more parts that can run concurrently. Each part of such a program is called a thread, and
each thread defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead
than multitasking processes.
There are two types of multitasking:
o Process-based multitasking: -
 Process-based multitasking is the feature that allows your computer to run two or
more programs concurrently.

o Thread-based multitasking: -
 Thread-based multitasking environment, the thread is the smallest unit of
dispatchable code. This means that a single program can perform two or more tasks
simultaneously.
Multithreading has several advantages over Multiprocessing such as:-
1. Threads are lightweight compared to processes.
2. Threads share the same address space and therefore can share both data and code.
3. Context switching between threads is usually less expensive than between processes.
4. Cost of thread intercommunication is relatively low that that of process intercommunication.
5. Threads allow different tasks to be performed concurrently.

JAVA Thread Model: -

[BY. VIPUL PRAJAPATI] Page 48


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Single-threaded systems use an approach called an event loop with polling.
In this model, a single thread of control runs in an infinite loop, polling a single event queue to
decide what to do next.
Once this polling mechanism returns with, say, a signal that a network file is ready to be read, then
the event loop dispatches control to the appropriate event handler.
This wastes CPU time.
In a singled-threaded environment, when a thread blocks (that is, suspends execution) because it is
waiting for some resource, the entire program stops running.
The benefit of Java's multithreading is that the main loop/polling mechanism is eliminated.
One thread can pause without stopping other parts of your program.
Multithreading allows animation loops to sleep for a second between each frame without causing
the whole system to pause.
When a thread blocks in a Java program, only the single thread that is blocked pauses. All other
threads continue to run.

Life Cycle of a Thread: -


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.

[BY. VIPUL PRAJAPATI] Page 49


[CCMS VADU] BCA-501-JAVA PROGRAMMING
-------
There are many state are there when Thread can be executed.
1. New born state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
A thread is always in one of these five states. It can move from one state to another via a variety of
ways.

New born state:- When we create a thread object, the thread is born and is said to be in newborn
state.
o The thread is not yet scheduled for running; at this state we can do only one of the Following
things.
 Schedule it for running using start() method.
 Kill it using stop() method.
o If we attempt to use any another method at this stage, an exception will be thrown.

Runnable state:- The runnable state means that the thread is ready for execution and is waiting
for the availability of the processor.
o The thread had joined the queue of threads that are waiting for execution.
o If all thread has equal priority, then they are given time slots for execution in First-come
First-serve manner.
o If we want a thread to give up control to another thread to equal priority before its turns
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.
o The thread runs until it give up control on its own or it is prevent by a higher priority thread.
o A running thread gives up its control in one of the following situation.
 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 times due to
creation reason, but do not want to kill it.

 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 the queue during this time period.
 The thread re-enter the runnable state as soon as this time period is elapsed.

 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.

[BY. VIPUL PRAJAPATI] Page 50


[CCMS VADU] BCA-501-JAVA PROGRAMMING

-------

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

Dead State:- Every thread has a life cycle, A running thread ends its life when it has completed
executing its run() method.
o It is a natural dead, we can kill it by sending the stop message to it at any state thus causing
a premature death to it.
o A thread can be killed as soon it is born, or while it is running, or even when its in “not
runnable” (blocked) condition.

Creating a Thread: -
Java defines two ways in which this can be accomplished:
o You can implement the Runnable interface.
o You can extend the Thread class, itself.

Create Thread by Implementing Runnable:-


The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )

You will define the code that constitutes the new thread inside run() method.
It is important to understand that run() can call other methods, use other classes, and declare
variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);

Here threadOb is an instance of a class that implements the Runnable interface and the name of
the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is
declared within Thread. The start( ) method is shown here:

void start( );

Create Thread by Extending Thread: -


The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class.

PROGRAM:-
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
[BY. VIPUL PRAJAPATI] Page 51
[CCMS VADU] BCA-501-JAVA PROGRAMMING

-------
if(i==1) yield();
System.out.println("\tFrom 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("\t From Thread B:- j=" +j);
if(j==3) stop();
}
System.out.println("Exit from B");
}
}

class C extends Thread


{
public void run()
{
for(int k=1;k<=5;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
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();

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

[BY. VIPUL PRAJAPATI] Page 52


[CCMS VADU] BCA-501-JAVA PROGRAMMING
-------
start Thread B
start Thread C
End of main Thread
From Thread B:- j=1
From Thread A :-i= 1
From Thread C: K=1
From Thread B:- j=2
From Thread A :-i= 2
From Thread B:- j=3
From Thread A :-i= 3
From Thread A :-i= 4
From Thread A :-i= 5
Exit from A
From Thread C: K=2
From Thread C: K=3
From Thread C: K=4
From Thread C: K=5
Exit from c

Create Thread by Runnable Interface: -


PROGRAM:-
Here is an example that creates a new thread and starts it running:

// Create a new thread.

class NewThread implements Runnable {


Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
/ This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--)
{ System.out.println("Child Thread: " + i);
/ Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e)
{ System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{ System.out.println("Main thread
interrupted.");
}
System.out.println("Main thread exiting.");
}
}

[BY. VIPUL PRAJAPATI] Page 53


[CCMS VADU] BCA-501-JAVA PROGRAMMING
-------
OUTPUT:-
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Thread Methods: -
Following is the list of important methods available in the Thread class.
These methods are invoked on a particular Thread object. The following methods in the Thread
class are static.
SN Methods Description
1 public void start() Starts the thread in a separate path of execution, then invokes the
run() method on this Thread object.
2 public void run() If this Thread object was instantiated using a separate Runnable
target, the run() method is invoked on that Runnable object.
3 public final void Changes the name of the Thread object. There is also a getName()
setName(String name) method for retrieving the name.

4 public final void Sets the priority of this Thread object. The possible values are
setPriority(int priority) between 1 and 10.

5 public final void The current thread invokes this method on a second thread,
join(long millisec) causing the current thread to block until the second thread
terminates or the specified number of milliseconds passes.
6 public final boolean Returns true if the thread is alive, which is any time after the
isAlive() thread has been started but before it runs to completion.

Invoking one of the static methods performs the operation on the currently running thread
SN Methods Description
1 public static void yield() Causes the currently running thread to
yield to any other threads of the same
priority that are waiting to be scheduled
2 public static void sleep(long Causes the currently running thread to
millisec) block for at least the specified number of
milliseconds
3 public static Thread Returns a reference to the currently
currentThread() running thread, which is the thread that
invokes this method.

Thread priorities: -
Thread priorities are used by the thread scheduler to decide when each thread should be allowed
to run.
In theory, higher-priority threads get more CPU time than lower-priority threads.
When the thread are created and started, a ‘Thread scheduler’ program in JVM will load them into
memory and execute them.
This scheduler will allot more JVM time to those threads which are having higher priorities.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a
constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
The minimum priority (shows by Thread.MIN_PRIORITY) of a thread is 1,and the maximum priority
(Thread.MAX_PRIORITY) is 10,and normal priority of a thread (Thread.NORM_PRIORITY) is 5.

[BY. VIPUL PRAJAPATI] Page 54


[CCMS VADU] BCA-501-JAVA PROGRAMMING

-------
PROGRAM:-//
Thread priorities
class myclass extends Thread
{
int count=0; //this count numbers
public void run()
{
for(int i=1;i<10;i--)
count++;//count number up to 10
/ display which thread has completed counting and its priority
System.out.println("CompleteThread:"+Thread.currentThread().getName());
System.out.println("Itspriority:"+Thread.currentThread().getPriority());
}

class prior
{
public static void main(String args[])
{
myclass obj=new myclass();

// create two threads


Thread t1=new Thread(obj,"one");
Thread t2=new Thread(obj,"two");

//set priorities for them


t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);// This mean priority no is 5

//start first t1 and then t2


t1.start();
t2.start();
}
}

OUTPUT:-
Complete Thread: two
Its priority:5
Complete Thread: one
Its priority:2

Thread synchronization (Monitoring): -


When a Thread is already acting on an object, preventing any other thread from acting on the same
object is called ‘Thread Synchronization’.
When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread synchronization.
The synchronized keyword in Java creates a block of code referred to as a critical section.
Every Java object with a critical section of code gets a lock associated with the object.
To enter a critical section, a thread needs to obtain the corresponding object's lock.
This is the general form of the synchronized statement:

synchronized (object)
{
// statements to be synchronized
}

Synchronized block ensures that a call to a method that is a member of object occurs only after the
current thread has successfully entered object's monitor.

[BY. VIPUL PRAJAPATI] Page 55


[CCMS VADU] BCA-501-JAVA PROGRAMMING

-------
PROGRAM:-
//Thread Synchronization - Two Threads acting on same object
class reserve implements Runnable
{
/ available berths are 1
int available=1;
int wanted;
//accept wanted berths at run time
reserve(int i)
{
wanted=i;
}
public void run()
{
synchronized(this) // synchroniz current object
{
//display available berth
System.out.println("Available Berths="+available);
//if available berths are more than wanted berths
if(available>=wanted)
{
//get the name of passenger
String name=Thread.currentThread().getName();
//allot the berth to him
System.out.println(wanted+ "Berths reserved for" + name);
try
{
Thread. sleep (1500);//wait for printing the ticket
available=available-wanted;
//update the no. of avialable berths
} catch (InterruptedException ie){}
}
//if available berths are less,display sorry
else System.out.println("Sorry, No Berths");
}//end of synchronized block
}
}
class safe
{
public static void main(String args[])
{
//tell that 1 berth is needed
reserve obj=new reserve(1);

//attach first thread to the object


Thread t1=new Thread(obj);

//attach sencond thread to the object


Thread t2=new Thread(obj);

//take the thread names as person name


t1.setName ("Rahul");
t2.setName ("Virendra");

/ send the requests for berth


t1.start ();
t2.start ();
}
}
OUTPUT:-
Available Berths=1
1 Berths reserved for Rahul
Available Berths=0

[BY. VIPUL PRAJAPATI] Page 56


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Sorry, No Berths
Deadlock of thread: -
Even if we synchronize the thread, there is possibility of other problem like ”DEADLOCK”.
When a thread has locked an object and waiting for another object to release by another thread
and other thread is also waiting for the first thread release the first object, both the thread will
continue waiting forever. This is called “Thread Deadlock”.
When Thread deadlock occurs, any further execution is stopped and the program will come to a
halt.

PROGRAM:-//
Thread DeadLock
class BookTicket extends Thread
{
//we assume train and compartment ad object
Object train,comp;
BookTicket(Object train,Object comp)
{
this.train=train;
this.comp=comp;
}
public void run()
{
//lock on train object
synchronized(train)
{
System.out.println("Book Ticket locked on train");
try
{
Thread.sleep(150);
}catch(InterruptedException e){}
System.out.println("BookTicket now waiting to lock on compartment");
synchronized(comp)
{
System.out.println("BookTicket locked on compartment");
}
}
}
}

class cancleTicket extends Thread


{
//we assume train and compartment ad object
Object train,comp;
cancleTicket(Object train,Object comp)
{
this.train=train;
this.comp=comp;
}
public void run()
{
//lock on train object
synchronized(comp)
{
System.out.println("cancle Ticket locked on compartment");
try
{
Thread.sleep(200);
}catch(InterruptedException e){}
System.out.println("cancleTicket now waiting to lock on train...");
synchronized(comp)
{
System.out.println("cancleTicket locked on train..");
}
}

-------

[BY. VIPUL PRAJAPATI] Page 57


[CCMS VADU] BCA-501-JAVA PROGRAMMING
}
}

class DeadLock
{
public static void main(String args[])
{
//take train,compratment as object of object class
Object train=new Object();
Object compartment=new Object();

//create objects to BookTicket,CancleTicket classes


BookTicket obj1=new BookTicket(train,compartment);
cancleTicket obj2=new cancleTicket(train,compartment);

//attach 2 threads to these object


Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);

//run the thread on the object


t1.start();
t2.start();
}
}

OUTPUT:-
Book Ticket locked on train
cancle Ticket locked on compartment
BookTicket now waiting to lock on compartment
cancleTicket now waiting to lock on train...
cancleTicket locked on train..
BookTicket locked on compartment

In this program, BookTicket thread & cancleTicket threads act in reverse direction creating a
deadlock situation.

Exception Handling:-
An exception is a condition that is caused by run-time error in the program.
An exception is an abnormal condition that arises in a code sequence at run time.
“Purpose of exception handling mechanism is to provide a means to detect and Report an
‘Exception circumstance ’so that appropriate action can be taken.”
The mechanism suggests incorporation of separate error handling code that perform the following
task:
o Find the problem(HIT the exception)
o Inform that an error has occurred (Throw the exception)
o Receive the error information(Catch the exception)
o Take corrective action(Handle the exception)
The error handling code basically consists of two segments, one to detect errors and to throw
exceptions & the other to catch exceptions & to take appropriate actions.

Following are the advantages of Exception-handling in Java:


o Exception provides the means to separate the details of what to do when something out of
the ordinary happens from the main logic of a program.
o One of the significance of this mechanism is that it throws an exception whenever a calling
method encounters an error providing that the calling method takes care of that error.
o With the help of this mechanism the working code and the error-handling code can be
disintegrated. It also gives us the scope of organizing and differentiating between different
errors types using a separate block of codes. This is done with the help of try-catch blocks.

o Furthermore the errors can be propagated up the method call stack i.e. problems occurring
at the lower level in the chain can be handled by the methods higher up the call chain.

[BY. VIPUL PRAJAPATI] Page 58


[CCMS VADU] BCA-501-JAVA PROGRAMMING

Syntax of Exception Handling Code:-

Try block
Statement that causes
an exception Exception object
Throws creator
exceptio
n object

Catch block
Statement that handles
the exception Exception handler

A method catches an exception using a combination of the try and catch keywords.
Java use a keyword try to preface a block of code that is likely to causes an error condition and
“throw” an exception.
A try/catch block is placed around the code that might generate an exception.
A Catch block defined by keyword catch ”catches” the exception “thrown” by the try block and
handles it appropriately.
Code within a try/catch block is referred to as protected code, and the syntax for using try/catch
looks like the following:
try
{
//Protected code
} catch (ExceptionName e1)

{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in protected code, the catch block (or a block) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.
To illustrate how easily this can be done, the following program includes a try block and a catch
clause which processes the ArithmeticException generated by the division-by-zero error:

PROGRAM:-
class Exc2 {
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

OUTPUT:-
Division by zero.
After catch statement.

Multiple catch Blocks: -

[BY. VIPUL PRAJAPATI] Page 59


[CCMS VADU] BCA-501-JAVA PROGRAMMING
A try block can be followed by multiple catch blocks.
The syntax for multiple catch blocks looks like the following:
try
{
//Protected
code }catch(ExceptionType
1 e1)

{
//Catch block
}catch(ExceptionType2 e2)

{
//Catch block
}catch(ExceptionType3 e3)

{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try
If an exception occurs in the protected code, the exception is thrown to the first catch block in the
list.
If the data type of the exception thrown matches ExceptionType1, it gets caught there.
If not, the exception passes down to the second catch statement.
This continues until the exception either is caught or falls through all catches, in which case the
current method stops execution and the exception is thrown down to the previous method on the
call stack.
PROGRAM:-
public class Multi_Catch
{
public static void main (String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;
int res=0;
try
{
res = num1/num2;
System.out.println("The result is" +res);
for(int ct =2;ct >=0; ct--)
{
System.out.println("The value of array are" +array[ct]);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error…. Array is out of Bounds");
}
catch (ArithmeticException e)
{
System.out.println ("Can't be divided by Zero");
}
}
}

OUTPUT:-
Can't be divided by Zero

The finally Keyword: -


The finally keyword is used to create a block of code that follows a try block.
A finally block of code always executes, whether or not an exception has occurred.

-------

[BY. VIPUL PRAJAPATI] Page 60


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following Syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

PROGRAM:-
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is
executed"); }
}
}
OUTPUT:-
Exception thrown :java.lang.ArrayIndexOutOfBoundsException
First element value: 6
The finally statement is executed

Note the followings:


1. A catch clause cannot exist without a try statement.
2. It is not compulsory to have finally clauses when ever a try/catch block is present.
3. The try block cannot be present without either catch clause or finally clause.
4. Any code cannot be present in between the try, catch, finally blocks.

Common Java Exception: -


SN Exception type Cause of Exception
1 ArithmeticException Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException Bad array indexes
3 ArrayStoreException When a program tries to store the wrong type of data
in an array.
4 FileNotFoundException Occur to access a nonexistent file.
5 IOException Occur by general I/O failures,such as inability to read
from file
6 NullPointerException Invalid use of a null reference.
7 NumberFormatException Invalid conversion of a string to a numeric format.
8 OutOfMemoryException Occur when there’s not enough memory to allocate a
new object.
9 SecurityException Occur when an applet tries to perform an action not
allowed by the browser’s security setting.
10 StringIndexOutOfBounds Attempt to index outside the bounds of a string.

[BY. VIPUL PRAJAPATI] Page 61


[CCMS VADU] BCA-501-JAVA PROGRAMMING
The throw Keywords: -
When we would like to through our own exception then we use throw keyword.
The throw statement causes termination of the normal flow of control of the java code and stops
the execution of the subsequent statements.
The throw clause transfers the control to the nearest catch block handling the type of exception
object throws.
If no such catch block exists, the program terminates.
The throw statement accepts a single argument, which is an object of the Exception class
Syntax to declare the throw statement,

throw new Throwable_subclass;

Example:-

throw new ArithmeticException();


throw new NumberFormatException();

PROGRAM:-
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}

class TestMyException
{
public static void main(String args[])
{
int x=5,y=1000;
try
{
float z=(float)x/(float)y;
if(z<0.01)
{
throw new MyException("Number is two small");
}
}
catch(MyException e)
{
System.out.println("Caught my Exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I m Always here");
}
}
}

OUTPUT:-
Caught my Exception
Number is two small
I m Always here

The throws Keywords: -


The throws statement is used by a method to specify the types of exceptions the method throws.
If a method is capable of raising an exception that it does not handle, the method must specify that
the exception have to be handled by the calling method.

-------

[BY. VIPUL PRAJAPATI] Page 62


[CCMS VADU] BCA-501-JAVA PROGRAMMING
This is done using the throws statement. The throws clause lists the types of exceptions that a
method might throw.

Syntax
type method-name(parameter-list) throws exception-list
{
// body of method
}

PROGRAM:-
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}

public static void main(String args[])


{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}

OUTPUT:-

Inside throwOne
Caught java.lang.IllegalAccessException: demo

Event Handling:-
Event handling is at the core of successful applet programming.
Most events to which your applet will respond are generated by the user.
These events are passed to your applet in a variety of ways, with the specific method depending
upon the actual event.
The most commonly handled events are those generated by the mouse, the keyboard, and various
controls, such as a push button.
Events are supported by the java.awt.event package.

The Delegation Event Model: -


The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events.
Its concept is quite simple:
1. A source generates an event and sends it to one or more listeners.
2. In this scheme, the listener simply waits until it receives an event.
3. Once received, the listener processes the event and then returns.
The advantage of this design is that the application logic that processes events is cleanly separated
from the user interface logic that generates those events.
A user interface element is able to "delegate" the processing of an event to a separate piece of
code.
In the delegation event model, listeners must register with a source in order to receive an event
notification.
This provides an important benefit: notifications are sent only to listeners that want to receive
them.

Events: -
[BY. VIPUL PRAJAPATI] Page 63
[CCMS VADU] BCA-501-JAVA PROGRAMMING

In the delegation model, an event is an object that describes a state change in a source.
It can be generated as a consequence of a person interacting with the elements in a graphical user
interface.
Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user
operations could also be cited as examples.
Events may also occur that are not directly caused by interactions with a user interface.
For example, an event may be generated when a timer expires, a counter exceeds a value, a
software or hardware failure occurs, or an operation is completed.
You are free to define events that are appropriate for your application.

Event Sources: -
A source is an object that generates an event.
This occurs when the internal state of that object changes in some way.
Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a specific
type of event.
Each type of event has its own registration method.
Basic Syntax:-

public void addTypeListener(TypeListener el)

Here, Type is the name of the event and el is a reference to the event listener.
For example, the method that registers a keyboard event listener is called addKeyListener().
The method that registers a mouse motion listener is called addMouseMotionListener( ).
This is known as multicasting the event. In all cases, notifications are sent only to listeners that
register to receive them.

Event Listeners: -
A listener is an object that is notified when an event occurs.
It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about specific
types of events.
Second, it must implement methods toreceive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event.
For example, the MouseMotionListener interface defines two methods to receive notifications
when the mouse is dragged or moved.
Any object may receive and process one or both of these events if it provides an implementation of
this interface.

Event Classes: -
The classes that represent events are at the core of Java's event handling mechanism.
At the root of the Java event class hierarchy is EventObject, which is in java.util.
It is the superclass for all events. Its one constructor is shown here:

EventObject(Object src)

Here, src is the object that generates this event.


EventObject is a superclass of all events.
AWTEvent is a superclass of all AWT events that are handled by the delegation event model.
The package java.awt.event defines several types of events that are generated by various user
interface elements.

Event Class Hierarchy


java.util.EventObject
|
+---java.awt.AWTEvent
|
+---java.awt.event.ActionEvent

[BY. VIPUL PRAJAPATI] Page 64


[CCMS VADU] BCA-501-JAVA PROGRAMMING
|
+---java.awt.event.ItemEvent
|
+---java.awt.event.AdjustmentEvent
|
+---java.awt.event.TextEvent
|
+----java.awt.event.ComponentEvent
|
+---java.awt.event.InputEvent
| |
| +---java.awt.event.KeyEvent
| |
| +---java.awt.event.MouseEvent
|
+---java.awt.event.FocusEvent
|
+---java.awt.event.ContainerEvent
|
+---java.awt.event.WindowEvent

Main Event Class with Description:-

SN Class Description
1 ActionEvent Generated when a button is pressed, a list item is double
clicked, or a menu item is selected.
2 ItemEvent Generated when a check box or list item is clicked; also
occurs when a choice selection is made or a checkable menu
item is selected or deselected.
3 AdjustmentEvent Generated when a scroll bar is manipulated.
4 TextEvent Generated when the value of a text area or text field is
changed.
5 ComponentEvent Generated when a component is hidden, moved, resized, or
becomes visible.
6 InputEvent Abstract super class for all component input event classes
7 KeyEvent Generated when input is received from the keyboard
8 MouseEvent Generated when the mouse is dragged, moved, clicked,
pressed, or released; also generated when the mouse-enters
or exits a component.
9 FocusEvent Generated when a component gains or loses keyboard focus.
10 ContainerEvent Generated when a component is added to or removed from a
container.
11 WindowEvent Generated when a window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.

The ActionEvent Class: -


An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu
item is selected.
The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event:
ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK.
There is an integer constant, ACTION_PERFORMED, which can be used to identify action events.
ActionEvent has these two constructors:
ActionEvent(Object src, int type, String cmd)

[BY. VIPUL PRAJAPATI] Page 65


[CCMS VADU] BCA-501-JAVA PROGRAMMING
ActionEvent(Object src, int type, String cmd, int modifiers)
-------
Here, src is a reference to the object that generated this event.
The type of the event is specified by type, and its command string is cmd.
The argument modifiers indicate which modifier keys (ALT, CTRL, META, and/or SHIFT) were
pressed when the event was generated.

Sn Method name Description


1 String When a button is pressed, an action event is
getActionCommand( ) generated that has a command name equal to
the label on that button.
2 int getModifiers( ) Returns a value that indicates which modifier
keys (ALT,CTRL, META, and/or SHIFT) were
pressed when the event was generated.

The ItemEvent Class: -


An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu
item is selected or deselected.
ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that signifies a change of
state.
ItemEvent has this constructor:

ItemEvent(ItemSelectable src, int type, Object entry, int state)

Here, src is a reference to the component that generated this event. For example, this might be a
list or choice element.
The type of the event is specified by type.
The specific item that generated the item event is passed in entry.
The current state of that item is in state.

Sn Method name Description


1 Object getItem( ) Can be used to obtain a reference to the
item that generated an event.
2 ItemSelectable Method can be used to obtain a reference
getItemSelectable( ) to the ItemSelectable object that
generated an event.
3 int getStateChange( ) Method returns the state change (i.e.,
SELECTED or DESELECTED) for the
event.

The AdjustmentEvent Class: -


An AdjustmentEvent is generated by a scroll bar.
There are five types of adjustment events.
The AdjustmentEvent class defines integer constants that can be used to identify them. The
constants and their meanings are shown here:

Sn Event name Description


1 BLOCK_DECREMENT The user clicked inside the scroll bar to
decrease its value.
2 BLOCK_INCREMENT The user clicked inside the scroll bar to
increase its value.
3 TRACK The slider was dragged.
4 UNIT_DECREMENT The button at the end of the scroll bar was
clicked to decrease its value.
5 UNIT_INCREMENT The button at the end of the scroll bar was
clicked to increase its value.
In addition, there is an integer constant, ADJUSTMENT_VALUE_CHANGED, that indicates that a
change has occurred.

[BY. VIPUL PRAJAPATI] Page 66


[CCMS VADU] BCA-501-JAVA PROGRAMMING
AdjustmentEvent has this constructor:

AdjustmentEvent(Adjustable src, int id, int type, int data)-------


Here, src is a reference to the object that generated this event.
The id equals ADJUSTMENT_VALUE_CHANGED.
The type of the event is specified by type, and its associated data is data.

Sn Method name Description


1 Adjustable getAdjustable( ) Returns the object that generated the
event.
2 int getAdjustmentType( ) Returns one of the constants defined
by adjustmentevent.
3 int getValue( ) When a scroll bar is manipulated, this
method returns the value represented
by that change.

The TextEvent Class: -


Instances of this class describe text events.
These are generated by text fields and text areas when characters are entered by a user or
program.
TextEvent defines the integer constant TEXT_VALUE_CHANGED.
The one constructor for this class is shown here:

TextEvent(Object src, int type)

Here, src is a reference to the object that generated this event.


The type of the event is specified by type.
The TextEvent object does not include the characters currently in the text component that
generated the event.
your program must use other methods associated with the text component to retrieve that
information.
For this reason, no methods are discussed for the TextEvent class.

The ComponentEvent Class: -


A ComponentEvent is generated when the size, position, or visibility of a component is changed.
There are four types of component events.
The ComponentEvent class defines integer constants that can be used to identify them.
The constants and their meanings are

Sn Event name Description


1 COMPONENT_HIDDEN The component was hidden.
2 COMPONENT_MOVED The component was moved.
3 COMPONENT_RESIZED The component was resized.
4 COMPONENT_SHOWN The component became visible.

ComponentEvent has this constructor:

ComponentEvent(Component src, int type)

Here, src is a reference to the object that generated this event. The type of the event is specified
by type.
ComponentEvent is the super-class either directly or indirectly of ContainerEvent, FocusEvent,
KeyEvent, MouseEvent, and WindowEvent.

ComponentEvent Method

Method returns the component that generated the event.

The InputEvent Class: -


The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for
component input events.

[BY. VIPUL PRAJAPATI] Page 67


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Its subclasses are KeyEvent and MouseEvent. The InputEvent class defines the following eight
integer constants that can be used to obtain information about any modifiers associated with this
event:
-------
The isAltDown(), isAltGraphDown(), isControlDown(), isMetaDown(), and isShiftDown()
methods test if these modifiers were pressed at the time this event was generated.
The forms of these methods are shown here:

boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )

InputEvent Method:

int getModifiers( )

Returns a value that contains all of the modifier flags for this event.

The KeyEvent Class: -


A KeyEvent is generated when keyboard input occurs.
There are three types of key events, which are identified by these integer constants:
KEY_PRESSED,KEY_RELEASED, and KEY_TYPED.
The first two events are generated when any key is pressed or released.
The last event occurs only when a character is generated.
There are many other integer constants that are defined by KeyEvent.
For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the
numbers and letters.
VK_ENTER, VK_ESCAPE, VK_CANCEL, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT,
VK_PAGE_DOWN, VK_PAGE_UP, VK_SHIFT, VK_ALT, VK_CONTROL
The VK constants specify virtual key codes and are independent of any modifiers, such as control,
shift, or alt.

KeyEvent is a subclass of InputEvent and has these two constructors:

KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

Here, src is a reference to the component that generated the event.


The type of the event is specified by type.
The system time at which the key was pressed is passed in when.
The modifiers argument indicates which modifiers were pressed when this key event occurred.
The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code.
The character equivalent (if one exists) is passed in ch.
If no valid character exists, then ch contains CHAR_UNDEFINED. For KEY_TYPED events, code will
contain VK_UNDEFINED.

Sn Method name Description


1 char getKeyChar( ) Returns the character that was entered
2 int getKeyCode( ) Returns the key code

The MouseEvent Class: -


There are seven types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:

Sn Event name Description


1 MOUSE_CLICKED The user clicked the mouse.
2 MOUSE_DRAGGED The user dragged the mouse.
3 MOUSE_ENTERED The mouse entered a component.
4 MOUSE_EXITED The mouse exited from a component.
5 MOUSE_MOVED The mouse moved.
6 MOUSE_PRESSED The mouse was pressed.

[BY. VIPUL PRAJAPATI] Page 68


[CCMS VADU] BCA-501-JAVA PROGRAMMING

7 MOUSE_RELEASED The mouse was released.

-------
MouseEvent is a subclass of InputEvent and has this constructor:

MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int
clicks,boolean triggersPopup)

src is a reference to the component that generated the event.


The type of the event is specified by type.
The system time at which the mouse event occurred is passed in when.
The modifiers argument indicates which modifiers were pressed when a mouse event occurred.
The coordinates of the mouse are passed in x and y. The click count is passed in clicks.
The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.

Sn Method name Description


1 int getX( ) Returns x coordinator.
2 int getY( ) Returns y coordinator.
3 Point getPoint( ) Obtain the coordinates of the mouse.
4 void translatePoint(int x, int Changes the location of the event.
y)
5 int getClickCount( ) Obtains the number of mouse clicks for this
event.
6 boolean isPopupTrigger( ) Tests if this event causes a pop-up menu to
appear on this platform.

The FocusEvent Class: -


A FocusEvent is generated when a component gains or loses input focus.
These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.
FocusEvent is a subclass of ComponentEvent and has these constructors:

FocusEvent(Component src, int type)

FocusEvent(Component src, int type, boolean temporaryFlag)

src is a reference to the component that generated this event.


The type of the event is specified by type.
The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to
false.
FocusEvent Method

boolean isTemporary( )

Indicates if this focus change is temporary.


The method returns true if the change is temporary. Otherwise, it returns false.

The ContainerEvent Class: -


A ContainerEvent is generated when a component is added to or removed from a container.
There are two types of container events.
The ContainerEvent class defines int constants that can be used to identify them:
COMPONENT_ADDED and COMPONENT_REMOVED.
They indicate that a component has been added to or removed from the container.
ContainerEvent is a subclass of ComponentEvent and has this constructor:

ContainerEvent(Component src, int type, Component comp)

src is a reference to the container that generated this event.


The type of the event is specified by type, and the component that has been added to or removed
from the container is comp
Sn Method name Description
1 Container getContainer( ) Reference to the container that generated

[BY. VIPUL PRAJAPATI] Page 69


[CCMS VADU] BCA-501-JAVA PROGRAMMING
this event
2 Component getChild( ) Returns a reference to the component that
was added to or removed from the container.

[BY. VIPUL PRAJAPATI] Page 70


[CCMS VADU] BCA-501-JAVA PROGRAMMING

The WindowEvent Class: -


There are seven types of window events.
The WindowEvent class defines integer constants that can be used to identify them.

Sn Event name Description


1 WINDOW_ACTIVATED The window was activated.
2 WINDOW_CLOSED The window has been closed.
3 WINDOW_CLOSING The user requested that the window be
closed.
4 WINDOW_DEACTIVATED The window was deactivated.
5 WINDOW_DEICONIFIED The window was deiconified.
6 WINDOW_ICONIFIED The window was iconified.
7 WINDOW_OPENED The window was opened.

WindowEvent is a subclass of ComponentEvent and has this constructor:

WindowEvent(Window src, int type)

src is a reference to the object that generated this event. The type of the event is type.

WindowEvent Method

Window getWindow( )
Returns the Window object that generated the event.

Sources of Events: -

SN Event source Description


1 Button Generates action events when the button is pressed.
2 Generates item events when the check box is selected or
Checkbox
deselected.
3 Choice Generates item events when the choice is changed.
4 Generates action events when an item is double-clicked;
List generates item events when an item is selected or
deselected.
5 Generates action events when a menu item is selected;
Menu Item generates item events when a checkable menu item is
selected or deselected.
6 Generates adjustment events when the scroll bar is
Scrollbar
manipulated.
7 Text components Generates text events when the user enters a character.
8 Generates window events when a window is activated,
Window closed, deactivated, deiconified, iconified, opened, or
quit.

Event Listener Interfaces: -


The delegation event model has two parts: sources and listeners.
Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package.
When an event occurs, the event source invokes the appropriate method defined by the listener
and provides an event object as its argument.
Event Listener Interfaces

SN Interface Description
1 ActionListener Defines one method to receive action events.
2 AdjustmentListener Defines one method to receive adjustment
events.
3 ComponentListener Defines four methods to recognize when a
component is hidden, moved, resized, or shown.

[BY. VIPUL PRAJAPATI] Page 71


[CCMS VADU] BCA-501-JAVA PROGRAMMING

[BY. VIPUL PRAJAPATI] Page 72


[CCMS VADU] BCA-501-JAVA PROGRAMMING

BCA AND PGDCA COLLEGE, IDAR ------------------------------------------------------- JAVA ----------


4 ContainerListener Defines two methods to recognize when a
component is added to or removed from a
container.
5 FocusListener Defines two methods to recognize when a
component gains or loses keyboard focus.
6 ItemListener Defines one method to recognize when the state
of an item changes.
7 KeyListener Defines three methods to recognize when a key is
pressed, released, or typed.
8 MouseListener Defines five methods to recognize when the
mouse is clicked, enters a component, exits a
component, is pressed, or is released.
9 MouseMotionListener Defines two methods to recognize when the
mouse is dragged or moved.
10 TextListener Defines one method to recognize when a text
value changes.
11 WindowListener Defines seven methods to recognize when a
window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.

The ActionListener Interface: -


This interface defines the actionPerformed( ) method that is invoked when an action event
occurs.
The general forms of these method is

void actionPerformed(ActionEvent ae)

The AdjustmentListener Interface: -


This interface defines the adjustmentValueChanged( ) method that is invoked when
anadjustment event occurs.
The general forms of these method is

void adjustmentValueChanged(AdjustmentEvent ae)

The ComponentListener Interface: -


This interface defines four methods that are invoked when a component is resized, moved, shown,
or hidden.
The general forms of these methods are

void componentResized(ComponentEvent ce)


void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

The ContainerListener Interface: -


This interface contains two methods.
When a component is added to a container, componentAdded( ) is invoked.
When a component is removed from a container, componentRemoved( ) is invoked
The general forms of these methods are

void componentAdded(ContainerEvent ce)


void componentRemoved(ContainerEvent ce)

The FocusListener Interface: -


This interface defines two methods
When a component obtains keyboard focus, focusGained( ) is invoked.

void focusGained(FocusEvent fe)

When a component loses keyboard focus, focusLost( ) is called.


void focusLost(FocusEvent fe)

[BY. VIPUL PRAJAPATI] Page 73


[CCMS VADU] BCA-501-JAVA PROGRAMMING

------- The ItemListener Interface: -


This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes.
The general forms of these method is

void itemStateChanged(ItemEvent ie)

The KeyListener Interface: -


This interface defines three methods.
The keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed and
released, respectively. The keyTyped( ) method is invoked when a character has been entered.
For example, if a user presses and releases the A key, three events are generated in sequence: key
pressed, typed, and released.
The general forms of these methods are

void keyPressed(KeyEvent ke)


void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

The MouseListener Interface: -


This interface defines five methods.
If the mouse is pressed and released at the same point, mouseClicked( ) is invoked.
When the mouse enters a component, the mouseEntered( ) method is called.
When it leaves, mouseExited( ) is called.
The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is pressed
and released, respectively.
The general forms of these methods are

void mouseClicked(MouseEvent me)


void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

The MouseMotionListener Interface: -


This interface defines two methods.
The mouseDragged( ) method is called multiple times as the mouse is dragged.
The mouseMoved( ) method is called multiple times as the mouse is moved.
The general forms of these methods are

void mouseDragged(MouseEvent me)


void mouseMoved(MouseEvent me)

The TextListener Interface: -


This interface defines the textChanged( ) method that is invoked when a change occurs in a text
area or text field.
The general forms of these method is
void textChanged(TextEvent te)

This interface defines seven methods.


The windowActivated( ) and windowDeactivated( ) methods are invoked when a window is
activated or deactivated, respectively.
If a window is iconified, the windowIconified( ) method is called. When a window is deiconified,
the windowDeiconified( ) method is called.
When a window is opened or closed, the windowOpened( ) or windowClosed() methods are
called, respectively.
The windowClosing( ) method is called when a window is being closed.
The general forms of these methods are
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)

[BY. VIPUL PRAJAPATI] Page 74


[CCMS VADU] BCA-501-JAVA PROGRAMMING
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

ROUGH WORK

Unit-4
What is applet?
“An applet represents Java byte code embedded in a web page.”

Applet Life Cycle: -

[BY. VIPUL PRAJAPATI] Page 75


[CCMS VADU] BCA-501-JAVA PROGRAMMING

Applet states include:


Born or Initialization
Running state
Idle state
Dead
state

Initialization state:-
1 Applet enters the initialization state when it is first loaded.
2 The init( ) method is the first method to be called.
3 This method is the first method to be called by the browser and it is execute only once.
4 So, the programmer can use this method to initialize any variable, creating component, set up
colours and create objects needed by the applet.
5 When this method execution is completed, browser looks for the next method: start().
6 Syntax of initialization method:-
public void init()
{
……….
………..
}
Running state:-
1 Applet enters the running state when the system calls the start() method of Applet class.
2 This method may be called multiples time when the Applet needs to be started or restarted.
3 For example, the user has minimized the web page that contains the applet and moved to
another page then this method’s execution is stopped.
4 When the user comes back to view the web page again, start() method execution will resume.
5 start() method may be called more than once.
public void start()
{
……….
………..
}

Idle or stopped state:-


1 An applet becomes idle when it is stopped from running.
2 stop () method called by the browser when the applet is to be stopped.
3 If the user minimize the web page, then this method is called & when the user again comes
back to this page start() method is called.
4 If we use a thread to run the applet, then we must use stop() method to terminate the thread.
5 Syntax of stop state:-

[BY. VIPUL PRAJAPATI] Page 76


[CCMS VADU] BCA-501-JAVA PROGRAMMING
public void stop()
{
……….
………..
}
Dead State:-
1 Dead state occur by destroy () method.
2 The method is called when the applet is being terminated from memory.
3 This method is called only on that time when the browser needs to Shut down.
4 When we quit the webpage then this method automatically called.
public void destroy()
{
……….
………..
}
Display state:-
1 Display state called whenever applet perform some output operation on the screen.
2 The paint( ) method is called each time your applet's output must be redrawn.
3 The paint( ) method has one parameter of type Graphics.
4 This parameter will contain the graphics context, which describes the graphics environment in
which the applet is running.
5 This context is used whenever output to the applet is required.
public void paint(Graphics g)
{
……….
………..
}

Program: - Simple java program which represent Applet life cycle.

/ An Applet
skeleton. import
java.awt.*; import
java.applet.*; /*
<applet code="AppletSkel" width=300
height=100> </applet>
*/
public class AppletSkel extends Applet
{
/ Called first.
public void init()
{
/ initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start()
{
/ start or resume execution
}
/ Called when the applet is
stopped. public void stop()
{
/ suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy()
{
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g)
{
// redisplay contents of window
}

[BY. VIPUL PRAJAPATI] Page 77


[CCMS VADU] BCA-501-JAVA PROGRAMMING
}

Where are the applet executed?


“Applet is executed by the program called applet engine which is similar to virtual machine that
exists inside web browser at client side.”

The Applet Class: -


Applet provides all necessary support for applet execution, such as starting and stopping.
It also provides methods that load and display images, and methods that load and play audio clips.

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet

Methods of Applet Class


SN Method Description
1 void destroy( ) Called by the browser just before an applet is terminated. Your
applet will override this method if it needs to perform any cleanup
prior to its destruction.
2 void init( ) Called when an applet begins execution. It is the first method
called for any applet.
3 void start( ) Called by the browser when an applet should start (or resume)
execution. It is automatically called after init( ) when an applet
first begins.
4 void stop( ) Called by the browser to suspend execution of the applet. Once
stopped, an applet is restarted when the browser calls start( ).
5 void showStatus(String Displays str in the status window of the browser or applet viewer.
str) If the browser does not support a status window, then no action
takes place.
6 void resize(int width, int Resizes the applet according to the dimensions specified by width
height) and height.
7 void resize(Dimension Resizes the applet according to the dimensions specified by dim.
dim) Dimension is a class stored inside java.awt. It contains two integer
fields: width and height.
8 boolean isActive( ) Returns true if the applet has been started. It returns false if the
applet has been stopped.
9 String Returns the parameter associated with paramName. null is
getParameter(String returned if the specified parameter is not found.
paramName)
10 String getAppletInfo( ) Returns a string that describes the applet.
11 URL getCodeBase( ) Returns the URL associated with the invoking applet.
12 URL getDocumentBase( ) Returns the URL of the HTML document that invokes the applet.
13 Image getImage(URL url) Returns an Image object that encapsulates the image found at the
location specified by url.
14 Image getImage(URL url, Returns an Image object that encapsulates the image found at the
String imageName) location specified by url and having the name specified by
imageName.
15 String Returns the parameter associated with paramName. null is
getParameter(String returned if the specified parameter is not found.
paramName)
16 void play(URL url) If an audio clip is found at the location specified by url, the clip is
played.
17 void play(URL url, String If an audio clip is found at the location specified by url with the
clipName) name specified by clipName, the clip is played.

Applet Context Class: -

[BY. VIPUL PRAJAPATI] Page 78


[CCMS VADU] BCA-501-JAVA PROGRAMMING
Applet Context is an interface that provides the means to control the browser environment in which
the applet is running.
SN Method Description
1 Applet getApplet(String Returns the applet specified by appletName if it is
appletName) within the current applet context. Otherwise, null is
returned.
2 Enumeration getApplets( ) Returns an enumeration that contains all of the
applets within the current applet context.
3 AudioClip getAudioClip(URL Returns an AudioClip object that encapsulates the
url) audio clip found at the location specified by url.
4 Image getImage(URL url) Returns an Image object that encapsulates the image
found at the location specified by url.
5 void showDocument(URL Brings the document at the URL specified by url into
url) view. This method may not be supported by
appletviewers.
6 void showStatus(String Displays str in the status window.
str)

Applet tag & Their Attributes [Passing Parameters in Applet Tag]: -

<APPLET
[CODEBASE =codebase_URL]
CODE =AppletFileName.class
[ALT=alternate_text]
[NAME=applet_instance_name]
WIDTH=pixels
HEIGHT=pixels
[ALIGN=alignment]
[VSPACE=pixels]
[HSPACE=pixels]
>
[<PARAM NAME=name1 VALUE=value1>]
[<PARAM NAME=name2 VALUE=value2>]
...........
...........
</APPLET>

Attribute Description
CODE =AppletFileName.class Name of the applet class file to be loaded.it must be
specified which execute java bytecode for the applet is
stored
[CODEBASE =codebase_URL] Specifies the URL of the directory in which the applet
(optional) resides.
WIDTH=pixles This defines width of applet.
HEIGHT=pixles This defines height of applet.
[NAME=applet_instance_name] Specified name of applet so that other applet on the
(optional) page may refer to this applet
[ALIGN=aligment] Specifies where on the page the applet will
appear[TOP,BOTTOM,LEFT,RIGHT,MIDDLE,ABSMIDDLE,
TEXTTOP,BASELINE]
[VSPACE=pixles] Specifies the amount of vertical blank space the
browser.
[HSPACE=pixles] Specifies the amount of horizontal blank space the
browser.
[ALT=alternate_text] Non-Java browsers will display this text where the
applet would normally go. This attribute is optional.
[<PARAM NAME=name2 Supply user-defined parameter to an applet.
VALUE=value2>] NAME indicates name of attribute.
VALLUE indicates value of that parameter.

Simple java applet program:-

[BY. VIPUL PRAJAPATI] Page 79


[CCMS VADU] BCA-501-JAVA PROGRAMMING
import java.awt.*;
import java.applet.*;
import java.net.*;
public class hellojava extends Applet
{
String str,param;
int fontSize;
public void init()
{
str=getParameter("String");
if(str==null)
str="java";
str="hello" + str;

}
public void start()
{
param=getParameter("fontSize");
fontSize = Integer.parseInt(param);
}
public void paint(Graphics g)
{
String msg;
URL url = getCodeBase();
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);

url = getDocumentBase(); // get document base


msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);

g.drawString(str,10,100);
g.drawString("Font size: " + fontSize,20,150);
showStatus("This is shown in the status window.");
resize(300,300);
}
}

HTML file for above program:-

<html>
<head>
<title> welcome to java applet</title>
</head>
<body>
<applet code=hellojava.class width=200
height=200> <param name="string"
value="APPLET">
<param name=fontSize value=14>
</applet>
</body>
</html>

Use of JAVA awt package: -


The full form of awt is Abstract Window Toolkit.
The awt package in JAVA enables the programmers to create GUI-based application.
It contain number of classes that helps to implement common Windows-based tasks, such as
manipulating windows, adding scroll bars, buttons, list items, text box etc…
All the classes are contained in java.awt package.
These classes are hierarchically arranged inside the awt
package. The awt provides support for both standard and applet
windows.
On each successive level in the hierarchy adds certain attributes to the GUI application.
Consider the following figure.

[BY. VIPUL PRAJAPATI] Page 80


[CCMS VADU] BCA-501-JAVA PROGRAMMING

Component
1. Component class is the super class of all other classes.
2. It is responsible for affecting the display of a graphics object on the screen.
3. It is also handle the various keyboards and mouse events of the GUI applications.

Container
1. The container object contains the other awt components.
2. It manages the other layout and placement of the various awt components within the container.
3. A container object can contain others containers object as well; thus allowing nesting of
containers.

Window
1. The window object realizes a top level window but without any border or menu bar.
2. It just specifies the layout of the window.
3. A typical window that you want to create in your application is not normally derived from the
Window class but from its subclass.

Panel
1. The supper class of applet is panel.
2. The panel class represents a window space on which application’s output is displayed.
3. It is just like a normal window having no border, title bar, menu bar etc…
4. A panel can contain within itself other panel as well.

Frame
1. The frame object realizes a top level window complete with border and menu bar.
2. It supports common window related events such as close, open, activate, deactivate etc…
3. Almost all the programs that we created while discussing applets and graphics programming
used one or more classes of the awt package.

Graphics Class:-
“Graphics class includes methods for drawing many different types of shapes, from simple line to
polygon to text in a variety of fonts.”

Methods of Graphics Class:-

Sn Method Description
1 Void drawRect(int top, int The upper-left corner of the rectangle is at top, left. The
left, int width, int height) dimensions of the rectangle are specified by width and height.
2 Void fillRect(int top, int Its draw rectangle fills with black colour.
left, int width, int height)

3 Void drawRoundRect(int A rounded rectangle has rounded corners. The upper-left


top, int left, int width, int corner of the rectangle is at top, left. The dimensions of the
height, rectangle are specified by width and height. The diameter of

[BY. VIPUL PRAJAPATI] Page 81


[CCMS VADU] BCA-501-JAVA PROGRAMMING
int xDiam, int yDiam) the rounding arc along the X axis is specified by xDiam. The
diameter of the rounding arc along the Y axis is specified by
yDiam.
4 Void drawOval(int top, int This method draws a circle or ellipse bounded in the region of
left, int width, int height) a rectangle starting at (top, left) with width & height.
5 Void fillOval(int top, int This method draw oval or ellipse fills with black colour.
left, int width, int height)
6 Void drawArc(int top, int The arc is bounded by the rectangle whose upper-left corner
left, int width, int height, is specified by top, left and whose width and height are
int startAngle, int specified by width and height. The arc is drawn from
sweepAngle) startAngle through the angular distance specified by
sweepAngle. Angles are specified in degrees. Zero degrees is
on the horizontal, at the three o'clock position. The arc is
drawn counterclockwise if sweepAngle is positive and
clockwise if sweepAngle is negative.
7 Void fillArc(int top, int left, These method draw arcs fill with black colour.
int width, int height, int
startAngle,
int sweepAngle)
8 Void drawPolygon(int x[ ], The polygon's endpoints are specified by the coordinate pairs
int y[ ], int numPoints) contained within the x and y arrays. The number of points
defined by x and y is specified by numPoints.
9 Void fillPolygon(int x[ ], int This method draw polygon fills with black colour.
y[ ], int numPoints)
10 Void drawLine(int x1,int This method is useful to draw a line connecting (x1,y1) and
y1,int x2,int y2) (x2,y2).
11 Void getFont() Return the currently used font
12 Void setFont(Font f) This method sets a particular font f for the text.
13 Void drawString(str,x,y) This method used to display string on X & Y position in applet.
14 Void Its set some colour for the
setColor(Color.Colorname) text.[pink,blue,cyan,pink,red,orange,magenta,darkGray,gray,l
ightGray,green,yellow,white]
15 Void getColor() Return the currently used Colour for text.
16 Void setBackground(Color Set the back ground colour of applet.
c)
17 Void fillRoundRect(int top, This method draws round rect fill with black colour.
int left, int width, int
height,
int xDiam, int yDiam)

Example of Graphics class method:-

import java.awt.*;
import java.applet.*;
/*
<applet code=graph_ex width=600 height=600 >
</applet>
*/
public class graph_ex extends Applet
{
public void paint (Graphics g)
{
setBackground(Color.cyan);
Font f=new Font("Arial",Font.BOLD,20);
g.setFont(f);
g.drawString("Here are a selection of blank shapes.",20,40);
g.drawLine(20,40,200,40);

g.setColor(Color.blue);
g.drawLine(20,50,70,90);

g.setColor(Color.red);
g.drawRect(100,50,32,55);

[BY. VIPUL PRAJAPATI] Page 82


[CCMS VADU] BCA-501-JAVA PROGRAMMING

g.setColor(Color.green);
g.drawOval(150,46,60,60);

g.setColor(Color.magenta);
g.drawArc(230,50,65,50,30,270);

g.setColor(Color.black);
g.drawString("Here are the filled equivalents.",20,140);
g.drawLine(20,140,200,140);

g.setColor(Color.yellow);
g.fillRect(100,150,32,55);

g.setColor(Color.pink);
g.fillOval(150,146,60,60);

g.setColor(Color.darkGray);
g.fillArc(230,150,65,50,30,270);

g.setColor(Color.orange);
int x[]={300,400,300,150};
int y[]={300,120,400,250};
int num=4;
g.fillPolygon(x,y,num);
}
}

JDBC-ODBC Connection:-
JDBC is Java application programming interface that allows the Java programmers to access
database management system from Java code.
Java Database Connectivity in short called as JDBC. It is a java API which enables the java
programs to execute SQL statements.
It is an application programming interface that defines how a java programmer can access the
database in tabular format from Java code using a set of standard interfaces and classes written in
the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple implementations
to exist and be used by the same application.
JDBC provides methods for querying and updating the data in Relational Database Management
system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the
correct Java packages and drivers and registering them with the JDBC Driver Manager that is
used as a connection factory for creating JDBC connections which supports creating and executing
statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the JDBC
architecture.
Generally all Relational Database Management System supports SQL and we all know that Java is
platform independent, so JDBC makes it possible to write a single database application that can run
on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for
accessing and managing database, but the difference is that JDBC is designed specifically for Java
programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three
programming activities:
1 It helps us to connect to a data source, like a database.
2 It helps us in sending queries and updating statements to the database and
3 Retrieving and processing the results received from the database in terms of answering to your
query.

Product Components of JDBC: -


JDBC has four Components:
1. The JDBC API.
2. The JDBC Driver Manager.
3. The JDBC Test Suite.

[BY. VIPUL PRAJAPATI] Page 83


[CCMS VADU] BCA-501-JAVA PROGRAMMING
4. The JDBC-ODBC Bridge.

1. The JDBC API:


The JDBC application programming interface provides the facility for accessing the relational
database from the Java programming language
The API technology provides the industrial standard for independently connecting Java
programming language and a wide range of databases.
The user not only execute the SQL statements, retrieve results, and update the data but can also
access it anywhere within a network because of it's "Write Once, Run Anywhere" (WORA)
capabilities.
Due to JDBC API technology, user can also access other tabular data sources like spreadsheets or
flat files even in the heterogeneous environment.
JDBC application programming interface is a part of the Java platform that have included Java
Standard Edition (Java SE ) and the Java Enterprise Edition (Java EE) in itself.
The latest version of JDBC 4.0 application programming interface is divided into two packages.
(A) java.sql
(B) javax.sql

2. The JDBC Driver Manager:


The JDBC Driver Manager is a very important class that defines objects which connect Java
applications to a JDBC driver.
Usually Driver Manager is the backbone of the JDBC architecture. It's very simple and small that is
used to provide a means of managing the different types of JDBC database driver running on an
application.
The main responsibility of JDBC database driver is to load all the drivers found in the system
properly as well as to select the most appropriate driver from opening a connection to a database.
The Driver Manager also helps to select the most appropriate driver from the previously loaded
drivers when a new open database is connected.

3. The JDBC Test Suite:


The function of JDBC driver test suite is to make ensure that the JDBC drivers will run user's
program or not.
The test suite of JDBC application program interface is very useful for testing a driver based on
JDBC technology during testing period.
It ensures the requirement of Java Platform Enterprise Edition (J2EE).

4. The JDBC-ODBC Bridge:


The JDBC-ODBC Bridge, also known as JDBC type 1 driver is a database driver that utilizes the
ODBC driver to connect the database.
This driver translates JDBC method calls into ODBC function calls.
The Bridge implements JDBC for any database for which an ODBC driver is available.
The Bridge is always implemented as the sun.jdbc.odbc Java package and it contains a native
library used to access ODBC.
“These first two components of JDBC the JDBC API and the JDBC Driver Manager manage to connect
to the database and then build a java program that utilizes SQL commands to communicate with
any RDBMS.”
“On the other hand, the last two components are used to communicate with ODBC or to test web
application in the specialized environment.”

ROUGH WORK

[BY. VIPUL PRAJAPATI] Page 84


[CCMS VADU] BCA-501-JAVA PROGRAMMING

JAVA practicals Solutions


1) Write a Java Program find the area of Circle.

class area
{
public static void main(String args[])
{
double pi,r,a;
pi=3.1416;
r=5; a=pi*r*r;
System.out.println(“This is the area of Circle”+a);
}
}

Output
This is the area of Circle78.54

2) Write a Java Program that will display Factorial of the Given Number.

Solution—1 (Without Command line argument)

class factorial
{
public static void main(String args[])

[BY. VIPUL PRAJAPATI] Page 85


[CCMS VADU] BCA-501-JAVA PROGRAMMING
{
int num=5; int
result=1;
while(num>0)
{
result=result*num;
num--;
}
System.out.println(“Factorial of Given No::”+result);
}
}

Output
Factorial of given No::120

Solution—2 (With Command line argument)

import java.io.*;
class factorial
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in);
String str;
Str=br.readLine();
int num=Integer.parseInt(str);
int result=1;
while(num>0)
{
result=result*num;
num--;
}
System.out.println(“Factorial of Given No::”+result);
}
}

Output
5
Factorial of given No::120

3) Write a Java Program that will display the sum of 1+1/2+1/3…+1/n. (Harmonic Series)

Solution—1 (Without Command line argument)

class pro3
{
public static void main(String args[])
{
double i,j; double
sum=0; double
num=3;
for(i=1;i<=num;i++)
{
j=1/i;
sum=sum+j;
}
System.out.println("\nSum of series is :-->"+sum);
}
}

Output
Sum of series is:1.8333333333333333

Solution—2 (With Command line argument)

import java.io.*;
[BY. VIPUL PRAJAPATI] Page 86
[CCMS VADU] BCA-501-JAVA PROGRAMMING
class pro3
{
public static void main(String args[]) throws IOException
{
double i,j,num;
double sum=0;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


String str;
Str=br.readLine();
num=Integer.parseInt(str);

for(i=1;i<=num;i++)
{
j=1/i;
sum=sum+j;
}
System.out.println("\nSum of series is :-->"+sum);
}
}

Output:-
3
Sum of series is: 1.8333333333333333

4) Write a Java Program that will display 25 prime no.

Solution—1 (Without Command line argument)

class primeno
{
public static void main(String args[])
{
int i, j, a = 0,k=1;
for (i = 1; i <= 100; i++)
{
a = 0;
for (j = 2; j <= i - 1; j++)
{
if (i % j == 0)
{
a = 1;
}
}
if (a != 1 && k<=25)
{
System.out.println("THis is the\t"+k+"\t primenumber-->" + i);
k=k+1;
}
}
}
}
Output:-
This is 1 prime number=1
This is 2 prime number=2
This is 3 prime number=3
This is 4 prime number=5

(same as Up to 25)
5) Write a Java Program that will accept Command-Line argument and Display the same.

import java.io.*;
class command

[BY. VIPUL PRAJAPATI] Page 87


[CCMS VADU] BCA-501-JAVA PROGRAMMING
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str;
str=br.readLine();
System.out.println("THis is Your String:->"+str);
}
}

Output:-
ABCD
This is Your String :->ABCD

6) Write a Java Program to sort the elements of an array is ascending order.

import java.io.*;
class ascending
{
public static void main(String args[]) throws IOException
{
//to accept command line argument

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

//create integer type array

System.out.print("Howmany element you want to enter::->");


int n=Integer.parseInt(br.readLine());
int arr[]=new int[n];

//accept integer element in to array

for(int i=0;i<n;i++)
{
Sysem.out.print("Enter Integer::->");
arr[i]=Integer.parseInt(br.readLine());
}
int limit=n-1;
for(int i=0;i<limit;i++)
{
for(int j=0;j<limit-i;j++)
{
if(arr[j]<arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}

//display the Ascending array

System.out.println(“These are ascending Number:-”)


for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
}

Output:-

[BY. VIPUL PRAJAPATI] Page 88


[CCMS VADU] BCA-501-JAVA PROGRAMMING

How many element you want to sort?-->


4
Enter int::->
12
Enter int::->
32
Enter int::->
1
Enter int::->
34
These are ascending Number:-
1
12
32
34

7) Write a Java Program which will read a text and count all occurrences of a particular word.

import java.util.*;
import java.io.*;
import java.lang.*;
public class StringCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:----->");
String base = br1.readLine();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter SubString which YOu want to count-->");
String searchFor = br.readLine();
int len = searchFor.length();
int result = 0;
if (len > 0)
{
int start = base.indexOf(searchFor);
while (start != -1)
{
result++;
start = base.indexOf(searchFor, start+len);
}
}
System.out.println(result);
}
}

8) Write a Java Program which will read a string and rewrite it in the alphabetical order eg.The
Word “STRING” should be written a “GINRST”.

import java.io.*;

class Aphabetic
{
public static void main(String args[]) throws IOException
{
String str;
char s[];

DataInputStream in = new DataInputStream(System.in);

System.out.print("Enter String: ");


str = in.readLine();

[BY. VIPUL PRAJAPATI] Page 89


[CCMS VADU] BCA-501-JAVA PROGRAMMING
s = str.toCharArray(); // Convert String into Character Array
for(int i=0; i<str.length(); i++)
{
for(int j=0; j<str.length(); j++)
{
if(s[i] <= s[j])
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}

System.out.println("After sorting the string...");


System.out.println(s);
}
}

9) Write a java program which show the application of constructors.


class Box {
double width;
double height;
double depth;
/ This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
/ compute and return volume
double volume() {
return width * height * depth;
}

}
class BoxDemo7 {
public static void main(String args[]) {
/ declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
/ get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
/ get volume of second box vol =
mybox2.volume();
System.out.println("Volume is " + vol);
}
}

10) Write a java program which show the use of methods overloading .
// Demonstrate method overloading.
class OverloadDemo
{ void test() {
System.out.println("No parameters");
}
/ Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
/ Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
/ overload test for a double parameter

[BY. VIPUL PRAJAPATI] Page 90


[CCMS VADU] BCA-501-JAVA PROGRAMMING
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}

class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
/ call all versions of test()
ob.test();
ob.test(10); ob.test(10,
20); result =
ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}

11) Write a java program which show the use of static members.
// Demonstrate static variables, methods, and blocks.
class UseStatic { static
int a = 3; static
int b;
static void meth(int x)
{ System.out.println("x = " +
x); System.out.println("a = " +
a); System.out.println("b = " +
b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String args[]) {


meth(42);
}
}

12) Write a java program which shows the nesting of methods.

class Nesting
{
int m,n;
Nesting(int x,int y) //Constructor method
{
m=x;
n=y;
}
int largest()
{
if(m>=n)
return m;
else
return n;
}
void display()
{
int large=largest(); // call method and store result in variable
System.out.println("Largest value is ==>"+large);
}
}

[BY. VIPUL PRAJAPATI] Page 91


[CCMS VADU] BCA-501-JAVA PROGRAMMING
class Nestingtest
{
public static void main(String args[])
{
Nesting nest=new Nesting(14,20);
nest.display();
}
}

13) Write a java program which explaining the concept of single inheritance.

/ A simple example of inheritance.


/ Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
/ Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{

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


}
}
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

15) Write a java program which show the method overriding.

[BY. VIPUL PRAJAPATI] Page 92


[CCMS VADU] BCA-501-JAVA PROGRAMMING
/ Method overriding.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
/ display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
/ display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

16) Write a java program which implements interface.

interface Callback
{
void callback(int param);
}

class Client implements Callback


{
/ Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}
class TestIface
{
public static void main(String args[])
{
Callback c = new Client();
c.callback(42);
}
}

17) Write a java program which implement multiple interfaces.

interface value
{
[BY. VIPUL PRAJAPATI] Page 93
[CCMS VADU] BCA-501-JAVA PROGRAMMING
float val=6;
void multi();
}
interface value1
{
float val=5;
void multi();
}
class multiplication implements value,value1
{
public void multi()
{
//multiplication of two numbers float
mul=(value.val*value1.val);
System.out.println("multiplication of two number="+mul);
}
}
class multiInterface
{
public static void main(String args[])
{
multiplication mu=new multiplication();
mu.multi();
}
}

18) Write a java program which shows importing of classes from other package.

 Save this program as a Addition.java

//step-1: creating a package pack with Addition class

package pack;//pack is package name


public class Addition
{
//instance variable
private double d1,d2;

public Addition(double a, double b)


{
d1=a;
d2=b;
}
//method to find sum of two numbers
public void sum()
{
System.out.println("Sum="+(d1+d2));
}
}

 Save this program as a use.java

//step-2: using the package pack


import pack. Addition;
class use
{
public static void main(String args[])

[BY. VIPUL PRAJAPATI] Page 94


[CCMS VADU] BCA-501-JAVA PROGRAMMING
{
//create Addition class object
Addition obj=new Addition(10,15.5);

//call the sum() method


obj. sum();
}
}
Steps to run this package:-
1) First compile package class by
javac –d . Addition.java
It’s make a folder in bin directory same name as package name which held class file of
package.
2) Then compile & run that program which are use this package
javac use. java & then run java use

19) Write a Java program which creates threads using the thread class.

//To creates a Thread and run it


//let the class extends Thread
class mythread extends Thread
{
//write run() method inside this class
public void run()
{
//only this code is executed by the Thread

for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
//another class
class demo
{
public static void main(String args[])
{
//create an object to mythread class
mythread obj=new mythread();

//create a thread and attach it to the object of mythread class


Thread t=new Thread(obj);

//now run the thread on the object


t.start();
//now this thread will execute the code inside run()

}
}

20) Write a Java program which shows the use of yield(),stop() and sleep() method.

class A extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
if(i==1) yield();
System.out.println("\tFrom Thread A :-i= "+i);

[BY. VIPUL PRAJAPATI] Page 95


[CCMS VADU] BCA-501-JAVA PROGRAMMING
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From Thread B:- j=" +j);
if(j==3) stop();
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;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
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();

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");


}
}

21) Write a Java program which shows the priority in thread.

//Thread priorities
class myclass extends Thread
{
int count=0; //this count numbers
public void run()
{
for(int i=1;i<10;i--)
[BY. VIPUL PRAJAPATI] Page 96
[CCMS VADU] BCA-501-JAVA PROGRAMMING
count++;//count number up to 10
/ display which thread has completed counting and its priority
System.out.println("Complete Thread:"+Thread.currentThread().getName());
System.out.println("Its priority:"+Thread.currentThread().getPriority());
}
}
class prior
{
public static void main(String args[])
{
myclass obj=new myclass();

// create two threads


Thread t1=new Thread(obj,"one");
Thread t2=new Thread(obj,"two");

//set priorities for them


t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);// This mean priority no is 5

//start first t1 and then t2


t1.start();
t2.start();
}
}
22) Write a Java program which use runnable interface.

class PrintString
{
public static void main (String args [ ])
{
StringThread t = new StringThread ("Java",5);
new Thread(t). start ( );
}
}
class StringThread implements Runnable
{
String str;
int num;
StringThread(String s, int n)
{
str = new String (s);
num =n;
}
public void run ( )
{
for (int i=1; i<=num; i++)
System.out.print (str+" ");
}
}

23) Write a Java program which use try and catch for exception handling.
class Exc2 {
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");

[BY. VIPUL PRAJAPATI] Page 97


[CCMS VADU] BCA-501-JAVA PROGRAMMING
}
catch (ArithmeticException e) {
// catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

24) Write a Java program which use multiple catch blocks.

public class Multi_Catch


{
public static void main (String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;

int res=0;
try
{
res = num1/num2;
System.out.println("The result is" +res);
for(int ct =2;ct >=0; ct--)
{
System.out.println("The value of array are"
+array[ct]); }
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error…. Array is out of Bounds");
}
catch (ArithmeticException e)
{
System.out.println ("Can't be divided by Zero");
}
}
}
25) Write a Java program which shows throwing our own exception.

import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);

[BY. VIPUL PRAJAPATI] Page 98


[CCMS VADU] BCA-501-JAVA PROGRAMMING
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5,y=1000;
try
{
float z=(float)x/(float)y;
if(z<0.01)
{
throw new MyException("Number is two small");
}
}
catch(MyException e)
{
System.out.println("Caught my Exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I m Always here");
}
}
}

26)Make a Applet that create two button named ”Red” and “Blue” when a button is pressed
the background color of the applets is set to the color named by the button’s label.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=500
height=500> </applet>
*/
public class ButtonDemo extends Applet implements ActionListener
{

Button red, blue;


public void init()
{

//create a two button red & blue


red = new Button("Red");
blue = new Button("Blue");

//add two button in applet


add(red);
add(blue);

//add actionlistener to the button


red.addActionListener(this);
blue.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
//Know the label of the button clicked by user
String str = ae.getActionCommand();

[BY. VIPUL PRAJAPATI] Page 99


[CCMS VADU] BCA-501-JAVA PROGRAMMING
//change the background color depending on the button clicked
if(str.equals("Red"))
{
this.setBackground(Color.red);
}
if(str.equals("Blue"))
{
this.setBackground(Color.blue);
}

}
}

1) To compile applet program

Javac ButtonDemo.java

2) To run applet program

appletviewer ButtonDemo.java

27) Write a Java Applet that create some text fields and text area to demonstrate features
of each.

// Demonstrate text field & text Area.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=400 height=400>
</applet>
*/
public class TextFieldDemo extends Applet implements ActionListener,TextListener
{
TextField name, pass;
TextArea area;
public void init()
{
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
area = new TextArea(5,30);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
add(area);

// register to receive action events


name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void textValueChanged (TextEvent e)
{
String input;
input=area.getText();

[BY. VIPUL PRAJAPATI] Page 100


[CCMS VADU] BCA-501-JAVA PROGRAMMING
}
public void paint(Graphics g)
{
g.drawString("Name: " + name.getText(), 6, 300);
g.drawString("Password: " + pass.getText(), 6, 320);

}
}

28) Create an applet with three textfield & two button add & subtract.User will enter two
values in the TextFields. When the add is pressed , the addition of the two values should be
displayed in the TextFields. Same the Subtract button should perform the subtraction
operation.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=EventDemo width=350 height=200>
</applet>
*/
public class EventDemo extends Applet implements ActionListener
{
TextField t1,t2,t3;
Button b1, b2;

Label l1,l2,l3;
public void init()
{
t1= new TextField(5);
t2= new TextField(5);
t3= new TextField(5);
l1= new Label("First number");
l2= new Label("Second number");
l3= new Label("The Final Result is");
b1=new Button("Addition");
b2=new Button("Subtraction");

b1.addActionListener(this);
b2.addActionListener(this);

add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
int n1= Integer.parseInt(t1.getText());
int n2= Integer.parseInt(t2.getText());
int n3=n1+n2;
t3.setText(Integer.toString(n3));
}
if(e.getSource()==b2)
{
int n1= Integer.parseInt(t1.getText());
int n2= Integer.parseInt(t2.getText());
int n3=n1-n2;
t3.setText(Integer.toString(n3));
[BY. VIPUL PRAJAPATI] Page 101
[CCMS VADU] BCA-501-JAVA PROGRAMMING
}
}
}

29) Create an applet to display the scrolling text. The text should move from right to left.
When it reaches to start of the applet border, it should stop moving and restart from the left.
When the applet is deactivated, it should stop moving. Its should restart moving from the
previous location when again activated.

import java.awt.*;
import java.applet.*;
/*
<applet code=scrolling_Text width=300
height=300> </applet>
*/
public class scrolling_Text extends Applet implements Runnable
{
int i=0,flag=0;

Thread t=new Thread();


public void run()
{

}
public void paint(Graphics g)

{
try
{
g.setColor(Color.red);
g.drawString("I.N.S.B. College,IDAR",i,50);
t.sleep(200);
if(i<280 && flag==0)
{
i=i+10;
}
else
{
if(i==0)
{
flag=0;
}
else
{
flag=1;
i=i-10;
}
}
repaint();
}
catch(Exception e){}
}
}

30) Write a program to create three scrollbar and a label. The background color of the
label should be changed according to the values of the scrollbars (The combination of the
values RGB)

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=scrollbar_RGB width=600 height=300>
</applet>
*/
public class scrollbar_RGB extends Applet implements AdjustmentListener

[BY. VIPUL PRAJAPATI] Page 102


[CCMS VADU] BCA-501-JAVA PROGRAMMING
{
Label lred,lblue,lgreen,l;
Scrollbar sred,sgreen,sblue;
int r,b,g;

public void init()


{
sred=new Scrollbar(0);
sgreen=new Scrollbar(0);
sblue=new Scrollbar(0);
l=new Label("Hello");
lred=new Label("Red");
lgreen=new Label("Green");
lblue=new Label("Blue");

add(l);
add(lred);
add(sred);
add(lblue);
add(sblue);
add(lgreen);
add(sgreen);

sred.addAdjustmentListener(this);

sblue.addAdjustmentListener(this);
sgreen.addAdjustmentListener(this);

}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
if(ae.getSource()==sred||ae.getSource()==sblue||ae.getSource()==sgreen)
{
r=sred.getValue();
g=sgreen.getValue();
b=sblue.getValue();
Color c=new Color(r,g,b);
l.setBackground(c);
}
}
}

31) Write a java program which copying a characters from one file to another.

import java.io.*;
class CopyChar
{
public static void main(String args[]) throws IOException
{
File inFile=new File("input.dat");
File outFile=new File("output.dat");

FileReader ins=null;
FileWriter outs=null;

ins=new FileReader(inFile);
outs=new FileWriter(outFile);

int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
ins.close();
outs.close();

[BY. VIPUL PRAJAPATI] Page 103


[CCMS VADU] BCA-501-JAVA PROGRAMMING

}
}

32) Write a java program which shows reading and writing bytes to a file.

import java.io.*;
class write_readByte
{
public static void main(String args[]) throws IOException
{
byte cities []={'G','U','J','A','R','A','T','\n', 'B','O','M','B','A','Y'};

FileOutputStream outfile=null;
FileInputStream infile=null;
int b;
outfile=new FileOutputStream("city.txt");

outfile.write(cities);
outfile.close();

infile=new FileInputStream("city.txt");
while((b=infile.read())!=-1)
{
System.out.println((char)b);
}
infile.close();

}
}

33) Write a java program which shows the copying bytes from one file to another.

import java.io.*;
class copyByte
{
public static void main(String args[]) throws IOException
{
FileInputStream infile=null;
FileOutputStream outfile=null;

byte byteRead;
infile=new FileInputStream("in.dat");
outfile=new FileOutputStream("out.dat");
do
{
byteRead=(byte) infile.read();
outfile.write(byteRead);
}
while(byteRead!=-1);
infile.close();
outfile.close();
}
}

34) Write a java program which shows reading and writing primitive data.

import java.io.*;
class readwritePrimitive
{

[BY. VIPUL PRAJAPATI] Page 104


[CCMS VADU] BCA-501-JAVA PROGRAMMING
public static void main(String args[]) throws IOException
{
File primitive=new File("prim.txt");
FileOutputStream fos=new FileOutputStream(primitive);
DataOutputStream dos=new DataOutputStream(fos);

dos.writeInt (1999);
dos.writeDouble (375.333);
dos.writeBoolean (false);
dos.writeChar ('R');
dos.close ();
fos.close ();

FileInputStream fis=new FileInputStream(primitive);


DataInputStream dis=new DataInputStream(fis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
dis.close();
fis.close();
}
}

35) Write a java program which shows the single file for storing and retrieving.

import java.io.*;
class ReadWriteInteger
{
public static void main(String args[]) throws IOException
{
//Declare Data Stream
DataInputStream dis=null;
DataOutputStream dos=null;

//Construct a File
File intFile=new File("read.txt");

//write integers to read.dat file


//create output stream for inFile file

dos=new DataOutputStream(new FileOutputStream(intFile));


for(int i=0;i<20;i++)
{
dos.writeInt((int)(Math.random() * 100));
}
dos.close();

//Reading integers from read.dat file


//create input stream for intFile file

dis=new DataInputStream(new FileInputStream (intFile));


for(int i=0;i<20;i++)
{
int n=dis.readInt();
System.out.print(n+ " ");
}
dis.close();

}
}
36) Write a java program which shows writing and reading with random access.

import java.io.*;

[BY. VIPUL PRAJAPATI] Page 105


[CCMS VADU] BCA-501-JAVA PROGRAMMING
class RandomIO
{
public static void main(String args[])throws IOException
{
RandomAccessFile file=null;

file=new RandomAccessFile("rand.dat","rw");
//writing to the file
file.writeChar('x');
file.writeInt(333);
file.writeDouble(322.33);

file.seek(0); // go to the begging


//Reading from the file
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());

file.seek(2); // go to the second item

/ go to the end and append false to the file


file.seek(file.length());
file.writeBoolean(false);

file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
}

[BY. VIPUL PRAJAPATI] Page 106


[CCMS VADU] BCA-501-JAVA PROGRAMMING

-: Questions of JAVA :-
Unit: - 1
1. What is object oriented Programming Language? How it’s Different from the procedure-oriented
Language?
2. What are the unique advantages of an object-Oriented Programming Paradigm?
3. Describe Common Features of Java. (Buzz words)
4. Explain Scope for member Variable & Function.
5. Explain java Magic Code, Compiler, interpreter with figure.
6. Explain Tools of Java.
7. What is relation between polymorphism, Function overloading and Operator Overloading.
8. Explain Control Structure of Java.
9. What is the Difference between C, C++ & Java?
10. Describe the Structure of Java Program.
11. What is Token? List the various types of token Supported by Java.
12. What is JVM? Explain Structure of JVM. How its Execute Java Program?
13. What is type casting? Why is it required in Java Program?
14. Explain Type Conversation in Java.
15. Explain Conditional Operator in Java With Example.
16. Explain Data Abstraction, Polymorphism & Encapsulation.
17. What is Garbage Collection?

Unit:-2
1. What is Constructor? What are its Special Properties?
2. Is Destructor support by Java? Explain with Reason.
3. Explain inheritance in java with Example.
4. Is multiple inheritances supported by Java? How its implements in Java?
5. Explain Method Overloading and Method Overriding.

What is the Difference between Method Overloading & Method Overriding? Define Each with
Example.
6. Explain Characteristic of abstract Class with Example.
7. What is Dynamic Method Dispatch?
8. Explain Difference between abstract class & Interface.
9. Explain Static Member with Example.
10. Explain Final Class with Example.
11. How we implement Nesting method in Java? Define with example.
12. Explain Random Class & String Tokenizer with example.
13. What is the Difference between Stack, Array & Vector? Explain Vector class With Example.
14. Explain Date & Calendar Class with example.
15. Explain Interface with Example. How Interface solve the problem of Inheritance? Explain with
example.
16. What is the use of wrapper Class in java? Explain it in brief.

[BY. VIPUL PRAJAPATI] Page 107


[CCMS VADU] BCA-501-JAVA PROGRAMMING
-------
17. What is the difference between String & String Buffer?
18. What is Package? What is Naming Convention? How package are Creating? Give Example.
19. Explain Java Packages.
20. Explain java.net, java.util, java.lang package.
21. Explain use of Super & this.
22. Explain usage of following keywords
New
This
Super
Extends

Unit:-3
1. What is thread? What is the Difference between Multi-Threading and Muti-Tasking?
2. Difference between Process & Thread. Explain Thread Life Cycle.
3. Explain Thread Creation. Explain with Program.
4. Explain Methods Of Thread.
5. Explain Priorities of Thread with Example.
6. What is Synchronization (Monitors) in Thread? When so we use it? Explain It with Example.
7. What is Deadlock? How to implement Deadlock in Thread?
8. What is Exception? How many types are Exception in Java? What is Exception Handling? How its
implement in java?
9. What is the use of try, catch in Java? Explain nested try catch with Example.
10. What is the difference between throw & throws?
11. How we can create our own user define Exception in Java with Example?
12. What is difference between final, finalize and finally in Java.
13. Write short note on Event Delegation Model.
14. Explain Event handling process.
15. Explain Event classes.
16. Explain Different source of Event.
17. Explain Event Listener interface.

18. Explain adapter Class.

Unit:-4
1. Difference between Application & Applet.
2. Explain Applet Skeleton. (Explain Applet Life Cycle.)
3. Explain passing parameter in Java Applet.
4. Explain Different Methods in Applet.
5. Explain Advantages & Disadvantage of Applet.
6. Explain use of Thread in Applet with Example.
7. Explain AWT package & Its Hierarchy.
8. Explain Graphics class in Applet.

[BY. VIPUL PRAJAPATI] Page 108


[CCMS VADU] BCA-501-JAVA PROGRAMMING
9. Explain methods of Graphics Class with example.
10. Explain working with Color Methods with example.
11. What is the Difference between Byte-Steam Classes & Character Stream Classes?
12. Explain Character Stream Classes.
13. Explain Byte Stream Classes.
14. What is Random access File? How is It Different from Sequential file? Why do we need a random
access File? Explain use of Seek pointer?
15. Explain StreamTokenizer Class.
16. Explain FilterStream class. Give appropriate Example.
17. Explain Piped Stream & Pushback Stream.
18. Explain Components JDBC & ODBC connection.

ROUGH WORK

[BY. VIPUL PRAJAPATI] Page 109


[CCMS VADU] BCA-501-JAVA PROGRAMMING

[BY. VIPUL PRAJAPATI] Page 110

You might also like