Вы находитесь на странице: 1из 100

The Power of Completeness…….

Java and Data Structures


Object Oriented Programming

for
with

nd
2 B.sc.,

Prepared by

NICE
COMPUTERS
NICE COMPUTERS No.1 in Kavali

UNIT – 1
1. Write about the object oriented paradigm?
The major objective of object oriented paradigm is to overcome
the drawbacks of procedural paradigm. Object oriented paradigm treats the
data as an important element in the program development, does not allow to
directly access from the program and unauthorized users. Functions called
methods are used to access, modify and store the data.
Combination of data and methods are called objects. Object
Oriented Paradigm allows decomposing the problem into number of entities
called objects.
Definition:
Object Oriented Programming is an approach that provides a
way of modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies of such
modules on demand.
Features of object oriented paradigm:
Object Oriented Paradigm has the following important features.
 Emphasis is given to the data rather procedure
 Program is divided into number of objects.
 Data cannot be accessed either by the program or by the unauthorized
users
 Methods are used as interface among the data and program
 Objects communicate through methods
 Follows bottom to top approach

Name Sal

Method Method Void setData()


{
----------
}
Void getData()
{
Method -----------
Method
}

OOPS with Java and DS 2


NICE COMPUTERS No.1 in Kavali

2. Write about the object oriented programming features?


(Or)
Write about the concepts of Object Oriented Programming?
Definition:
Object Oriented Programming is an approach that provides a
way of modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies of such
modules on demand.
Like any object oriented programming language, even java
supports the following object oriented programming concepts.
1. Data Abstraction or Encapsulation
2. Inheritance
3. Polymorphism
4. Dynamic binding
5. Message Communication
Data Abstraction and Encapsulation:
It is the striking feature of a class. Wrapping up of data and
methods as single unit in the class is known as Encapsulation. Data is stored
in the center of an object. This cannot be directly accessed from the
program. Methods are wrapped around the data. These work as interface
among the program and data.
The insulation of data from direct access from the program is
called Data Hiding or protection.
Abstraction is representing essential features without giving the
background details. It separates the Usage from implementation.
Inheritance:
It is an important feature o any object oriented programming
language. It supports the concept of hierarchical classification. Inheritance is
the process of reusing the properties of existed class rather re-defining all
over again. Inheritance is mostly used to enhance or modify the existed class
definition. Here the existed class is called the super class and the new
extended class is called sub class. The sub class has the members of both
super and sub classes.
Bird

Flying Bird Non-Flying Bird

Robin Swallow Penguin Kiwi

OOPS with Java and DS 3


NICE COMPUTERS No.1 in Kavali

Polymorphism:
Polymorphism is another important feature. The meaning of
polymorphism is many forms. That is the ability to take more than one
forms. For example operator + is used on two purposes one is to add any two
numbers and to concatenate any two strings.
Another example to polymorphism is method overloading. That
is selecting a method from multiple methods of the same name and unique
signature. Selection of method depends on the number and type of
arguments send to the method.
Dynamic binding:
Binding is selection of method in response to the call. If it done
during the runtime then it is called dynamic binding or run time
polymorphism.
For example Interface shape has draw() method. It is overridden
in different implementing classes like Circle, Box and Triangle. The
reference of shape interface calls draw() method of any class according the
object to which it refers.
Shape

draw()

Circle Object Box Object Triangle Object

draw() draw() draw()

Message Communication:
The process of programming in object oriented language involves
1. Creating classes
2. Creating objects belongs to the classes
3. Establishing communication among the objects.
Objects communicate by sending or receiving the message by
calling the method of one object from another object like the way people
pass the message called message passing.

Ob.setName(“Balagurusami”);

Object Method Information

OOPS with Java and DS 4


NICE COMPUTERS No.1 in Kavali

3. Write about the benefits of OOP?


OOP offers number of benefits to both the designer and the
user. Object orientation contributes to the solutions of many problems like
Development, Quality maintenance, less maintenance cost and productivity.
The advantages of OOP are
 We can eliminate the redundant code through inheritance.
 We can use the existed code modules. This leads to reduce of
development time and improves the productivity
 Data hiding helps to develop secured applications
 It is possible to have multiple members with the same name in different
objects (Encapsulation)
 It is easy to partition the work in a project through objects.
 It is easy to update an existed system
 Software complexity can be easily managed
Though it is possible to use all these benefits in any object
oriented application, any or all of these features are used according to the
project.
4. Write about the applications of OOP?
The most popular applications of OOP are in the areas of user
interface design for windows. OOP simplify the development o complex
applications due to their unique features. The areas of OOP applications are.
1. Real-time systems
2. Simulation and modeling
3. Object-Oriented databases
4. Hypertext, hypermedia and expertext
5. Artificial Intelligence and expert systems
6. Neural networks and parallel programming
7. Decision support and office automation systems
8. CIM/CAD/CAM systems
5. Write about the features of java?
The inventors of java designed the java so that it could offer
solutions to the problems encountered in modern programming. Sun
microsystems officially describe the java as.
1. compiled and interpreted
2. Platform independent and portable
3. Object Oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small

OOPS with Java and DS 5


NICE COMPUTERS No.1 in Kavali

7. Multithreaded and interactive


8. High performance
9. Dynamic and extensible
Compiled and interpreted:
Execution of a java program is done in two steps. That is
compiling and interpreting. First the source code is compiled by the java
compiler (javac), produces the byte code. Byte code is not the executable
code which cannot be executed. The java interpreter (java) generated the
machine code, which will be executed by the computer. So java is called
both compiled and interpreted.
Platform independent and portable:
Java application developed on one platform can be easily moved
and used on another platform without any modifications. Here the platform
difference is the difference in operating system or in architecture.
Internet is a network of networks with millions of computers
belongs to different platforms. Hence java became a popular language to
develop internet applications.
Object Oriented:
Java supports all the common object orient programming features
like Data hiding, Abstraction, Inheritance, Encapsulation and inheritance
Robust and Secured:
Security is an important issue for a language which is used to
develop internet applications. Byte code verifier of JVM ensures that no
virus is communicated with applets. In absence of pointers java application
cannot access unauthorized memory.
Distributed:
Java provides some of the concepts like RMI, Networking and
Servlets. Which help to develop distributed applications like intranet and
internet applications.
Simple, Small and familiar:
Java is a simple and small language. Most of the features of C and
C++ are added in java. Java does not support unsafe features like pointers,
preprocessor statement, goto, operator overloading and multiple inheritance.
Java uses many constructs of C and C++. Hence java code looks like C and
C++ code.
Multithreaded and interactive:
Multithreading is the natural feature of java. It allows performing
multiple tasks at a time through a single java application.

OOPS with Java and DS 6


NICE COMPUTERS No.1 in Kavali

High Performance:
Execution of byte code or intermediate code is much faster than
the native code of C and C++
Dynamic and Extensible:
Java is capable of loading classes from the library dynamically.
Java supports of using functions belong to other languages called native
methods.

6. State the differences among java and C, C++?


Differences among java and C:
Lot many things are common in C and Java. Java is an object
Oriented programming language. Some of the features of C language are not
added due to the security reasons.
1. Java does not support the keywords goto, sizeof, typedef
2. Java does not support the data types like enum, struct and union
3. Java does not support the type modifiers auto, extern, register, unsigned
4. Java does not support pointers.
5. Java does not support pre-processor directives
6. Java has two operators >>>, <<< (Shift assigning) and instanceof
operator
7. Java has labeled break and continue
8. Java supports all the common object oriented programming features
Differences among java and C++
Java is a pure object oriented programming language. Where as
C++ is an extension to C. C++ supports both procedural and object oriented
programming. The following are the differences among C++ and Java
1. Java does not support operator overloading
2. Java does not support multiple inheritance using classes
3. Global variables cannot be declared in java. Every variable must be a
member of any class
4. Java has no Destructors

C++

C Java

OOPS with Java and DS 7


NICE COMPUTERS No.1 in Kavali

7. Write how java associated with WWW (World Wide Web)?


Java and Internet:
Java is strongly associated with internet. “Hot java” is the web
browser developed in java. Applets are the small java programs add
dynamism to the web pages. Applets are associated with the web pages.
These are downloaded along with the web pages, executed by any java
enabled web browser.
Java and WWW (World Wide Web):
World Wide Web is a homogeneous network of networks,
connected with millions of computers around the globe. It is an information
retrieval system. This system contains web sites belongs to different
organizations. Collection of web pages is called a web site. These web pages
are developed in HTML. Hyper links are used to navigate among the web
pages.
Because HTML is a tag based formatting language. Only static
web pages can be developed. Applets are the small java programs used to
develop interactive web pages. Java helped to develop web pages with
animations, graphics, games and special effects.
Applet is a small java program developed and compiled byte code
of which is stored in the web server. <Applet> tag is used to bind an applet
with HTML page.
How an applet is executed:
1. User sends the request to the web server; In return the web server
sends the requested document to the client.
2. As specified in the <Applet> tag the byte code is down loaded in to
the local machine
3. The JIT (Just in Time) interprets the byte code and produces the
managed executable code.
4. The executable code is executed by the java enables web browser

HTML Document 1 Applet Source


2 Code
JIT
3 Byte Code
1
Web Browser
<Applet>
4
HTML
Output Document

Server
Client
OOPS with Java and DS 8
NICE COMPUTERS No.1 in Kavali

8. Write about the Web Browsers?


Internet is a heterogeneous network of network. It is with the
vast information of different formats. Web browser is client-side software
used to download and execute the web pages developed in HTML. Web
browser has tools to navigate among different web pages, mailer to send and
receive the e-mails etc. There are different web browsers available to browse
the internet.
1. Hot java:
It is the first java enabled web browser, developed entirely using
java platform. It is the first web browser executed java applets. It is
developed by “Sun micro systems”. Now, hot java web browser is available
for Solaris, Windows 95 and Windows NT.
2. Netscape Navigator:
It is one of the most widely used web browsers today. It is
developed by Netscape communications. It is a general purpose browser
executes applets also. Now, Netscape navigator is available for Windows,
Solaris and Macintosh. It also supports scripting languages.
3. Internet Explorer:
It is the most widely used web browser available freely with the
windows. It is a general purpose browser executes applets also. It also
supports different scripting languages. Internet Explorer uses JIT to execute
the applets.

9. Write about the java environment?


Java environment includes number of development tools and
number of classes and interfaces.
JDK (Java Development Kit)
Number of tools used to develop and test any java application is
a part of JDK called java development kit. There are different versions of
JDK available in market. Latest version of JDK is JSDK1.6.0. (Java
Software Development Kit). JDK includes
 Javac (Java Compiler)
 Java (Java Interpreter)
 Appletviewer (To develop and test applets)
 Javap (Java Dis-assebmbler)
 Javadoc (To create documentation automatically)
 Jdb (Java Debugger)

OOPS with Java and DS 9


NICE COMPUTERS No.1 in Kavali

Java API (Application Program Interface)


JDK provides a library of classes, interfaces and constants to
develop any java application. These resources are managed as packages and
sub packages.
Java.lang: Collection of classes to implement basic java features.
Java.util: Collection of utility classes to calculate Date and Time operations.
Java.io: Collection of classes to perform basic Console, File input and
output.
Java.net: Collection of classes to perform connections among different
computers.
Java.awt: Collection of classes and interfaces to develop window
applications.
Java.applet: collection of classes to develop web based small java programs
called applets.

10. Write about the structure of a java program?

Document Section

Package Statement

Import Statement

Interface Statements

Class Definitions

Main Method class

Any java program has class definitions, import statements and


class hierarchies.
Stand alone programs and applets:
Any java program has one or more class definitions. A class
definition has different members. These members include data fields,
methods and classes. Any java application can be divided into stand-alone
applications and applets. Any stand-alone application executes from the
main() method. Where as applets execute from the init() method. An applet
is a java application embedded in a HTML document.
Packages:
Re-usability is the primary feature of any language. Java
supports reusability by means of packages and inheritance. Package is a

OOPS with Java and DS 10


NICE COMPUTERS No.1 in Kavali

collection of re-usable classes. Where package is a folder and classes are


files in the folder. JDK(Java Development Kit) provides a hierarchy of
classes called java API. These classes can be imported into any java program
using import statement. “java” is the root package in JDK. It has other
packages with different category of classes.
Example:
Java.io // Defines number of input and output classes.
Java.util //Defines number of utility classes.
Importing classes and packages:
Import is the statement used to import a class or all the classes
of a package. Specifying only the class name imports a single class.
Specifying * imports all the classes of a package.
Example:
Import java.util.Date; // It imports only the Date class.
Import java.util.*; //It imports all the classes of util package.
Sub classes and super classes :
Because java is an object oriented programming language, it
supports hierarchical relationship among the classes. Suppose A and B are
two classes and there is a line or edge between two, then the class A which is
at the higher hierarchy is called super class. Class B which derives from A is
called a sub class. Java supports simple, multi-level, hierarchical and hybrid
inheritance but not multi-level inheritance.
Example: Object

Number String Trowable

Integer Double Exception Error

9. Write about the JVM (Java Virtual Machine)?


(Or)
Write how to implement a java program?
(Or)
Write how to execute a java program?
(Or)
How java works like an object Oriented Programming Language?

OOPS with Java and DS 11


NICE COMPUTERS No.1 in Kavali

In case of “c” and “c++” languages the compilation process


translates the source code into native language of computer. The native code
generated by one computer may not work on another computer called
platform dependency.
Implementing a java program:
Source Code Java compiler Byte Code JVM Computer
(hello.java) (Javac) (hello.class) (HWR)

Remote Remote
JVM Computer (HWR)

While executing a java program the source code is compiled by


the java compiler (javac) first. The java compiler produces the byte code. It
is more compact and efficient than the executable code generated by “c” and
c++ programs. The byte code is native language to the JVM (Java Virtual
Machine). The java interpreter (java) of JVM executes the byte code. Since
every computer supports JVM, byte code can be executed by any computer.
So java is called platform independent language. Since java programs run in
native mode, they run 100 times slower than the c and c++ programs. But
java has lot of advantages comparatively with c and c++.
1. Java byte code runs on any computer that supports JVM.
2. Java byte code is compact than native code of c and c++.
3. JVM provides additional security by checking the foreign code using
byte code verifier.
JIT (Just in time) is a compiler installed at the client. It loads
and compiles the byte code by downloading from the server.
Java microprocessor is another tool which translates the byte
code into native code. It improves the performance of java application even
better than a c and c++ application. It improves the performance of java
application even better than a “C” and “C++” application.

OOPS with Java and DS 12


NICE COMPUTERS No.1 in Kavali

JVM (Java Virtual Machine):


It behaves like a computer within computer. So it is called JVM.
It is with the combination of class loader, byte code verifier and java
interpreter (java). The class loader loads the remote classes in to the local
memory. The byte verifier allows only byte code to the interpreter. The java
interpreter produces the native code to the machine.

Class Loader
Source Code
(hello.java) Byte Code
Verifier

Compiler
(javac) JIT/Java Micro Java Interpreter
Processor (java)

Byte Code
(hello.class) Computer HWR

JVM
Execution of a java program:
A java program can be implemented in three steps.
1. Developing the program
2. Compiling the program
3. Interpreting the program

Step1: A java program can be developed in any text editor. It is saved with
.java extension.

class Hello
{
public static void main(String args[])
{
System.out.println(“Hello world”);
}
}

Step2: java program is compiled with the java compiler(javac).


>Javac Hello.java

Step3: The byte code generated by the compiler is executed by the java

OOPS with Java and DS 13


NICE COMPUTERS No.1 in Kavali

interpreter
>java Hello
10. Write about the Command line arguments?
Sending arguments from the command line to the main method
of the program, while executing the program is called command line
arguments. When we send command line arguments to the main() method
while interpreting the program, the JVM creates an array of strings with the
arguments and send to the main.
Through the reference of array of strings we can access the
arguments into the main. It helps to improve the flexibility in application
development.
Example:
>javac Demo.java
>java Demo hello I am the learner

Hello I am the learner

Class Demo
{
Public static void main(String args[])
{ O/p
for(int i=0;i<args.length;i++) Hello
I
System.out.print(args[i]+” “); am
} The
} learner

Individual elements of command line arguments are accessed


from the main using the index of args[]

11. Write about the tokens in java?


Smallest part of any java program is called java tokens.
According to their functionality java tokens can be classified into
1. Keywords
2. Identifiers
3. Constants or literals
4. Operators
5. Separators

OOPS with Java and DS 14


NICE COMPUTERS No.1 in Kavali

Keywords:
These are the reserved words in java. Each keyword has a
specific purpose in java. There are totally 60 keywords used in java. All the
keywords must be written in lower case. Because java is a case-sensitive
language. Out of these keywords const and goto have no functionality.
Identifiers:
These are the words used for naming the variables, arrays,
classes, interfaces, methods and classes. The following rules must be
followed while selecting proper identifier.
1. These may be of any length
2. Reserved words cannot be used
3. First character must not be a digit or special symbol
4. Special symbols cannot be used other than _(underscore)
Identifiers must be meaning full, short, easily typed and self
descriptive. The following naming conventions are used in java.
 Class name must be in capitalized format
 When more than one word are used in a name then, the second and
subsequent words must be capitalized
 All the data fields must be in small case
 All the constants must be in capital case
Constants or literals:
These are the values stored in the computer memory. These may
be classified into
 Integer constants
 Floating point constants
 Character Constants
 String constants
 Boolean constants
Operators:
Different operators are used to write expressions in java. These
operators can be classified into arithmetic, relational, logical, increment
decrement, short-cut, conditional and bitwise operators.
Separators:
These are the symbols used to indicate group of code divided. () ,
; {} [] . are some of the separators.

OOPS with Java and DS 15


NICE COMPUTERS No.1 in Kavali

12. Write about the statements in java?


A statement is an executable combination of tokens terminated
with a semicolon. Statements are executed in a sequence as they appear. The
total statements in java can be classified into
1. Empty statements
2. Labeled statements
3. Expression statements
4. Selection statements
5. Iterative statements
6. Jump statements
7. Synchronizing statements
8. Guarding statements
13. Write about the constants used in Java?
These are the values stored in the computer memory. The values
of which do not change during execution of program. These constants can be
classified into
Constants
Numeric
Integer
Decimal
Ex: 345, -897, 0
Octal
Ex: 0345
Hexadecimal
Ex: 0X97A67
Real Constant
Fixed
Ex: 12.45, -45.89, 0
Scientific
Ex: 12E-5
Character
Single Character
Ex: ‘x’, ‘P’, ‘;’

String
Ex: “nice”, “Nice”
Back slash character
Ex: \n, \t, \b, \0, \’, \”, \\

OOPS with Java and DS 16


NICE COMPUTERS No.1 in Kavali

14. What is variable?


(Or)
Declaration of variable?
(Or)
Assigning values to the variables?
Variable:
A variable is an identifier represents a storage location to store a
value. Its value changes during the execution of the program. The name of
the variable must be a valid identifier. The following rules must be followed
while selecting proper identifier.
a. These may be of any length
b. Reserved words cannot be used
c. First character must not be a digit or special symbol
d. Special symbols cannot be used other than _(underscore)
Identifiers must be meaning full, short, easily typed and self
descriptive. The following naming conventions are used in java.
Ex: length, breadth, area, peri
Declaration:
Declaration of variable allocates the memory allocation in the
primary memory. Declaration of variable does three things.
1. It tells the compiler the name of variable
2. It specifies the type of data which going to be stored
3. The place of declaration decides the scope of variable
Assigning values:
A value can be assigned to the variable after its declaration. Values can
be assigned to the variables in two ways.
1. By using an assigning statement.
2. By using a read statement.
Assigning:
Syntax: Variable Name = Value
Example:
int x=40;
float y=12.56;
char z;
z=’p’;
Read statement:
Syntax: variable name = (Reading statement)
String name=(new Scanner(System.in)).nextLine(); //To read a line
int y=(new Scanner(System.in)).nextInt(); //To read integer
float x=(new Scanner(System.in)).nextFloat(); //To read Float

OOPS with Java and DS 17


NICE COMPUTERS No.1 in Kavali

15. Write about the data types used in java?


Java supports different data types to allocate the memory to store
different constants of different types and ranges. These types can be
classified into.
Data types

Primitive
Numeric

Integer
Byte 1Byte
Short 2 bytes
Int 4 bytes
Long 8 bytes
Floating point
Float 4bytes
Double 8 bytes
Non-Numeric
Char 2 bytes
Boolean 2 bytes
Non - Primitive

Class
Arrays
Interface

16. Write about the scope of variables?


Variables in java can be classified into three types
 Instance variables
 Class variables
 Local variables
 Block variables
Instance variables are the non-static data fields of a class.
Memory allocation of these data fields happen on creating an object belongs
to the class. The variables hold different values to different objects.
Class variables are the static data fields. These are global to the
total class and its objects. These data fields are used to store welfare data to
all the objects and constants.

OOPS with Java and DS 18


NICE COMPUTERS No.1 in Kavali

Local variables are the variables declared with in a method. The


scope of these variables is limited to the method in which they are defined.
Block variables are variables defined within a block {}
associated with any of the control structures. The scope of these variables is
limited to the block.

17. Write about the symbolic constants?


Symbolic constants are the constants appear repeatedly in a
number of places with in the program. While using these constants we face
two problems, that is
1. problem in modification of program
2. problem in understanding the program
Modifiability:
Whenever we need to change value of constant, then we need to
search and modify wherever it has been used. Otherwise the program may
give unexpected result.
Understandability:
Proper names must be used to improve the readability. Different
constants are defined with different names though they are assigned with the
same values.
Syntax:
Final type Constant = value
Example:
class Constants
{
final int PASS_MARK=100;
final float PI=3.4;
};
The following rules must be followed while defining symbolic constants
1. These must be written in capitals
2. The values cannot be changed once they are assigned with values
3. These are declared for types. But not like #define statements in C and
C++
4. These must be defined as class members only
18. Write about the type casting in java?
Some times in an assigning statement, the type of expression
may be different from type of assigning statement. In such case expression
type must be changed to variable type.

OOPS with Java and DS 19


NICE COMPUTERS No.1 in Kavali

Auto casting:
Some times expression type is automatically converted into
variable type called auto casting or implicit casting. In java the lower types
will be automatically converted to higher types.
Byte short
Byte, short int
Byte, short, int long
Float double
Byte, short, int float
Byte, short, int, float double
Examples:
Short x=45;
Int y=x;

Int x=25;
Float y=x+22;
Type casting:
Some times expression type must be explicitly converted to
variable type using typecast operator. It is an instruction to the compiler. In
an expression an integer constant is considered as “int” type. In any
assigning statement a real constant is considered as float type.
Syntax:
Variable = (Variable type) Expression
Examples:
Float x = (float) 5/2;

Byte x=20;
Short y = (short) x+10;

Float x = (float) 12.25;


Float y=12.25f;
Note: Boolean type cannot be converted into any other type.

OOPS with Java and DS 20


NICE COMPUTERS No.1 in Kavali

UNIT II
1. Write about the operators used in java?
Java is rich in operators. These operators are used to write
expressions. These are used to manipulate data and variables. These
operators are classified as
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assigning operator
5. Increment and decrement operator
6. conditional operator
7. bitwise operator
8. special operator
1. Arithmetic operators:
+, -, *, /, % are the arithmetic operators. These work same as in
other languages. These work on all primitive types other than Boolean type.
The unary minus multiplies the operand by -1.
Integer Arithmetic:
When all the operands in an arithmetic expression are of integer
type then the expression is called an integer expression. All ways an integer
expression returns an integer value.
Example: 5/2 return 2
Real Arithmetic:
When all the operands in an arithmetic expression are of floating
point type then the expression is called real arithmetic. All ways a float
expression returns an exact or approximate result.
Example: 20.5/6.4 returns 3.20313
Mixed-mode Arithmetic:
When one of the operand is real and another is integer then the
expression is called mixed mode arithmetic. If either operand is of real type,
then other operand is converted into real type. The result of expression is
converted into real type.
Example: 15/10.0 returns 1.5
2. Relational operators:
<, >, <=, >=, ==, != are the relational operators. These operators
are used to compare any two values in order to take logical decisions. In java
any relational expression returns either true or false.
Example: 10<5 returns false

OOPS with Java and DS 21


NICE COMPUTERS No.1 in Kavali

3. Logical operators:
&&, ||, ! are the logical operators used to append multiple
relational expressions to take a logical decision. In java any logical
expression returns either true or false.
&& (And logical operator):
Multiple relational expressions concatenated with “And”
logical operator is called “And” logical expression. It returns true if all the
relational expressions returns true. It returns false if any one of the relational
expression returns false.
Example:
10<20&&40<=40&&80!=20 returns true
40!=40&&80>20 returns true
|| (Or logical Operator):
Multiple relational expressions concatenated with “Or” logical
operator is called “Or” logical expression. It returns false if all the relational
expressions returns false. It returns true if any one of the relational
expression returns true.
Example: 40>80||60!=80||20!=20 returns true
! (Not logical operator):
It is a negation operator
Example:
! (30<=20) returns true
! (40==40) return false
4. Assigning operator:
= is an assigning operator used to assign the value of an
expression to the variable. Java also supports short hand arithmetic
operators. Short hand operators result more compact and easy readable code.
+=, -=, *=, /=, %= are the short hand operators.
Example:
Int x=10;
X+=20; //x becomes 30
5. Increment decrement operators:
++, -- are the increment and decrement operators used to
increment and decrement the value of a variable by 1. These operators are
used as both prefix and postfix operators.
In case of prefix operator, the value of variable is incremented
or decremented before other operations are performed.
Example:
Int x=40;
Int y=++x; //the value of y is 41, x is 41

OOPS with Java and DS 22


NICE COMPUTERS No.1 in Kavali

In case of postfix operator, the value of variable is incremented


or decremented by 1 after other operations are performed.
Example:
Int x=40;
Int y=x++; //the value of y is 40 and x is 41
6. Conditional operator:
?, : are two special operators used to write conditional
expressions. Conditional expression is written in place of simple if else
control statements.
Syntax:
Var = (condition) ? <exp1> : <exp2>
According to the above syntax, if the condition is true then, the
value of expression1 is assigned to variable otherwise the value of
expression2 is assigned to the variable.

7. Bit-wise operators:
Java provides different bit-wise operators to manipulate the data
at bit level. These operators are mostly used to implement encrypt and
decrypt algorithms for secured data communication. These operators are not
used with float or double type of data. These operators are Logical bitwise
and shift operators.

Operator Meaning

& bitwise AND


| bitwise OR
^ bitwise XOR
~ One’s Complement
<< Shift left
>> Shift right
>>> Shift right with zero fill

8. Special Operators:
Java supports some of the special operators like instanceof, (.)
member selection operator.
Instanceof operator is used to check weather an object is belongs
to a particular class.
(.) member selection operator is used to select a member from an
object.

OOPS with Java and DS 23


NICE COMPUTERS No.1 in Kavali

2. Write about the Evaluation of arithmetic expression?


(Or)
Write about the presidency of arithmetic operators?
Combination of constants, operands and arithmetic operators is
called an arithmetic expression.
Evaluation or execution of an arithmetic expression happens
according to the priority or presidency of arithmetic operators. First
expression will be evaluated and its result will be assigned to the variable.
The precedence of arithmetic operators is as follows.

Operator Presidency

*/% 1st
+- 2nd
= Last

Example:
X= 9-4+3*2-1 (1st pass 3*2)
X=9-4+6-1 (2nd pass 9-4)
X=5+6-1 (3rd pass 5+6)
X=11-1 (4th pass 11-1)
X=10 (5th pass x=10)

x
10

3. Write about the presidency of operators in java


Each operator in java has its priority. It determines how an
expression is executed when more than one operator is existed with in an
expression. The operators with highest priority are executed first. Operators
with lower priority are executed next. The operators with the same priority
are executed either from the left or right. Priority of operators is as follows.
Priority:
. () [] - ++ -- ! ~ (typecast) * / % + - << >> >>> < <= > >=
instanceof == != & ^ | && || ?: = shortcut operators
Associativity :
Left to right: Arithmetic, relational, logical, increment/decrement, bit-wise
and special operators
Right to left : Unary minus, Conditional and assigning operator

OOPS with Java and DS 24


NICE COMPUTERS No.1 in Kavali

4. Write about different Mathematical functions used in java?


In java Different mathematical functions are defined with in the
class java.lang.Math. All the mathematical functions available in c and c++
are defined as static methods in the Math class.
Class java.lang.Math
{
-----------------
-----------------
Public static double sqrt(x)
Public static double pow(x)
Public static double sin(x)
Public static double cos(x)
Public static double tan(x)
Public static double asin(x)
Public static double acos(x)
Public static double atan2(x)
Public static double log(x)
Public static double abs(x)
Public static double acos(x)
Public static double floor(x)
Public static double ceil(x)
--------------------
--------------------
}

5. Write about different control structures used in java?


The control flow statements of a language determine the order of
statements execution in a program. Java language supports the following
control flow statements.
1. if statement
2. if-else statement
3. switch-case statement
4. break statement
5. continue statement

OOPS with Java and DS 25


NICE COMPUTERS No.1 in Kavali

if-statement: -
The if statement is used to control the flow of execution of
statements. The general form of if statement is

Syntax:
if (condition)
{
statements
}
According to the above syntax if the condition is true, then the
statements will be executed. If the condition is false, then the statements will
be skipped from the execution.
Ex: -
if (a>b)
System.out.println(a);
if-else statement: -
It is the control structure used to process two possibilities. The
general form of if-else statement is
Syntax:
if (condition)
{
statements
}
else
{
statements
}
According to the above syntax if the condition is true, then
statements under the if conditional statement are executed, otherwise the
statements under the else part will be executed
Ex: -
if(a>b)
System.out.println(a);
else
System.out.println(b);

OOPS with Java and DS 26


NICE COMPUTERS No.1 in Kavali

Switch Statement: -
The switch statement causes a particular group of statements to
be chosen from several available groups. The selection is based upon the
current value of an expression that is included within the switch statement
matches with the case constant associated with the case defintion. The
general form of switch statement is

switch (<expression>)
{
case <const1>:
statements
break;
case <const2>:
statements
break;
default:
statements
}
Here the expression is evaluated first. If the value of expression
matches with any of the case constant, then all the statements from proper
case will be executed. However, if the value of expression doesn’t matches
with any case constant labeled by the case keyword, then the default case is
executed. When break statement is encountered, switch statement is
terminated and any other remaining statements are ignored. A break
statement is used to force an immediate exit from the control structure.
break statement: -
The break statement is used to terminate the execution of
either switch or any iterative control structure. It can be used within a do-
while, while, for or a switch statement. The break statement is written
simply as break; The break statement causes the transfer of control out of
entire switch statement or any loop, to the first statement following the
switch statement or any loop.
Syntax:

{
--------------
--------------
Break;
-------------
-------------
}
OOPS with Java and DS 27
NICE COMPUTERS No.1 in Kavali

Continue statement: -
The continue statement is used to skip the execution of
remaining statements of the loop and to proceed for the next iteration. The
continue statement can be included within a while, a do-while or a for
statement. It is written simply as continue;.

Syntax:
{
--------------
--------------
Continue;
-------------
-------------
}

Note: java does not support goto control structure.

6. Write about the iterative or looping control structures in java?


A single or block of statements executed repeatedly is called a
loop or iteration. The java programming language uses three iterative or
looping control structures to construct iterations. They are,
1. while loop
2. do-while loop
3. for loop
while Iterative control structure: -
It is the simple and fundamental iterative control structure.
Which is used to execute a statement or group of statements repeatedly until
a condition becomes false. It is an entry controlled iterative control structure.
The general form while is as follows.
Syntax:
While (condition)
{
block of statements
}

According to the above syntax, the body of the loop will be


repeatedly executed as long as the condition is true. The loop will be
terminated when the condition is false.
Ex:
fact=1;i=1;

OOPS with Java and DS 28


NICE COMPUTERS No.1 in Kavali

while (i<=n)
{
fact=fact*i;
i++;
}
Do-while Iterative control structure: -
The do-while iterative control structure works similar to while
loop. The difference is that in case of do-while loop the condition is checked
after the body of the loop is executed. So it is called exit controlled iterative
control structure. It is only the control structure terminated with a semicolon.
The general form of do-while statement is,
Syntax:
Do
{
statements
}while(condition);
According to the above syntax, the body of the loop will be
executed as long as the condition is true.
Ex: -
fact=1;I=1;
do
{
fact=fact*I;
i++;
}while(I<=n);

for iterative control structure:-


The for loop is the most commonly used iterative control structure in
application development. However, the for loop is a flexible and powerful
iterative control structure. It is an entry controlled iterative control structure.
It has two parts. That is conditional statement and the body. The general
form of the for statement is,
Syntax:
for(expression-1;expression-2;expression-3)
{
statements;
}

OOPS with Java and DS 29


NICE COMPUTERS No.1 in Kavali

Ex:
for(i=1,fact=1;i<=n;i++)
fact=fact*i;
According the above syntax, expression-1 are the initialization
statements of variables. It is executed once and at the beginning of loop
execution. Expression-2 is the conditional expression. It is checked for each
iteration of the loop. It determines the loop termination.Expression-3 is the
increment or decrement expression. It changes the value of loop control
variable. This expression is executed at the end of each iteration.

7. Define the following?


a. Class
b. Object
a. Defining a Class:
Class is a user defined type in java. Class definition has number
of members. These include variables and the code. Variables declared with
in the class are called data fields and the functions defined with in a class are
called methods. Data fields are used to store the data in an object, where as
methods are used to access, manipulate and store the data in the data fields.
Class is similar to basic data type. A variable called instance or object has to
create to store the data.
Here the name of the class must be a valid identifier and must be
in a capitalized format

Syntax: Example:

class <name> class rect


{ {
Type nameofdatafield; int l,b;
Type nameofdatafield; void setsides(int x,int y)
Type nameofmethod(Parameters) {
{ l=x; b=y;
Statements; }
} int getarea()
Type nameofmethod(Parameters) {
{ return l*b;
Statements; }
} };
};

In the above example l, b are the data fields, which are used
to store the length and breadth of rectangle. setSides() is a method used to

OOPS with Java and DS 30


NICE COMPUTERS No.1 in Kavali

set two sides of rectangle. getArea() is an another method used to get the
area of rectangle.
b. Creating an object:
Defining a class may not allocate the memory allocation of
any of its members, because class is a template.
A variable or an instance belongs to class has to create to
allocate the memory allocation of members. Instance of a class is called an
object. Any number objects can be created belongs to a single class. Each
object stores the data belongs to different entities.
An object can be created in two steps.
1. Creating an object using new operator.
2. Storing the reference of object into the reference variable.
Example:
Rect ob; (Creating the reference)
Ob=new Rect(); (Creating the object)

ob
Rectangle
Object

Accessing the class members:


Class members can be accessed by using the member access
operator (.).
Syntax:
<reference>.<member>(Parameters)
Example:

Import java.util.*; Class Demo


Class Rect {
{ Public static void main(String args[])
Int l,b; {
Void setSides(int x,int y) Rect ob=new Rect();
{ Ob.setSides(4,5);
L=x; System.out.pintln(“Area=”+ob.getArea());
B=y; System.out.println(“Perimeter=”+ob.getPeri());
}
Int getArea() }
{ }
Return l*b; O/p
} Area=20
Int getPeri() Perimeter=18
{
Return 2*(l+b);
}
} with Java and DS
OOPS 31
NICE COMPUTERS No.1 in Kavali

Multiple references to a common object:


Reference of one object can be assigned to another reference of
the same type. Here object will not be copied but only the reference is
copied.
Example:
Rect ob1=new Rect();
Ob1 Rect ob2=ob1;

Rectangle
Object
Ob2

8. What is constructor?
Constructor is a special kind of method used to initialize the data
fields while creating an object. The following rules must be followed while
declaring the constructor.
1. The name constructor must be equalant to the name of class
2. It cannot be defined as private
3. It may accept any number of arguments.
4. It doesn’t return any value.
5. It cannot be called once an object is created.
Syntax:
<name of class>(list of arguments)
{
Statements
}
Example:
Class Rect Class Demo
{ {
Int l,b; Public static void main(String args[])
Rect(int x,int y) {
{ Rect ob=new Rect(3,4);
L=x; System.out.println(“Area=”+ob.getArea());
B=y; }
} }
Int getArea() O/p
{ Area=12
Return l*b;
}
};

OOPS with Java and DS 32


NICE COMPUTERS No.1 in Kavali

9. Write about the method overloading?


In procedural languages it is not possible to define multiple
functions with the same name. But in any object oriented programming
language like java, it is possible to define multiple functions with the same
name. While defining multiple functions with the same name, make sure that
the difference is provided in parameters. Difference in parameters can be
provided by making the difference in number, type and sequence of
arguments. Proper method is selected according to the arguments we send to
the method.
Example:
Class Rect Class Demo
{ {
Int l,b; Public static void main(String args[])
Void setSides(int x) {
{ Rect ob1=new Rect();
L=b=x; Ob1.setSides(3);
} Rect ob2=new Rect();
Void setSides(int x,int y) Ob2.setSides(4,5);
{ System.out.println(“Area of Square”+ob1.getArea());
L=x;b=y; System.out.println(“Area of rectangle”+ob2.getArea());
} }
Int getArea() }
{
Return l*b; O/p
} Area of Square 9
} Area of rectangle 20

10. Write about the static members?


The normal data fields and methods defined in a class are called
instance members. Because these are created every time a new object is
created.
Both the data fields and methods can be defined as static
members using static keyword. Static members are called class members,
because these members are common to all the instances of a class. These
members can be directly accessed either by the class name or any instance
belongs to the class.
Static data fields:
The data fields defined with the keyword static are called static
data fields. The se data fields are used to define constants. These are written
in capitals to identify that it is a constant.

OOPS with Java and DS 33


NICE COMPUTERS No.1 in Kavali

Static method:
The methods defined with the keyword static are called static
methods. These methods are used as the utility functions in java.
Example:
Class Math
{
Static final double PI= -----;
Static final double S= -----;
Static double sqrt(double x)
Static int pow(int b,int e)
--------------------
--------------------
}

Math is the class of java.lang package. It defines different


constants and methods to perform mathematical operations.
Example of usage of static members:
Class Circle
{
Static double getArea(int r)
{
Return Math.PI*Math.pow(r,2);
}
};
Class Demo
{
Public static void main(String args[])
{
Double x=Circle.getArea(7);
System.out.println(“Area of circle”+x);
}
}

The static members have several restrictions:


1. Static methods can call only static members
2. These can only access static data
3. These cannot refer to this and super.

OOPS with Java and DS 34


NICE COMPUTERS No.1 in Kavali

11. Write about the nesting of methods?


Calling a method by another method of the same class is called
nesting of methods.

Import java.util.*;
Class Nesting
{
Int x,y; Class Demo
Void input() {
{ Public static void main(String args[])
System.out.println(“Enter two numbers:”); {
X=(new Scanner(System.in)).nextInt(); Nesting ob=new Nesting();
Y=(new Scanner(System.in)).nextInt(); Ob.input();
sum(); }
} }
Void sum()
{
System.out.println(“Sum=”+(x+y));
}
}

In the above example object calls the input() method. In return it


calls the method sum().

12. Write about the inheritance in java?


Inheritance is one of the important features of any object
oriented programming language.
The mechanism of deriving a new class from an old one is
called inheritance (or derivation). The old class is called as the super class
and the new one is called the sub class. It supports the concept of
hierarchical classification.
In OOP, the concept of inheritance provides the idea of
reusability. This means that we can add additional features to an existing
class without modifying it. This is possible by deriving a new class from the
existing one. The new class will have the features of both super and sub
classes.
Advantages:
1. Inheritance allows to construct re-usable components.
2. A common code can be used in different modules.
3. Enhancements can be done to the existed classes.
4. The behavior existed class can be changed by overriding the members.

OOPS with Java and DS 35


NICE COMPUTERS No.1 in Kavali

Forms of Inheritance:-
The mechanism of deriving a new class form an old one is called
inheritance (or derivation). Inheritance is classified into different forms
based on the levels of inheritance.
1. Single inheritance.
2. Multiple inheritance.
3. Multilevel inheritance.
4. Hierarchical inheritance.
Single Inheritance:
Inheriting a single class into another class is called single
inheritance. According to the syntax class A has the members of only A.
class B has the members of both A, B. Here the existed class A is called
super class and the new class B is called sub class.
class A
{
A -------------
-------------
};
class B extends A
{
B ------------
------------
};

Multiple Inheritance:
Inheriting multiple classes into a single class is called multiple -
inheritance. Java does not support multiple-inheritance with classes. But
supports through interfaces.
interface A
{
-------------
-------------
A B };
interface B
{
------------
C ------------
}
class C implements A,B
{
------------
------------
}

OOPS with Java and DS 36


NICE COMPUTERS No.1 in Kavali

Multilevel inheritance:
Inheriting the sub class of one class into another class is called
multilevel inheritance. According to the syntax class A is the super class.
Class B is the indirect super class. Class C is the sub class. Class A has the
members of A. class B has the members of both A, B. class C has the
members of A, B, C.
class A
{
-------------
A -------------
};
class B extends A
{
B ------------
------------
}
class C extends B
C {
------------
------------
};

Hierarchical Inheritance:
Inheriting a single class into multiple classes is called
hierarchical inheritance. According to the syntax class A is inheriting into
multiple classes that is B, C. Both the classes B, C have the members of A.

class A
{
-------------
A -------------
};
class B extends A
{
------------
B C
------------
}
class C extends A
{
------------
------------
};

OOPS with Java and DS 37


NICE COMPUTERS No.1 in Kavali

13. Write about the overriding of methods?


When the super, sub classes have the methods with the same
name, arguments and return type then, sub class members overrides the
super class members with in the sub class object.
Overriding is used to change the behavior of a method while
using all other resources of a class.
Example:
Import java.util.*;
Void output()
Class First
{
{
System.out.println(“x=”+x);
Int x;
System.out.println(“y=”+y);
Void setNum()
}
{
}
System.out.print(“x=”);
Class Demo
X=(new Scanner(System.in)).nextInt();
{
}
Public static void main(String args[])
Void output()
{
{
Second ob=new Second();
System.out.println(“x=”+x);
Ob.setNum();
}
Ob.output();
}
}
Class Second extends First
}
{
O/p x=45
Int y;
Y=30
Void setNum()
{
X=45
Super.setNum();
Y=30
System.out.print(“y=”);
Y=(new Scanner(System.in)).nextInt();
}

In the above example, the sub class object has the methods of
both the super and sub class. But the sub class object can access the sub
class methods, because sub class methods override the super class methods.
14. Write about the final data fields, final methods and final classes?
Final is the key word used to declare the final data fields, methods
and classes.
Final data fields:
The data fields defined with the key word final are called final
data fields. The values of which are assigned while their declaration. The
values of final data fields cannot be changed. These are used to define the
constants.

OOPS with Java and DS 38


NICE COMPUTERS No.1 in Kavali

Example:
Class Thread
{
Final static int MIN_PRIORITY=1;
Final static int NORM_PRIORITY=5;
Final static int MAX_PRIORITY=10;
--------------------
---------------------
};
Final methods:
The methods defined with the keyword final are called final
methods. These methods can be used as normal methods. But, final methods
cannot be override in its sub classes to change their behavior.
Final class:
These are the classes defined with the keyword final. Final
classes work like normal classes. But, these classes cannot be extended into
other classes.

15. What is finalizer method?


Constructor is a special kind of method used to initialize the
object. It executes while creating an object. Finalize() is also a special kind
of method executes when object is de-allocated by the garbage collector.
The purpose of finalize method is to clean up not object resources like file
descriptors and windows system fonts etc.
Syntax:
Class Box Finalize()
{ {
Int b,w,h; System.out.println(“Object is being clared”);
Box(int x,int y,int z) }
{ };
B=x;
W=y;
H=z;
}
Int getVolume()
{
Return b*w*h;
}

OOPS with Java and DS 39


NICE COMPUTERS No.1 in Kavali

16. What is abstract method or abstract class?


Abstract method is a method which has no implementation that
is no body. The abstract method must be defined with the keyword abstract.
If any class has at least a single abstract method then the class is called an
abstract class.
An object belongs to abstract class cannot be created unless we
override all the abstract methods in its sub class.
1. We cannot create an object belongs to the abstract class.
2. All the abstract methods of the abstract class must be override in its
sub class
3. We cannot define either abstract constructor or static method
Example:
abstract class Result
{
Abstract void setMarks()
Abstract void getResult()
};

17. Write about the visibility control or specifiers?


(Or)
Write about the access modifiers in java?
In general all the members of super class are extended into the
sub class. Some times, it is needed to restrict the members to access and
extend. Java provides different visibility specifiers to control the access and
extend. These are default, private, protected and public.
Default:
If we do not specify any specifier then it is called default
member. These members can be accessed and extended any where with in
the program. Default members of other packages can not be accessed and
extended.
Public:
Public members have global access. These can be accessed and
extended any where with the program and other packages.
Private:
Private specifier is used to promote data hiding or protection
in any object oriented programming language. The visibility of private
members is limited to the same class.

OOPS with Java and DS 40


NICE COMPUTERS No.1 in Kavali

Protected:
Protected members works like default members with in the
same program. Protected member of other packages cannot be accessed but
can be extended into the sub classes.

Modifier
Default Public Protected Private
Access
Same class Yes Yes Yes Yes
Other class
Yes Yes Yes No
same package
Sub class same
Yes Yes Yes No
package
Other class
No Yes No No
other package
Sub class other
No Yes Yes No
package

OOPS with Java and DS 41


NICE COMPUTERS No.1 in Kavali

UNIT III
1. Define Array?
(Or)
Write about a single dimensional array?
A variable belongs to any type can store maximum a single
value. An array is a derived type used to store multiple values with the same
name.
Array:
An array is a set of elements belongs to the same type stored in
consecutive memory allocations. All the elements are represented by the
same name. Every element in the array is identified with its index. In java
index of the first element is ‘0’ and the index of the last element is ‘n-1’.
Where n is the size of array.
Creating an Array:
An array is created in three steps.
1. Creating the reference
2. Allocating the memory
3. Storing values in it
The reference of an array is created with the type and the name of
reference.
int[] x;
x
(or)
int x[];

Memory allocation of array elements is done using the new


operator. Type and size of array is specified while creating an array.

int[] x=new int[5];


x

Values to an array are initialized using the name of array and its
index.
x[0]=10;
x[1]=20; x
x[2]=x[0]+x[1]; 10 20 30 -10 200
x[3]=x[0]-x[1];
x[4]=x[0]*x[1];

OOPS with Java and DS 42


NICE COMPUTERS No.1 in Kavali

Initializing while declaration:


Set of elements are initialized while declaration of an array
without using the new operator.
int[] x={10,20,50,60,80}

x
10 20 50 60 80
Length:
Length is the property of an array. It returns the length of an
array. In the above example ‘x.length’ gives 5.
2. Write about the Two-Dimensional array?
(Or)
Define the matrix?

Two Dimensional array:


Set of single dimensional arrays of the same size referred with the
same name is called a two dimensional array or matrix. A matrix is defined
in two steps, which is defining the reference and allocating the memory
allocation of matrix using ‘new’ operator. While defining the matrix number
of rows and columns are specified.
Syntax:
Type name[][]=new type[rows][cols]
Exmaple:
int x[][]=new int[3][4];

Initializing while declaration:


Set of sets of elements can be initialized while declaration of a
matrix.
Example:
Int x[][]={{2,3,4,5,6},{6,5,4,3,2},{15,24,34,43,52}};

2 3 4 5 6 x[0][3]

x
6 5 4 3 2 x[1][1]

15 24 34 43 52

x[2][2]

OOPS with Java and DS 43


NICE COMPUTERS No.1 in Kavali

Variable size array:


An array with variable number of columns can be created. To
create variable size array, first create an array of references and then allocate
the memory allocation of individual rows using ‘new’ operator.
Example:
int [][]=new int x[3][]; //creating reference array

x[0]=new int[2]; //creating individual rows


x[1]=new int[4];
x[2]=new int[3];

x[0]

x[1]

x[2]

3. Write about the String handling in java?


Set of characters place in double quotations is called a string. In
c, c++ a string is considered as a single dimensional character array.
In java String is a user defined type. Whenever a string is
created java runtime creates an object belongs to String class and initialized
through its constructor.
String str=”Nice”;
Is equalant to
String str=new String(“Nice”);

String handling:
The string class has number of methods. By using which we
can perform string operations.
Class String
{
String toUpperCase() // To convert into Uppercase
String toLowerCase() // To convert into lowercase
int length() // To find the length of string
char charAt(int) // to get a character at index
int CompareTo(String) // To compare two strings
int indexOf(char ch) // To find the index of a character from front
int lastIndexOf(char ch) // To find the index of a character from front
boolean equals(String) //To compare two strings
boolean equalsIgnoreCase(String) // To compare two string by ignoring case
-------------------
-------------------
}
OOPS with Java and DS 44
NICE COMPUTERS No.1 in Kavali

StringBuffer:
StringBuffer is a sub class to the class String. It is used to create
variable length string. It provides different methods to insert a character, a
string any where with in the string, append a string etc.

Class StringBuffer
{
Void setCharAt(int index, char ch) //modify a character at index
Void append(String str) //Appends a string
Void insert(int index, String str) //Inserts a string
----------
----------
}

4. Write about the vector?

Vector is class defined in java.util. This class can be used to


create a generic and dynamic array called vector. A vector can hold any
number of objects of any type. Size of vector is specified while creating an
object belongs to vector. Though the size is specified unlimited number of
objects can be stored.
Advantages of vectors:
1. Any type of objects can be stored
2. Any number of objects can be created
3. Object can be inserted, deleted and appended
The vector class has following methods:
Class Vector
{
Void addElement(Object) // To add an object
Int size() // Returns the size of vector
Void removeElement(Object) // Removes an element
Void removeElementAt(int) // Removes element at an index
Void removeAllElements() // Remove all the elements
Void insertElementAt(Object,int) // Inserts element at index
Void copyInto(Object[]) // Stores Objects into array
--------------------
--------------------
}

OOPS with Java and DS 45


NICE COMPUTERS No.1 in Kavali

Example:
Import java.util.*;
Class Demo
{
Public static void main(String args[])
{
Vector v=new Vector();
v.addElement(“Basic”);
v.addElement(“Cobol”);
v.insertElementAt(“Pascal”,1);
String x[]=new String[v.size()];
v.copyInto(x);
for( int i=0;i<x.length;i++)
System.out.println(x[i]);
}
}
O/p Basic
Pascal
Cobol

5. Write about the wrapper classes?


The utility collection classes like Sets, Lists and Maps do not
accept primary types, accepts only objects. To handle Collection classes’
primary types must be converted into object types.
Java.lang package provides wrapper classes to wrap primary
types with the objects. Almost every primary type has its wrapper class.
These classes are the sub classes to the class Number.
Number

Integer Long Character Float Double Byte Short

Class Number
{
int intValue()
float floatValue()
char charValue()
-------------
-------------
}

OOPS with Java and DS 46


NICE COMPUTERS No.1 in Kavali

These wrapper classes helps to refer collection of elements


belongs to different types as single set.
class Demo O/p
{ 12
public static void main(String args[]) 45.23
{ X
Object x[]=new Object[5]; 67.45
x[0]=new Integer(12); 2345
x[1]=new Float(45.23f);
x[2]=new Character(‘x’);
x[3]=new Double( 67.45);
x[4]=new Long(2345);
for(int i=0;i<x.length;i++)
System.out.println(x[i]);
}
}

6. Define interface?
(Or)
What is interface and write how an interface is implemented?
An interface is a special kind of class. An interface is used on
two purposes, which are to define the constants and to define the
specification. Data fields and methods can be defined in an interface like a
normal class.
The data fields defined with in a class are by default final static
data fields. These data fields are mostly used to define the constants. These
constants are accesses with the name of interface because, these are of static
type. The values of these data fields cannot be changed because, these are of
final type.
Interface Constants
{
Double PI=3.14;
};

The methods defined within an interface are by default public


abstract type. Hence an interface is called as a pure abstract class. An
instance belongs to an interface cannot be created unless we override the
abstract methods in its implementing class.

OOPS with Java and DS 47


NICE COMPUTERS No.1 in Kavali

Syntax:
Interface <Name of interface>
{
----------------
---------------
}
Class <name of class> implements <Name of interface>
{
----------------
----------------
}

Multiple inheritance:
Multiple interfaces can be extended in a class and multiple
interfaces can also implement in a single class
Example:
Interface Constants
{ Constants Circle
Double PI=3.14;
}
Interface Circle
{ CircleImpl
Void setRad(int x);
Double getArea();
Double getCir();
}
Class CircleImpl implements Constants, Circle
{
Int rad;
Public void setRad(int x)
{
Rad=x; Class Demo
} {
Public double getArea() Public static void main(String args[])
{ {
Return Pi*rad*rad; Circle ob=new CircleImpl();
} Ob.setSides(7);
Public double getCir() System.out.println(“Area=”+ob.getArea());
{ System.out.println(“Circumfarance=”+ob.getCir());
Return 2*PI*rad; }
} }
}

OOPS with Java and DS 48


NICE COMPUTERS No.1 in Kavali

7. What is a package and write the procedure to create a package?


Reusability is one of the important features of java. Java
supports reusability by extending classes and implementing interfaces.
Package: Package is a collection of re-usable classes and interfaces. Once
the package is defined, then its resources can be accessed into any java
program. Import statement is used to import a class or all the classes of a
package.
Import java.util.*; // It imports all the classes of util package
Import java.util.Date; // It imports the Date class from util package

Advantages of packages:
1. Promotes the re-usability
2. Two classes can be defined with the same name in different packages
3. Helps to hide a class
4. It separates the designing from coding.
Java API packages:
Java API provides a large number of classes grouped into
different packages and sub packages according to functionality. This API is
used to develop java applications.

Package Name Purpose


Java.lang These are the classes directly used by the compiler. These classes
are directly imported into every application
Java.util Provides number of utility classes like collections classes and to
perform date and time operations
Java.io Provides number of classes to perform different input and output
operations
Java.awt Provides number of classes to design graphical interface
Java.net Provides number of classes to do network programming
Java.applet Provides number of classes to develop applets

java

lang util io awt net

Creating a package:
We can create our own package in order to re-use in different
applications. A package can be created in 3 steps

OOPS with Java and DS 49


NICE COMPUTERS No.1 in Kavali

1. Creating a folder with the name package


2. Defining classes/interfaces in the package folder
3. Compiling the classes/interface
4. Setting the class path to the parent folder of package
5. Accessing the package and its classes
Step1: Creating the folder with the name of package
C:\>md
shape
Step2: Defining the classes under the package folder
The class definition must be started with the package statement.
The class and all its methods must be of public type.
C:\>cd shape
C:\Shape> edit Box.java
package shape;
public class Box
{
Int b, w, h;
public void setSides(int x, int y ,int z)
{
B=x;w=y;h=z;
}
public int getVolume()
{
Return b*w*h;
}
}

Step3: Compile all the classes of package


Shape>javac Box.java
Step4: Setting the class path to the parent folder
D:\> set classpath=c:\;.;
Step5: Accessing the package
import shape.*;
class Demo
{
Public static void main(String args[])
{
Box ob=new Box();
Ob.setSides(3,4,5);
System.out.println(“Volume=”+ob.getVolume());
}
}
OOPS with Java and DS 50
NICE COMPUTERS No.1 in Kavali

UNIT IV

1. What is a thread? Write how java supports multi-threading?


(Or)
Explain how to create a thread in java?
Thread:
Executing multiple programs simultaneously is called multi-
threading. Multi-threading is a conceptual programming where a program is
divided into two or more sub programs and are implementing at the same
time.
A unique property of java is its ability to support multi-
threading. In java multiple threads are defined as multiple blocks of code.
Execution of java application always starts from the main method called
main thread. The main thread starts all the other threads called sub threads.
All the threads execute in parallel one after another.
Class Demo
{
Public static void main(String args[])
{ Main
---------------- Thread
----------------
}
}

------------ ------------ Switching ------------


Switching ------------
------------ ------------
Public void run() Public void run() Public void run()
{ { {
------------ ------------ ------------
} } }
------------ ------------ ------------

Thread1 Thread2 Thread3

Creating threads in java:


In java a thread can be created in two ways that is
1. By extending the Thread class
2. By implementing Runnable interface

OOPS with Java and DS 51


NICE COMPUTERS No.1 in Kavali

Creating a thread by extending the Thread class:


Java.lang.Thread is an implementing class of Runnable. It has all
the life cycle methods to create and control the thread. Start() method of
Thread class registers the thread to the O.S, which calls the run() method. By
default run() method has nothing to execute. We can place thread code with
in the run() method by overriding in the extending class of Thread.
Example:

Class MyThread extends Thread


{ O/p
int st, end; One 1
MyThread(String str, int s, int e) Two 101
{ Three 201
super(str); One 2
st=s; end=e; Two 102
setPriority(5); Three 202
start(); -----------
} -----------
public void run()
{
for(int i=st;i<=end;i++)
System.out.println(getName()+”:”+i);
}
}
Class Demo
{
public static void main(String args[])
{
new MyThread(“one”, 1, 100);
new MyThread(“two”, 101, 200);
new MyThread(“Three”, 201, 300);
}
}

Creating a thread by implementing Runnable interface


Runnable interface has single public abstract method called
run(). We cannot create a thread by implementing Runnable interface alone,
because it has no other methods to create and control the life of a thread.
To create a thread by implementing Runnable interface, we also
take the help of Thread class and it methods. The following steps are taken
to create a thread by implementing Runnable interface.

OOPS with Java and DS 52


NICE COMPUTERS No.1 in Kavali

1. Implementing the Runnable interface by overriding run() method.


2. Sending the reference of Runnable implanting object to the Thread
object.
3. Calling the start() method of Thread object.

Class MyThread implements Runnable


{
Public void runnable()
{
For(int i=1;i<=50;i++)
System.out.println(“One:”+i);
}
}
Class Demo
{
Public static void main(String args[])
{
MyThread ob=new MyThread();
Thread th=new Thread(ob);
th.start();
for(int i=51;i<=100;i++)
System.out.println(“main:”+i);
}
}

2. Write about the life cycle of thread?


During the life time of thread it is at different states. These
include,
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
1. New born state:
The state of thread on creating an object belongs to thread is
called new born state.
Example:

MyThread th=new MyThread();

New born state

OOPS with Java and DS 53


NICE COMPUTERS No.1 in Kavali

2. Runnable state:
On calling the start method of thread object, Thread is registered
with the queue of threads of O.S. O.S sends the thread to the runnable state
that is ready to run state.
New born state

th.start();

3. Running:
Executing the statements of a thread is called the runnable
state. When one thread is executing, other threads will be at waiting state
called runnable state. A thread will be swapped among the runnable and
running states.
New born state

th.start();

Runnable Running

Other Threads
4. Blocked state:
Sleep:
When the sleep method is called, then the thread will be send to
the blocked state for specified number of milliseconds. It will automatically
come to the running state after the completion of specified milliseconds.
New born state

th.start();

Runnable Running

After 1 sec Blocked th.sleep(1000);

OOPS with Java and DS 54


NICE COMPUTERS No.1 in Kavali

Suspend(), resume():
Suspend is the method, which sends the thread into the blocked
state. It will come to the running state on resume() is called.

New born state

th.start();

Runnable Running

Resume() Blocked Suspend()

5. Dead state:
The thread goes to the killed state either after completion of
thread execution or by calling the stop() method.

3. Write about the priority of threads?


Each thread is assigned with a priority. Processor time is given
more to the threads with more priority, less to the threads with less priority.
By default a thread is assigned with the normal priority 5.
The thread class defines 3 constants to assign the priority to the
threads.
Class Thread
{
Final static int MIN_PRIORITY=0;
Final static int NORM_PRIORITY=5;
Final static int MAX_PRIORITY=10;
------------------------
------------------------
};

Example:
MyThread th1=new MyThread();
th1.setPriority(Thread.NORM_PRIORITY);
th1.start();

OOPS with Java and DS 55


NICE COMPUTERS No.1 in Kavali

4. Write about the Synchronization and dead lock?


Synchronization:
When multiple threads using the common resource then
sometimes, it may leads to serious problems. For example a method is used
to perform read and write operations on the file, multiple threads are using
the same method to perform opposite operations then, it results unexpected
result.
If the commonly used method is defined as Synchronized method
then a monitor is placed on a thread first called. Another thread is executed
on the completion of first thread execution.
Synchronization is done two ways
1. By defining the commonly used method as synchronized method
using the keyword Synchronized.
Example:
synchronized static void display(String name, int st, int end)
{
for(int i=st;i<=end;i++)
System.out.println(str+” “+i);
}

2. By placing the commonly used object in the Synchronized block


synchronized(ob)
{
Ob.display(getName(), st, end);
}

Dead lock:
Dead lock occurs when two synchronized methods have circular
dependency on a pair of synchronized objects. For Example one thread
enters the monitor on object X and another thread enters the monitor on
object Y.
If the thread in X tries to call any synchronized method on Y,
thread in Y tries to call any synchronized method on X, then it results dead
lock.
Thread1 Thread2

synchronized method2() synchronized method1()


{ {
method1(); method2();
} }

OOPS with Java and DS 56


NICE COMPUTERS No.1 in Kavali

5. Write about the types of errors in java?


Error or bug is an abnormal event in a program, causing the
program to produce unexpected result or some times terminate the
execution.
According to the root of errors, errors can be classified into
1. Compile time errors
2. Run time errors
Compile time errors:
All syntax errors are considered as compile time errors. These
errors are recognized and reported by the compiler during the compilation of
program. Compiler will not generate byte code unless compile time errors
are rectified.
The most common errors are:
1. Missing semicolons
2. Missing of {}
3. Misspelling keywords and identifiers
4. Use of undeclared variables
5. Improper type casting etc.
Runtime-errors:
Sometimes, a program may compile properly and successfully
produces the byte code, but may not run properly. Such programs may
produce bad result or terminate abnormally.
The most common run-time errors are:
1. Due to the bad logic used in program
2. Dividing an integer by zero
3. Accessing negative index of an array
4. Using null objects
5. Invalid conversion from string to number etc.

6. What is exception and write different exceptions in java?


An exception is an abnormal event which causes program to
produce abnormal result, terminates the execution of program. Divide by
zero is an exception rises on dividing an integer by zero.
Java provides a hierarchy of classes to handle the exceptions in
java. Throwable is the super class to all the hierarchy. It is the solid class
defines all the methods used to handle the exceptions.

OOPS with Java and DS 57


NICE COMPUTERS No.1 in Kavali
Throwable

Exception

ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
ClassNotFoundException
NumberFormatException

IOException
Arithmetic Exception: Rises when an integer is divide by zero
ArraIndexOutOfBoundsException: Raises when a negative index or an index
which is beyond its size is accessed
NullPointerException: Rises when a reference with a null value is used to
access members
ClassNotFoundException: Rises when class loader fails to load the class
either in the current folder or in classpath directory
NumberFormatException: Rises when fails to convert a string into number.
IOException: Rises when program fails to access, write on to console.
How an exception is raised:
When the java runtime encounters a run time error, then java
runtime creates an object belongs associate class. The exception object is
stored with the source and details of exception. If the exception is not
handled by the program then it will be handled by the default exception
handler by terminating the program execution. The default exception handler
publishes the details of exception on console.
ExceptionObject

Source and Details of


Exception

OOPS with Java and DS 58


NICE COMPUTERS No.1 in Kavali

7. Write about the exception handling in java?


(Or)
Write how to use multiple catch blocks?
Run-time errors which can be handled are called exceptions. Java
provides try-catch mechanism to handle the run-time exceptions. The source
of exception is placed with in the try block. One or more catch blocks are
defined under the try block.
Catch block is not executed when there is no exception with in
the try block. When there is an exception raised with in the try block then an
object belongs to exception is created and its reference is send to the
matching catch block. Here the catch block is used to handle the exception.
Program execution resumes after the completion of catch block execution. If
the type of exception does not match with any of the catch blocks then
exception is handled by the default exception by terminating the program.
Syntax:
Import java.util.*;
Class Demo
{
Public static void main(String args[])
{ run 1:
int x, y, z; Enter two numbers
try 5
{ 0
System.out.println(“Enter two numbers”); Cannot divide by zero
X=(new Scanner(System.in)).nextInt(); run 2:
y=(new Scanner(System.in)).nextInt(); Enter two numbers
z=x/y; 15
System.out.println(“Division=”+z); xy
} Inproper Input
catch(ArithmeticException ae) run 3:
{ Enter two numbers
System.out.println(“Cannot devide by zero”); 15
} 3
catch(InputMismatchException ime) Division=5
{
System.out.println(“Inproper Input”);
}
}
}

In the above example when the denominator is zero


ArithmeticException is raised and handled. When the denominator is not a
number then InputMismatchException is raised.

OOPS with Java and DS 59


NICE COMPUTERS No.1 in Kavali

8. Write about the finally block?


Finally block is used in association with either try or try-catch
block. It is the compulsory to execute block. It executes in all the case that is
 When no exception raised
 Exception raised but not handled
 Exception raised and handled.
It is mostly used to close the opened database connections and
to close the opened files.
Syntax:

try ---------------------------- try


{ {

} }
finally catch(Exceptiontype e)
{ {

} }
finally
{

9. Write about the user defined exceptions?


(Or)
Write how to throw an exception?
All the exception classes are the sub classes to the class
Exception, which is the sub class to the class ‘Throwable’. Only the run-time
exception are identified and handled by the java run time.
Logical errors can not be identified and handled by the java
runtime. We can define our own exception type by extending ‘Exception’
class. As java run time do, we can
 Hit the exception (Finding the exception)
 Throw the exception using throw statement
 Catch the exception using catch block

OOPS with Java and DS 60


NICE COMPUTERS No.1 in Kavali

Example:
Run1:
import java.util.*; Enter the cmr: 500
class MyException extends Exception Enter the pmr: 200
{ No.of units: 300
MyException(String str) Total Bill: 1125
{ It is the end of program
super(str); Run 2:
} Enter the cmr: 200
} Enter the pmr: 500
class Demo Invalid readings
{ It is the end of program
public static void main(String args[])
{
int cmr, pmr, nu;
float bill;
System.out.print(“Enter the cmr:”);
cmr=(new Scanner(System.in)).nextInt();
System.out.print(“Enter the pmr:”);
pmr=(new Scanner(System.in)).nextInt();
try
{
If(pmr>cmr)
throw (new MyException(“Invalid readings”));
Nu=cmr-pmr;
Bill=nu*3.75;
System.out.println(“No.of units:”+nu);
System.out.println(“Total bill:”+bill);
}
catch(MyException me)
{
System.out.println(me.getMessage());
}
finally
{
System.out.println(“It is the end of program”);
}

}
}

OOPS with Java and DS 61


NICE COMPUTERS No.1 in Kavali

10. Write how applet differs from a java application?


(Or)
Why do we need applets?
(Or)
What is an applet?
HTML is a web based programming language used to develop
web pages. Web pages developed in HTML are static web pages. These web
pages can present the formatted data but cannot interact with the users,
because HTML has no data types, control structures, functions and user
interface controls to provide interaction.
Applet:
An applet is a small java program placed with in a HTML
document. Applet is byte code compiled from a java program (.class file).
Applet is loaded in to the computer along with the HTML page. Applet is
executed by the java runtime loaded in the computer.
Applets are used to perform arithmetic operations, display
graphics, play sounds, accept user input, create animation and play
interactive games.
How applet differs from a java application?
Though applet is a small java program, it is not a fully featured
java application. Since applets are used in internet, there are certain
limitations in developing applets.
1. Applet has no main() method. Execution starts in pre defined order.
2. Applet cannot be an individual program. It must be place within the
web page.
3. Applet must be small to easily download in internet
4. Applet cannot access the file system of local system
5. Applet cannot start any program in the local system
6. Applet cannot communicate with other servers
7. Applets are restricted from using C and C++ libraries.

OOPS with Java and DS 62


NICE COMPUTERS No.1 in Kavali

11. Write the procedure to develop and execute an applet?


(Or)
How to create an executable Applet?
(Or)
Write steps to develop an applet?
The following procedure is followed in developing and executing
an applet.
Step1: Building Applet Code
Java.applet package provides a class called Applet. It has all the
life cycle methods of Applet. Graphics is the class of java.awt has the
methods to paint on the banner of an applet.
To create an applet, Applet class is extended into our own class.
Init () method is overrided to initialize the applet, start() method is overrided
to set the background and foreground and paint(Graphics) method is
overrided to paint on to the banner using its methods.
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
String str;
public void init()
{
str=”Hello world”;
}
public void start()
{
setForeground(Color.red);
}
Public void paint(Graphics g)
{
g.drawString(“Hello world”,50,100);
}
}

Step2: Creating executable Applet


Compile the applet using the java compiler. It produces the
executable Applet in a form of .class file

>javac MyApplet.java

OOPS with Java and DS 63


NICE COMPUTERS No.1 in Kavali

Step3: Adding applet to the HTML page


<Applet> tag is used to add applet to the html page. Applet is
added to the HTML page in the body section

<html>
<head>
<title>Demo of Applet</title>
</head>
<body>
<Applet code=”MyApplet.class” width=300 height=300>
</Applet>
</body>
</html>

Step4: Executing the applet


Appletviewer is used to execute the applet.

>Appletviewer MyApplet.html

12. Write how to design a web page?


HTML is the formatting language used to develop web pages.
Collection of we pages is called as a web site. Individual web pages are
inter-connected using hyper links. HTML has no data types, control
structures and functions. It has only tags to format the web page.
Tag is a key word placed with in “< >”. Tags are of two types
that is singular and container. Singular tag has only the beginning part,
where as container tag has both the beginning and ending parts.
Any HTML program is saved with .html extension and
executed by any web browser like Internet explorer, Netscape Navigator or
Mosaic etc.
Total web page is written with in <html> and </html> tags.
Any HTML page has three sections.
1. Comment Section
2. Head Section
3. Body Section
Comment Section:
It is an optional section in web page. This section is used to write
the details of a web page and developer etc. It will not be executed by the
browser.

OOPS with Java and DS 64


NICE COMPUTERS No.1 in Kavali

Head Section:
It is an optional section in web page. This section is used to
interact with the browser and other programs.
Body Section:
It is the mandatory section HTML. All the contents written in the
body section will be printed on the browser.
Example:

<HTML>
<!--
Sample html program
-->
<HEAD>
<TITLE>My first page</TITLE>
</HEAD>
<BODY >
<H1>Hello world</H1>
<BODY>
<HTML>

13. Write about the Applet tag?


<APPLET> is a html tag used to add an applet to the HTML
document. It has different attributes to format the applet in a HTML
document.

Attributes Purpose
Codebase To specify the name of applet and its location (URL an applet)
Code To specify the name of applet with .class extension
With To specify the with of applet (In pixels)
Height To specify the height of applet (In pixels)
Align To align the applet with respect of web page (left, right and
center)
Name To specify the name of Applet to refer in script
Vspace To specify the vertical space among the applet and text
Hspace To specify the horizontal space among the applet and text
Param It is tag within the <Applet> tag used to send the parameters to
the applet from HTML page.

OOPS with Java and DS 65


NICE COMPUTERS No.1 in Kavali

Vspace

Hspace
Height

Width

14. Write about the Life cycle of an applet?


Every applet inherits all of the life-cycle methods from Applet
class. An applet undergoes into different states while its execution. These
states includes
1. New born or initialization state
2. Running state
3. Idle state
4. Dead or destroyed state
Browser loads the Applet

Creates the object belongs to applet


init()

Initializing state

Restart start()

Running state
Object belongs to Graphics

Public void paint(Graphics g)


{
Loosing &
Gaining focus
----------------
----------------
} stop()

Idle State
destroy()

Dead state End (Exit from browser)

OOPS with Java and DS 66


NICE COMPUTERS No.1 in Kavali

New born state:


On loading the applet, the run-time creates an object belongs to
applet class and calls init() method. The state of which is called initialization
state. The init() method is used to initialize the values, set the foreground
and background color of the applet.
Running state:
The applet enters into the running state when run-time calls the
start() method. The start method is used to create threads
Display State:
After the execution of start method run-time creates an object
belongs to Graphics and send its reference to paint() method. The paint
method paints the banner using the methods of Graphics class.
Idle or stopped state:
Once the paint method is executed then applet goes to the idle
state and executes the stop() method. The stop() method is used to terminate
the Threads
Dead state:
Applet goes to the dead state on unloading the applet from
memory by terminating from the web page. The destroy() method is
executed on sending the applet to the dead state.

15. Write how to send parameters to an applet?


(Or)
Write about the <param> tag?
(Or)
Write about the HTML to Applet communication?
<Param> is the tag used to send the parameters from an html
page to the applet. The <param> tag has two attributes that is name and
value. Here the ‘name’ specifies the name of parameter and values specifies
the value to be send to the applet.
Applet has a method called getParameter (), it accepts the name
of parameter as argument and gets the value from the applet.
<Param> tag is used to customize the applet from html page.
Example:

OOPS with Java and DS 67


NICE COMPUTERS No.1 in Kavali

Writing an Applet:
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
String str;
public void init()
{
str=getParameter(“one”);
}
public void paint(Graphics g)
{
g.drawString(str,50,100);
}
}

>javac MyApplet.java

Sending parameter to Applet:

MyApplet.html
<html>
<body>
<center>
<applet code=”MyApplet.class” width=300 height=300>
<param name=one value=”Hello world”>
</applet>
</center>
</body>
</html>

>Appletviewer MyApplet.html

16. Write about the HTML tags?


HTML is tag based programming language used to format the
web-page. Here tag is keyword placed with in < >. Tags in HTML cab
divided into singular and container tags. Singular tag has no closing part,
where as container tag has both opening and closing parts.
The following are some of the important tags used in HTML.

OOPS with Java and DS 68


NICE COMPUTERS No.1 in Kavali

Tag Purpose
<br> Next line character
<b></b> To format the text in bold
<i></i> To format the text in italic
<u></u> To format the text in underline
<h1></h1> To format the headings
-----------
<h6></h6>
<center></center> To align the text in center
<p> To give the paragraph break
<Hr> To draw the horizontal line
<Font></font> To format the font
<Img> To place an image in a HTML page
<Applet></applet> To insert an applet in a HTML page
<!--  Commentation in html

17. Write an applet which interacts with the user.


(Or)
Develop font animation applet?
Example:
//<applet code="MyApplet.class" width=300 height=300></applet>
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MyApplet extends Applet
{
TextField txt1;
Label l1,l2;
Button b1;
public void init()
{
setLayout(null);
l1=new Label("Enter text");
l1.setBounds(50,50,100,25);
add(l1);
txt1=new TextField();
txt1.setBounds(175,50,100,25);
add(txt1);
l2=new Label();
l2.setBounds(50,150,225,100);
add(l2);

OOPS with Java and DS 69


NICE COMPUTERS No.1 in Kavali
b1=new Button("Start");
b1.setBounds(100,100,100,25);
add(b1);
b1.addActionListener(new Listener());
}
class Listener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String str=txt1.getText();
Font f;
for (int i=5;i<=20;i++)
{
try{Thread.sleep(300);}catch(Exception e){}
f=new Font("Arial",Font.BOLD,i);
l2.setFont(f);
l2.setText(str);
if(i==20)
i=5;
}
}
};
};
O/p

OOPS with Java and DS 70


NICE COMPUTERS No.1 in Kavali

UNIT V
1. Write about the Bubble sort?
It is the easiest sorting method. It is the reverse to the selection
sort. The basic idea behind the bubble sort is to pass through the list several
times. In each pass we compare each element in the list with its next
elements, that is a[i] with a[i+1]. We exchange them when they are not in
order.
Algorithm:
1. Repeat through step4 a total number of n-1 times
2. Repeat step3 for elements in unsorted portion of the vector
3. If the current element in the vector is greater than next element in the
vector then exchange element.
4. If no exchanges were made then return, else reduce the size of the
unsorted vector by 1
Example:
Pass1:

33 44 22 11 66 55

33 44 22 11 66 55

33 22 44 11 66 55

33 22 11 44 66 55

33 22 11 44 66 55

33 22 11 44 55 66

After pass2:
22 11 33 44 55 66

After pass 3:

11 22 33 44 55 66

return

OOPS with Java and DS 71


NICE COMPUTERS No.1 in Kavali

Implementation:
void bubblesort(int p[],int n)
{
int l, temp, i, exg;
for(l=n-1;l>0;l--)
{
for(exg=0,i=0;i<l;i++)
{
if(p[i]>p[i+1])
{
temp=p[i];
p[i]=p[i+1];
p[i+1]=temp;
exg++;
}
if(exg==0)
return;
}
}
}

2. Write about the selection sort?


One of the easiest ways to sort a list is by selection sort.
Beginning with the first element in the list, search is performed to locate
the element which has the smallest value. When the smallest element is
found then it is exchanged with the first element in the list. A search for the
second smallest element is then found. It is exchanged with the second
element. It must be continued for the total list.
Algorithm
1. Repeat through step5 a total of n-1 times
2. Record the portion of the vector already sorted
3. Repeat step4 for the elements in the unsorted portion of the vector
4. Record location of the smallest element in unsorted vector
5. Exchange first element on unsorted vector with smallest element
Example:
42 23 74 11 65 58

11 23 74 42 65 58

11 23 74 42 65 58

11 23 42 74 65 58

11 23 42 58 65 74

OOPS with Java and DS 72


NICE COMPUTERS No.1 in Kavali

Implementation:

void selsort(int p[], int n)


{
int i, pass, min, min_idex, temp;
for(pass=0;pass<n-1;pass++)
{
for(min_ide=pass,i=pass+1;i<n;i++)
{
if(p[i]<p[min_idx])
min_idx=i;
if(pass!=min_idx)
{
temp=p[min_idx];
p[min_idx]=p[pass];
p[pass]=temp;
}
}
}
3. Write about the Insertion sort?
It is a sorting method by using which we can sort the elements
either in ascending or descending orders. The following algorithm is used to
sort the element using inserting sort.
Algorithm
The insertion sort algorithm scans ‘a’ from a[0] to a[n]. Inserting
each element a[k] to its proper position in the previously sorted sub array
a[0], a[1], a[2],……………….a[k-1]. This is
Pass1: a[0] is by itself sorted
Pass2: a[1] is inserted either before or after a[0] so that a[0], a[1] is sorted
Pass3: a[2] is inserted into its proper place in a[0], a[1].
It continues on and on until all the elements are sorted by
inserting each element at its position.
Example:
`
-∞ 77 33 44 11 88 22 66 55

-∞ 33 77 44 11 88 22 66 55

-∞ 33 44 77 11 88 22 66 55

-∞ 11 33 44 77 88 22 66 55

-∞ 11 33 44 77 88 22 66 55

OOPS with Java and DS 73


NICE COMPUTERS No.1 in Kavali
-∞ 11 22 33 44 77 88 66 55

-∞ 11 22 33 44 66 77 88 55

-∞ 11 22 33 44 55 66 77 88

Implementation:

void insertsort(int p[], int n)


{
int pass, i, temp;
for(pass=2;pass<=n;pass++)
{
temp=a[pass];
for(i=pass-1;temp<a[i];pass++)
a[i+1]=a[i];
a[i+1]=temp;
}
}

4. Write about the Quick sort?


Quick sort is a popular sorting method. The name comes from the
fact that quick sort can sort a list of elements faster than any other sorting
algorithms. The basic strategy of quick sort is to divide and conquer. Hence
quick sort is also called partition exchange sort. Suppose an array ‘x’ is
stored in memory then take the first element, the first job is placing the first
element in its proper position after the array is sorted. To do this, start
accessing the elements after key element and elements from the last.
Continue until the swap case is attained.

a[i]<a[k] , a[j]>a[k]

When both the conditions are false then, swap the elements (a[i] a[j])
Continue until J<=i
Example:

40 30 10 50 70 60 90 20 80 66

OOPS with Java and DS 74


NICE COMPUTERS No.1 in Kavali

Pass1:

40 30 10 50 70 60 90 20 80 66

40 30 10 20 70 60 90 50 80 66

20 30 10 40 70 60 90 50 80 66

Pass2:

20 30 10 40 70 60 90 50 80 66

70 60 66 50 80 90

50 60 66 70 80 90

Pass3:
20 30 10 40 50 60 66 70 80 90

20 10 30 40

10 20 30 40

Resultant vector:

10 20 30 40 50 60 70 80 90

Implementation:

void quicksort(int a[],int lb,int tub)


{
Int x;
if(ub>lb)
{
x=split(a,lb,ub);
Quicksort(a,lb,x-1);
Quicksort(a,x+1,ub);
}
}

OOPS with Java and DS 75


NICE COMPUTERS No.1 in Kavali

int split(int a[], int lb, int ub)


{
int key, p, q, t;
key=lb;
p=lb+1;
q=ub;
while(p<=q)
{
while(a[p]<a[key])
p++;
while(a[q]>a[key])
q--;
if(q>p)
{
t=a[p];
a[p]=a[q];
a[q]=t;
}
}
t=a[key];
a[key]=a[q];
a[q]=t;
return q;
}
5. What is stack? Write different operations performed on stack?
A stack is a linear structure in which items are added, removed
from one end. Examples of stacks are a stack of dishes, a stack of coins and
a stack of chairs. Where items are added and removed only from the top. It is
called last in first out [LIFO].
Definition:-
“A stack is a list of elements in which element are inserted,
deleted only at one end called top of stack”. The elements are removed from
a stack in the reverse order to the order of insertion. Top is a pointer which
always points to the top element of the stack. Inserting an element at the top
is called push. Deleting an element from the top of the stack is called pop.
Displaying an element at the specified position from the top is called ‘peep’.
Changing of such elements is called change. Displaying elements from the
top to the first is called display. When there are no elements in the stack.
Then the state of stack is called ‘stack underflow’. When the stack is filled
with the elements then the state of stack is called ‘stack overflow’.

OOPS with Java and DS 76


NICE COMPUTERS No.1 in Kavali
6 6
9 9 9
8 8 8
7 7 7
5 5 5 5

Push(5) Push(7) Push(15) Pop() Pop()


Push(8) Pop() Pop()
Push(9) Stack over flows 6 Pop()
Push(6) Pop() Stack under flows

9,8,7,5

Operations on stack:-
The following operations are performed on stack.
1. Push
2. Pop
3. Change
4. Peep
5. Display.

1. Push operation:-
Adding a new element to the top of the stack is called push
operation. While performing the push operation, follow the following
algorithm.
1. [Check for stack over-flow]
if top=MAX-1 then
write ‘stack overflows’
return
2. [Increment the top pointer by one]
Top<-top+1
3. [Store the element at the top]
S[top]=x
2. pop operation:
Removing an element from the top of the stack is called pop
operation. While performing the pop operation follow the following
algorithm.
1. [Check for stack under flow]
if (top=-1) then
write ‘stack under flow’
return null.
2. [Decrement the top pointer]

OOPS with Java and DS 77


NICE COMPUTERS No.1 in Kavali

Top  top-1
3. [Return formal top element]
return s[top+1]
3. Peep operation:-
Displaying an element at the required position is called
“peep” operation. While performing the peep operation follow the following
Algorithm
1. [Check for the stack under flow]
if (top=-1) then
write ‘stack under flow’
return null.
2. [Check for valid position]
if top-pos+1<0
write ‘improper position’
return null
3. [Return element at the required position]
return s[top-pos+1]
4. Change operation:-
Changing an element at the required position is called change.
Check for the stack underflow. While performing the change operation
follow the following algorithm.
1. [Check for the stack under flow]
if (top=-1) then
write ‘stack under flow’
return null.
2. [Check for valid position]
if top-pos+1<0
write ‘improper position’
return null
3. [Change the element at the pos]
s[top-pos+1] x
6. What is queue and explain different operations performed on queue?
Applications:
A Queue is a linear data structure where addition of new element
takes place at the end of the queue, deletion takes place from the front.
Queue’s applications are common in the field of computer sciences. For
example, there may be Queue of tasks waiting to print by the printer;
number of files may be waiting to write on the hard disk and number of
applications which are waiting to be processed by the processor. Queue

OOPS with Java and DS 78


NICE COMPUTERS No.1 in Kavali

works on the principle of FIFO (First In First Out). Where the first item
added to the queue is the first item to get remove.
Definition:
“Queue is a linear data structure stores multiple elements. New
elements are added at the rear end, elements are deleted from the front end.
To perform the Queue operations two pointers that is the front and rear are
used”. The front pointer always points the front elements of the queue. Rear
pointer points the rare elements of the Queue. When the Queue has no
elements the front elements then the state of the Queue is called Queue
underflow. When the rear is said to the max-1 then Queue doesn’t allows
any new elements to add. The state is called Queue overflow. Queue works
on the principle of FIFO (First In First Out).

5 5 6 8 3 2

Add(5)
Add(6) Add(9)
Add(8)
Add(3) over flow
Add(2)

5 6 8 3 2 5 6 8 3

Delete()
2 Delete() Delete()
Delete()
Delete() Under flow
Delete()
3,8,6,5

The following operations can be performed on the queue.


1. Adding
2. Deleting
Adding:
Adding a new element to the end of queue is called add
operation. Follow the following algorithm to perform add operation.
1. [Check for over flow]
if rear=MAX-1 then
write ‘Queue overflows’
return

OOPS with Java and DS 79


NICE COMPUTERS No.1 in Kavali

2. [Increment rear pointer]


R R+1
3. [Insert the element]
Q[R]  Y
4. [Set the front pointer adding the first element]
If F=-1 then
F 0
Return.
Removing:
Removing an existed element from the front of the queue is
called delete operation. Follow the following algorithm to perform delete
operation in a queue.
1. [Check for queue under flow]
If F=-1 then
write ‘Queue underflows’
return null
2. [Store the front element]
x  Q[front]
3. [Set the front pointer properly]
If front=rear then
front rear -1
else
front front+1
end if
4. [Return the former front element]
return x.

7. What is circular queue? Write the operations on circular queue?


A Queue is a linear data structure where addition of new
element takes place at the end of the queue, deletion takes place from the
front. The normal Queue implemented using an array suffers from
limitation. In a simple Queue implantation there is a possibility that the
Queue is reported as full when the rare is set to n-1, though there are free
spaces to take more elements.

3 2 5 3 2

Add(5)

Queue overflows
OOPS with Java and DS 80
NICE COMPUTERS No.1 in Kavali

To overcome this limitation, we can implement the Queue as a circular


Queue. Here when the rear pointer reaches n-1 then, the next element is
stored in the first slot of the array. The Queue would be reported as full only
when all the slots in the array are filled with the elements.
Operations on circular Queue:-
Like normal Queue all the operations performed on normal
queue can be performed on circular Queue. The common operations
performed on a circular queue are
1. Adding (insert)
2. Remove (delete)
3. Display
1. Adding:-
Adding a new element to the circular Queue is called insert.
When the C.Q. is with the full of elements then display Queue overflows, if
not increment the rare pointer by one and insert the element at the rare
pointer. If rare pointer is n-1 then set it to the beginning of the Queue.
Algorithm:-
1. [Check for Queue Over flow]
if (front=0 and rear=MAX-1) or (front=rear-1) then
write(‘Queue over flow’)
return
2. [Reset the rear pointer]
if rear=MAX-1 then
rear0
else
rear rear+1
end if
3. [Insert the element]
Q[rear] x
4. [Reset front pointer]
if front=-1 then
front front+1
2. Delete:-
Removing an element from the front of the Queue is called
‘Delete’ return the front element of the Queue and set the front pointer. If
front pointer is at n-1 then set it to the beginning of the Queue, otherwise
increment the value of front pointer by one. When both the front and rare
pointers are same then set them to ‘-1’. When the Queue has no elements
then display the message ‘underflows’.
1. [Check for Queue underflow]

OOPS with Java and DS 81


NICE COMPUTERS No.1 in Kavali

if front=-1 then
write (‘Queue underflow’)
return null
2. [Delete the element]
x Q[front]
3. [Increment the pointer]
If front=MAX-1 then
front 0
else if front=rear then
front rear -1
end if
4. return x

8. Write about the double ended Queue?


(Or)
Write about the DEqueue?
The word DEqueue is a short form of double ended queue. It is
a linear data structure in which items added and removed from both the
ends. In other words it is a combination of both stack and queue. According
to the insertion and deletion of elements DEqueue can be classified into
1. IRDEqueue
2. ORDEqueue
IRDEqueue
It is a double ended queue where adding a new element is done
at the rear of the queue, deletion is done from both the ends.
delete delete
f
40 23 50
r
insert
ORDEqueue
It is a double ended queue where deleting an element is done
only from the front end but, adding a new element is done from both the
ends. So it is called output restricted double ended queue.

OOPS with Java and DS 82


NICE COMPUTERS No.1 in Kavali

delete
f
40 23 50
r
insert insert

9. Write about the priority queues?


A priority queue is a collection of elements, where elements are
stored according to the priority levels. The order in which the elements
should get added or removed is decided by the priority of the elements.
1. The element with higher priority is processed before any element of lower
priority
2. If there are elements with the same priority then the element added first in
the queue would get processed first.
Priority queues are used for implementing job scheduling by the
operating system, where jobs with higher priorities are to process first.
According to the priority of elements priority queues can be classified into
1. Ascending priority queues
2. Descending priority queues
In ascending priority queues elements are arranged in ascending
order. In descending priority queues elements are arranged in descending
priority.
In both the cases first element is always deleted and all other
elements are re-arranged so that first element is always at ‘0’. New element
is added at rear.
1. Adding
f f

-1 10 30 50
r r
Add(10)
Add(50)
Add(30)

2. Removing:
f f
10 30 50 30 50

r r
10 remove

OOPS with Java and DS 83


NICE COMPUTERS No.1 in Kavali

10. Write about the parsing of arithmetic expression?


Infix expression:
When the operators are placed with the operands, then the
expression is called an infix expression. Normally we give infix expression
to the compiler. The compiler coverts the infix expression into the postfix or
prefix expression. And then expression will be evaluated.
Postfix expression:
When the operators are written as postfix to the operands then the
expression is called postfix expression.
Prefix Expression:
When the operators are written as prefix to the operands then the
expression is called prefix expression.
Example:
Infix expression: (a+b)*(c+d)
Postfix expression: ab+cd+*
Prefix expression: *+ab+cd
Parsing of Expression:
Evaluating an arithmetic expression is called parsing an
expression. It can be done two ways
1. Postfix
2. prefix
Parsing of postfix expression
Algorithm:
1. Input the postfix expression
2. Scan the expression from left to right
3. During our scanning
1. if you find an operand then push it onto the stack, continue
scanning
2. if you find an operator then pop the top 2 elements from the
stack and allow your operator to work on these operands, push
the intermediate result onto the stack and continue scanning
3. When you reach the end of the string. There should be only one
element in the stack. Pop this element to get the value of post fix
expression.
Parsing of prefix expression:
Algorithm:
1. Input the prefix expression
2. Reverse the prefix expression
3. Scan the expression from left to right
4. During our scanning

OOPS with Java and DS 84


NICE COMPUTERS No.1 in Kavali

a. if you find an operand then push it onto the stack,


continue scanning
b. if you find an operator then pop the top 2 elements from
the stack and allow your operator to work on these
operands, push the intermediate result onto the stack and
continue scanning
c. When you reach the end of the string. There should be
only one element in the stack. Pop this element to get the
value of prefix expression.

11.What is linked list? State the advantages of list over arrays?


(Or)
Write the construction of a linked list?
Disadvantages of Arrays (Static list):
For storing similar data in memory we can use either an array or
linked list. Array is a set of elements of the same type stored in consecutive
memory allocation. The memory allocation of array happens during the
compilation of the program. Hence an array cannot be expanded or
compressed. Due to the lack of flexibility in arrays stacks, Queues
implementing with arrays suffers from overloading. New elements may not
be inserted and the old elements may not be deleted.
All the above disadvantages of array can be overcome by the
complex data structure linked list.
A linked list can grow or shrink in size during its life time.
Linked list does not need consecutive memory allocations, because
individual nodes are created in different memory allocations but, logically
linked. Insertion and deletion of elements can be easily done with out
shifting the position of elements.
Linked list (Dynamic List):
Linked list is a very common data structure often used to store
similar data in memory. The individual elements are stored in different
memory allocations but, still bound together by referring to each other. The
order of elements is maintained by explicit links between them. Every
element in a linked list is considered as a node. Each of which stores two
items of information. That is the data and the link of other node. Here the
link is a pointer or an address that indicates the location of next node
explicitly. The NULL stored in the last node indicates that it is the last node
in the list. Always the reference of the first node is stored in a head pointer.

OOPS with Java and DS 85


NICE COMPUTERS No.1 in Kavali

Append a node:
Adding a new element at the end of the list is called ‘append’
to append a node follow the following algorithm.
1. create a new node
2. Store the data into the data part, Null into the link part.
3. If the head pointer has the null value, then store the reference of new
node in the head.
4. Otherwise find the last node and store the reference of new node into
the link part of the last node.
Case 1:
Head
null

append(20)
Head
20 null

Case 2:
append(50)

Head
20 50 null

Traversing the list:


Visiting all the nodes of a list from head to tail is called traversing.
To traverse the list, follow the following algorithm
1. If the head is stored with null then display that, the list is empty.
2. Otherwise traverse the list from head using link of each node.
Case 1:
head
null
Display()
List is empty
Case2:

head
10 30 50 null

Display()

10 30 45

OOPS with Java and DS 86


NICE COMPUTERS No.1 in Kavali

Implementation:
class Node
{ class Demo
int data; {
Node link; public static void main(String args[])
} {
class List Node n=new Node();
{ n.append(23);
Node head; n.append(45);
List() n.append(80);
{ n.append(72);
head=null; }
} }
void append(int x)
{
Node temp, p;
temp=new Node();
temp.data=x;
temp.link=null;
if(head==null)
head=temp;
else
{
for(p=head;p.link!=null;p=p.link);
p.link=temp;
}
}
void display()
{
Node p;
if(head==null)
System.out.println(“List is empty”);
else
{
for(p=head;p!=null;p=p.link)
System.out.println(“\t”+p.data);
}
}
}

OOPS with Java and DS 87


NICE COMPUTERS No.1 in Kavali

12. Write the procedure to delete a node?


Deleting a specified element from the list is called delete operation.
The following operation is used to perform delete operation.
1. accept the element
2. Search for the given element with in the list.
3. If element is not existed then display proper message.
4. Other wise store the link part of specified node into the link part of
previous node.
5. Delete the specified element.

Case 1: Head
null

delete(10);

no elements are existed

Case 2:
Head
20 50 null

delete(20)

Head
20 50 null

Case 3:

Head 20 40 60 NULL

Delete(40)

Head 20 40 60 NULL

OOPS with Java and DS 88


NICE COMPUTERS No.1 in Kavali

Implementation:
void del(int x)
{
Node p,pre;
if(head==null)
System.out.println(“List is empty”);
else if(head.data==x)
{
p=head;
head=head.link;
}
else
{
for(p=head;p!=null;pre=p,p=p.link)
if(p.data==x)
break;
if(p==null)
System.out.println(“No such element is existed”);
else
pre.link=p.link;
}
}

13. Write about different types of Linked Lists?


Linked list is a very common data structure often used to store
similar data in memory. The individual elements are stored in different
memory allocations but, still bound together by referring to each other. The
order of elements is maintained by explicit links between them. Every
element in a linked list is considered as a node. Each of which stores two
items of information. That is the data and the link of other node. Here the
link is a pointer or an address that indicates the location of next node
explicitly.
According the construction of lists, linked lists can be classified
into header linked lists and doubly linked lists.
Header linked lists:
A header linked list is a linked list which always contains a
special node called the header node, at the beginning of the list. The
following are two widely used header lists.
1. Grounded header list:
It is a header list where the last node contains the null pointer.
The name of which has come from the fact that the null pointer is considered
as ground in case of null.
Head 20 40 60 NULL

OOPS with Java and DS 89


NICE COMPUTERS No.1 in Kavali

2. Circular header list:


In the circular header list last node contains the address of the
first node. But, not grounded. Circular linked lists are frequently used
instead of ordinary linked lists. Because many operations are mush easier to
state and implement using header list. The reasons are,
1. The null pointer is not used and hence all pointers contain valid
addresses.
2. Every node has a predecessor. So the first node may not request a
special case.

Head 20 40 60

*Doubly linked list:


Linked list is a linear data structure which is used to store multiple
values belongs to same type. A linked list is build with number of nodes
logically linked with each other by storing the address of next node into
current node. Each node has two parts that is the data and link. The data part
stores the actual information and the link pointer stores the reference o next
node. Head is the pointer which stores the reference of first node. It is stored
with null value if the list is empty.
Disadvantages of singly linked lists:
1. It is not possible to traverse the list in reverse order.
2. We can not perform search operation from middle of list in any of
directions.
3. To make the list more flexible a doubly linked list is designed.
Definition:
A doubly linked list is a linear data structure used to store
multiple values in a logically consecutive memory allocation. Each node in a
doubly linked list has three parts that is the left pointer which stores the
previous node reference, data which stores the actual information and right
pointer which stores the reference of right pointer.
There are two pointers called first, last. Which are used to store
the reference of first and last node.
Example:
first last
null null

append(10);

OOPS with Java and DS 90


NICE COMPUTERS No.1 in Kavali

first last
null 10 null

append(20);
first last
null 10 20 null

14. What is tree and explain different trees?


A tree is a non-linear data structure that represents hierarchical
relationship between individual data elements. Trees encounters in every life
that is in real and computer applications. In tree structure every node may
point number of other nodes. Tree is a very flexible data structure used in
number of applications.
General tree:
A tree is an acyclic graph has one node at the top is called root.
It is at the level ‘0’. Some nodes will be at the level ‘1’ called branch nodes.
The level of any node is the length of its path from the root. In a tree if a
node has any number of sub nodes then the tree is called general tree.
A

B C

D E F

Binary tree:
Although the nodes in a general tree contains any number of
pointers to the other tree nodes, a large number of data structures have at the
most two pointers to the other tree nodes. This type of tree is called binary
tree.
A

B C

D E F

OOPS with Java and DS 91


NICE COMPUTERS No.1 in Kavali

Strictly binary tree:


A binary tree is said to be strictly binary tree if every non-leaf
node has two sub nodes or two sub trees.
A

B C

D E

Complete binary tree:


If all the leaf nodes of a strictly binary tree are at the same level,
then the tree is called complete binary tree.

B C

D E F G

Binary search tree:


If, in a binary tree all the elements in left sub tree of a root are
less than the value of root, all the elements in right sub tree of a root are
greater than the value of root, then the tree is called binary search tree.

4 8

3 5 7 9

OOPS with Java and DS 92


NICE COMPUTERS No.1 in Kavali

15.What is binary search tree (BST)? Explain the operations on tree?


A binary search tree is a binary tree with some special
properties. The data values of all the nodes in the left sub-tree are less than
that of the root. The data values of all the nodes in the right sub-tree are
greater than that of the root. The left sub-tree and right sub-tree are
themselves binary search trees.
Construction:
A binary tree can be build using the linked list. Every node has
three parts. That is the data, left and right. The left pointer has the reference
of left node and right pointer has the reference of right node. If the node is a
leaf node then both the left, right stored with null. The following algorithm
is used to construct the BST. The root node reference is stored in pointer
called head.
1. Create a node and store the data init
2. Store the null values in both the left, right pointers of the new node.
3. If the tree is empty then store the reference of new node into the head
pointer.
4. Otherwise, using the head pointer by traversing either left or right find the
parent node address to the new node.
5. Add the new node to the binary tree.
Example:
head
6
6
4 8

6 6
3 5 7 9

6 6 6 6

Linked List Representation

Traversals:
Visiting selected or all the nodes in a pre-defined order is called
traversing. The primary reason for visiting a node is to process the contents
of the nodes. The tree can be traversed using three methods.

OOPS with Java and DS 93


NICE COMPUTERS No.1 in Kavali

Pre-order traversal
Post-order traversal
In-order traversal
Pre-order traversal:
It is known as depth-first traversal. In this traversal the root node
is visited prior to the left and right nodes in a sub tree. The rule for pre-order
traversal is
1. visit the root-node
2. then visit the nodes in the left sub-tree in pre-order
3. finally visit the nodes in the right sub-tree in pre order

Post-order traversal:
It is known as breadth-first traversal. In this traversal the root
node is visited after the left and right nodes in a sub tree. The rule for pre-
order traversal is
1. visit the node in the left sub-tree in post order
2. then visit the node in the right sub tree in post order
3. finally visit the root node
In-order traversal:
In this traversal the root node is visited in between the node in
left and right sub-trees.
1. Visit the node in the left sub-tree in in-order.
2. Visit the root node.
3. Finally visit the nodes in the right sub-tree in in-order
Example:

6
Pre-order: 6 4 3 5 8 7 9
4 8 Post-order: 3 5 4 7 9 8 6
In-order: 3 4 5 6 7 8 9

3 5 7 9

OOPS with Java and DS 94


NICE COMPUTERS No.1 in Kavali

16. What is a graph? Explain the types of graphs?


Graphs are the non-linear data structures. It describes certain
type of relation ship among the data items. Tree is also a kind of graph
where data items have parent child relation ship. A general graph is a
structure that represents a less restrictive relation ship between data items.
Example:
A common example for a graph is a collection of cities and roads
between them.
Definition:
A graph G is a collection of two sets V and E. V is the collection
of vertices or nodes. E is the collection edges. Where, edge is an arc which
connects two nodes or vertices.

G=(V,E)
V(G)=(v0,v1,,……..vn)
E(G)=(e0,e1,………en)
Types of graphs:
Graphs can be classified as both directed and undirected. If
every edge in a graph G is marked by a direction then the graph is called
direct graph. It is often called as digraph. If directions are not marked for
any edge then the graph is called un-direct graph.
Direct graph:
If every edge i,j in E(G) of a graph is marked by a direction
from i to j then the graph is called direct graph. A directed graph is often
called as digraph. In the graph specified bellow pairs of vertices (1,2) and
(2,1) will represent two different edges where as in un-direct graph both will
be treated as a single edge.

Direct graph

G=(V,E)
V(G)={1,2,3}
E(G)={(1,2),(2,1),(3,2)}

OOPS with Java and DS 95


NICE COMPUTERS No.1 in Kavali

Un-direct graph:
If directions are not marked for any edge then the graph is
Un-direct
called un-direct graph. A normal graph
tree or a binary tree can be a perfect un-
direct graph.
1

2 3

4
G=(V,E)
V(G)={1,2,3,4}
E(G)={(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)}

Applications of graphs:
Graphs are use-full data structures for modeling various kinds of
processes or structures. Cities and high-ways form a graph. Components on
the circuit board form a graph. An organic chemical compound can be
consisted as a graph with the atoms as vertices and the bonds between them
as edges.
17. Write about the representation of graphs?
According to the field of computer sciences graphs can be
represented in two ways.
1. Adjacency matrix
2. Adjacency list

Adjacency Matrix:
A graph may be direct or un-direct can be conveniently
represented by an adjacency matrix. Which is also called an incidence
matrix. A graph contains ‘n’ node can be represented by a square matrix
containing ‘n’ rows and ‘n’ columns. The matrix is formed by placing ‘1’ in
the ith row and ith column of the matrix, if there is an edge between the
nodes i&j of the graph. Otherwise places a ‘0’
Example:

OOPS with Java and DS 96


NICE COMPUTERS No.1 in Kavali
1
1

2
2 3

3
4

Adjucent Matix

1 2 3 4
1 0 1 1 1 1 2 3
2 1 0 1 1 1 0 1 0
3 1 1 0 1 2 1 0 1
4 1 1 1 0 3 0 0 0

Adjacency list:
The ‘n’ rows of an adjacency matrix can be represented as ‘n’
listed lists. There is one list for each node in the graph ‘G’. Each list will
contain adjacent nodes. Each node has two fields. That is vertex and link.
The vertex field of a node will contain the nodes that are adjacent to the
node. The adjacency list can be easily build using adjacency matrix.

Adjucent List
1

2
2 3 4 null

1 3 4 null
Adjucent Matix
1 2 4 null
1 2 3 4
1 0 1 1 1
1 2 3 null
2 1 0 1 1
3 1 1 0 1
4 1 1 1 0

OOPS with Java and DS 97


NICE COMPUTERS No.1 in Kavali

18. Write about the graph traversals?


Visiting all the nodes in a graph systematically is called
traversal. In all the practical applications of graphs, there is a need to visit all
the nodes in a systematic order. There are two popular ways of visiting
nodes of a graph i.e.,
1. Depth-First search.
2. Breadth-First search.
Depth-First search:-
The depth first search algorithm is almost equal ant to pre-order
traversal in trees. In graph traversal there are two differences which do not
appear in trees. Because the graph contain cycles, algorithm reaches the
same node for the second time. The graph may not be connected, so the
traversal algorithm may fail to reach all vertices from a single starting point.
Algorithm:-
1. Choose any node in the graph. Design it as the search node and mark it
visited.
2. Find a node that is adjacent to search node using the adjacency matrix of
the graph. This node must not have been visited before. Designate this as
the new search node & mark it is as visited.
3. Repeat step-(2) using new search node; When all the adjacent nodes to a
search nodes have been visited, return to previous search node and
continue from there.
4. When a return to the previous search node in step-3 is impossible. Then
search from the originally chosen search node is completed.
5. If the graph still contains unvisited nodes choose any node that has not
been visited and repeat step-(1) to step-(4).
This algorithm is called a depth-first search because the search
continues progressively deeper in a recursive manner.

0 2

1 3

Adjacent matrix:
0 1 2 3 4
0 0 1 1 0 0
1 0 0 1 0 0
2 0 0 0 0 0
3 0 1 1 0 1
OOPS with Java
4 and
0 DS0 1 0 0 98
NICE COMPUTERS No.1 in Kavali

Adjacent:
Path1:0,1,2
0:1,2 Path2:3,4
1:2
2:
3:1,2,4
4:2

Breadth-First search:-
Essentially the breadth-first search begins at a given node and
then proceeds to all the nodes directly connected to that node.
1. Begin with any node, mark it as visited.
2. Proceed to the next node having an edge connected to the node in step-(1)
mark it as visited.
3. Come back to the node in step-(1) descend along an edge towards an
unvisited node and mark the new node as visited.
4. Repeat step-(3) until all bodes adjacent to the node in step-(1) have been
marked as visited.
5. Repeat step(1) to(4) starting from the node visited in (2) then starting
from the node visited in step-(3) in the order visited. Keep this up as long
as possible before starting a new scan.
A A F C B

F C B D
F C B
C B D G

D G E

E J
D E G

J K
J K

OOPS with Java and DS 99


NICE COMPUTERS No.1 in Kavali

Programs to refer:
1. stacks using array
2. queue using array
3. circular queue
4. Linked list operations.
5. Doubly linked list implementation.
6. Binary Search tree construction

OOPS with Java and DS 100

Вам также может понравиться