Veerachary CBCS JAVA III Sem-Watermark
Veerachary CBCS JAVA III Sem-Watermark
com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
UNIT- I
Basic concepts of Object Oriented Programming (OOPs Concepts):
The basic concepts of OOP:
Objects
Classes
Data Abstraction
Data Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Massage passing
1. Objects: Objects are basic run time entities in an object oriented system. The objects are
representing a person, place, a bank account, and a table of data or any item that the program
may handle.
Objects are chosen such that they match closely with real world objects. Objects takes up
space in the memory and have an associated address. While program is executing the objects
may interact with each other by sending messages. Each object contains data and code to
manipulate the data. Objects are represented as shown below.
Person Object
Name
Basic pay Data
salary()
tax() Methods
2. Classes: A class may be thought of as a “data type” and an object as a “variable” of that type.
(OR) Class is a group of objects that have the same properties. Once a Class has been defined,
we can create any number of objects belonging to that class. A class is thus a collection of
objects of similar type.
Example: mango, orange and apple are members of the class “Fruits”
fruit mango;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 2
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Classes are User-defined data types and behave like the built-in types of programming
language.
3. Data Abstraction: Abstraction refers to the act of representing essential features without
including the background details. Classes use the concept of abstraction.
4. Data Encapsulation: The mechanism of combining the data and methods into a single unit
(called class) is known as Data encapsulation. Data encapsulation is the most striking feature of
a class. The data not accessible to the outside world and only those methods, which are
wrapping in the class, can access it. The insulation of the data from direct access by program is
called Data Hiding.
The figure illustrates, that a single function name can be used to handle different number
and different type of arguments.
6. Inheritance: Inheritance is the process by which objects of one class can acquire the
properties of objects of another class. Inheritance supports the concept of hierarchical
classification.
For example, the bird parrot is derived from the class flying birds, which is again a part
of class bird. Bird
Attributes:
Feathers
Lay eggs
Attributes: Attributes:
Property of Inheritance
Parent
Parent class or Base class or super class Features
Parent
features
Child class or Derived class or sub class
Child features
Inheritance provides the concept 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
(child) from existing one (parent). The new class will have the combined features of both the
classes.
7. Dynamic Binding: Binding refers to the linking of a procedure call to the code to be
executed in response to the call. Dynamic binding means the code associated with a given
procedure call is not known until the time of the call at run time. It is associated with
polymorphism and inheritance.
For example, in the previous example every object have draw( ) method. Draw procedure
will be redefined in each class that defines the object. At runtime the code matching the objects
under current reference will be called.
8. Message Passing: Another important feature of OOPs is massage passing. By using this
facility objects communicate with each other by sending and receiving information much the
same way as people pass messages to one another. This concept makes it easier to talk about
building systems that directly model their real world counter parts. This technique involves the
following 3 steps.
i) Creating classes that define objects and their behavior.
ii) Creating objects from class definition.
iii) Establish communication between objects.
Message Method( )
JAVA HISTORY:
Java is a general purpose; object oriented programming language developed by sun
Microsystems of USA in 1991. Originally called oak by James Gosling, one of the inventors of
the language, java was designed for the development of software for consumer electronic
devices likes TV’s, VCR s, toasters and such other electronic machines.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 5
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
The java team which included Patrick Naughton discovered that the existing languages
like C and C++ had limitations in terms of both reliability and portability. However, they
modeled their new language Java on C and C++ but removed a number of features of C and
C++ that were considered as sources of problems and thus made Java a really simple, reliable,
portable and powerful language.
Java milestones:
YEAR Development
1990 Sun Microsystems decided to develop special software that could be used to
manipulate consumer electronic devices. A team of sun micro systems programmer
headed by James Gosling was formed to undertake this task
1991 After exploring the possibility of using the most popular object-oriented
language C++ , the team announced a new language named “oak”
1992 The team known as Green Project Team by sun, demonstrated the application
of their new language to control a list of home applications using hand-held
device with a tiny touch-sensitive screen
1993 The world wide web (www) appeared on internet and transformed the text-
based internet into a graphical-rich environment. The Green Project team came up
with the Idea of developing Web applets using the new language that could run on
all types of computers connected to internet.
1994 The team developed a web browser called “Hat java’ to locate and run applet
programs on internet. Hot java demonstrated the power of new language, thus
making it instantly popular among the internet users
1995 Oak was renamed “java”, due to some legal snags (problems), Java was just a
name and is not acronym. Many popular companies include Netscape and
Microsoft announced their support of java.
1996 Java established itself not only as leader for internet programming but also as
general-purpose, object-oriented programming language. Sun releases JDK 1.0
1997 Sun releases JDK 1.1
1998 Sun releases Java 2 with version 1.2 of the Software Development Kit (SDK) 1.2
1999 Sun releases Java 2 platform Standard Edition (J2SE) and Enterprise Edition
(J2EE)
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released. This is known as J2SE 5.0
The most powerful feature of Java is that it is a “Platform- Neutral” language. Java is the
first programming language that is not tied to any particular operating system. Programs
developed in Java can be executed anywhere on any system.
Platform-Independent and Portable: The most significant contribution of java over other
languages is portability. Java programs can be easily moved from one computer system to
another, anywhere and anytime. Changes and upgrades in operating systems, processors and
system resources will not force any changes in java programs.
Java ensures portability in two ways. First java compiler generates byte code instructions
that can be implemented on any machine. Secondary, the size of primitive data types are
machine independent.
designed so that it would be easy to translate directly into native machine code for very high
performance by using a just-in-time compiler. Java architecture is also designed to reduce
overheads during runtime.
Dynamic & Extensible: Java is a dynamic language. Java is capable of dynamically linking in
new class libraries, methods and objects.
Java supports functions written in other languages such as C and C++. These functions
are known as native methods.
Differences between Java and C:
Java is a lot like C but major difference between java and C is that Java is an object-
oriented language
Java does not include structures, unions and enum.
Java does not support type def, size of, go to
Java does not define the type modifier keywords auto, extern, register, signed, and
unsigned.
Java does not support explicit pointer.
Java does not include a preprocessor and therefore we cannot use #define, #include,
#ifdef statements.
Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
Java adds new operators such as instance of and >>>.
Java add labeled break and continue statements.
Java adds many features that required for object-oriented programming
Differences between Java and C++:
Java is true object oriented language while C++ basically C with object-oriented extension.
Java appears to be similar to C++ when we consider only the “extension” part of C++.
Listed below are some major C++ features that we intentionally omitted from java or
significantly modified.
Java does not support operator overloading.
Java does not have template classes as in C++.
Java does not support multiple inheritances of classes. This is accomplished using a new
feature called “interface”
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 9
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Java does not support global variables. Every variable and method is declared with in a
class and form part of that class.
Java does not use pointers. C++
There are no header files in java. C
Java
Java
Source
Code
Java
Compiler
Application
Applet Type Type
Output Output
Java Environment
Java environment includes a large number of development tools and hundreds of classes
and methods. The development tools are part of the system known as Java Development Kit
(JDK) and the classes and methods are parts of the Java Standard Library (JSL) also known
as the Application Programming Interface (API).
Java Development Kit (JDK): The JDK comes with a collection of tools that are used for
developing and running Java programs. They include:
1. appletviewer: it enables us to run Java applets.
2. javac (java compiler): which translates Java source code to byte code.
3. java (java interpreter): which runs applets and applications by reading and interpreting
byte code files.
4. javadoc: creates HTML format documentation from java source code files.
5. javah: produces header files for use with native methods.
6. javap (java disassembler): which enables us to convert byte code files into a program
description.
7. jdb (java debugger): which helps us to find errors in our program.
The way these tools are applied to build and run application programs is illustrated in
following figure.
Text Editor
javac
java jdb
Application Program Interface (API): API includes hundreds of classes and methods grouped
into several functional packages. Most commonly used packages are:
1. Language support package: A collection of classes and methods required for
implementing basic features of java.
2. Utilities package: A collection of classes to provide utility functions such as date and
time functions.
3. Input / Output package: A collection of classes required fir input/ output manipulation.
4. Networking package: A collection of classes for communicating with other computer
via internet.
5. AWT package: The Abstract Window Tool kit package contains classes that implements
platform independent graphical user interface.
6. Applet package: This includes a set of classes that allows us to create Java applets.
Installation of Java
The first step in the installation of Java is to download the Java Development Kit (JDK)
from the java.sun.com. We must choose the right version of Java at the time of download
keeping in mind the existing platform. Once the set up file downloaded, we may proceed to
install Java.
To install Java, we need to perform the following steps:
1. Double-click the .exe file to initiate the installation procedure. The welcome screen
appears as shown below.
2. The Welcome screen shows the licensing terms and conditions. Click the Accept button
to begin Java installation. The progress screen appears as shown below.
3. The progress screen depicts the percentage of installation that has been completed. Once
the installation is complete, the complete screen appears as shown below.
4. The Complete screen depicts the successful installation of Java on the computer system.
Click the Finish button to end the installation process.
Byte code
Bytecode is nothing but intermediate representation of Java source code which is
produced by the Java compiler by compiling the source code. This byte code is machine
independent code. It is not a completely compiled code but it is an intermediate code
somewhere in the middle which is later interpreted and executed by JVM.
Bytecode is a machine code for JVM. But the machine code is platform specific whereas
bytecode is platform independent that is the main difference between them. It is stored in
“.class” file which is created after compiling the source code.
Java tokens
Java programs are a collection of classes. The smallest individual unit in the program
is known as token. Java language includes the following tokens:
1. White space, 2. Identifiers, 3. Literals, 4. Operators, 5. Separators, and 6. Keywords.
1. White space: Java is a free-form language. This means that you do not need to follow any
special indentation rules. For example, if the program have been written all on one line or in any
other strange way you felt like typing it, as long as there was at least one white space character
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 14
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
between each token that was not already delineated by an operator or separator. In Java, white
space is a space, tab, or new line.
2. Identifiers: Identifiers are programmer designed tokens. They are used for naming classess,
methods, variables, objects, packages and interfaces in a program.
Thumb Rules: These are the rules to be followed when declaring identifiers.
An identifier can have alphabets, digits and underscore and dollar-sign characters.
They must not begin with a digit.
Java is case-sensitive (uppercase & lowercase letters are distinct), so VALUE is a
different identifier than Value.
Some examples of valid identifiers are:
Avg Temp count a4 $test this_is_ok
Invalid variable names include: 2count high-temp Not/ok
3. Literals: A constant value in Java is created by using a literal representation of it. For
example, here are some literals:
Integer literal: 100
Real (Floating point) literal: 98.6
Single character literal: ‘X’
String literal: “This is a test”
Boolean literal: true (or) false
4. Operators: An operator is a symbol that takes one or more arguments and operates on them
to produce a result.
5. Separators: In Java, there are a few characters that are used as separators. These are used to
indicate where group of code are divided and arranged. The most commonly used separator in
Java is the semicolon.
Symbol Name Purpose
Used to enclose parameters in method definition.
() Parenthesis
. Used to define a block of code for classes and methods.
{} Braces
6. Java Keywords: There are 50 reserved keywords currently defined in the Java language.
Keywords have specific meaning in Java
These keywords cannot be used as names for a variable, Class or method.
All the keywords are to be written in lower-case letters.
Java keywords are:
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Constants in java refer to fixed values that do not change its value during the execution of
a program. Java supports several types of constants they are
JAVA Constants
Single character constant: A single character constant contains a single character enclosed
with in a pair of single quote marks. Examples of character constants are:
‘5’ ‘X’ ‘;’ ‘ ’
The character constant ‘5’ is not same as the number 5. The last constant is blank space.
String Constants: A string constant is a sequence of characters enclosed between double
quotes. The characters may be alphabets, digits, special characters and blank spaces.
Examples of string constants: “Hello java”, “1992”, “14+12”, “...” , “ ”
Boolean constants: Boolean constants are true and false. Java does not use integers to represent
true or false.
Example: boolean x= true;
Backslash character constants: These are used in output methods. These characters are also
known as escape sequences. These constants are given below.
Constant Meaning
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\’ single quote
\” double quote
\\ back slash
Variables
A variable is an identifier that denotes a storage location used to store a constant value.
Unlike constants, a variable may take different values in different times during the execution of
a program. A variable name can be chosen by the programmer in a meaningful way.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 18
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Scope of variables: Scope of a variable determines the area in which a variable can be
accessed. Java variables are actually classified into three types.
1. Instance variables
2. Class variables
3. Local variables
Instance variables: These are declared inside the class and these are created when the objects are
instantiated. They take different values for each object.
Class variables: These are also declared inside the class and are global to the class. And belongs
to the entire set of objects the class creates. They take common value for all the objects.
Local variables: Variables declared and used inside methods are called local variables. These
variables are not available for use outside the method definition. Local variables can also be
declared inside program blocks that are defined between an opening brace {and closing brace}.
Data Types
Every variable in java has a data type. Data type specifies the size and type of
values that can be stored into a variable. Java language is rich in data types. Data types in Java
under various categories are shown below.
Byte Long
Short Int
The below table shows the memory size and range of all four integer data types.
Type Size Minimum value Maximum value
byte 1 byte -128 127
short 2 bytes -32,768 32,767
int 4 bytes –2,147,483,648 2,147,483,647
long 8 bytes –9,223,372,036,854,775,808 9,223,372,036,854,775,807
Floating-Point Type: Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision. There are two kinds of floating-point
types: float and double, which represent single and double-precision numbers respectively.
Floating point data types supports a special value known as Not-a-Number (NaN) for
undefined numbers like zero by zero etc.
Character Data type: In Java, the data type used to store characters is char. char in Java is
not the same as char in C or C++. Java uses Unicode to represent characters. Unicode defines a
fully international character set that can represent all of the characters found in all human
languages.
It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 2 bytes.
Boolean type: Java has a simple type, called Boolean for logical values. It can have only one of
two possible values, true or false. It is used when we want to test a particular condition during
the execution of a program.
Declaration of variables: Variables are the names of storage locations. After designing suitable
variable names, we must declare them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is?
2. It specifies what type of data the variable will hold?
3. The place of declaration decides the scope of a variable.
Syntax: Data type variable1, variable2, variable3, ……… variableN;
Example: int count;
float x, y;
Documentation section
Suggested
Package statement Optional
Import statement Optional
Interface statement Optional
Class definitions
Optional
Main method class
{
Main method definition
Essential
}
Fig : General Structure of a java program
Documentation section: The documentation section comprises a set of comment lines giving
the name of the program, the author and other details, which the programmer would like to refer
to at a later stage.
1) Single line comments: //…………..
2) Multi line comments: /* …………*/ and /** …………. */
Package Statement: The first statement allowed in a java file is a package statement. This
statement declares a package name and informs the compiler that the classes define here belong
to this package.
Example: package student;
Import statement: The next thing after a package statement may be a number of import
statements. This similar to the #include statements in C
Example: import java.io.*;
Interface Statements: An interface is like a class but includes group of method declarations.
This is also an optional section and is used only when we wish to implement the multiple
inheritance features in the program. Interface is a new concept in java.
Class Definitions: A java program may contain multiple class definitions. Classes are the
primary and essential elements of java program. These classes are used to map the objects of
real-world problems.
Main Method Class: Every java stand-alone program requires a main method as its starting
point; this class is the essential part of java program. The main method creates objects of
various classes and establishes communications between them. On reaching the end of main,
the program terminates and control passes back to the operating system.
Simple Java Program:
/* this is a simple Java program */
class Simple
{
public static void main (String args[ ] )
{
System.out.println (" ****** This is my first Java program******");
}
}
Save it as: Simple.java
Compilation: javac Simple.java
Execution: java Simple
Output: ******This is my first Java program******
Class declaration: The first line of the above program class Simple declares a class, which is
an object-oriented construct. class is a keyword and declares that a new class definition follows.
Simple is a java identifier that specifies the name of the class to be defined.
Opening Brace: Every class definition in java begin with an opening brace “ { “ and ends with
matching closing brace } , appearing in the last line in the example. This is similar to C++ class
construct.
The Main Line: The third line of the above program public static void main(String args[ ])
define a method named main . Every java program must include the main( ) method. This line
contains keywords, public, static and void.
public The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all over classes.
static The keyword static, which declares this method as one that, belongs to the
entire class and not a part of any objects of class. The main must always be
declared as static since the interpreter uses this method before any objects
are created.
void The type modifier void states that the main method does not return any
value, but simply prints some text to the screen.
String args[ ] declares parameters named args, which contains an array of objects of the
class type “String”.
The output statement: The only executable statement in the program is
System.out.println(“****** This is my first java program ******”);
This is similar to printf( ) statement of C. In the above statement println( ) method is a
member of the out object, which is static data member of System class.
We must save this program in a file called Test.java ensuring the file name contains the
class name properly. This file called source file. Note that all java source files will have the
extension of “.java”.
Compiling the program: To compile the program, execute the compiler javac, specifying the
name of the source file on the command line, as shown below:
C:\> javac Test.java
If everything is ok, the javac compiler creates a file called Test.class that contains the
byte code version of the program. The Java byte code is the intermediate representation of your
program that contains instructions the Java interpreter will execute.
Running the program: To actually run the program, we must use the Java interpreter called
java. To do so, pass the class name as a command-line argument, as shown here:
C:\>java Test
Now, the interpreter looks for main method in the program and begins execution from
there and produces the output.
Output: Welcome to the world of java
Let us learn java
Source Code
Java Compiler
Byte Code
Giving values to variables: A variable must be given a value after it has been declared but
before it is used in an expression. It is of two types.
1. By using an assignment statement
2. By using a read statement.
By using an assignment statement: A simple method of giving value to a variable is through
the assignment statement as follows.
VariableName= value;
Example: count=100;
X=255.5;
It is also possible to assign a value to a variable at the time of declaration. This process of
giving initial values to variables is known as initialization.
Datatype variablename= value;
Example: int x=10;
By using a read statement: We may also give values to variables interactively through the
keyboard using the readLine( ) method.
Example: // program to read data from the keyboard interactively
import java.io.*
class Addition
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int a, b, c;
System.out.println(“Enter two values”); The interactive input and output of the
a= Integer.parseInt(dis.readLine( )); above program is:
b= Integer.parseInt(dis.readLine( ));
Enter two values
c= a+ b;
10
System.out.println(“Sum=”+c);
20
}
Sum=30
}
Getting values of variables: A computer program is written to manipulate a given set of data
and to display or print the results. Java supports two output methods that can be used to send the
results to the screen.
print( ) method // print and wait
println( ) method // print a line and move to next line
Standard default values: In Java, every variable has a default value. If we don’t initialize a
variable when it is first created, Java provides default value to that variable type automatically
as shown in below table:
Type of variable Default value
byte zero: (byte) 0
short zero: (short) 0
int zero: 0
long zero: 0L
float 0.0f
double 0.0d
char null-character
boolean false
reference null
Naming conventions in Java: Naming conventions are the set of rules to be followed to
give names to the variables, classes and other tokens of a Java program. It is a better
programming practice to follow the naming conventions. The following are the rules suggested
in Java.
Package names in Java are written in all small letters.
Example: java.io, java.awt, java.lang, …..
Each word of a class name and interface name starts with a capital letter.
Example: String, DataInputStream, ….
Method names starts with small letter, then each word that follows starts with a capital
letter.
Example: readLine( ), parseInt( ), …..
Variable names also follow the above rules as methods, words may be separated by
underscore ( _ ).
Example: age, empName, emp_Sal, …..
Constants should be written using all capital letters, words are separated by underscore.
Example: PI, MAX_VALUE, …
All the key words should be written in all small letters.
Example: public, static, void, int, float, ….
Integer Arithmetic: An arithmetic operation involves only integer operands is called integer
arithmetic.
Example: 10+20=30, here 10, 20 are integers.
Real Arithmetic: An arithmetic operation involves only real operands is called real arithmetic.
Example: a=20.5, b=6.4; => a+b= 26.9. Here, a & b are real operands.
Mixed mode Arithmetic: When one operand is real and other is integer then that expression is
called mixed mode arithmetic.
Example: 15/10.0=1.5. here, 15 is integer and 10.0 is real operand.
// Example program for Arithmetic operators.
import java.io.*
class Arith
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis= new DataInputStream(System.in);
int a,b;
System.out.println(“Enter two numbers”);
a=Integer.parseInt(dis.readLine( ));
b=Integer.parseInt(dis.readLine( ));
System.out.println(“Addition=”+(a+b));
System.out.println(“Subtraction=”+(a-b));
System.out.println(“Multiplication=”+(a*b));
System.out.println(“Quotient=”+(a/b));
System.out.println(“Remainder=”+(a%b));
}
}
The output of the program is as follows:
Enter two numbers
20
3
Addition=23
Subtraction=17
Multiplication=60
Quotient=6
Remainder=2
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 29
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Relational operators: These operators are used to compare two quantities depending on their
relation. An expression containing relational operators is called as relational expression.
Operator Meaning
== Equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Example: 4.5<=10 is TRUE
-35>=0 is FALSE
//Example program on Relational operators
import java.io.*;
class Relation
{
public static void main(String args[ ])throws IOException
{
float a=15.0F, b=20.75F, c=15.0F;
System.out.println(“a<b is”+(a<b));
System.out.println(“a>b is”+(a>b));
System.out.println(“a= =c is”+(a= =c));
System.out.println(“a<=c is”+(a<=c));
System.out.println(“a>=b is”+(a>=b));
System.out.println(“b!=c is”+(b!=c));
}
}
The output of above program is:
a<b is true
a>b is false
a= =c is true
a<=c is true
a>=b is false
b!=c is true
Logical operators: In addition to the relational operators, Java has three logical operators.
Which are given below:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
These operators are used to form compound conditions by combining two or more
relations.
Example: a>b && x= =10
Like the simple relational operators, a logical operator also returns either true or false.
Truth table:
Op-1 Op-2 Op-1 && Op-2 Op-1 || Op-2
True True True True
True False False True
False True False True
False False False False
Assignment operators: Assignment operators are used to assign the value of an expression to a
variable. The usual assignment operator is ‘=’. In addition, Java has a set of shorthand
assignment operators which are used in the form
V Op = Exp;
Example: x + = 3 is equal to x = x + 3.
Statement with shorthand assignment operator Statement with simple assignment operator
a+ =1 a=a+1
a - =1 a=a–1
a* =1 a=a*1
a/ =b a=a/b
a% =b a = a% b
Shorthand assignment operators have three advantages.
i) It is easier to write the expression
ii) The statement is more concise and easier to read.
iii) Use of shorthand operator results in a more efficient code.
Increment and Decrement operators:
Increment operator(++): It increments the value of variable by 1 on which it is operating.
There are two types of increment operators. I) pre increment II) post increment.
i) Pre increment operator: It first increment the operand and then the result is assigned to the
variable on the left.
Ex: int x=3, y;
y= ++x;
In the above statement: x value becomes 4 and y takes 4.
ii) Post increment operator: It first assigns the value to the variable on the left and then
increment the operand.
Ex: int x=3, y;
y= x++;
In the above statement: x value becomes 4 but y takes 3.
Decrement operator(- -): It decrements the value of variable by 1 on which it is operating.
There are two types of decrement operators. I) pre decrement II) post decrement.
iii) Pre decrement operator: It first decrement the operand and then the result is assigned to the
variable on the left.
Ex: int x=3, y;
y= - -x;
In the above statement: x=2, y=2
iv) Post decrement operator: It first assigns the value to the variable on the left and then
decrement the operand.
Ex: int x=3, y;
y= x- -;
In the above statement: x=2 but y=3.
Conditional operator: The character pair ?: is the conditional operator. It is also called as
ternary operator because it is used on three operands. The general syntax of the conditional
operator is: exp1 ? exp2 : exp3
The conditional operator works as follows: exp1 is evaluated first, if it is true exp2 is
evaluated and its value becomes the value of expression. If exp1 is false exp3 is evaluated and
its value becomes the value of expression.
Ex: int a=10, b=20, big;
big= (a>b)? a : b;
System.out.println(big); // prints 20
Bitwise operators: Bitwise operators are used to perform operations on bits(0 and 1). They
convert the numbers into binary system and then apply bitwise operators. Bitwise operators may
not be applied to float or double.
Operator Name
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< left shift operator
>> right shift operator
~ complement operator
>>> right shift with zero fill
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 33
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Bitwise OR(|): It returns 1, when both or any one of two bits is 1 otherwise 0.
Ex: x = 1101
y = 1001
x | y= 1101
Left shift operator(<<); It moves the bits towards leftside and 0’s are added from rigrt.
Ex: x = 0000 0000 1011 1101
x<<3 = 0000 0101 1110 1000
Right shift operator(>>): It moves the bits towards right an 0’s are added from left.
Ex: x = 0000 0000 1011 1101
x>>3 = 0000 0000 0001 0111
Right shift with zero fill: When dealing with positive numbers there is no difference between
>> and >>>. When dealing with negative numbers, the >>> operator shifts zeros into all the
upper bits, including high order bit, thus making a negative number into positive.
ii) if…else
iii) nested if….else
iv) else….if ladder
v) switch
II) Looping control structures ( Decision making and Looping (or) Iterative statements)
i) While loop
ii) do while loop
iii) for loop
iv) for each(enhanced for) loop
III) Jumping control Structures
i) break
ii) labelled break
iii) continue
iv) labelled continue
Decision making and Branching statements (or) Conditional control structures:
Branching: When a program breaks the sequential flow and jumps to another part of code is
called as branching.
i) if: The if structure is also called as conditional statement. If the “test expression” is true then
statement-block will be executed. Otherwise the statement-block is skipped and the
execution will jump to the statement-x.
Syntax: Flowchart: entry
test
if( test expression) expression true
?
{
Statement-block
Statement-block; false
}
Statement-x; Statement-x
false
In this type of statement if the test expression is true then the “true-block statements” will
be executed. Otherwise “false-block” statements will be executed.
iii) Nested if…else: Writing of if…else statement in another if or else statement is called as
Nested if…else.
In this, if the condition1 is false statement-3 will be executed; otherwise it continues to
perform condition2. If condition2 is true statement-1 will be executed. Otherwise statement-
2 will be executed and then control is transferred to statement-x.
Syntax: Flowchart:
if(condition1) false true
{ Condition1
if(condition2) ?
{ Statement-1; }
Statement-3
else false true
{ statement-2; } Condition2
} ?
else
{ Statement-2 Statement-1
Statement-3;
}
Statement-x;
Statement-x
else
System.out.println(“Largest value is=”+c);
}
else
{
if(b>c)
System.out.println(“Largest value is=”+b);
else
System.out.println(“Largest value is=”+c);
}
}
}
iv) else…if ladder: There is another way of putting ifs together when multipath decisions are
involved.
Syntax: if(condition1)
statement-1;
else if(condition2)
statement-2;
else if(condition3)
statement-3;
:
:
else if(condition n)
statement-n;
else
default-statement;
statement-x;
This construct is known as else…if ladder. The conditions are evaluated from the top to
downwards. As soon as the true condition is found, the statement associated with it is executed
and the control is transferred to the statement-x. When all the ‘n’ conditions become false, then
the final else containing the default-statement will be executed.
v)
Flow chart:
Entry
True False
Condition1
?
True False
Statement-1 Condition2
?
True False
Statement-2 Condition3
?
True False
Statement-3
Condition n
?
Statement-n default-statement
Statement-x
break;
:
:
default:
default-block;
break;
}
Statement-x;
The “expression” is an expression or characters. Value-1, value-2,….. are the constants
and are known as case labels.
Flow chart:
Entry
expression
expression=value-1 block-1
expression=value-2
block-2
:
(no match found) default
default-block
Statement-x
//Example program to display the name of the day depending on the number entered from
keyboard.
import java.io.*;
class Days
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int day;
System.out.println(“Enter a number between (1-7)”);
day=Integer.parseInt(dis.readLine( ));
switch(day)
{
case 1: System.out.println(“”Monday”);
break;
case 2: System.out.println(“Tuesday”);
break;
case 3: System.out.println(“Wednesday”);
break;
case 4: System.out.println(“Thursday”); The output of the program is:
break; Enter a number between (1-7)
case 5: System.out.println(“Friday”);
2
break;
Tuesday
case 6: System.out.println(“Saturday”);
break;
case 7: System.out.println(“Sunday”);
break;
default: System.out.println(“Number not valid”);
break;
}
}
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 44
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
True
Body of the
Test True
Loop
Condition
False
In the Entry controlled loop, the conditions are tested before the start of the loop
execution. If the conditions are not satisfied then the body of the loop will not be executed.
In the Exit controlled loop, the test is performed at the end of the body of the loop and
therefore the body of the loop is executed unconditionally for the first time.
A looping process would include following four steps:
i) Setting and initialization of a counter
ii) Test for a specified condition for execution of the loop
iii) Execution of the statements in the loop
iv) Increment the counter.
The while is an Entry controlled loop statement. The test condition is evaluated and is the
condition is true then the body of the loop is executed. After execution of the body, the
condition is once again evaluated and if it is true, the body is executed once again. This process
of repeated execution of body continues until the condition is false.
// Example program to print 1 to 10 numbers
class Printing
{
public static void main(String args[ ])
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
do-while loop: It is an Exit controlled loop statement. In some situations it may be necessary to
execute the body of the loop before the test is performed. Such situations can be handled with
the help of do-while statement. The basic form of do-while statement is:
Initialization;
do True
{
Body of the loop Condition
Body of the loop
} while(condition); False
On reaching the do statement, the program proceeds to evaluate the body of the loop first.
At the end of the loop, the condition is evaluated. If the condition is true once again the body of
the loop is executed. This process continues until the condition becomes false.
// Example program to find the sum of natural numbers.
import java.io.*;
class Natural
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
for loop: The for loop is another entry controlled loop, this provide a more concise loop
structure. The basic form of the loop is:
for (initialization ; condition ; increment/decrement)
{
Body of the loop
}
initialization
True
Condition Body of the loop Increment/decrement
False
for each (enhanced for) loop: The enhanced for loop is also called as for each loop. It is
introduced in J2SE 5.0. This is more used with arrays and enumerations. Generally to access
array elements, we use indexes. But using for each, we can directly access each element of the
array without indexes. The basic form of for each loop is:
for (variable: Expression)
{
Statements
}
Example: int x[ ]= {10, 20, 30};
for (int k : x)
System.out.print(k+” “);
The above code prints: 10 20 30.
Nested loops:
If a loop is combined in another loop, it is said to be a nested loop. In a nested loop, the
inner loop gets executed for each iteration of the outer loop. Commonly a “for loop” takes
another for loop within.
Example: Generally to print a double dimensional array we use nested for loop.
Ex: int a[ ][ ]={ {1,2,3}, {4,5,6}, {7,8,9} };
for (int i=0; i<3; i++)
{
System.out.println(“ “);
for(int j=0; j<3; j++)
{
System.out.println(“\t”+ a[i][j]);
}
}
In the above program ‘j’ takes values from 0 to 2 for each iteration of outer loop.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 50
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Labeled break: We can give a label to a block of statements. A label is any valid Java variable
name. To give a label to a loop, place it before the loop with a colon at the end.
Example: Outer: for(int i=1; i<=10; i++)
{
System.out.println(“Hi”);
for(int j=1; j<=10; j++)
{ Output:
System.out.println(“Hello”); Hi
Hello
if( j= =2) Hello
break Outer;
}
}
Continue: It may be necessary to skip a part of the body of the loop under certain conditions.
This can be possible by using continue statement.
Syntax: continue;
Example: class ContDemo
{
public static void main(String args[ ])
{
for(int i=1; i<=5; i++)
{
if(i= =3)
continue;
System.out.print(i);
}
}
}
The above code prints 1 2 4 5. It means 3rd iteration is skipped.
Labeled continue: If we want to jump outside a nested loop or to continue a loop that is outside
the current one, then we use the labeled continue statement.
Example: Outer: for(int i=1; i<11; i++)
{
for(int j=1; j<11; j++)
{
System.out.println(“ ”+(i*j));
if( i= =j)
continue Outer;
}
}
Q: What is a class? And explain about defining a class, creating objects and accessing
class members with examples.
A: A class is a template, blueprint,or contract that defines what an object’s data fields and
methods will be. An object is an instance of a class. You can create many instances of a class. A
Java class uses variables to define data fields and methods to define actions.
A class in Java can be created by using the keyword “class”.
Defining a class:
class classname [extends superclass name]
{
[fields declarations;]
[methods declarations;]
}
In the above syntax “classname” is the name of the class. Everything inside the square
brackets is optional. This means that the following would be a valid class definition.
Example: class Empty
{
}
Because the body is empty, this class does not contain any properties and therefore
cannot do anything.
Fields declaration: It is similar to declaring local variables but they may have access modifiers
like public, private, static and etc.
Example: class Rectangle
{
int length;
int width;
}
These variables are also called as instance variables or member variables.
Methods declaration: A class with only data fields has no life. We must therefore add methods
that are necessary for manipulating the data. Methods are declared inside the body of the class,
but immediately after declaration of instance variables. The general format of a method
declaration is:
type methodname (Parameter_List)
{
Method_body;
}
Method declaration has four parts.
i) The name of the method (methodname)
ii) The type of the value the method returns (type)
iii) A list of parameters (Parameter_List)
iv) The body of the method.
Example: class Rectangle
{
int length;
int width;
void getData (int x, int y)
{
length=x;
width=y;
}
}
If a method does not return any value then the return type is “void”.
Creating objects: Objects in Java are created using the “new” operator. The new operator
creates an object of the specified class and returns a reference to that object.
Syntax: classname objectname= new classname( );
Example: Rectangle rect1= new Rectangle( );
Accessing class members: All variables must be assigned values before they are used. Since
we are outside the class, we cannot access the instance variables and the methods directly. To
do this, we must use the object and the dot operator.
Syntax: objectname. variablename= value;
objectname. methodname(parameterlist);
Example: rect1.length=10;
rect1.getData(10, 11);
Example: class Rectangle
{
int length;
int width;
void getData (int x, int y)
{
length=x;
width=y;
}
int rectArea( )
{
int area=length* width;
return(area);
}
}
class RectArea
{
public static void main(String args[ ])
{
int area1, area2;
Rectangle rect1=new Rectangle( );
Rectangle rect2=new Rectangle( );
rect1.length=15;
rect1.width=10;
area1=rect1.length*rect1.width; Output:
rect2.getData(20,12); Area1=150
area2=rect2.rectArea( );
System.out.println(“Area1=”+area1); Area2=240
System.out.println(“Area2=”+area2);
}
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 55
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Here interface is the keyword and InterfaceName is any valid variable (just like class
name)
Example: interface Area
{
final static float pi=3.14f;
float compute(float x, float y);
}
Implementation of Interfaces: Interfaces are used as “super classes” whose properties are
inherited by classes. This is done as follows:
class classname implements interfacename
{
Body of class;
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 56
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Example program for calculating area of rectangle and circle using interfaces:
interface Area
{
final static float pi=3.14F;
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return (x*y);
}
}
class Circle implements Area
{
public float compute(float x, float y)
{
return (pi*x*x); Output:
} Area of rectangle: 200
}
class InterfaceTest Area of circle: 314
{
public static void main(String args[ ])
{
Rectangle rect = new Rectangle( );
Circle cir = new Circle( );
Area a;
a= rect;
System.out.println(“Area of rectangle:” +a.compute(10,20));
a= cir;
System.out.println(“Area of circle:” +a.compute(10,0));
}
}
A: Java does not provide an explicit way to implement multiple inheritance i.e., a class can
never extend multiple classes. But this can be achieved using interfaces. This possible because
of two reasons
i) A class can implement multiple interfaces
ii) A class can simultaneously extend a class and implement one or more interfaces
The above forms are shown below:
1. interface A 2. class A
{……… {………
} }
interface B interface B
{……… {………
} }
class C implements A, B class C extends A implements B
{……… {………
} }
The following program illustrates how interfaces can be used to simulate multiple
inheritance. The program contains an interface named “Allowance” and classes named
“Employee” and “Salary”.
(Note: this program is also an example for accessing interface variables)
interface Allowance
{ interface class
int da=2000; Employee
Allowance
int hra=3000;
}
class Employee
{ Salary
private int empno;
private String name; class
public void getData(int eno, String n)
{
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 58
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
empno= eno;
name= n;
}
public void show( )
{
System.out.println(“Employee number:” +empno);
System.out.println(“Employee name:” +name);
}
}
class Salary extends Employee implements Allowance
{
private double sal;
Output:
public void getData(int eno, String n, double s)
{ Employee number: 7369
super.getData(eno, n); Employee name: Siri
sal= s;
} Total salary:25000
public void total( )
{
super.show( );
System.out.println(“Total salary:” +(sal+da+hra));
}
}
class Test
{
public static void main(String args[ ])
{
Salary e1= new Salary( );
e1.getData(7396,”Siri”,20000);
e1.total( );
}
}
J2SE 5.0 allows us to use the enumerated type in Java using the “enum” keyword. The
names of an enum type’s fields are generally written in uppercase letters, because they are
constants. Common examples include compass directions (NORTH, SOUTH, and EAST,
WEST) and days of week.
Advantages of using the enumerated type are:
Compile time type safety.
We can use the enum keyword in switch statement.
Efficient.
Consider the following example it specifies a days_of_week using enum type:
Example:
class enumTest
{
enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRI DAY,SATURDAY};
public static void main(String args[ ])
{
for(Days d:Days.values( ))
System.out.println(d);
}
}
Q: Explain Object Oriented Paradigm. (OR) Object orientation.
A:
The major factor in the invention of Object Oriented Approach is to overwrite some false
that are encountered in the Procedure oriented approach.
OOP treats data as critical element in the program development and does not allow it to
move freely around the system.
It tides data more closely to the functions that operate on it and protects it from accidental
modifications from outside functions.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 60
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Function
Data
Object B Object C
Function Function
Data Data
Example:
class Person
{
private int age;
private String name;
void setDetails(int a, String n)
{
age=a;
name=n;
}
void talk( )
{
System.out.println(“My name is:”+name);
System.out.println(“My age is:”+age);
}
}
In this example, we are providing security to the data members by using private keyword,
which means they can not be accessible by outside classes(i.e. Data Hiding).
Polymorphism: Polymorphism is another important OOPs concept. Polymorphism means the
ability to take more than one form. For example, an operation may exhibit different behaviors in
different instances (objects). The behavior depends upon the types of data used in the operation
Example: Consider the operation of addition for two numbers, the operation generates a
sum. If the operands are strings, then the operation would produce a third string by
concatenation Shape
Draw ( )
The figure illustrates, that a single function name can be used to handle different number and
different type of arguments.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 62
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Method overriding takes place only when a method with same signature in present in
both parent and child class.
Example: class One
{
public void show( )
{
System.out.println(“This is parent class”);
}
}
class Two extends One
{
public void show( )
{
System.out.println(“This is child class”);
} Output:
}
class Test This is child class
{ This is child class
public static void main(String args[ ])
{
Two t= new Two( );
t.show( );
t.show( );
}
}
Inheritance: Inheritance is the process by which objects of one class can acquire the properties
of objects of another class. (OR) The mechanism of deriving a new class from an old one is
called Inheritance. Inheritance supports the concept of hierarchical classification.
Inheritance provides the concept 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
(child) from existing one (parent). The new class will have the combined features of both the
classes.
Inheritance provides reusability of the code, which means to reuse something that already
exists rather than writing the same thing again.
It allows modifiability without affecting the existing class.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 64
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
System.out.println(“Hello Alpha”);
}
}
class Beta extends Alpha
{
public void display( )
{
System.out.println(“Hello Beta”);
}
}
class SingleInh
{
public static void main(String args[ ]) Output:
{ Hello Alpha
Beta b1= new Beta( );
b1.show( ); Hello Beta
b1.display( );
}
}
Multi level Inheritance: If a class is derived from the class, which is derived from another
class, it can be called as Multi level inheritance. A Super class
Syntax: class A
{…..
}
class B extends A B Intermediate
{….. Super class
}
class C extends B
{….. C Sub class
}
Example:
class Alpha
{
public void show( )
{
System.out.println(“Hello Alpha”);
}
}
class Beta extends Alpha
{
public void display( )
{
System.out.println(“Hello Beta”);
}
}
class Gamma extends Beta
{
public void show2( )
{
System.out.println(“Hello Gamma”);
}
}
class MultiLevelInh
{
public static void main(String args[ ]) Output:
{ Hello Alpha
Gamma g= new Gamma( );
g.show( ); Hello Beta
g.display( ); Hello Gamma
g.show2( );
}
}
Hierarchical Inheritance: If two or more classes are derived from one super class is known as
Hierarchical Inheritance.
A
Syntax: class A
{…..
}
class B extends A
{…..
} B C D
class C extends A
{…..
}
class D extends A
{…..
}
Hybrid Inheritance: This is the combination of any two types of inheritances. Java does not
support this type of inheritance.
B D
Single inheritance
String stringname;
stringname =new String(“string”);
The two statements may be combined as follows:
String stringname=new String(“string”);
The String class defines a number of methods that allows us to accomplish a variety of
string manipulation tasks.
Method call Task to be performed
s2=s1.toLowerCase( ) Converts the string s1 to all lower case
s2=s1.toUpperCase( ) Converts the string s1 to all Upper case
s2=s1.replace(‘X’, ’Y’) Replaces all appearances of X with Y
s2=s1.trim( ) Remove white spaces at beginning and end of string s1
s1.equals(s2) Returns true, if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns true, if s1=s2, ignoring the case
s1.length( ) Gives the length of s1
s1.charAt(n) Gives nth character of s1
s1.compareTo(s2) Return negative if s1 < s2
Positive if s1> s2
Zero if s1 is not equal to s2
s1.concat(s2) Concatenates s1 and s2
s1.substring(n) Gives substring starting from nth character
s1.substring(n, m) Gives substring starting from nth character to mth
character (not including mth)
String.valueOf(p) Creates a string object of the parameter p
p.toString( ) Creates a string representation of the object p
s1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’
s1.indexOf(‘x’, n) Gives the position of ‘x’ that occurs after nth position
in the string s1.
(Note: Refer practical program no: 4)
Q: Write short notes on StringBuffer class?
A: StringBuffer is a peer class of String. While “String” creates strings of fixed length.
StringBuffer creates flexible length strings and that can be modified in terms of both length
and content. We can insert characters into or delete characters from a string.
Method Task
append( ) Used to concatenate the string in string buffer
insert( ) Used to insert any string at the specified position in the given string
reverse( ) Used to reverse the string present in string buffer
setCharAt( ) Used to set specified character in buffered string at specified position
delCharAt( ) Used to delete the specified character at a given position from the buffered
string
Example:
s1.append(s2) concatenates s1 & s2 strings
s1.insert(n,s2) inserts the string s2 at nth position of s1
s1.reverse( ) reverses the string s1
s1.setCharAt(n,’x’) modifies the nth character to x
s1.delCharAt(n) deletes the character at nth position of s1
(Note: Refer practical program no: 4)
Q: What is the difference between String and StringBuffer?
A: The differences between String and StringBuffer are listed below
StringBuffer objects must be instantiated using “new” but String can also be instantiated
without using “new”.
StringBuffer objects are mutable(self changeable). Whereas, String objects are
immutable.
StringBuffer provides functions like setCharAt( ).delCharAt( ),etc.
StringBuffer allocates extra 16 bytes of memory.
StringBuffer can be treated as a dynamic string.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 71
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Q: What are exceptions and exception handling? What are its advantages?
A: An exception is a condition that is caused by a run-time error in the program. When the
java interpreter encounters an error such as dividing an integer by zero, it creates an exception
object and throws it. If the exception object is not caught and handled properly, the interpreter
will display an error message and will terminate the program.
If we want the program to continue with the execution of the remaining code, then we
should try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This is called as exception handling.
Advantages:
It ensures safer termination of a program.
User has a chance to correct the accidental mistakes while running a program.
The program becomes robust and more user-friendly.
It allows different handling code-blocks for different types of errors.
The error handling code basically consists of two segments, one to detect errors and to
throw the exceptions and the other to catch exceptions and to take appropriate actions.
Exception handling mechanism includes following keyword: try, catch, throw, throws
and finally.
Syntax: try block
Statement that Exception object
try block: “ try” block contains the code in which runtime error may occur. It throws Exception
object. A try block must be followed by at least one catch block or a finally block.
catch block: catch block contains the statements that are used to handle the runtime error. If the
catch parameter matches with the type of exception object, then the exception is caught and the
statements in that catch block will be executed. Otherwise, the exception is not caught and the
default exception handler will cause the execution to terminate.
finally block: the finally block is always executed, regardless of whether or not an exception is
thrown. Writing the finally block for try block is optional unless there is no catch block.
Example: class Error3
{
public static void main(String args[ ])
{
int a=10;
int b=5; Output:
int c=5;
int x, y;. Division by zero
try y=1
{
x=a/(b-c); //Exception here
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
y= a/(b+c);
System.out.println(“y=”+y);
}
}
UNIT-II
Q: What is an Algorithm? And how do you analyse it?
A: An algorithm is a step by step procedure to solve a problem. In normal language,
algorithm is defined as a sequence of statements which are used to perform a task. In computer
science, an algorithm can be defined as follows...
An algorithm is a sequence of unambiguous instructions used for solving a problem,
which can be implemented (as a program) on a computer.
Algorithms are used to convert our problem solution into step by step statements. These
statements can be converted into computer programming instructions which forms a
program. This program is executed by computer to produce solution. Here, program takes
required data as input, processes data according to the program instructions and finally
produces result as shown in the following picture.
Example of Algorithm: Let us consider the following problem for finding the largest value in
a given list of values.
Problem Statement : Find the largest number in the given list of numbers?
Input : A list of positive integer numbers. (List must contain at least one number).
Output : The largest number in the given list of positive integer numbers.
Consider the given list of numbers as 'L' (input), and the largest number as 'max' (Output).
Algorithm:
Step 1: Define a variable 'max' and initialize with '0'.
Step 2: Compare first number (say 'x') in the list 'L' with 'max', if 'x' is larger than 'max',
set 'max' to 'x'.
Step 3: Repeat step 2 for all numbers in the list 'L'.
Step 4: Display the value of 'max' as a result.
Q: What is flowchart?
A: A flowchart is a type of diagram that represents an algorithm, workflow or process,
showing the steps as boxes of various kinds, and their order by connecting them with arrows.
This diagrammatic representation illustrates a solution model to a given problem. Flowcharts
are used in analyzing, designing, documenting or managing a process or program in various
fields.
There are many different types of flowcharts, and each type has its own repertoire of
boxes and notational conventions. The two most common types of boxes in a flowchart are:
a processing step, usually called activity, and denoted as a rectangular box
a decision, usually denoted as a diamond.
Common shapes: The following are some of the commonly used shapes used in flowcharts.
Generally, flowcharts flow from top to bottom and left to right.
Q: What are Arrays? What are the advantages and disadvantages of Arrays?
A: Array is set of values of similar type. Array elements share common name and array
elements are stored in sequential memory locations.
To refer to the elements of array we use indexes. Array indexing starts from “zero”.
Predetermination of array size is must except in the case of giving values at time of declaring an
Array.
Advantages(Pros) of Arrays:
It is capable of storing many elements at a time.
It allows random accessing of elements using indexes.
Disadvantages(Cons) of Arrays:
Predetermining the size of array is must.
There is a chance of memory wastage.
To delete one element in the array, we need to traverse (visit) throughout the array.
To insert element into the array, we need to traverse throughout the array.
Q: What are the types of Arrays and how to create and initialize one dimensional Array?
A: Array is set of values of similar type. Array elements share common name and array
elements are stored in sequential memory locations.
Arrays can be of many types they are:
One dimensional arrays(1-D)
Two dimensional arrays(2-D) and
Multi dimensional Arrays(N-D)
One dimensional Array: An array with only one subscript is called as single subscripted
variable (or) one dimensional Array.
Creation of Arrays: Creation of Array involves three steps. They are:
1) Declaring an Array (or) Declaration of Arrays
2) Creating memory locations
3) Putting values in to the memory locations
Declaration of Arrays: Arrays in java may be declared in two forms
Syntax: type arrayname[ ]; (or) type[ ] arrayname;
*** In Java, all arrays store the allocated size in a variable named “length”. We can obtain the
length of the array “a” using “a.length”.
Multi dimensional Arrays: Multi dimensional arrays usemore than two indexes to refer to its
elements. Generally, it represents a set of matrices.
For example, in Java a Three-dimensional Array can be declared as follows:
Syntax: type arrayname[ ][ ][ ]= new type[size][size][size];
(or)
type[ ][ ][ ] arrayname= new type[size][size][size];
Address of an element of an array say “A[ I ]” is calculated using the following formula:
Address of A [ I ] = B + W * ( I – LB )
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)
Example: Given the base address of an array B[1300…..1900] as 1020 and size of each
element is 2 bytes in the memory. Find the address of B[1700].
Solution:
The given values are: B = 1020, LB = 1300, W = 2, I = 1700
Address of A [ I ] = B + W * ( I – LB ) = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]
Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:
(1) Row Major System
(2) Column Major System
Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix
Important: Usually number of rows and columns of a matrix are given ( like A[20][30] or
A[40][60] ) but if it is given as A[Lr- – – – – Ur, Lc- – – – – Uc]. In this case number of rows
and columns are calculated using the following methods:
Number of rows (M) will be calculated as = (Ur – Lr) + 1
Number of columns (N) will be calculated as = (Uc – Lc) + 1
Examples:
An array X [-15……….10, 15……………40] requires one byte of storage. If beginning
location is 1500. Determine the location of X [15][20].
Solution:
As you see here the number of rows and columns are not given in the question. So they are
calculated as:
Number of rows say M = (Ur – Lr) + 1 = [10 – (- 15)] +1 = 26
Number of columns say N = (Uc – Lc) + 1 = [40 – 15)] +1 = 26
(i) Column Major Wise Calculation of above equation
The given values are: B = 1500, W = 1 byte, I = 15, J = 20, Lr = -15, Lc = 15, M = 26
Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]
= 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)]
= 1500 + 1 * [30 + 26 * 5] = 1500 + 1 * [160]
= 1660 [Ans]
(ii) Row Major Wise Calculation of above equation
The given values are: B = 1500, W = 1 byte, I = 15, J = 20, Lr = -15, Lc = 15, N = 26
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)]
= 1500 + 1 * [26 * 30 + 5] = 1500 + 1 * [780 + 5]
= 1500 + 785
= 2285 [Ans]
Q: What is a stack?
A: Stack is a linear data structure in which elements are added and removed from only one
end. It is a structure, which works on the LIFO (Last In-First Out) principle.
In a stack, the elements are added at the top and removed from the top.
Graphical representation: Push Pop
Top
The top pointer should initially stored with’-1’, which indicates the “stack is empty”
Before inserting an element into the stack, a condition should be checked whether the
stack is full or not.
If stack is full then print the message “stack is full”. Otherwise, increment the top pointer
by one and insert the element into the stack.
Before deleting an element from the stack, a condition should be checked. Whether the
stack is empty or not.
If empty, then print a message “stack is empty”, otherwise delete the element to which
top pointer is currently pointing and decrement the top by 1.
Example: push(10) 4 push(20) 4 push(30) 4
3 3 3
30
2 2 2
1 20 1 20 1
top=0 10 0 top=1 10 0 top=2 10 0
push(40) 4 push(50) 50 4
40 3 40 3
2 30 2
30
1 1
20 20
top=3 0 top=4 0
10 10
Now, stack is pointing to the maximum position of array, since stack is full, and we
cannot insert items into the stack.
If we perform delete operation on the above stack, the top element 50 is deleted and top is
decremented by 1.
pop( ) 4 pop( ) 4
40 3 3
30 2 30 2
20 1 20 1
top=3 10 0 top=2 10
0
Program to implement PUSH and POP operations on stack using array method.
class Stack
{
private static int MAX=5;
private int a[ ]=new int[MAX];
int top;
Stack( )
{
top= -1;
}
public void push(int v)
{
if(top>=MAX)
System.out.println("Stack is full");
else
{
top++;
a[top]=v;
}
}
public void pop( )
{
if(top= = -1)
System.out.println("Stack is empty");
else
{
System.out.println("Element deleted is:"+a[top]);
top- -;
}
}
public void display( )
{
if(top= = -1)
System.out.println("Stack is empty");
else
{
System.out.println("Stack elements:");
for(int i=top;i>=0;i- -)
System.out.println(a[i]);
}
} Save: StackArray.java
} Compilation: javac StackArray.java
class StackArray Execution: java StackArray
{ Output: Stack elements:
public static void main(String args[ ]) 50
{ 40
Stack s=new Stack( ); 30
s.push(10); 20
10
s.push(20); Element deleted is:50
s.push(30); Stack elements:
40
s.push(40); 30
s.push(50); 20
10
s.display( );
s.pop( );
s.display( );
}
}
) ab+ Empty
* ab+ *
c ab+c *
+ ab+c* +
d ab+c*d +
* ab+c*d +*
e ab+c*de +*
End ab+c*de*+ Empty.
UNIT-III
Q: What is recursion? And ow to use stack in Recursion? (OR) Execution of recursive
calls.
A: If a function is called within the same function, is said to be recursion. It means
recursion is the process by which a function calls itself; such function is called as recursive
function.
All recursive fumctions must have the following.
1. Base case (when to stop)
2. Work towards base case
3. Recursive call
Example:
factorial(5) = 5*4*3*2*1
again 4*3*2*1 is equal to (5-1) i.e 4!
From this we can write, factorial (5) =5*factorial(4)
=5*4*factorial(3)
=5*4*3*factorial(2)
=5*4*3*2*factorial(1)
=5*4*3*2*1
Code for the above example is:
public int factorial(int n)
{
if(n= =0 || n= =1)
return (1);
else
return(n*factorial(n-1)); //recursive call
}
Every call to the method creates a new set of local variables in the stack. So with the help
of stack only we can execute the recursive functions. Even sequence of function calls also gets
executed with the help of stacks.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 97
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
n=1
return to Funtion
n=2 n=2
return to Funtion return to Funtion
n=3 n=3
n=3
return to Funtion return to Funtion
return to Funtion
n=4 n=4
n=4 n=4
return to Funtion return to Funtion
return to Funtion return to Funtion
Initial After 1st recursion 2nd recursion 3rd recursion 4th recursion
n=1
return to Funtion
n=2 n=2*1=2
return to Funtion
return to Funtion
n=3 n=3 n=3*2=6
return to Funtion return to Funtion
return to Funtion
n=4 n=4 n=4
n=4*6=24
return to Funtion return to Funtion
return to Funtion return to Funtion
n=5 n=5 n=5 n=5 n=5*24=120
th
4 recursion Result
Linear recursion: If a function is called itself only once then such functions are said to be
linear recursive functions.
void main( )
{
A( );
}
void A( )
{
:
A( );
:
}
Non-Linear recursion: If a function is called itself more than one time such functions are said
to be non-linear recursive functions.
void main( )
{
A( );
}
void A( )
{
A( );
:
A( );
:
}
Front rear
end end
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 100
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
0 1 2 3 4
i) Add 10 to this queue.
10
0 1 2 3 4
front=0
rear=0
0 1 2 3 4
front rear
0 1 2 3 4
front rear
iv) Now delete an element:
20 30
0 1 2 3 4
front rear
Program to implement Queue using array method.
class Queue
{
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 102
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
..
. front rear
Dequeue (Double Ended Queue): In this insertion and deletion occur at both the ends i.e. front
and rear end of the queue.
Insertion deletion
Data Link
Double linear linked list: In this every node, consist of three parts; information and two
reference parts. Left link stores the address of previous node and right link store the address of
next node. It allows two-way and linear traversal in the list.
node1 node2 node3
null Data Right Left Data Right Left Data null
Link Link Link Link
Double circular linked list: In this every node consists of three parts; information and two
reference parts. It allows two-way and circular traversal in the list.
node1 node2 node3
Left Data Right Left Data Right Left Data Right
Link Link Link Link Link Link
Node1
Now, we add one more node to the list with the data 20 and later 30, 40 then the list will
be: 1010 1020 1030 1040
10 1020 20 1030 30 1040 40 NULL
Node1
Now, we can add one more data 20 and later 30, 40, and then the list will be:
1010 1020 1030 1040
NULL 10 1020 1010 20 1030 1020 30 1040 1030 40 NULL
L 0
node1 node2 node3 node4
Inserting a node:
Take a reference part named “ptr” and move it from first node to a node that is prior to
the inserting position.
Allocate memory for a temporary node, read information.
Make links as shown in the diagram.
Handle it differently if it is insertion at last node.
1010 1020 1030 1040
NULL 10 1020 1010 20 1050 1050 30 1040 1030 40 NULL
1020 25 1030
Deleting a node: Take a reference part named “ptr” and move it from first node to a node that
is prior to the deleting position. Disconnect the link between the nodes and establish new link
between the nodes that are present before and after the deleted node.
Head=1010
Top=1010
push(20): 1010 1020
10 1020 20 NULL
Head=1010
Top=1020
push(30) 1010 1020 1030
10 1020 20 1030 30 NULL
Head=1010
Top=1030
Now, we perform pop( ) operation on the above linked stack:30 is deleted.
pop( ): 1010 1020
10 1020 20 NULL
Head=1010
Top=1020
pop( ): 1010
10 NULL
Head=1010
Top=1010
If we perform again pop( ) operation on the above Stack, the linked stack is empty, i.e.
Head=NULL, Top=NULL.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 112
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Queues using linked list: Queue can also be implemented using linked list and known as
“linked Queue”. Linked Queue requires two pointers. Initially these pointers are stored with
NULL.
Front pointer always stores the address of first node and
Rear pointer stores the address of last node.
Example: Let us draw a linked queue and insert some nodes into the linked queue.
insert(10): 1010
10 NULL
front=1010
rear=1010
insert(20): 1010 1020
10 1020 20 NULL
front=1010
rear=1020
insert(30) 1010 1020 1030
10 1020 20 1030 30 NULL
front=1010
rear=1030
Now, we perform qdelete( ) operation on the above linked queue:10 is deleted.
qdelete( ): 1020 1030
20 1030 30 NULL
front=1020
rear=1030
qdelete( ): 1030
30 NULL
front=1030
rear=1030
If we perform again deletion operation on the above Queue, the linked queue is empty,
i.e. front=NULL, rear=NULL.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 113
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
UNIT-IV
Q: What is a tree? Explain tree terminology?
A: A tree is a finite set of nodes and it has a unique node called the “root” node.
root
A Level1
B C Level2
D E F G Level3
H I J K Level4
40
35 56
22 48 65
28
Advantages:
Searching in binary tree becomes faster.
Binary tree provides 6 traversals.
Two of six traversals give sorted order of the elements.
Maximum and minimum elements can be directly picked up.
10
8 15
5 12 20
9
1 18 30
Insertion:
First, check whether the element is less than or greater than the root element.
If the element is less than root, continue with left sub tree.
If the element is greater than root, continue with right sub tree.
Repeat the above two steps till an empty node encounters.
Create a node and insert it there.
Traversing: Traversing is a method of visiting every node in a specific order. The main three
traversals of a binary tree are:
i) In order.
ii) Pre order.
iii) Post order.
In order traversal: It gives us element in ascending order. In order traversal follows LVR
method (L-left, V-Visit vertex, R-Right).
1) Move to the root node of a tree.
2) Move to its left node if exists.
3) Repeat the second step till a node with no left encounters.
4) Now, print the element and move to right if it exists.
5) Repeat the above three steps for all pending nodes in a stack manner.
LVR(tree t)
{
if(t)
{
LVR(t.left);
System.out.println(t.x);
LVR(t.right);
}
}
Pre order traversal: It follows VLR method.
1) Move to the root node of a tree.
2) Print the element and move to left node if exists.
VLR(t);
}
public void showLRV( )
{
System.out.println("\nLRV :\n");
LRV(t);
}
tree insert(tree t, int v)
{
if(t= =null)
{
t = new tree( );
t.x = v;
t.left = null;
t.right = null;
}
else if(v<t.x)
t.left = insert(t.left, v);
else if(v>t.x)
t.right = insert(t.right, v);
return t;
}
public void LVR(tree t)
{
if(t!= null)
{
LVR(t.left);
System.out.print("\t"+t.x);;
LVR(t.right);
}
}
public void LRV(tree t)
{
if(t!= null)
{
LRV(t.left);
LRV(t.right);
System.out.print("\t"+t.x);
}
}
.’. G= (V, E)
Vertices are also called as nodes or points, displayed as circles.
Edges are called as lines or arcs.
An edges with orientation ( ) is directed edge, while an edge with no orientation ( -- ) is
undirected edge.
Types of graphs:
1. Directed graph: If every edge in the graph is directed edge, then that graph is called as
directed graph. A B
V= {A, B, C, D, E } C D
E={ (A, B), (A, C), (A, E), (B, D), (C, E), (D, E)} E
2. Undirected graph: Undirected graph is a graph, in which every edge has no direction.
V= {v1, v1, v3, v4} v1 v2
E={(v1,v2),(v1,v3),(v2,v1),(v2,v4),(v3,v1),(v3,v4),v4,v2),(v4,v3)} v3 v4
3. Connected graph: A graph ‘G’ is connected if there is a path between every pair of
vertices.
4. Sub graph: Sub graph is a graph in which vertex& edge sets are sub sets of G.
5. Trivial graph: It is a graph with only one vertex without any edge.
6. Complete graph: A graph G is said to be complete graph with ‘n’ vertices has n(n-1)/2
edges.
7. Weighted graph: A graph ‘G’ is weighted, if each edge in G is assigned a non negative
numerical value. 15 20
8. Connected directed graph (or) strongly connected graph: A directed graph ‘G’ is said
to be strongly connected, if for each pair of vertices (v1, v2) there is a path from v1 to v2
and v2 to v1.
A B
10.Insolated node: A node which is not adjacent to any other node is called isolated node.
11.Null graph: A graph containing only isolated nodes is called a Null graph.
A B
C D
Applications of graphs: Graphs are used in many applications. They are used in
i) Analysis of electrical networks.
ii) Study of molecular structure.
iii) The representation of airlines routes.
iv) Networks.
v) Topological sorting.
vi) Finding shortest paths.
Q: What are the operations of Graph ADT?
A: The Graph ADT refers to all vertices of graphs, whether directed, undeirected,
weightedor unweighted.
4. vertices( ): returns the number of vertices in the graph.
5. edges( ): returns the number of edges in the graph.
6. existsEdge(i, j) ): returns true if edge(i, j) exists, false otherwise.
7. putEdge( ): puts the edge into the graph.
8. removeEdge(i, j): removes the edge (i, j).
9. degree(i): returns the degree of the vertex i, defined only for undirected graphs.
10.inDegree(i): returns the in-degree of vertex i.
11.outDegree(i): returns the out-degree of vertex i.
Adjacency matrix: In this representation the size of square matrix is taken as equal to the
number of vertices in the given graph. The elements of adjacency matrix are filled with either 1
or 0. If an edge is presented between (Vi, Vj) then the element is filled with 1. Otherwise the
element value is set with’0’.
G Graph
V Set of Vertices
(i, j) Edge connecting Vi and Vj
A[i][j] Adjacency matrix element
i, j Vertices
If ‘G’ is a digraph:
1 if (i, j) exists
A[i][j] = 0 otherwise
If ‘G’ is a undirected graph:
1 if (i, j) or (j, i) exists
A[i][j] = 0 otherwise.
Example: 1 2 3 4
1) 1 V={ 1, 2, 3, 4} 1 0 1 0 1
2
E= {(1, 2), (1,4), (2,4), (3,1), 2 0 0 0 1
(3,2), (4,3)} 3 1 1 0 0
3 4 4 0 0 1 0
Directed graph
v1 v2 v3 v4 v5
V1 V2 V={ v1, v2, v3, v4}
2)
E= {(v1, v2), (v1, v3), (v2, v1), v1 0 1 1 0 0
v2 1 0 1 0 0
V3 (v2, v3), (v3, v1), (v3, v2)
(v3, v4), (v3, v5), (v4, v3) v3 1 1 0 1 1
V5 v4 0 0 1 0 1
V4 (v4, v5), (v5, v3), (v5, v4)}
v5 0 0 1 0 1
Undirected graph
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 124
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Adjacency Lists: Graphs can be represented as adjacency lists that use arrays of linked lists.
Example: vertices
1 2 3 4 null
1 V={ 1, 2, 3, 4}
E= {(1,2), (1,3), (1,4),
2 1 3
null
(2,1), (2,3), (3,1) 3 null
2 3 1 2 4
(3,2), (3,4), (4,1)
(4,3) } 4 1 3 null
4
Undirected graph
vertices
1 V={ 1, 2, 3, 4} 2 3
1 null
E= {(1,2), (1,3), (2,4),
(3,2), (4,3) } 2 4 null
2 3
3 2 null
4
4 3 null
Directed graph
Q: Explain Graph traversals (or) Explain depth first and breadth first search methods.
A: There are any mainly two methods for traversing in a graph.
i) DFS(Depth First Search)
ii) BFS(Breadth first search)
DFS: It uses STACK to hold the nodes that are waiting to be processed
First we examine the starting node ‘A’.
Then we examine each node along a path ‘P’, which begins at ‘A’ .i.e. we process one of
the neighbors of ‘A’ and continue along the path.
After coming to the end of ‘P’. we back track on ‘P’ until we can continue along another
path.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 125
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
1 6 7
A D G
2 9 8 Result: ABCFIDGHE
B E H
3 4 5
C F I
Algorithm:
1. Initialize all nodes to ready state.
2. Start with a node and push the node ‘A’ in the stack.
3. POP the top node ‘X’ from the stack. Print X.
4. Push all its neighbors omitting the processed ones in to the Stack.
5. Repeat the above two steps till all the elements of graph are visited.
6. Pop all the elements of the stack and print them to complete DFS.
Pseudo code to implement DFS (Depth First Search)
void DepthFirst(Graph G)
{
boolean visited[MAX];
int v;
for(all v in G)
visited[v]=FALSE;
for(all v in G)
if(!visited[v])
traverse(v);
}
void traverse(int v)
{
int w;
visited[v]=TRUE;
visit(v);
for( all w adjacent to v)
if(!visited[w])
traverse(w);
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 126
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
2 3 7 Result: ABEDCGHFI
B E H
5 8 9
C F I
Algorithm:
1. Initialize all nodes to ready state.
2. Start with a node and place it in the Queue.
3. remove an element ‘X’ from queue and Print X.
4. Place all its neighbors omitting the processed ones in the Queue
5. Repeat the above two steps till all the elements of graph are visited.
6. Delete all the elements of the queue and print them to complete BFS.
Pseudo code to implement BFS (Breadth First Search):
void BreadthFirst(Graph G)
{
Queue q;
boolean visited[MAX];
int v,w;
for(all v in G)
visited[v]=FALSE;
initialize(q);
for(all v in G)
{
if(!visited[v])
{
addQueue(v,q);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 127
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
do
{
deleteQueue(v,q);
visited[v]=TRUE;
visit(v);
for( all w adjacent to v)
if(!visited[w])
addQueue(w);
}while(!empty(q));
}
}
}
2 2
3 4 5 3
6
1 1
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 128
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
There are two different algorithms to find out minimum spanning tree:
Kruskal’s algorithm
Prim’s algorithm
Step- 1: step- 2:
Select v1 and update the Select v4 the vertex whose
adjacent vertex weights. weight is minimum and
update the adjacent vertex
weights.
Vertex Visited Dist Path Vertex Visited Dist Path
V1 T 0 V1 V1 T 0 V1
V2 F 2 V1 V2 F 2 V1
V3 F 4 V1 V3 F 4 V1
V4 F 1 V1 V4 T 1 V1
V5 F X - V5 F 2 V4
V6 F X - V6 F 2 V4
V7 F X - V7 F 3 V4
Step- 3: Step- 4:
Select v2 the vertex whose weight Select v5 the vertex whose weight
is minimum and update the is minimum and update the
adjacent vertex weights. adjacent vertex weights.
Vertex Visited Dist Path Vertex Visited Dist Path
V1 T 0 V1 V1 T 0 V1
V2 T 2 V1 V2 T 2 V1
V3 F 4 V1 V3 F 4 V1
V4 T 1 V1 V4 T 1 V1
V5 F 2 V4 V5 T 2 V4
V6 F 2 V4 V6 F 2 V4
V7 F 3 V4 V7 F 3 V4
Step- 5: Step- 6:
Select v6 the vertex whose weight Select v7 the vertex whose weight
is minimum and update the is minimum and update the
adjacent vertex weights. adjacent vertex weights.
Vertex Visited Dist Path Vertex Visited Dist Path
V1 T 0 V1 V1 T 0 V1
V2 T 2 V1 V2 T 2 V1
V3 F 4 V1 V3 F 4 V1
V4 T 1 V1 V4 T 1 V1
V5 T 2 V4 V5 T 2 V4
V6 T 2 V4 V6 T 2 V4
V7 F 1 V6 V7 T 1 V6
V3 T 4 V1
V4 T 1 V1 2
V5 T 2 V4
1
V6 T 2 V4 V6 V7
V7 T 1 V6
Total cost= 2+4+1+2+2+1=12
The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will
be having (9 – 1) = 8 edges.
After sorting:
Weight Src Dest
1 7 6
2 8 2
2 6 5
4 0 1
4 2 5
6 8 6
7 2 3
7 7 8
8 0 7
8 1 2
9 3 4
10 5 4
11 1 7
14 3 5
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 131
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Now pick all edges one by one from sorted list of edges
6. Pick edge 8-6: Since including this edge results in cycle, discard it.
8. Pick edge 7-8: Since including this edge results in cycle, discard it.
10. Pick edge 1-2: Since including this edge results in cycle, discard it.
Since the number of edges included equals (V – 1), the algorithm stops here.
Example: 0 1 2 3 4
a 6 10 3 15 25
In the above array, we would like to search key=15. The comparison starts from first
element as shown below.
0 1 2 3 4
a 6 10 3 15 25
key
Here, key is not equal to a[0], compare with next element.
0 1 2 3 4
a 6 10 3 15 25
key
Here, key and a[1] are not equal, compare with next element.
0 1 2 3 4
a 6 10 3 15 25
key
Here, key and a[2] are not equal, compare with next element.
0 1 2 3 4
a 6 10 3 15 25
key
Here, key and a[3] values are equal. So the key element is found in the 3rd index position.
Searching is not completed yet, compare with the last element.
0 1 2 3 4
a 6 10 3 15 25
key
Here, key is not equal to a[4]. Now searching is complete. Our key value is found at 3 rd
index position.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 134
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
Steps:
First step in binary search is that the list should be properly ordered i.e. sorted into ascending
order.
Then compare the key element with middle element.
If both are equal then the number we are searching is found and searching complete,
otherwise continue searching.
If key is not equal to the middle element then see whether the key is less than or greater than
the middle element.
If the key is less than middle element then the key can be found left side of middle element.
Since we take the left side list which is less than middle element.
If the key is greater than the middle element then the key can be found right side of middle
element. Since we take the right side list which is greater than middle element.
Again compare the key value with the middle element in the new list and repeat the same
steps until key is found in the list or list get empty.
Ex: Assume that we want to search the number 60 in the following list of numbers present in
the array, i.e. key=60.
0 1 2 3 4 5 6 7 8 9
a 30 60 10 80 20 100 40 70 50 90
5 6 7 8 9
a 60 70 80 90 100
high = n-1;
mid = (low+high)/2;
while( low <= high)
{
if ( key= =a[mid])
{
System.out.println("Element found at"+mid+" index position");
found = 1; Output:
break; Enter size of the array
} 10
else if( key<a[mid] )
Enter elements in sorted order
{
10
high = mid-1;
20
}
30
else if( key>a[mid] )
{ 40
low = mid+1; 50
} 60
mid = (low+high)/2; 70
} 80
if ( found= =0) 90
System.out.println(" element not found"); 100
} Enter searching element
} 60
Element found at 5 index position
Q: What is sorting? What are different sorting techniques?
A: Sorting is a process used to arrange the array elements in a specific order i.e. either
ascending or descending. There are several techniques:
i) Bubble sort
ii) Selection sort
iii) Insertion sort
iv) Quick sort
v) Merge sort
vi) Heap sort, etc.
Consider an example: int a[5]={6,4,7,1,5};
After sorting the elements in ascending order, the elements will be: {1, 4, 5, 6, 7}.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 138
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
4 6 6 6 6 6 6 4 4 4 4 4 4 4
7 7 7 7 7 7 7 7 7 7 6 5 5 5
1 1 1 4 4 4 4 6 6 6 7 7 7 6
5 5 5 5 5 5 5 5 5 5 5 6 6 7
int i, j, n, temp;
System.out.println("How many values:");
n=Integer.parseInt(dis.readLine( ));
int a[ ]=new int[n];
System.out.println("Enter Values:");
for(i=0; i<n; i++)
a[i]=Integer.parseInt(dis.readLine( ));
for(i=0; i<n-1; i++)
for(j=i+1; j<n; j++)
if(a[i]>a[j])
{
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
System.out.println("After Sorting:");
for(i=0; i<n; i++)
System.out.print("\t"+a[i]);
}
}
Save: BubbleSort.java
Compilation: javac BubbleSort.java
Execution: java BubbleSort
Output: How many values:
5
Enter Values:
12
4
16
8
20
After Sorting: 4 8 12 16 20
Procedure:
In this technique, take any element (key), compare with its previous elements until it
finds the key element value is greater than other element.
If key element value is less than the other element, then swap them.
This procedure should be continued until all elements in the array are sorted.
6 4 4 4 4 4 4 1 1 1 1
4 6 6 6 6 6 1 4 4 4 4
7 7 7 7 7 1 6 6 6 6 5
1 1 1 1 1 7 7 7 7 5 6
5 5 5 5 5 5 5 5 5 7 7
for(j=i; j>0; j- -)
{
if(t<a[j-1])
a[j]=a[j-1];
else
break;
}
a[j]=t;
}
System.out.println("After Sorting");
for(i=0; i<n; i++)
System.out.print("\t"+a[i]);
}
}
Save: InsSort.java
Compilation: javac InsSort.java
Execution: java InsSort
Output: How many values:
5
Enter Values:
24
65
12
36
42
After Sorting 12 24 36 42 65
Q: Explain the procedure for selection sort.
A: It is efficient on large lists, and generally performs worse than insertion sort. The
selection sort performs the same number of comparisons as the bubble sort: n*(n-1)/2.
Procedure:
In this sorting technique, first element value is considered as minimum and this minimum
value is compared with remaining elements of the same array.
While comparing, if you find the index whose value is less than the first element and
minimum of remaining elements, then swap the values. After swapping the first element
got the proper position.
Now take the second element as minimum value and compared with remaining elements
and you finds the index whose value is less than second element and minimum of
remaining elements, and then swap them.
The same procedure continued until all elements are sorted.
6 6 6 6 1 1 1 1 1 1 1 1
4 4 4 4 4 4 4 4 4 4 4 4
7 7 7 7 7 7 7 7 7 7 7 5
1 1 1 1 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5 5 7
k=i;
for(j=i+1; j<n; j++)
{
if(a[j]<min)
{
min= a[j];
k= j;
}
}
t= min;
a[k]= a[i];
a[i]= t;
}
System.out.println("After Sorting:");
for(i=0; i<n; i++)
System.out.print("\t"+a[i]);
}
}
Save: SelSort.java
Compilation: javac SelSort.java
Execution: java SelSort
Output: How many values:
5
Enter Values:
50
30
10
20
40
After Sorting: 10 20 30 40 50
Procedure:
Pick an element, called a “pivot” from the list (here we are choosing last element).
Reorder the list so that all elements which are less than the pivot come before the pivot
element and the elements greater than pivot comes after it.
After this partitioning, the pivot is in its proper position.
Recursively sort the sub-list of lesser elements and the sub-lists of greater elements.
Example: The quick sort takes the last element (9) and places it such that all the numbers in the
left sub-list are smaller and all the numbers in the right sub-list are bigger. It then quick sorts
the left sub-list ({1}) and then quick sorts the right sub-list ({63, 72, 64, 58, 14, 27}) in similar
fashion. This is a recursive algorithm, since it is defined in terms of itself. This reduces the
complexity of programming.
Initial Data 27 63 1 72 64 58 14 9
1st pass 1 <9> 63 72 64 58 14 27
63 72 64 58 14 27
14 < 27 > 72 64 58 63
2nd pass 1 9 14 27 72 64 58 63
72 64 58 63
58 < 63 > 64 72
3rd pass 1 9 14 27 58 63 64 72
(Note: Refer practical program no:18)
Algorithm:
STEP 1: Logically, think the given array as Complete Binary Tree.
STEP 2: For sorting the array in ascending order, check whether the tree is satisfying Max-
heap property at each node, (For descending order, Check whether the tree is satisfying Min-
heap property).Here we will be sorting in Ascending order.
STEP 3: If the tree is satisfying Max-heap property, then largest item is stored at the root of the
heap. (At this point we have found the largest element in array, Now if we place this element at
the end(nth position) of the array then 1 item in array is at proper place).We will remove the
largest element from the heap and put at its proper place(nth position)inarray.
After removing the largest element, which element will take its place?
We will put last element of the heap at the vacant place. After placing the last element at
the root, The new tree formed may or may not satisfy max-heap property. So, If it is not
satisfying max-heap property then first task is to make changes to the tree, So that it satisfies
max-heap property.
(Heapify process: The process of making changes to tree so that it satisfies max-heap
property is called heapify). When tree satisfies max-heap property, again largest item is stored
at the root of the heap. We will remove the largest element from the heap and put at its proper
place(n-1 position) in array.
Repeat step 3 until size of array is 1 (At this point all elements are sorted.)
Efficiency of Insertion sort: Let us now analyze the efficiency of the bubble sort. We can
easily understand from the algorithm that is first pass of the program does (n-1) comparisons.
The next pass of the program does (n-2) comparisons and so on. The total number of
comparisons at the end of sort would be:
=(n-1)+(n-2)+(n-3)+…………..+3+2+1.
=n*(n-1)/2
=n2 i.e. Time complexity =O(n2)
Efficiency of Merge sort: It is O(nlogn). Merge sort is a divide and conquer algorithm. Think
of it in terms of 3 steps.
1. The divide step computes the midpoint of each of the sub-arrays. Each of this step just
takes O(1) time.
2. The conquer step recursively sorts two subarrays of n/2 (for even n) elements each.
3. The merge step merges n elements which takes O(n) time.
Now, for steps 1 and 3 i.e. between O(1) and O(n), O(n) is higher. Let's consider steps 1 and
3 take O(n) time in total. Say it is cn for some constant c.
How many times are these steps executed?
For this, look at the tree below - for each level from top to bottom Level 2 calls merge
method on 2 sub-arrays of length n/2 each. The complexity here is 2 * (cn/2) = cn Level 3 calls
merge method on 4 sub-arrays of length n/4 each. The complexity here is 4 * (cn/4) = cn and so
on ...
Now, the height of this tree is (logn + 1) for a given n. Thus the overall complexity is (logn +
1)*(cn). That is O(nlogn) for the merge sort algorithm.
12.A program to create single linked list and perform insert, delete operations
13.A program to create double linked list and perform insert, delete operations
Default:
class Geek
{
void display( )
{
System.out.println("Hello World!");
}
}
Private:
class A
{
private void display( )
{
System.out.println("It is a private method");
}
}
class PriDemo
{
public static void main(String args[ ])
{
A obj = new A( );
//trying to access private method of another class
obj.display( );
}
}
Save: PriDemo.java
Compilation: javac PriDemo.java
PriDemo.java:14: display( ) has private access in A
obj.display();
^
1 error
Protected:
class Alpha
{
protected void display( )
{
System.out.println("This method is protected");
}
}
class Beta extends Alpha
{
public void show( )
{
System.out.println("Hello");
}
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 157
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
class ProtDemo
{ Save: ProtDemo.java
public static void main(String args[ ]) Compilation: javac ProtDemo.java
{
Beta obj = new Beta( ); Execution: java ProtDemo
obj.display( ); Output: This method is protected
obj.show( );
} Hello
}
Public:
class X
{
public void display( )
{
System.out.println("Iam Saying...");
}
}
class Y extends X
{
public void show( )
{
System.out.println("Hello");
}
}
class PubDemo Save: PubDemo.java
{
public static void main(String args[ ]) Compilation: javac PubDemo.java
{ Execution: java PubDemo
Y obj = new Y( );
obj.display( ); Output: Iam Saying...
obj.show( ); Hello
}
}
2. A program to demonstrate polymorphism in Java.
Static Polymorphism:
class Calc
{
public void sum (int x, int y)
{
System.out.println(“Sum=”+(x+y));
}
public void sum (double x, double y)
{
System.out.println(“Sum=”+(x+y));
}
public void sum (int x, int y, int z)
{
System.out.println(“Sum=”+(x+y+z));
}
}
class MethOverLoad Save: MethOverLoad.java
{ Compilation: javac MethOverLoad.java
public static void main(String args[ ])
{ Execution: java MethOverLoad
Calc c1= new Calc( ); Output: Sum=29
c1.sum(9, 20);
c1.sum(10.5, 22.5); Sum=33.0
c1.sum(9, 20, 11); Sum=40
}
}
Dynamic Polymorphism:
class One
{
public void show( )
{
System.out.println(“This is parent class”);
}
}
class Two extends One
{
public void show( )
{
System.out.println(“This is child class”);
}
}
class MethodOverRide
{
String class:
import java.io.*;
class StringTest
{
public static void main(String args[ ])
{
String s1="abc", s2="xyz";
System.out.println("Length:" +s1.length( ));
System.out.println("Concatenation:" +s1.concat(s2));
System.out.println("Uppercase:" +s1.toUpperCase( ));
System.out.println("Lowercase:" +s1.toLowerCase( ));
System.out.println("Substring(1,2):" +s1.substring(1,2));
System.out.println("Replace:" +s1.replace('c', 'v'));
System.out.println("Character at position 2:" +s1.charAt(2));
int k= s1.compareTo(s2);
if(k>0)
System.out.println(s1+ "is big");
else if(k<0)
System.out.println(s2 + "is big");
else
System.out.println(s1 + "and" + s2 + "are equal");
if(s1.equals(s2))
System.out.println(s1 + "and" + s2 + "are equal");
else
System.out.println(s1 + "and" + s2 + "are not equal");
if(s1.equalsIgnoreCase(s2))
System.out.println(s1 + "and" + s2 + "are equal");
else
System.out.println(s1 + "and" + s2 + "are not equal");
}
}
Save: StringTest.java
Compilation: javac StringTest.java
Execution: java StringTest
Output: Length:3
Concatenation:abcxyz
Uppercase:ABC
Lowercase:abc
Substring(1,2):b
Replace:abv
Character at position 2:c
xyzis big
abcandxyzare not equal
abcandxyzare not equal
StringBuffer:
class StringBufferTest
{
public static void main(String args[ ])
{
String s1=new String("MADAM");
StringBuffer dup=new StringBuffer(s1);
String s2= dup.reverse( ).toString( );
if(s1.equalsIgnoreCase(s2))
System.out.println(s1 + "is palindrome");
else
System.out.println(s1 + "is not palindrome");
}
}
Save: StringBufferTest.java
Compilation: javac StringBufferTest.java
Execution: java StringBufferTest
Output: MADAM is palindrome
5. A program to demonstrate Exception Handling.
class ExceptHand
{
public static void main(String args[ ])
{
int a=10, b=5, c=5, x, y;
try
{
x = a / (b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
finally
{
y = a / (b+c);
System.out.println("y="+y);
}
}
}
Save: ExceptHand.java
Compilation: javac ExceptHand.java
Execution: java ExceptHand
Output: Division by zero
y=1
6. A program to perform matrix multiplication.
import java.io.*;
class MatrixMulti
{
public static void main(String args[ ])throws IOException
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 163
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]
{
DataInputStream dis=new DataInputStream(System.in);
int m, n, p, q, i, j, k;
System.out.println("Enter size of 1st matrix:");
m= Integer.parseInt(dis.readLine());
n= Integer.parseInt(dis.readLine());
System.out.println("Enter size of 2nd matrix:");
p= Integer.parseInt(dis.readLine());
q= Integer.parseInt(dis.readLine());
if(n != p)
{
System.out.println("Mltiplication not possible");
}
else
{
int a[ ][ ]= new int[m][n];
int b[ ][ ]= new int[p][q];
int c[ ][ ]= new int[m][q];
System.out.println("Enter values into 1st matrix:");
for(i=0; i<m; i++)
for(j=0; j<n; j++)
a[i][j]= Integer.parseInt(dis.readLine());
System.out.println("Enter values into 2nd matrix:");
for(i=0; i<p; i++)
for(j=0; j<q; j++)
b[i][j]= Integer.parseInt(dis.readLine());
for(i=0; i<m; i++)
for(j=0; j<q; j++)
{
c[i][j]= 0;
for(k=0; k<n; k++)
c[i][j] = c[i][j]+ a[i][k]*b[k][j];
}
System.out.println("Matrix multiplication is:");
for(i=0; i<m; i++)
{
System.out.println(" ");
for(j=0; j<q; j++)
System.out.print("\t"+ c[i][j]);
}
}
}
}
Save: MatrixMulti.java
Compilation: javac MatrixMulti.java
Execution: java MatrixMulti
Output: Enter size of 1st matrix:
3
3
Enter size of 2nd matrix:
3
3
Enter values into 1st matrix:
1
2
3
1
2
3
1
2
3
Enter values into 2nd matrix:
1
2
3
1
2
3
1
2
3
Matrix multiplication is:
6 12 18
6 12 18
6 12 18
7. A program to implement stack ADT using array.
class Stack
{
private static int MAX=5;
{
InfixToPostfix obj = new InfixToPostfix( );
Scanner sc = new Scanner(System.in);
System.out.print("Infix : \t");
String infix = sc.next( );
System.out.print("Postfix : \t"+obj.convert(infix));
}
}
Save: InfixToPostfix.java
Compilation: javac InfixToPostfix.java
Execution: java InfixToPostfix
Output: Infix : (a+b)*c+d*e
Input Stack Postfix
#
( #(
a #( a
+ #(+ a
b #(+ ab
) # ab+
* #* ab+
c #* ab+c
+ #+ ab+c*
d #+ ab+c*d
* #+* ab+c*d
e #+* ab+c*de
#+ ab+c*de*
# ab+c*de*+
Postfix : ab+c*de*+
9. A program to evaluate postfix expression.
import java.io.*;
import java.util.*;
class Stack
{
private int a[ ]=new int[20];
int top;
Stack( )
{
top=0;
}
public void push(int v)
{
if(top<20)
a[top++]=v;
else
System.out.println("Overflow");
}
public int pop( )
{
if(top>0)
return a[- -top];
else
{
System.out.println("Underflow");
return -1;
}
}
public boolean isEmpty( )
{
return top==0;
}
}
class PostFix
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
int a, b, c=0;
String str, s;
Stack s1=new Stack( );
int i;
System.out.print("Enter Postfix expression:");
str=dis.readLine( );
StringTokenizer st=new StringTokenizer(str,",");
while(st.hasMoreTokens( ))
{
s=st.nextToken( );
if(("+-*/").indexOf(s)>=0)
{
b= s1.pop( );
a= s1.pop( );
1 would be to move the n-1 discs (assuming that there were a total of n discs) from pole 1 to
pole 2. For moving these (n -1) discs, we again follow the same strategy of considering them as
1 disc plus a set of n-2 discs. Step 3 would also be similar. This gives us the recursive solution.
Recursive Algorithm: The recursive solution to move n discs from the start pole to the
end pole using an auxiliary pole is given below.
Base Case - When n = 1
Move the disc from start pole to end pole
Recursive Case - When n > 1
Step 1: Move (n-1) discs from start pole to auxiliary pole.
Step 2: Move the last disc from start pole to end pole.
Step 3: Move the (n-1) discs from auxiliary pole to end pole.
Steps 1 and 3 are recursive invocations of the same procedure.
Program:
import java.io.*;
public class TowersOfHanoi
{
public void solve(int n, String start, String auxiliary, String end)
{
if (n = = 1)
{
System.out.println(start + " -> " + end);
}
else
{
solve(n - 1, start, end, auxiliary);
System.out.println(start + " -> " + end);
solve(n - 1, auxiliary, start, end);
}
}
public static void main(String[ ] args)
{
TowersOfHanoi towersOfHanoi = new TowersOfHanoi( );
System.out.print("Enter number of discs: ");
Scanner scanner = new Scanner(System.in);
int discs = scanner.nextInt( );
towersOfHanoi.solve(discs, "A", "B", "C");
}
}
Save: TowersOfHanoi.java
Compilation: javac TowersOfHanoi.java
Execution: java TowersOfHanoi
Output: Enter number of discs: 3
A -> C
A -> B
C -> B
A -> C
B -> A
B -> C
A -> C
11.A program to implement Queue ADT using Array.
class Queue
{
private static int MAX=10;
private int a[ ]=new int[MAX];
int front, rear;
Queue( )
{
front= rear = -1;
}
public void insert(int v)
{
if(rear<MAX)
{
rear++;
a[rear]=v;
}
else
System.out.println("Queue is full");
}
public void del( )
{
if(rear= = -1)
System.out.println("Queue is empty");
else
{
front++;
System.out.println("Element deleted is:"+a[front]);
}
}
public void display( )
{
if(rear= = -1)
System.out.println("Queue is empty");
else
{
System.out.println("Queue elements:");
for(int i=front+1; i<=rear; i++)
System.out.println(a[i]);
}
}
}
class QArray
{ Save: QArray.java
public static void main(String args[ ]) Compilation: javac QArray.java
{ Execution: java QArray
Queue q=new Queue( ); Output: Queue elements:
q.insert(30); 30
q.insert(40); 40
q.insert(50); 50
q.display( ); Element deleted is:30
q.del( ); Queue elements:
q.display( ); 40
} 50
}
12.A program to create single linked list and perform insert, delete operations.
import java.io.*;
class node
{
public int x;
public node next;
}
class LinkedList
{
public node first;
LinkedList( )
{
first = new node( );
first.next= null;
}
void add (int v)
{
node temp=new node( );
temp.x= v;
temp.next= null;
node ptr=first;
while(ptr.next!=null)
ptr= ptr.next;
ptr.next= temp;
}
void insert(int p, int v)
{
node ptr= first,temp;
for(int i=1; i<=p-1; i++)
ptr= ptr.next;
temp= new node( );
temp.x= v;
temp.next= ptr.next;
ptr.next= temp;
}
void del(int p)
{
node ptr= first,temp;
for(int i=1; i<=p-1; i++)
ptr=ptr.next;
temp= ptr.next;
ptr.next= ptr.next.next;
temp= null;
}
void show( )
{
System.out.println("\nList Elements:");
for(node ptr=first.next; ptr!=null; ptr=ptr.next)
System.out.print("\t"+ptr.x);
}
}
class SListTest
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
String con=" ";
int x, op, p, v;
LinkedList L1=new LinkedList( );
System.out.println("Enter elements to create");
do
{
x=Integer.parseInt(dis.readLine( ));
L1.add(x);
System.out.print("Add more?(y,n):");
con=dis.readLine( );
}while(con.equalsIgnoreCase("y"));
L1.show();
do
{
System.out.println("\n 1.Insert\n 2.Delete \n 3.Display \n 4.Exit");
System.out.println("\nSelect an option:");
op=Integer.parseInt(dis.readLine( ));
if(op= =1)
{
System.out.println("Enter Position to insert:");
p= Integer.parseInt(dis.readLine( ));
System.out.println("Enter Value to insert:");
v= Integer.parseInt(dis.readLine( ));
L1.insert(p,v);
}
if(op= =2)
{
System.out.println("Enter Position to delete:");
p= Integer.parseInt(dis.readLine( ));
L1.del(p);
}
L1.show( );
}while(op<4);
}
}
Save: SListTest.java
Compilation: javac SListTest.java
Execution: java SListTest
Output: Enter elements to create
10
Add more?(y,n):y
20
Add more?(y,n):y
40
Add more?(y,n):y
50
Add more?(y,n):n
List Elements:
10 20 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 1
Enter Position to insert: 3
Enter Value to insert: 30
List Elements:
10 20 30 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 2
Enter Position to delete: 5
List Elements:
10 20 30 40
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 4
List Elements:
10 20 30 40
13.A program to create double linked list and perform insert, delete operations.
import java.io.*;
class node
{
public int x;
public node next;
public node prev;
}
class DoubleLinkedList
{
public node first;
public node last;
DoubleLinkedList( )
{
first= new node( );
first.next= null;
first.prev= null;
last= first;
}
void add (int v)
{
node temp= new node( );
temp.x= v;
temp.next= null;
last.next= temp;
temp.prev= last;
last= temp;
}
void insert(int p, int v)
{
node ptr= first,temp;
for(int i=1; i<=p-1; i++)
ptr= ptr.next;
if(ptr.next= =null)
add(v);
else
{
temp= new node( );
temp.x= v;
temp.next= ptr.next;
ptr.next.prev= temp;
ptr.next= temp;
temp.prev= ptr;
}
}
void del(int p)
{
node ptr= first,temp;
for(int i=1; i<=p-1; i++)
ptr= ptr.next;
if(ptr.next.next==null)
{
temp= last;
last= last.prev;
last.next= null;
}
else
{
temp= ptr.next;
ptr.next= ptr.next.next;
ptr.next.prev= ptr;
}
temp=null;
}
void show( )
{
System.out.println("\nList Elements:Left to Right");
for(node ptr=first.next; ptr!=null; ptr=ptr.next)
System.out.print("\t"+ptr.x);
System.out.println("\nList Elements:Right to Left");
for(node ptr=last; ptr.prev!=null; ptr=ptr.prev)
System.out.print("\t"+ptr.x);
}
}
class DListTest
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
String con=" ";
int x, op, p, v;
{
a = new int [5];
front = rear = -1;
}
Queue(int size)
{
a = new int[size];
front = rear = -1;
}
void insert(int x)
{
int p;
p = (rear+1)% a.length;
if(p = = front)
System.out.println("Queue Overflow ");
else
{
rear = p;
a[rear] = x;
if(front = = -1)
front = 0;
}
}
boolean empty( )
{
if(front = = -1)
return true;
else
return false;
}
int delete( )
{
int x = a[front];
if(front = = rear)
front = rear = -1;
else
front =(front+1)% a.length;
return x;
}
void display( )
{
if(front = = -1)
System.out.println("Queue underflow");
else
{
System.out.println("Elements of Queue are");
int i = front;
while(i != rear)
{
System.out.println(a[i]);
i = (i+1)% a.length;
}
System.out.println(a[i]);
}
}
void destroy( )
{
front = rear= -1;
}
}
public class CircularQueue
{
public static void main(String args[ ])
{
Queue q = new Queue( ); //Queue of size 5
int ch;
Scanner sc =new Scanner(System.in);
do
{
System.out.println("Menu\n1.insert\n2.delete\n3.display\n4.destroy\n5.exit\n");
System.out.println("Enter choice :");
ch=sc.nextInt( );
switch(ch)
{
case 1:
System.out.println("Enter data to insert");
int x=sc.nextInt( );
q.insert(x);
break;
case 2:
if(q.empty( ))
System.out.println("Queue underflow");
else
{
int z =q.delete( );
System.out.println("data deleted =" + z );
}
break;
case 3: q.display( );
break;
case 4: q.destroy( );
break;
case 5: break;
default : System.out.println("Wrong Choice");
}
}while(ch!=5);
}
}
Save: CircularQueue.java
Compilation: javac CircularQueue.java
Execution: java CircularQueue
Output: Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 1
Enter data to insert 10
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 1
Enter data to insert 20
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 1
Enter data to insert 30
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 3
Elements of Queue are
10
20
30
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 2
data deleted =10
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 3
Elements of Queue are
20
30
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 5
15.A program to implement circular queue using linked list method.
class node
{
public int x;
public node next;
}
class CircularQueue
{
public node front, rear;
CircularQueue( )
{
front=rear=null;
}
void insert(int v)
{
node temp=new node( );
temp.x= v;
if(front= =null)
front=rear=temp;
else
{
rear.next=temp;
rear=temp;
}
rear.next=front;
}
int del( )
{
if(front= =null)
{
System.out.println("Queue overflow");
System.exit(1);
}
int v= front.x;
node temp= front;
if(front= =rear)
front=rear=null;
else
{
front=front.next;
rear.next=front;
}
temp= null;
return v;
}
void show( )
{
System.out.println("Circular Queue Elements:");
for(node ptr=front; ptr!=rear; ptr=ptr.next)
System.out.print("\t"+ptr.x);
System.out.print("\t"+rear.x);
}
}
class CQLTest
{
public static void main(String args[ ])
{
CircularQueue q1=new CircularQueue( );
q1.insert(30);
q1.insert(40);
q1.insert(50);
q1.insert(60);
q1.show();
System.out.println("\nDeleted element:"+q1.del( ));
System.out.println("After deleting:");
q1.show( );
}
}
Save: CQLTest.java
Compilation: javac CQLTest.java
Execution: java CQLTest
Output: Circular Queue Elements:
30 40 50 60
Deleted element:30
After deleting:
Circular Queue Elements: 40 50 60
t.right = null;
}
else if(v<t.x)
t.left = insert(t.left, v);
else if(v>t.x)
t.right = insert(t.right, v);
return t;
}
public void LVR(tree t)
{
if(t!=null)
{
LVR(t.left);
System.out.print("\t"+t.x);;
LVR(t.right);
}
}
public void LRV(tree t)
{
if(t!=null)
{
LRV(t.left);
LRV(t.right);
System.out.print("\t"+t.x);
}
}
public void VLR(tree t)
{
if(t!= null)
{
System.out.print("\t"+t.x);
VLR(t.left);
VLR(t.right);
}
}
}
class BTreeTest
{
public static void main(String args[ ])
{
Save: MyMergeSort.java
Compilation: javac MyMergeSort.java
Execution: java MyMergeSort
Output: 4 11 23 28 43 45 65 77 89 98
maxheap(arr, i);
}
/* Function to swap largest element in heap */
public static void maxheap(int arr[ ], int i)
{
int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i)
{
swap(arr, i, max);
maxheap(arr, max);
}
}
/* Function to swap two numbers in an array */
public static void swap(int arr[ ], int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[ ] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Heap Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt( );
int arr[ ] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt( );
sort(arr);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println( );
}
}
Save: HeapSort.java
Compilation: javac HeapSort.java
Execution: java HeapSort
Output: Heap Sort Test
Enter number of integer elements
10
Enter 10 integer elements
12 54 26 38 64 28 90 5 10 81
Elements after sorting
5 10 12 26 28 38 54 64 81 90
20.A program to implement linear and binary search on strings.
Linear search:
import java.io.*;
class LinearSearch
{
public void linsearch(String string[ ], String search)
{
int i;
int flag = 0;
for(i = 0; i<10; i++)
{
if (search.equals(string[i]))
{
flag = 1;
break;
}
}
if (flag = =1)
{
System.out.println("Word found at position " +(i+1));
}
else
{
System.out.println("Word not found.");
}
}
words[0] = college
words[1] = degree
words[2] = huzurabad
words[3] = karimnagar
words[4] = satavahana
words[5] = sri
words[6] = to
words[7] = university
words[8] = vaagdevi
words[9] = welcome
Enter word to search for: vaagdevi
found at index 8