Академический Документы
Профессиональный Документы
Культура Документы
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
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()
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”);
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.
C++
C Java
Server
Client
OOPS with Java and DS 8
NICE COMPUTERS No.1 in Kavali
Document Section
Package Statement
Import Statement
Interface Statements
Class Definitions
Remote Remote
JVM Computer (HWR)
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”);
}
}
Step3: The byte code generated by the compiler is executed by the java
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
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
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.
String
Ex: “nice”, “Nice”
Back slash character
Ex: \n, \t, \b, \0, \’, \”, \\
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
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;
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
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
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
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.
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
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);
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;
-------------
-------------
}
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);
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.
Syntax: Example:
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
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
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;
}
};
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)
--------------------
--------------------
}
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));
}
}
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
{
------------
------------
}
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
{
------------
------------
};
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.
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.
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
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[];
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];
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?
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]
x[0]
x[1]
x[2]
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
----------
----------
}
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
Class Number
{
int intValue()
float floatValue()
char charValue()
-------------
-------------
}
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;
};
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; }
} }
}
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.
java
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
UNIT IV
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
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.
th.start();
Runnable Running
5. Dead state:
The thread goes to the killed state either after completion of
thread execution or by calling the stop() method.
Example:
MyThread th1=new MyThread();
th1.setPriority(Thread.NORM_PRIORITY);
th1.start();
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
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
} }
finally catch(Exceptiontype e)
{ {
} }
finally
{
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”);
}
}
}
>javac MyApplet.java
<html>
<head>
<title>Demo of Applet</title>
</head>
<body>
<Applet code=”MyApplet.class” width=300 height=300>
</Applet>
</body>
</html>
>Appletviewer MyApplet.html
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>
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.
Vspace
Hspace
Height
Width
Initializing state
Restart start()
Running state
Object belongs to Graphics
Idle State
destroy()
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
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
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
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
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;
}
}
}
11 23 74 42 65 58
11 23 74 42 65 58
11 23 42 74 65 58
11 23 42 58 65 74
Implementation:
-∞ 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
-∞ 11 22 33 44 66 77 88 55
-∞ 11 22 33 44 55 66 77 88
Implementation:
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
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:
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]
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
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
3 2 5 3 2
Add(5)
Queue overflows
OOPS with Java and DS 80
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
delete
f
40 23 50
r
insert insert
-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
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
head
10 30 50 null
Display()
10 30 45
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);
}
}
}
Case 1: Head
null
delete(10);
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
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;
}
}
Head 20 40 60
append(10);
first last
null 10 null
append(20);
first last
null 10 20 null
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
B C
D E
B C
D E F G
4 8
3 5 7 9
6 6
3 5 7 9
6 6 6 6
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.
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
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)}
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:
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
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
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