Top Banner
Java and Data Structures 1 IIBSC Object Oriented Programming with Java and Data Structures Syllabus UNIT-1: Java Fundamentals Fundamentals of Object Oriented Programming: Object Oriented paradigm –Basic concepts of Object Oriented Programming- Benefits of OOP- Applications of OOP. Java Evolution: Java Features- How java differs from C and C++ -java and Internet- java and World Wide Web- Web Browsers –Hardware and Software Requirements-Java Environment. Overview of Java Language: Simple Java Program –Java Program structure-Java Tokens-Java statements-Implementing a Java Program- Java Virtual Machine- Command Line arguments. Constants, Variables, and Data types: Constants-Variables-Data types-Declaration of Variables-Giving values to Variables-Scope of Variables-Symbolic constants – Type Casting. (Chapters :1,2,3,4) Unit-2 :Oops Concepts in Java Operators and Expressions: Arithmetic Operators- Relational Operators- Logical operators-Assignment Operators – Increment and Decrement operators – Conditional operators – Bitwise Operators – Special Operators – Arithmetic Expressions- Evaluation of Expressions – Precedence of Arithmetic operators – Operators precedence and Associativity. Decision Making and Branching : Decision Making with if statement – Simple if statement - if else statement – Nesting If else statement – the elseif ladder- the switch statement – The ? : operator. Decision Making and Looping : The while statement – the do statement- The for statement – Jumps in Loops. Class, Objects and Methods : Defining a Class- Fields Declaration – Methods Declaration – Creating Objects – Accessing class members – Constructors – Methods Declaration- creating objects- accessing class members –constructors – Methods Overloading –Static members – Nesting of Methods – Inheritance –Overriding Methods – Final
241

Java and data structure

Feb 03, 2023

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java and data structure

Java and Data Structures 1IIBSC

Object Oriented Programming with Java and Data Structures

Syllabus

UNIT-1: Java Fundamentals

Fundamentals of Object Oriented Programming: Object Orientedparadigm –Basic concepts of Object Oriented Programming- Benefits ofOOP- Applications of OOP.

Java Evolution: Java Features- How java differs from C and C++ -javaand Internet- java and World Wide Web- Web Browsers –Hardware andSoftware Requirements-Java Environment.

Overview of Java Language: Simple Java Program –Java Programstructure-Java Tokens-Java statements-Implementing a Java Program-Java Virtual Machine- Command Line arguments.

Constants, Variables, and Data types: Constants-Variables-Datatypes-Declaration of Variables-Giving values to Variables-Scope ofVariables-Symbolic constants – Type Casting. (Chapters :1,2,3,4)

Unit-2 :Oops Concepts in Java

Operators and Expressions: Arithmetic Operators- RelationalOperators- Logical operators-Assignment Operators – Increment andDecrement operators – Conditional operators – Bitwise Operators –Special Operators – Arithmetic Expressions- Evaluation ofExpressions – Precedence of Arithmetic operators – Operatorsprecedence and Associativity.

Decision Making and Branching : Decision Making with if statement –Simple if statement - if else statement – Nesting If else statement– the elseif ladder- the switch statement – The ? : operator.

Decision Making and Looping : The while statement – the dostatement- The for statement – Jumps in Loops.

Class, Objects and Methods : Defining a Class- Fields Declaration –Methods Declaration – Creating Objects – Accessing class members –Constructors – Methods Declaration- creating objects- accessingclass members –constructors – Methods Overloading –Static members –Nesting of Methods – Inheritance –Overriding Methods – Final

Page 2: Java and data structure

Java and Data Structures 2IIBSC

variables and Methods – Final classes- Abstract Methods and classes-Visibility control. (Chapters : 5,6,7,8)

UNIT-III: Packages and Interfaces in Java

Arrays, Strings and Vectors : One dimensional Arrays – Creating anArray- Two dimensional Arrays –Strings –Vectors- Wrapper classes –Enumerated types.

Interfaces: Multiple Inheritance: Defining Interfaces – Extendinginterfaces- implementing Interfaces – Accessing interface variables.

Packages: Java API packages – Using system packages – NamingConventions- Creating packages – Accessing a package –Using apackage – Adding a Class to a package – Hiding Classes –StaticImport. (Chapters :9, 10,11)

UNIT-IV : Multithread Programming an Applets

Multithreaded Programming: Creating Threads –Extending the Threadclass –Stopping and Blocking a Thread –Life Cycle of a Thread –UsingThread Methods – Thread Exceptions –Thread Priority –Synchronizations.

Managing Errors and Exceptions: Types of Errors – Exceptions –Syntax of Exception handling code- Multiple catch statements – UsingFinally statement –throwing our own Exceptions – Using Exceptionsfor debugging.

Applet Programming : How Applets differ from Applications –Preparingto write Applets –Building Applet Life Cycle –Creating an executableApplet- Designing a Webpage- Applet Tag –passing parameters toApplets – Aligning the display –More about HTML tags – DisplayingNumerical values –Getting input from the user. (Chapters : 12, 13,14)

UNIT -5 : Data structures

Sorting: Bubble Sort- Selection sort – Insertion Sort.

Stacks and Queues: Stacks –Queues –circular Queue –Dequeues –Priority Queue – Parsing Arithmetic Expressions.

Page 3: Java and data structure

Data

Method Method

Method Method

Java and Data Structures 3IIBSC

Linked List: Simple Linked List – Finding and deleting specificLinks –Double Ended Lists. Abstract Data types –sorted Lists –Doubly Linked Lists

Advanced Sorting: Quick sort

Binary Trees: Tree Terminology Finding a Node –Inserting a Node –Traversing the tree –finding Maximum and Minimum values –Deleting aNode –Efficiency of Binary Trees – Trees Represented as Arrays

Graphs: Introduction to Graphs – Searches –Minimum Spanning Tree –Topological Sorting with Directed Graphs – Connectivity in DirectedGraphs.

Prescribed Books:

1.E. Balaguruswamy , programming with Java, a primer ,3e, TATAMcGraw –Hill company (2008) (Chapters: 1 to 14).

2.Robert Lafore, Data Structures & Algorithms in Java, secondEdition , pearson Education(2008(Chapters :3,4,5,7 (only quicksort), 8,13)

3. Jhon R Hubbard, Programming with Java, Second Edition, Schaum’soutline series, Tata McGraw Hill(2007).

1.Fundamentals of Object-Oriented Programming

1.Object-Oriented ParadigmOOP treats data as a critical element in the program development anddoes not allow it to follow freely around the system. It ties datamore closely to the function s that operate on it and protects itfrom unintentional modification by other functions. OOP allows us todecompose a problem into a number of entities called Objects andthen build data and functions. The combination of data and methodsmake up an object as shown in fig.

Page 4: Java and data structure

Java and Data Structures 4IIBSC

Fig. Object=Data +MethodsSome features of object-oriented paradigm are:

Emphasis is on data rather than procedure. Programs are divided into what are known as objects. Data structures are designed such that they characterize the

objects. Methods that operate on the data of an object are tied together

in the data structure. Data is hidden and cannot b accessed by external functions. Objects may communicate with each other through methods. New data and methods can be easily added when whenever

necessary. Follows bottom-up approach in program design.

Object oriented programming is an approach that provides a wayof modularizing programs by creating partitioned memory areafor both data and functions that can be used as templates forcreating copies of such modules on demand. Since the memorypartitions are independent, the objects can be used in avariety of different programs without modifications.2.Basic Concepts of Object-Oriented programming Objects and Classes Objects are the basic runtime entities in an object-oriented system.An object may represent real world entity represent a person, aplace, a bank account etc. The entire set of data and code of anobject can be made a user-defined data type using the concept of aclass. A class may be thought of a ‘data type’ and an object as a‘variable’ of that data type. Once a class has been defined, we cancreate any number of objects belonging to that class. Each object isassociated with the data of type class with which they are created.Representation of object is shown blow.

ObjectPerson Name BasicPaySalary()Tax()

Page 5: Java and data structure

Data and Methods

Information “in” Information “out”

Bird

Flying Bird Non flying Bird

Java and Data Structures 5IIBSC

Data

Methods

Data Abstraction and EncapsulationThe wrapping up of data and methods into a single unit(called class)is known as encapsulation. Data encapsulation is the most strikingfeature of a class. The data is not accessible to the outside worldand only those methods, which are wrapped in the class, can accessit. This insulation of the data from direct access by the program iscalled data hiding. Encapsulation makes it possible for objects tobe treated like “block boxes” as shown in fig.

InheritanceInheritance is the process by which objects of one class acquire theproperties of objects of another class. Inheritance supports theconcept of hierarchical classification. For example , the bird robinis a part of the class flying bird, which is again a part of theclass bird. As shown in fig.

In OOP, the concept of inheritance provides the idea of reusability.This means that we can add additional features to an existing classwithout modifying it. This is possible by deriving a new class fromthe existing one. The new class will have the combined features ofboth the classes. Thus the real appeal and power of the inheritancemechanism is that it allows the programmer to reuse a class that isalmost, but not exactly , what he wants.Polymorphism

Polymorphism is another important OOP concept. Polymorphism meansthe ability to take more than one form. For example , an operation

Page 6: Java and data structure

ShapeDraw()

Box objectDraw(Box)

Circle ObjectDraw(circle)

Object5

Object1

Object2

Object4 Object3

Java and Data Structures 6IIBSC

may exhibit different behavior in different instances. The behaviordepends upon the types of data used in the operation. Fig shows thata single function name can be used to handle different number anddifferent types of arguments.

Polymorphism plays an important role in allowing objects havingdifferent internal structures to share the same external interface.Dynamic Binding

Binding refers to the linking of a procedure call to the code to beexecuted in response to the call. Dynamic binding means that thecode associated with a given procedure call is not known until thetime of the call at runtime. It is associated with polymorphism andinheritance.Message Communication

An object-oriented program consists of a set of objects thatcommunicate with each other. The process of programming in anobject-oriented language, therefore, involves the following basicsteps:1.Creationg classes that define objects and their behavior.2.Creating objects from class definitions.3. Establishing communication among objects.Objects communicate with one another by sending and receivinginformation much the same way as people pass messages to one anotheras shown in fig.

Fig. Network of objects communicating between them

Page 7: Java and data structure

Method ()Sending Object Receiving ObjectMessage

Java and Data Structures 7IIBSC

A message for an object is a request for executing of a procedure,and therefore will invoke a method(procedure) in the receivingobject that generates the desired result, as shown in fig.

Message triggers a method Message passing involves specifying thename of the object, the name of the method(message) and theinformation to be sent . For example , consider the statementEmployee.salary(name);Here, Employee is the object, salary is the message and name is theparameter that contains information.

Employee . salary (name); Object

Information Message

Objects have a life cycle. They can be created and destroyed.Communication with an object is feasible as long as it is alive.3. Benefits of OOPOOP offers several benefits to both the program designer and theuser. Object-oriented contributes to the solution of many problemsassociated with the development and quality of software products.The new technology promises greater programmer productivity, betterquality of software and lesser maintenance cost. The principleadvantages are:

Through inheritance, we can eliminate redundant code and extendthe use of existing classes.

We can build programs from the standard working modules thatcommunicate with one another, rather than having to startwriting the code from scratch. This leads to saving ofdevelopment time and higher productivity.

The principle of data hiding helps the programmer to buildsecure programs that cannot be invaded by code in other partsof the program.

It is possible to have multiple objects to coexist without anyinterference.

It is possible to map objects in the problem domain to thoseobjects in the program.

It is easy to partition the work in a project based on objects.

Page 8: Java and data structure

Java and Data Structures 8IIBSC

The data-centered design approach enables us to capture moredetails of a model in an implementable form.

Object-oriented systems can be easily upgraded from small tolarge systems.

Message passing techniques for communicating between objectsmake the interface description with external systems muchsimpler.

Software complexity can be easily managed.4. Applications of OOPApplications of OOP are beginning to gain importance in many areas.The most popular application of object-oriented programming , up tonow, has been in the area of user interface design such as windows.There are hundreds of windowing systems developed using OOPtechniques.Real-business systems are often much more complex and contain manymore objects with complicated attributes and methods. OOP is usefulin this type of applications because it can simplify a complexproblem . The promising areas for application of OOP includes:

Real-time systems Simulation and modeling Object-oriented databases Hypertext, hypermedia and expertext AI and expert systems Neural networks and parallel programming Decision support and office automation systems CAM/CAD system.

2.Java EvolutionJava Milestones

Year Development1990 Sun Microsystems decided to develop special software

that could be used to manipulate consumer electronicdevices. A team of Sun Microsystems programmers headedby James Gosling was formed to undertake this task.

1991 After exploring the possibility of using the mostpopular object-oriented language C++, the team announceda new language named “Oak”.

1992 The team , known as Green Project team by Sun ,demonstrated the application of their new language tocontrol a list of home appliances using a hand-helddevice with a tiny touch –sensitive screen.

1993 The World Wide Web (WWW) appeared on the Internet andtransformed the text-based Internet into graphical-rich

Page 9: Java and data structure

Java and Data Structures 9IIBSC

environment. The Green Project team came up with theidea of developing Web applets.

1994 The team developed a Web browser called ”HotJava” tolocate and run applet programs on Internet. HotJavademonstrated the power of the new language , thus makingit instantly popular among the Internet users.

1995 Oak was renamed “Java”, due to some legal snags. Java isjust a name and is not an acronym. Many popularcompanies including Netscape and Microsoft announcedtheir support to Java.

1996 Java established itself not only as a leader forInternet programming but also as a general-purpose,object-oriented programming language. Sun releases JavaDevelopment Kit1.0.

1997 Sun releases Java Development Kit1.1(JDK1.1)1998 Sun releases Java 2 with version 1.2 of the software

Development(SDK1.2).1999 Sun releases Java 2 Platform, Standard Edition(J2SE) and

Enterprise Edition(J2EE).2000 J2SE with SDK1.3 was released.2002 J2SE with SDK1.4 was released.2004 J2SE with JDK5.0 (instead of JDK1.5) was released. This

is known as J2SE5.0.The most striking feature of the language is that it is a platform-neutral language.2. Java FeaturesThe inventors of Java wanted to design a language which could offersolutions to some of the problems encountered in modern programming.

Compiled and InterpretedUsually a computer language is either compiled or interpreted. Javacombines both these approaches thus making Java a two-stage system.First, Java compiler translates source code into what is known asbytecode instructions. Bytecodes are not machine instructions andtherefore, in the second stage, Java interpreter generates machinecode that can be directly executed by the machine that is runningthe Java program.

Platform-Independent and PortableThe most significant contribution of Java over other languages isits portability. Java programs can be easily moved from one computersystem to another, anywhere and anytime. Changes and upgrades inoperating systems, processors and system resources will not force

Page 10: Java and data structure

Java and Data Structures 10IIBSC

any changes in Java programs. This is the reason why Java has becomea popular language for programming on Internet which interconnectsdifferent kinds of systems worldwide. We can download a Java appletfrom a remote computer onto our local system via Internet andexecute it locally.Java ensures portability in two ways. First, Java compiler generatesbytecode instructions that can be implemented on any machine.Secondly, the size of the primitive dat types are machine –independent.

Object-OrientedJava is true object-oriented language. Almost everything in Java isan object. All program code and data reside within objects andclasses. Java comes with an extensive set of classes , arranged inpackages, that we can use in our programs by inheritance.

Robust and secureJava has strict compile time and runtime checking for data types. Itis designed as a garbage-collected language relieving theprogrammers virtually all memory management problems. Java alsoincorporates the concept of exception handling which captures serieserrors and eliminates any risk of crashing the system.Security becomes an important issue for a language that is used forprogramming on internet. Java system not only verify all memoryaccess but also ensure that no viruses are communicated with anapplet. The absence of pointers in java ensures that programs cannotgain access to memory locations without proper authorization.

DistributedJava is designed as a distributed language for creating applicationson networks. It has ability to share both data and programs. Javaapplications can open and access remote objects on Internet aseasily as they can do in a local system. This enables multipleprogrammers at multiple remote locations to collaborate and worktogether on a single project.

Simple, small and FamiliarJava is a small and simple language. To make the language lookfamiliar to the existing programmers, it was modeled on C and C+languages.

Multithreaded and InteractiveMultithreaded means handling multiple tasks simultaneously. Javasupports multithreaded programs. This means that we need not wait

Page 11: Java and data structure

Java and Data Structures 11IIBSC

for the application to finish one task before beginning another. Forexample, we can listen to an audio clip while scrolling a page andat the same time download an applet from a distant computer. Thisfeature greatly improves the interactive performance of graphicalapplications.

High performanceJava performance is impressive for an interpreted language, mainlydue to the use of intermediate bytecode. Java architecture isdesigned to reduce overheads during runtime. Further, theincorporation of multithreading enhances the overall execution speedof Java programs.

Dynamic and ExtensibleJava is a dynamic language. Java is capable of dynamically linkingin new class libraries, methods, and objects. Java programs supportfunctions written in other languages such as C and C++. Thesefunctions are known as native methods. This facility enables theprogrammers to use the efficient functions available in theselanguages. Native methods are linked dynamically at runtime.

Ease of DevelopmentJava 2 Standard Edition(J2SE)5.0 support features, such asGenerics , Enhanced for Loop, Autoboxing or unboxing , TypesafeEnums, Varargs, Static import and Annotion. These features reducethe work of the programmer by shifting the responsibility ofcreating the reusable code to compiler. The resulting source code isfree from bugs because the errors made by the compiler are less whencompared to those made by programmers.

Scalability and PerformanceJ2SE5.0 assures a significant increase in scalability andperformance by improving the startup time and reducing the amount ofmemory used in Java2 runtime environment. Memory utilization isreduced by sharing data in the shared archive among multiple JVMprocess.

Monitoring ManageabilityJava supports a number of APIs, such as JVM Monitoring andManagement API , Sun Management Platform Extension, Logging,Monitoring and Management Interface, and Java ManagementExtension(JMX) to monitor and manage Java applications. Javaprovides tools, such as jconsole, jps, jstat, and jstatd to make useof monitoring and management facilities.

Page 12: Java and data structure

Java and Data Structures 12IIBSC

Desktop ClientJ2SE 5.0 provides enhanced features to meet the requirements andchallenges of the Java desktop users. It provides an improved Swinglook and feel called Ocean. This feature is mainly used fordeveloping graphics applications that require OpenGL hardwareacceleration.

Miscellaneous FeaturesIn addition to the above features, J2SE 5.0 supports the featuressuch as:

Core XML Support J2SE5.0 adds a powerful XML feature to the Java platform. Javacontains some special packages for interface, to instantiate SimpleAPI for XML(SAX) and Document Object Model(DOM) parsers to parse anXML document, transform the content of an XML document, and validatean XML document against the schema.

Supplementary Character Support Java adds the 32-bit supplementary character support as part of theUnicode 4.0support. The supplementary characters are encoded withUTF-16 values to generate a different character called, surrogatecode point.JDBC RowSet

Java supports JDBC RowSet to send data in a tabular format betweenthe remote components of a distributed enterprise application. JDBCRowSet contains CachedRowsSet and WebRowSet objects. TheCachedRowSet object is a JavaBean component which acts like acontainer. This object contains a number of rows of data, which areretrived from the database. The data stored in the CacheRowSet canbe directly accessed without connecting to the database or any otherdata source. The WebRowSet object can operate without beingconnected to the database or data source. The WebRowSet object usesXML format to read and write the rowset.3.How JAVA Differs from C and C++

Java and C

Java is a object-oriented language. Java team did not include someof the C features in Java.

Java does not include the C unique statement keywords sizeof ,and typedef.

Page 13: Java and data structure

Java and Data Structures 13IIBSC

Java does not contain the data types struct and union. Java does not define the type modifiers keywords auto, extern,

register, signed, and unsigned. Java does not support an explicit pointer type. Java does not have a preprocessor and therefore we cannot use

#define , #include, and #ifdef statements. Java requires that the functions with no arguments must be

declared with empty parenthesis and not with the void keywordas done in C.

Java adds new operators such as instanceof and >>>. Java adds labeled break and continue statements. Java adds many features required for object-oriented

programming.Java and C++

Java is a true object-oriented language while C++ is basically Cwith object-oriented extension. However, some Object-orientedfeatures of C++ make the C++ code extremely difficult to follow andmaintain. Listed below are some major C+ feature that wereintentionally 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 inheritance of classes. This is

accomplished using a new feature called “interface”. Java does not support global variables. Every variable and

method is declared within a class and forms part of that class. Java does not use pointers. Java has replaced the destructor function with a finalize()

function. There are no header files in Java.

4. Java and Internet

Java is strongly associated with the Internet because of the factthat the first application program written in Java was HotJava, aWeb browser to run applets on Internet. Internet users can use Javato create applet programs and run them locally using a “Java-enabledbrowser’ such as HotJava. They can also use a Java-enabled browserto downloaded an applet located on a computer anywhere in theInternet and run it on his local computer. In , fact Java appletshave made the Internet a true extension of the storage system of thelocal computer.

Page 14: Java and data structure

Internet

Remote Applet

Remote Computer

Local Computer

Bytecode Applet Source code

Java Web Browser Bytecode

User’s Computer

Remote Computer

HTML Document

Java and Data Structures 14IIBSC

Internet users can also set up their Web sites containing Javaapplets that could be used by other remote users of Internet. Theability of Java applets to hitch a ride on the informationsuperhighway has made Java a unique programming language for theInternet. In fact, due to this, Java is popular known as Internetlanguage.5.Java and World Wide Web World Wide Web(WWW) is an open-endedinformation retrieval system designed to be used in the Internet’sdistributed environment. This system contains what are known as Webpages that provide both information and controls. The web system isopen-ended and we can navigate to a new document in any direction.This is made possible with the help of Hyper Text Mark upLanguage(HTML). Web pages contain HTML tags that enable us to find ,retrieve, manipulate and display documents worldwide.

Before Java, the World Wide Web was limited to the display of stillimages and texts. However, the incorporation of Java into Web pageshas made it capable of supporting animation, graphics, games, and awide range of special effects. With the support of Java, the Web hasbecome more interactive and dynamic. Java communicate with a Web page through a special tag called<APPLET>. Fig shows this process.

1. The user sends a request for an HTML document to the remotecomputer’s Web server. The Web server is a program that acceptsa request, processes the request, and sends the requireddocument.

2. The HTML document is returned to the user’s browser. Thedocument contains the APPLET tag, which identifies the applet.

3. The corresponding applet bytecode is transferred to the user’scomputer. This bytecode had been previously created by the Javacompiler using the Java source code file for that applet.Fig: Java’s interaction with the web

Page 15: Java and data structure

Bytecode

HTML DocumentApplet Tag

Web ServerOutput

USER

RequestJava and Data Structures 15

IIBSC

4. The Java-enabled browser on the user’s computer interprets thebytecodes and provides output.

5. The user may have further interaction with the applet but withno further downloading from the provider’s Web server. This isbecause the bytecode contains all the information necessary tointerpret the applet.

6.Web BrowsersWeb browsers are used to navigate through the information found onthe net. They allow us to retrieve the information spread across theInternet and display it using the hypertext markup language (HTML).Examples of Web browsers, among others, include:

HotJava Netscape Navigator Internet Explorer

HotJavaHotJava is the Web browser from Sun Microsystems that enables thedisplay of interactive content on the Web, using Java language.HotJava is written entirely in Java and demonstrates thecapabilities of the Java programming language. When the Java language was first developed and ported to theInternet, no browsers were available that could run Java applets.HotJava is currently available for the platform Solaris, windows95,Windows NT, windows XP. HotJaAva is the biggest draw is that it wasthe first Web browser to provide support for the Java language, thusmaking the Web more dynamic and interactive.

Netscape Navigator

Page 16: Java and data structure

Java and Data Structures 16IIBSC

Netscape Navigator from Netscape communications corporation, is ageneral-purpose browser that can run Java applets. With versionsavailable for Windows 95, NT, Solaris and Apple Macintosh NetscapeNavigator is one of the most widely used browsers today.Netscape Navigator has many useful features such as visual displayabout downloading process and indication of the number bytesdownloaded. It also supports JavaScript, a scripting language usedin HTML document.

Internet ExplorerInternet Explorer is another popular browser developed by Microsoftfor Windows95, NT and XP Workstations. Both the Navigator andExplorer use tool bars, icons menus and dialog boxes for easynavigation. Explorer uses a just-in-time(JIT) compiler which greatlyincreases the speed of execution.

Hardware and Software RequirementsJava is currently supported on Windows 95, Windows NT, Windows XP,Sun Solaris, Macintosh and UNIX machines. The minimum hardware andsoftware requirements for Windows 95 version for Java are asfollows.

IBM-compatible 486 system . Minimum of 8MB memory Windows 95 software. A windows-compatible sound card, if necessary. A hard drive A CD-ROM drive A Microsoft-compatible mouse.

Java Support SystemsSupport System DescriptionInternetConnection

Local computer should be connected to theInternet

Web Server A program that accepts request forinformation and sends the requireddocuments.

Web Browser A program that provides access to WWW andruns Java applets.

HTML A language for creating hypertext for theweb.

APPLET Tag For placing Java applets in HTML document.Java Code Java code is used for defining Java

applets.Bytecode Compiled Java code that is referred to in

Page 17: Java and data structure

Text Editor

Java Source code Javadoc HTML Files

Javac

Java Class File Javah Header Files

Java and Data Structures 17IIBSC

the APPLET tag and transferred to the usercomputer.

Java EnvironmentJava environment includes a large number of development tools andhundreds of classes and methods. The development tools are part ofthe system known as Java Development Kit(JDK) and the classes andmethods are part of the Java Standard Library(JSL), also known asApplication Programming Interface(API).

Java Development KitThe Java Development Kit comes with a collection of tools are usedfor developing and running Java programs.Tool DescriptionAppletviewer

Enables us to run Java applets(without actuallyusing a Java-compatible browser).

java Java interpreter, which runs applets and applications by reading and interpreting byte code files.

javac The Java compiler, which translates Java source code to bytecode files that the interpreter can understand.

javah Produces header files for use with native methods

javap Java disassemble, which enables us to convert bytecode files into a program description.

jdb Java debugger, which helps us to find errors in our programs.

The way these tools are applied to build and run application programs isshown in fig. To create a Java program, we need to create a source codefile using a text editor. The source code is then compiled using the Javacompiler javac and executed using the Java interpreter java. The Javadebugger jdb is used to find errors , if any , in the source code. Acompiled Java program can be converted into a source code with the help ofJava disassemble javap.Fig: Process of building and running Java application programs

Page 18: Java and data structure

Java jdb

Java Program Output

Java and Data Structures 18IIBSC

Application Programming InterfaceThe Java Standard Library(API) includes hundreds of classes and methods grouped into several functional packages. Most commonly usedpackages are:

Language Support Package : A collection of classes and methods required for implementing basic features of Java.

Utilities Package: A collection of classes to provide utility functions such as date and time functions.

Input / Output Package : A collection of classes required for input/output manipulation.

Networking Package: A collection of classes for communication with other computers via internet.

AWT Package: The Abstract Window Tool Kit package contains classes that implements platform –independent graphical user interface.

Applet Package: This includes a set of classes that allows us to create Java applets.

The use of these library classes will become evident when we start developing Java program.

3.Overview of Java LanguageIntroductionJava is a general-purpose , object-oriented language. We can developtwo types of Java programs:

Stand-alone applications Web applets

Stand-alone applications are programs written in Java to carry outcertain tasks on a stand-alone local computer. In fact, Java can beused to develop programs for all kinds of applications , whichearlier, were developed using languages like C and C++. HotJavaitself is a Java application program. Executing a stand-alone Javaprogram involves two steps:

1.Compiling source code into bytecode using javac compiler

Page 19: Java and data structure

Java Source code

Java enabled Web Browser Java Interpreter

Java Compiler

Output Output

Java and Data Structures 19IIBSC

2. Executing the bytecode program using java interpreter.

Applets are small Java programs developed for Internet applications.An applet located on a distant computer(Server) can be downloadedvia Internet and executed on a local computer(Client) using a Java-capable browser. We can develop applets for doing everything fromsimple animated graphics to complex games and utilities.

Fig:Two ways of using JavaSimple Java ProgramA simple program that prints a line of text as output.class SampleOne{

public static void main(String args[]){

System.out.println(“Java is better than C++.”);}

}

Class DeclarationThe first line class SampleOne declares a class, which is an object–oriented construct. Java is a true object-oriented language andtherefore, everything must be placed inside a class. class keywordand declares that a new class definition follows. SampleOne is aJava identifier that specifies the name of the class to be defined.

Opening BraceEvery class definition in Java begins with an opening brace “{“ andends with a matching closing brace “}”, appearing in the last linein the example. This is similar to C++ class construct.

Page 20: Java and data structure

Java and Data Structures 20IIBSC

The main LineThe third line public static void main(String args[]) defines amethod named main. Conceptually , this is similar to the main()function in C/C++. Every Java application program must include themain() method. This is the starting point for the interpreter tobegin the execution of the program. A Java application can have anynumber of classes but only one of them must include a main method toinitiate the execution.This line contains a number of keywords ,public,static, and void.

public : The keyword public is an access specifier that declaresthe main method as unprotected and therefore making it accessible toall other classes this is similar to the C++ public modifier.

static: Next appears the keyword static, which declares this methodas one that belongs to the entire class and not a part of anyobjects of the class. The main must always be declared as staticsince the interpreter uses this method before any objects arecreated.

void: The type modifier void states that the main method does notreturn any value.All parameters to a method are declared inside a pair ofparentheses. Here, String args[] declares parameter named args,which contains an array of objects of the class type String.

The Output LineThe executable statement in the program is System.out.println(“Java is better than C++.”);

This is similar to the printf() statement of C. Since Java is a trueobject oriented language, every method must be part of an object.The println method is a member of the out object, which is a staticdata member of System class. This line prints the string Java isbetter than C++. to the screen. The method println always appends anewline character to the end of the string. This means that anysubsequent output will start on a new line. Note the semicolon atthe end of the statement. Every Java statement must end with asemicolon.

More of JavaThis program when compiled and run produces the output y=2.23607/* More Java statements

Page 21: Java and data structure

Java and Data Structures 21IIBSC

*This code computes square root*/import java.lang.Math;class SquareRoot{

public static void main(String args[]){

double x=5;double y;y=Math.sqrt(x);System.out.println(“y= “+y);

}}The statement double x=5; declares a variable x and initializes itto the value 5 and the statement. Double y; merely declares avariable y.The statement y=Math.sqrt(x); invokes the method sqrt of the Mathclass, computes square root of x and then assigns the result to thevariable y. The output statement System.out.println(“y=”+y); displays the resulton the screen as y=2.23607. Here , the + acts as the concatenationoperator of two strings. The value of y is converted into a stringrepresentation before concatenation.

Use of Math FunctionsNote that the first statement in the program is importjava.lang.Math; The purpose of this statement is to instruct theinterpreter to load the Math class from the package lang. Math classcontains the sqrt method required in the program.

CommentsJava permits both the single –line comments and multi –line commentsavailable in C++. The single line comments begin with // and at theend of the line as shown on the lines declaring x and y. For longercomments, we can create long multi-line comments by starting with a /* andending with a */ as shown at the beginning of the program.

Java Program StructureA Java program may contain many classes of which only one classdefines a main method. Classes contain data members and methods thatoperate on the data members of the class. Methods may contain datatype declarations and executable statements. To write a Java

Page 22: Java and data structure

Java and Data Structures 22IIBSC

program, we first define classes and then put them together. A Javaprogram may contain one or more section as shown below.

suggested Optional

Essential

Documentation SectionThe documentation section comprises a set of comment lines givingthe name of the program, the author and other details, which theprogrammer would like to at a later stage. Comments must explain whyand what of classes and how of algorithms. This would greatly helpin maintaining the program. Java also uses a third style ofcomment /** …*/ known as documentation comment. This form of commentis used for generating documentation automatically.

Package StatementThe first statement allowed in a Java file is a package statement.This statement declares a package name and informs the compiler thatthe classes defined here belong to this package. Example: packagestudent; The package statement is optional.

Import statementsThe next thing after a package statement may be a number of importstatements. This si similar to the #include statement in C. Exampleimport student.test; This statement instructs the interpreter toload the test class contained in the package student. Using importstatement, we can have access to classes that are part of othernamed packages.

Interface statementsAn interface is like a class but includes a group of methoddeclarations. This is also an optional section and is used only whenwe wish to implement the multiple inheritance feature in theprogram.

Class Definitions

Documentation SectionPackage StatementImport StatementsInterface StatementsClass DefinitionsMain method class{main methoddefinition}

Page 23: Java and data structure

Java and Data Structures 23IIBSC

A Java program may contain multiple class definitions. Classes arethe primary and essential elements of a Java program. These classesare used to map the objects of real-world problems. The number ofclasses used depends on the complexity of the problem.Main Method classSince every Java stand-alone program requires a main method as itsstarting point, this class is the essential part of a Java program.A simple Java program may contain only this part. The main methodcreates objects of various classes and establishes communicationsbetween them. On reaching the end of main, the program terminatesand the control passes back to the operating system.

Java TokensSmallest individual units in a program are known as tokens. Insimple terms, a Java program is a collection of tokens, comments andwhite spaces. Java language includes five types of tokens. They are:

Reserved Keywords Identifiers Literals Operators Separators

Java Character SetThe smallest units of Java language are the characters used to writejava tokens. These characters are defined by the Unicode characterset, an emerging standard that tries to create character for a largenumber of scripts world wide.The Unicode is a 16-bit character coding system and currentlysupports more than 34,00 defined characters derived from 24languages.

KeywordsJava language has reserved 50 words as keywords. Since keywordshave specific meaning in Java, we cannot use them as names forvariables, classes, methods and so on. All keywords are to bewritten in lower-case letters. abstract

assert boolean Break byte case catch

char class const continue

default do double

else enum extends Final finally float forgoto if implemen

tsImport instanc

eofint Interfa

celong native New package private protected publicreturn short Static Strictf super throws transie

Page 24: Java and data structure

Java and Data Structures 24IIBSC

p nttry void Volatile While switch synchroni

zedthis

Throw

IdentifiersIdentifiers are programmer-designed tokens. They are used for namingclasses, methods, variables, objects, labels packages and interfacesin a program. Java identifiers follow the following rules:1.They can have alphabets, digits, and the underscore and dollarsign characters.2. They must not begin with the digit.3.Uppercase and lowercase letters are distinct.4. They can be of any length.Identifiers must be meaningful , short enough to be quickly andeasily typed and long enough to be descriptive and easily read. Javadevelopers have followed some naming conventions.

Names of all public method and instance variables start with aleading lowercase letter. Ex: sum.

When more than one words are used in a name , the second andsubsequent words are marked with a leading upper case letters.Ex. totalMarks.

All private and local variables use only lowercase letterscombined with underscores. Ex: batch_strength.

All classes and interfaces start with a leading uppercaseletter Ex: Student.

Variables that represent constant values use all uppercaseletters and underscore between words. Ex:TOTAL

LiteralsLiterals in Java are a sequence of characters that representconstant values to be stored in variables. Java language specifiesfive major types of literals. They are

Integer literals Floating literals Characters literals String literals Boolean literals

OperatorsAn operator is a symbol that takes one or more arguments and operateon them to produce a result.SeparatorsSeparators are symbols used to indicate where groups of code aredivided and arranged.

Page 25: Java and data structure

Java and Data Structures 25IIBSC

Name What is used forParentheses()

Used to enclose parameters in method definition andinvocation, also used for defining precedence inexpressions, containing expressions for flowcontrol, and surrounding cast types.

braces{ } Used to contain the values of automaticallyinitialized

Brackets[] Used to declare array types and for dereferencingarray values

Semicolon; Used to separate statementsComma , Used to separate consecutive identifiers in a

variable declaration, also used to chain statementstogether inside a ‘for’ statement

Period . Used to separate package names from sub-packagesand classes also used to separate a variable ormethod from a reference variable.

Java StatementsA statement is an executable combination of tokens ending with asemicolon(;) mark. Statements are usually executed in sequence inthe order in which they appear. However , it is possible to controlthe flow of execution, if necessary, using special statements.Statement

Description Remarks

EmptyStatement

These do nothing and are used duringprogram development as a place holder.

Same as Cand C++

LabeledStatement

Any statement may begin with a label.Such labels must not be keywords,already declared local variables orpreviously used labels in this module.Labels in Java are used as thearguments of Jump statements.

Identicalto C and C++ excepttheir usewith jumpstatements

Expressionstatement

Most statements are expressionstatements. Java has seven types ofExpression statements. Assignment, Pre-Increment, Pre-Decrement, Method calland Allocation Expression

Same as C++

Selectionstatement

These select one of several controlflows. Three are three types ofselection statements in Java: if, if-else and switch

Same as Cand C++

Iteratio These specify how and when looping will Same as C

Page 26: Java and data structure

Java Statements

Selection Statement Iteration Statement Jump Statement

Expression StatementLabeled statement

Control statement

Synchronization stateGuarding statement

switch

If-else

if break

continue

returndo

while for

Java and Data Structures 26IIBSC

nStatement

take place. There are three types ofiteration statements: while, do andfor.

and C++except forjumps andlabels.

JumpStatements

Jump statements pass control to thebeginning or end of the current block ,or to a labeled statement. Such labelsmust be in the same block, or to alabeled statement. Such labels must bein the same block, and continue labelsmust be on an iteration statement. Thefour types of Jump statement are break,continue, return and throw.

C and C++do not uselabels withjumpstatements.

Synchronizationstate

These are used for handling issues withmultithreading.

Nowavailablein C an C++

GuardingStatement

Guarding statements are used for safehandling of code that may causeexceptions. These statements use thekeywords try, catch , and finally.

Same as inC++ exceptfinallystatement.

Implementing a Java ProgramImplementation of a Java application program involves a series ofsteps. They include:

Creating the program Compiling the program Running the program

Page 27: Java and data structure

Source Code

Java Compiler

Bytecode

Windows InterpreterABC Interpreter Macintosh Interpreter

Machine Code Machine Code Machine Code

Java and Data Structures 27IIBSC

Creating the programWe can create a program using any text editor. Assume that we haveentered the following program.class Test{

public static void main(String args[]){

System.out.println(“Hello! “);System.out.println(“Welcome to the world of Java”);System.out.println(“Let us learn Java.”);

}} We must save this program in a file called Test.java ensuring thatthe filename contains the class name properly. This file is calledthe source file. If a program contains multiple classes, the filename must be the class name of the class containing the main method.

Compiling the programTo compile the program, we must run the Java Compiler javac, withthe name of the source file on the command line as shown below.

Javac Test.java

If everything is OK, the javac compiler creates a file calledTest.class containing the bytecodes of the program. Aftercompilation javac complier create a file with extension .classcontaining the bytecodes of the program.

Fig: Implementation of java programs

Page 28: Java and data structure

Windows Computer ABC Computer Macintosh Computer

Java Program Java Compiler Virtual Machine

Bytecode Java Interpreter Machine Code

Java and Data Structures 28IIBSC

Running the ProgramWe need to use the Java interpreter to run a stand alone program. Atthe command prompt, type

java Test

Now, the interpreter looks for the main method in the program andbegins execution from there, our program and gives result.

Machine NeutralThe compiler converts the source code files into bytecode files.These codes are machine-independent and therefore can be run on anymachine. That is, a program compiled on an IBM machine will run on aMacintosh machine.Java interpreter reads the bytecode files and translates them intomachine code for the specific machine on which the Java program isrunning.

Java Virtual MachineJava compiler produces an intermedia code known as bytecode for amachine that does not exist. This machine is called Java VirtualMachine and it exists only inside the computer memory. It is asimulated computer within the computer and does all major functionsof a real computer. Fig shows the process of compiling a Javaprogram into bytecode which is also referred to as virtual machinecode.

Process of compilationThe virtual machine code is not machine specific. The machinespecific cod is generated by the Java interpreter by acting as anintermediary between the virtual machine and the real machine as infig. Remember that the interpreter is different for differentmachines.

Page 29: Java and data structure

Real Machine

User

Java and Data Structures 29IIBSC

Process of converting byte code into machine codeFig. shows how Java works on a typical computer. The Java objectframe work(Java API) acts as the intermediary between the userprograms and the virtual machine which in turn acts as theintermediary between the operating system and the Java objectframework.

Layers of interactions for Java programsCommand Line argumentsThere may be occasions when we may like our programs to act in aparticular way depending on the input provided at the time ofexecution. This is achieved in Java programs by using what are knownas command line arguments. Command line arguments are parametersthat are supplied to the application program at the time ofexecution.class Test{

public static void main(String args[]){

System.out.println(“Hello! “);System.out.println(“Welcome to the world of Java”);System.out.println(“Let us learn Java.”);

}}It may be called program Test was invoked for execution of thecommand line is as follows:java Test

Here, we have not supplied any command line arguments. Even if wesupply arguments, the program does not know what to do with them. In

Page 30: Java and data structure

Java and Data Structures 30IIBSC

main(String args[]) method , args is declared as an array ofstrings(known as string objects). Any arguments provided in thecommand line(at the time of execution) are passed to the array argsas its elements. We can simply access the array elements and usethem in the program as we wish. For example, consider the commandlinejava Test BASIC FORTRAN C++ JAVAThis command line contains four arguments. These are assigned to thearray args as follows:BASIC ---- -> args[0]FORTRAN -----> args[1]C++ -----> args[2]JAVA -----> args[3]The individual elements of an array are accessed by using an indexor subscript like args[i]. The value of i denotes the position ofthe elements inside the array. For example, args[2] denotes thethird element and represents C++.Program :Use of command line arguments//Program uses command line arguments as inputclass ComLineTest{

public static void main(String args[]){

int count, i=0;String string;count=args.length;System.out.println(“Number of arguments =”,+count);while( i < count){

String string;count = args.length; System.out.println(“Number of arguments = “ +count);while(i < count){

String= args[i];i= i+1;System.out.println(i+ “ ; “+” Java

is”+string+” ! ”);}

} }}This program illustrates the use of command line arguments. Compileand run the program with the command line as follows:

Page 31: Java and data structure

Java and Data Structures 31IIBSC

java ComLineTest Simple Object Oriented Distributed Robust Secureportable Multithreaded Dynamic

Upon execution, the command line arguments Simple, Object Oriented,etc are passed to the program through the array args. That is theelement args[0] contains Simple args[1] contains Object Oriented andso on. These elements are accessed using the loop variable I as anindex. The index is incremented using a while until all thearguments are accessed. TThe number of arguments is obtained by statement count= args.length;Output:Number of arguments =01 Java is Simple 2 Java is Object Oriented 3 Java is Distributed 4 Java is Robust 5 Java is Secure 6 Java is portable 7 Java is Multithreaded 8 Java is Dynamic

Programming StyleJava is a freeform language. We need not have to indent any lines tomake the program work properly. Java system does not care where onthe line we begin typing. We should try to use this fact to ouradvantage for producing readable programs. Although severalalternate styles are possible , we should select one and try to useit with total consistency.For example , the statement System.out.println(“Java is Wonderful”);Can be written asSystem.out.println(“Java is Wonderful”);OrSystem.out.Println(“Java is Wonderful”);

4. Constants, Variables, and Data typesConstantsConstants in Java refer to fixed values that do not change duringthe execution of a program.

Page 32: Java and data structure

Java and Data Structures 32IIBSC

Integer ConstantsAn integer constant refers to a sequence of digits. There are threetypes of integers, namely, decimal integer, octal integer andhexadecimal integer.

Decimal integers consists of a set of digits, 0 through 9,preceded by an optional minus sign. Valid examples of decimalinteger constants are: 123 -32 0 . Embedded spaces, commas,and non-digit characters are not permitted between digits.

An octal integer constant consists of any combination of digitsfrom the set 0 through 7, with a leading 0. Some examples ofoctal integer are: 03 012

A sequence of digits preceded by ox or OX is considered ashexadecimal integer. They may also include alphabets A throughF or a through f. A through F represent the numbers 10 through15. Ex 0X2 0Xbc

Real constantsNumbers containing fractional parts are called real constants. Ex:215 , .95, -.23A real number may also be expressed in exponential (orscientific )notation. For example, the value 215.65 may be writtenas 2.1565e2 in exponential notation. e2 means multiply by 102. Thegeneral form is mantissa e exponent. The mantissa is either a realnumber expressed in decimal notation or an integer. The exponentinteger with an optional plus or minus sign. The letter separatingthe mantissa and the exponent can be written in either lowercase oruppercase. Ex: .065e4 12e-2 1.2e+5 -1.2e-1.

String character constantsA single character constant contains a single character enclosedwithin a pair of single quote marks. Ex ‘5’ ‘X’ ‘ ‘

String constantsA string constant is a sequence of characters enclosed betweendouble quotes. The characters may be alphabets, digits, specialcharacters and blank spaces. Ex. “Hello Java” “2009” “well done”

Backslash character constantsJava supports some special backslash character constants that areused in output methods.

Constant Meaning‘\b’ Back space‘\f’ Form feed

Page 33: Java and data structure

Data Types in JAVA

Primitive(Intrinsic)

Numeric Non-Numeric Classes Interface Arrays

Non-Primitive(Derived)

Integer Floating-pointCharacter Boolean

Java and Data Structures 33IIBSC

‘\n’ New line‘\r’ Carriage

return‘\t’ Horizontal tab‘\’’ Single quote‘\” ‘ Double quote‘\\’ Backslash

VariablesA variable is an identifier that denotes a storage location used tostore a data value. Unlike constants that remain unchanged duringthe execution of a program, variable may take different values atdifferent times during the execution of the program. Some examplesof variable names are : average, height.

Data typesEvery variable in Java has a data type. Data types specify the sizeand type of values that can be stored Java language is rich in itsdata types. Data types in Java under various categories are shown infig.

Integer TypesJava supports four types of integers. They are byte , short, int,and long. Java does not support the concept of unsigned types andtherefore all Java values are signed meaning they can be positive ornegative. Table shows the memory size and range of all the fourinteger data types.

Type Size Minimum value Maximum valueByte One byte -128 127Short

Two bytes -32,768 32,767

Int Fourbytes

-2,147,483,648 2,147,483,647

Long Eightbytes

-9,223,372,036,854,775,808

9,223,372,036,854,775,807

Page 34: Java and data structure

Java and Data Structures 34IIBSC

It should be remembered that wider data types require more time formanipulation and therefore it is advisable to use smaller data types, wherever possible.

Floating point TypesFloating point type to hold numbers containing fractional parts suchas 22.89. There are two kinds of floating point storage in Java. Thefloat type values are single-precision numbers while the doubletypes represent double precision numbers.

Character TypeIn order to store character constants in memory , Java provides acharacter data type called char. The char type assumes a size of 2bytes but , basically , it can hold only single character.

Boolean TypeBoolean type is used when we want to test a particular conditionduring the execution of the program. There are two values that the aBoolean type can take: true or false. Boolean type is denoted by thekeyword Boolean and uses only one bit of storage.

Declaration of variablesIn Java, variables are the names of storage locations. Aftersuitable 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 the variable. A

variable must be declared before it is used in the program.The general form of declaration of a variable is : type variable1,variable2, ….. .. .. variable;Variables are separated by commas. A declaration statement must endwith a semicolon. Some valid declarations are:int count;float x,y;double p1; byte b; char c1,c2,c3;

Giving values to variablesA variable must be given a value after it has been declared butbefore it is used in an expression. This can be achieved in twoways:

1. By using an assignment statement

Page 35: Java and data structure

Java and Data Structures 35IIBSC

2. By using a read statement.

Assignment statementA simple method of giving value to a variable is through theassignment statement as follows: variableName=value; Ex: initialValue=0; finalValue=100; yes=’x’;It is also possible to assign a value to a variable at the time ofits declaration. This takes the form: type variableName=value; Ex: int finalValue=100;The process of giving initial values to variables is known as theinitialization. The ones that are not initialized are automaticallyset to zero.

Read StatementWe may also give values to variable interactively through thekeyboard using the readLine() method as shown in program belowReading data from keyboardimport java.io.DataInputStreamclass Reading{

public static void main(String args[]){

DataInputStream in=new DataInputStream(System.in);int intNumber = 0;float floatNumber=0.0f;try{

System.out.println(Enter an integer : “);intNumber= Integer.parseInt(in.readLine());System.out.println(Enter a float number : “);floatNumber =

Float.valueOf(in.readLine()).floatValue();}catch(Exception e){ }System.out.println(“int Number =”+intNumber);System.out.println(“floatNumber= “+floatNumber);

}}The readLine() method (which is invoked using an object of the classDataInputStream) reads the input from the keyboard as a string which

Page 36: Java and data structure

Java and Data Structures 36IIBSC

is then converted to the corresponding data type using the data typewrapper classes. The keywords try and catch are used to handle anyerrors that might occur during the reading process.

Scope of VariablesJava variables are actually classified into three kinds:

Instance variables. Class variables Local variables

Instance and class variables are declared inside a class. Instancevariables are created when the objects are instantiated andtherefore they are associated with the objects. They take differentvalues for each object. On the other hand, class variables areglobal to a class and belong to the entire set of objects that classcreates. Only one memory location is created for each variable.Variables declared and used inside methods are called localvariables. They are called so because they are not available for useoutside the method definition. Local variable can also be declaredinside program blocks that are defined between an opening brace{ and a closing brace }. These variables are visible to the programonly from the beginning of its program block to the end of theprogram block. When the program control leaves a block, all thevariables in the block will cease to exist. The area of the programwhere the variable is accessible is called its scope.

Symbolic ConstantsWe often use certain unique constants in a program. These constantsmay appear repeatedly in a number of places in the program. Oneexample of such a constants is 3.142, representing the value of themathematical constant “pi”.

ModifiabilityWe may like to change the value of “pi” from 3.142 to 3.14159 toimprove the accuracy of calculator.UnderstandabilityA constant is declared as follows: final type symbolic-name =value; Valid examples of constant declaration are:final int STRENGTH = 100;final float PI = 3.14159;1.Symbolic names take the same from as variable names. But, they arewritten in CAPITALS to visually distinguish them from normalvariable names. This is only a convention, not a rule.

Page 37: Java and data structure

Java and Data Structures 37IIBSC

2. After declaration of symbolic constants, they should not beassigned any other value within the program by using an assignmentstatement. For example, STRENGTH=200; is illegal.3. Symbolic constants are declared for types. This is not done in Cand C++ where symbolic constants are defined using the #definestatement.They can NOT be declared inside a method. They should be used onlyas class data members in the beginning of the class.

Type CastingThere is a need to store a value of one type into a variable ofanother type. In Such situations, we must cast the value to bestored by proceeding it with the type name in parentheses. The syntax is type variable1=(type) variable2; The processed of converting one data type to another is calledcasting. int m=50; byte n=(byte)m; casting is often necessary when a method returns a type differentthan the one we require.

Casts that results in No Loss ofinformationbyte Short, char, int , long, float,

doubleshort int, long, float, doublechar int, long, float, doubleint long, float, double long Float, doublefloat Double

Automatic ConversionFor some types, it is possible to assign a value of one type to avariable of a different type without a cast. Java does theconversion of the assigned value automatically. This is known asautomatic type conversion. Automatic type conversion is possibleonly if the destination type has enough precession to store thesource value. For example , int is large enough to hold a bytevalue. Therefore, byte b=75; int a=b; are valid statements.class TypeWrap{

Page 38: Java and data structure

Java and Data Structures 38IIBSC

public static void main(String args[]{

byte b=50;int i=123456789;long l=1234567654321L;float f=3.142F;System.out.println(“Variables: b=”+b+” i= “+i+” l = “+l +”

f = “+f);System.out.println(“Types converted:”);System.out.println(“(short)b = ”+short(b));System.out.println(“(short)I = ”+short(i));System.out.println(“(float)l=”+float(l));System.out.println(“(int)f = ”+int(f));

}}

Getting values of variablesA computer program is written to manipulate a given set of data andto display or print the results. Java supports two output methodsthat can be used to send the results to the screen.

print() method println() method

The print() method sends information into a buffer. This buffer isnot flushed until a new line character is sent. As a result, theprint() method prints output on one line until a newline characteris encountered. For example, the statements

System.out.print(“Hello”);System.out.print(“Java!”);

Will display the words Hello Java! on one line and waits fordisplaying further information on the same line. We may force thedisplay to be brought to the next line by printing a newlinecharacter as shown below:System.out.print(‘\n’);

For example, the statementsSystem.out.print(“Hello”);System.out.print(\n”);System.out.print(“Java!”);

Will display the output in two lines as follows:Hello

Page 39: Java and data structure

Java and Data Structures 39IIBSC

Java!The println()method, by contrast , take the information provided anddisplays it on a line followed by a line feed. This means that thestatementsSystem.out.println(“Hello”);System.out.println(“Java!”);Will produce the following output:HelloJava!The statement System.out.println(); will print a blank line.Standard default valuesIn Java, every variable has a default value. If we don’t initializea variable when it is first created, Java provides default value tothat variable type automatically as shown in table.Default values for various types

Type ofvariable

Default value

Byte Zero : (byte)0Short Zero : (short)0Int Zero : 0Long Zero : 0LFloat 0.0fDouble 0.0dChar Null characterboolean falsereference Null

5.Operators and ExpressionsJava operators can be classified into a number of related categoriesas below:

1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment and decrement operators6. Conditional operators7. Bitwise operators8. Special operators

Arithmetic operatorsArithmetic operators are used to construct mathematical expressionsas in algebra. Java provides the basic arithmetic operators. Theunary minus operator, in effect , multiplies its single operand by -1. Therefore, a number preceded by a minus sign changes its sign.

Page 40: Java and data structure

Java and Data Structures 40IIBSC

Operator Meaning+ Addition or unary plus- Subtraction or unary minus* Multiplication/ Division% Modulo division (Remainder)

Arithmetic operators are used as shown below:a-b a+b a*b a/b a%b -a*bHere a and b may be variables or constants and are known asoperands.

Integer arithmeticWhen both the operands in a single arithmetic expression such as a+bare integers, the expression is called an integer expression, andthe operation is called integer arithmetic. Integer arithmeticalways yields an integer value. a/b, when a and b are integer types,gives the result of division of a by b after truncating the divisor.This operation is called the integer division.

Real ArithmeticAn arithmetic operation involving only real operands is called realarithmetic.

Mixed –mode ArithmeticWhen one of the operands is real and the other is integer, theexpression is called a mixed –mode arithmetic expression. If eitheroperand is of the real type, then the other operand is converted toreal and the real arithmetic is performed. The result will be areal.class ArithmeticOp{

public static void main(String args[]){

int a=10,b=2;System.out.println(“a=”+b);System.out.println(“b=”+b);System.out.println(“a+b=”+(a+b));System.out.println(“a-b=”+(a-b));System.out.println(“a*b=”+(a*b));System.out.println(“a/b=”+(a/b));System.out.println(“a%b=”+(a%b));

}}Relational operators

Page 41: Java and data structure

Java and Data Structures 41IIBSC

We often compare two quantities, and depending on their relation ,take certain decisions. Java supports six relational operators inall. These operators and their meanings are shown in table

Operator Meaning< Is less than<= Is less than or

equal to> Is greater than>= Is greater than or

equal to == Is equal to != Is not equal to

A simple relational expression contains only one relational operatorand is of the following form:

ae-1 relational operator ae-2ae-1 and ae-2 are arithmetic expressions, which may be simpleconstants, variables or combination of them. When arithmeticexpressions are used on either side of a relational operator, thearithmetic expressions will be evaluated first and then the resultscompared. That is, arithmetic operators have a higher priority overrelational operators.class RelationalOp{

public static void main(String args[]){

int a=15,b=20,c=25;System.out.println(“a =”+a+” b = ”+b+” c = “+c);System.out.println(“a < b is ”+(a<b));System.out.println(“a <= b is ”+(a<=b));System.out.println(“a > b is ”+(a>b));System.out.println(“a>= b is ”+(a>=b));System.out.println(“a == b is ”+(a==b));System.out.println(“a!=b is ”+(a!=b));

}}Logical operatorsJava has three logical operators. The logical operators && and ||are used when we want to from compound conditions by combining twoor more relations. An example is: a>b && x==10An expression of this kind which combines two or more relationalexpressions is termed as a logical expression or a compoundrelational expression.Op-1 Op-2 Op-1&&op-2 Op-1||op-2

Page 42: Java and data structure

Java and Data Structures 42IIBSC

true true True Truetrue true False Truefalse true False Truefalse fals

eFalse False

Assignment operatorsAssignment operators are used to assign the value of an expressionto a variable. We have seen the usual assignment operator, ‘=’. Inaddition , Java has a set of ‘shorthand’ assignment operators whichare used in the form

v op=exp;

Where v is a variable, exp is an expression and op is a Java binaryoperator. The operator op=is know as the shorthand assignmentoperator. The assignment statement v op=exp; is equivalent to v=v op(exp); with v accessed only once. Consider an example x+=y+1;This is same as the statement x= x+(y+1);

Increment and Decrement operatorsThe operator ++ adds 1 to the operand while – subtracts 1 . Botheare unary operators and are used in the following form:

++m; or m++; - -m; or m- -;

A prefix operator first adds 1 to the operand and then the result isassigned to the variable on left. On the other hand, a postfixoperator first assigns the value to the variable on left and thenincrements the operand.class IncrementOperator{

public static void main(String args[]){

int a=15, b=20;System.out.println(“a = ”+a+” b = “+b);System.out.println(“++a = ”+ ++a);System.out.println(“b++ = ”+ b++);System.out.println(“a = ”+a+” b = “+b);

}}

Page 43: Java and data structure

Java and Data Structures 43IIBSC

Conditional operatorThe character pair ? : is a ternary operator available in Java. Thisoperator is used to construct conditional expressions of the form

exp1 ? exp2 :exp3

Where exp1, exp2 , and exp3 are expressions.

The operator ?: works as follows :exp1 is evaluated first. If it isnonzero(true), then the expression exp2 is evaluated and becomes thevalue of the conditional expression. If exp1 is false, exp3 isevaluated and its value becomes the value of the conditionalexpression.

Bitwise operatorsJava has a distinction of supporting special operators known asbitwise operators for manipulation of data at values of bit level.These operators are used for testing the bits, or shifting them tothe right or left. Bitwise operators may not be applied to float ordouble.

OperatorMeaning

& Bitwise AND! Bitwise OR^ Bitwise exclusive OR~ One’s complement<< Shift left>> Shift right>>> Shift right with zero fill

Special operatorsJava supports some special operators of interest such as instanceofoperator and member selection operator(.).

The instanceof operatorThe instanceof is an object reference operator and returns true ifthe object on the left –hand side is an instance of the class givenon the right –hand side. This operator allows us to determinewhether the object belongs to a particular class or not.

Example:Person instanceof student

Page 44: Java and data structure

Java and Data Structures 44IIBSC

Is true if the object person belongs to the class student ;otherwise it is false.

Dot operatorThe dot operator(.) is used to access the instance variables andmethods of class objects. Examples: person1.age person1.salary() It is also used to access classed and sub-packages from a package.

Evaluation of ExpressionsExpressions are evaluated using an assignment statement of the formvariable=expression;Variable is any valid Java variable name. When the statement isencountered, the expression is evaluated first and the result thenreplaces the previous value of the variable on the left –hand side.

Precedence of arithmetic operatorsAn arithmetic expression without any parentheses will be evaluatedfrom left to right using the rules of precedence of operators. Thereare two distance priority levels of arithmetic operators in Java:

High priority * / %Low priority + -

The basic evaluation procedure includes two left-to-right passesthrough the expression. During the first pass, the high priorityoperators(if any) are applied as they are encountered. During thesecond pass ,the low priority operators(if any) are applied as theyare encountered. Consider the following evaluation statement:X=Consider the following evolution statement:

X=a-b/3+c*2-1When a =9-12/3+3*2-1 and is evaluated as follows:

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

Second passStep3 : x=5+6-1Step4 :x=11-1Step5: x=10

However, the order of evaluation can be changed by introducingparentheses into an expression. Consider the same expression withparentheses as shown below:

Page 45: Java and data structure

Java and Data Structures 45IIBSC

9-12/(3+)*(2-1)

Whenever the parentheses are used, the expressions withinparentheses assume highest priority . If two or more sets ofparentheses appear, the expression contained in the left-most set isevaluated first and right-most in the last. The above expression executes in First pass

step1 : 9-12/6*(2-1)Step2 :9-12/6*1

Second passStep3 : 9-2*1Step4 : 9 - 2

Third passStep5 =7

This time, the procedure consists of three left –to- right passes.Parentheses may be nested, and in such cases, evaluation of theexpression will proceed outward from the innermost set ofparentheses.

Type Conversions in ExpressionsJava permits mixing of constants and variables of different types inan expression. If byte, short and int variables are used in anexpression, the result is always promoted to int, to avoid overflow.If a single long is used in expression. The whole expression ispromoted to long.

Automated Type conversion chartchar Byte short in long float double

char int Int int int long float doublebyte int Int int int long float doubleShort int Int int int long float doubleInt int Int int int long float doublelong long Long long long long float doublefloat float Float float float float float doubledouble double double double double double double double

The final result of an expression is converted to the type of thevariable on the variable on the left of the assignment sign beforeassigning the value to it. However, the following changes areintroduced during the final assignment .1.float to int causes truncation of the fractional part.2. double to float causes rounding of digits.3.long to int causes dropping of the excess higher order bits.

Page 46: Java and data structure

Java and Data Structures 46IIBSC

Casting a valueJava performs type conversion automatically. However, there areinstances when we want to force a type conversion in a way that isdifferent from automatic conversion. The process of such a localconversion is known as casting a value.

The general for of a cast is (type_name) expression

Where type name is one of the standard data types. The expressionmay be a constant, variable or a expression.

class Casting{

public static void main(String args[]){

float sum=0.0F;for(int i=1;i<=10;i++){

sum=sum+1/(float)i;System.out.println(“i = ”+i);System.out.println(“ sum = ”+sum);

}}

}Generic Type CastingGenerics is one of the significant enhancements to Java by J2SE5.0programming language. Generics eliminate the need of explicit typecasting in collections. A collection is a set of interfaces andclasses that sort and manipulate a group of data into a single unit.To retrieve elements from a collection, we need to typecast theelements, because each element in a collection is considered to bean object. Also, typecasting is an unsafe operation because thecompiler cannot check the wrong casts. The compiler throws anexception if the casts fail at runtime. When using generics, thecompiler inserts type casts at appropriate places to implement typecasting. Therefore, the typecast becomes implicit rather thanexplicit. Generics also determines the typecast errors at compiletime rather than run time. Now, collections can contain objects ofonly one type. Using Generics, we can specify the type informationof data using a parameter. The type information specifies the classand hierarchy of classes and interfaces to which the object belongs.The syntax to declare a generic class is :

Page 47: Java and data structure

Java and Data Structures 47IIBSC

class SampleGenericClass<T>{ }

Here, <T> indicates that the SampleGenericClass class is of generictype.

Operator precedence and AssociativelyEach operator in Java has a precedence associated with it. Thisprecedence is used to determine how an expression involving morethan one operator is evaluated. There are distinct levels ofprecedence and an operator may belong to one of the levels. Theoperators at the higher level of precedence evaluated first. Theoperators of the same precedence are evaluated either from left toright or from right to left, depending on the level. This is knownas the associatively property of an operator.

Summary of Java operatorsOperator Description Associatively Rank.()[]

Member selectionFunction callArray elementreference

Left to right 1

-++--!-(type)

Unary minusIncrementDecrementLogical negationOnes complementCasting

Right to left 2

*/%

MultiplicationDivisionModulus

Left to right 3

+-

AdditionSubtraction

Left to right 4

<<>>>>>

Left shiftRight shiftRight shift with zerofill

Left to right 5

<<=>>=Instanceof

Less thanLess than or equal toGreater than Greater than or equalto Type comparison

Left to right 6

==!=

EqualityInequality

Left to right 7

Page 48: Java and data structure

Java and Data Structures 48IIBSC

& Bitwise AND Left to right 8^ Bitwise XOR Left to right 9| Bitwise OR Left to right 10&& Logical AND Left to right 11|| Logical OR Left to right 12?: Conditional operator Right to left 13=Op=

Assignment operatorsShorthand assignment

Right to left 14

Mathematical functionsMathematical functions are frequently used in analysis of real-life . Java supports these basic functions through Math classdefined in the java.lang package. Table lists the math functionsdefined in the Math class. These functions should be used asfollows. Math.function_name(). Ex: double y=Math.sqrt(x);Function

Action

sin(x) Returns the sine of the angle x in radianscos(x) Returns the cosine of the angle x in radianstan(x) Returns the tangent of the angle x in radiansasin(y) Returns the angle whose sine is yacos(y) Returns the angle whose cosign is yatan(y) Returns the angle whose tangent is yatan2(x,y)

Returns the angle whose tangent is x/y

pow(x,y)

Returns x raised to y(xy)

exp(x) Returns e raised to x(ex)log(x) Returns natural logarithm of xsqrt(x) Returns square root of xceli(x) Returns the smallest whole number greater than or

equal to x(rounding up)floor(x)

Returns the largest whole number less than or equalto x(rounded down)

rint(x) Returns the truncated value of x.round(x)

Returns the integer closest to the argument

abs(a) Returns the absolute value of amax(a,b)

Returns the maximum of a and b

min(a,b)

Returns the minimum of a and b

Page 49: Java and data structure

Test expr ?

Entry

False

True

Java and Data Structures 49IIBSC

6.Decision Making and BranchingJava language possesses such decision making capabilities andsupports the following statements known as control or decisionmaking statements.

1. If statement2. Switch statement3. Conditional statement

Decision making with If statement

The if statement is a powerful decision making statement and is usedto control the flow of executing of statements. It is basically atwo-way decision statement and is used in conjunction with anexpression.

It takes the following form: If(test expression)

It allows the computer to evaluate the expression first and then,depending on whether the value of the expression is true or false,it transfers the control to a particular statement. This point ofprogram has two paths to follow, one for the true condition and theother for the false condition as shown in above fig. The if statement may be implemented in different forms depending onthe complexity of conditions to be tested.

1. Simple if statement2. If. . .else statement3. Nested if . . .else statement4. Else if ladder

Simple if statement The general form of a simple if statement is

if(test expression){

Statement-block;}Statement –x;

Page 50: Java and data structure

False

Test expr ?

Entry

True block Statements

True

Next statement-x

Java and Data Structures 50IIBSC

The statement-block may be a single statement or a group ofstatements. If the test expression is true, the statement-block willbe executed ; otherwise the statement block will be skipped and theexecution will jump to the statement-x;

Flowchart of simple if control

class ifTest{

public static void main(String arg[])int i, count;float[] height={176.5F, 174.2F, 168.0F, 170.7F, 189.0F};count=0;for(i=0;i<5;i++){

If(height>170.0)count++;

}System.out.println(Number of persons with height>170.0

is”+count);}The If-else statementThe if . . else statement is an extension of the simple ifstatement. The general form isIf(test expression){

True-block statement(s)}else{

False-block statements(s);}Statement-x;If the test expression is true, then the true-block statementsimmediately following the if statement, are executed, otherwise thefalse-block statements are executed. In either case, either true-

Page 51: Java and data structure

Test expr ?

Entry

False

False block Statements

Statement-x

Flowchart of if . . else control

True block Statements

True

Java and Data Structures 51IIBSC

block or false –block will be executed, not both. It is shown infig.

ExampleClass IfElseTest{

public static void main(String args[]){

int number[]={50, 65, 77, 71, 84};int even=0, odd=0;for(int i=0; i<number.length; i++){

If(number[i]%2==0)even+=1;

elseodd+=1;

}Sytem.out.println(“Even Numbers: ”+even+” Odd Number:

“+odd);}

}Nesting of if - -else statementsWhen a series of decisions are involved, we may have to use morethan one if- - else statement in nested form as follows:

If(test condition1){

If(test condition2){

Statement1;}else{

Statement2;

Page 52: Java and data structure

Test expr ?

Entry

False True

Test expr ?True

Statement1

Statement-x

Flowchart of nested if . . else statements

Statement2

False

Statement2

Next statement

Java and Data Structures 52IIBSC

}else{

Statement3;}Statement-x;

If the condition1 is false, the statement3 will be executed ,otherwise it continues to perform the second test. IF the condition2true, the statement1will be evaluated, otherwise the statement2 willbe evaluated and then the control is transferred to the statement-x.

Example:class IfElseNesting{

public static void main(String args[]){ int a=325,b=712,c=432;System.out.println(“Largest value is : “);if(a>b){

if(a>c){

System.out.println(a);}else{

Page 53: Java and data structure

Entry

Test expr ?False

Default statement

Statement-x

Flowchart of else . . . if ladder

Statement-n

True

Next statement

Test expr ?True False

Statement1

Test expr ?True False

Statement2

Test expr ?True False

Statement3

Java and Data Structures 53IIBSC

Sytem.out.println(c );}

}else{

If(c>b){

Sytem.out.println( c);}else{

Sytem.out.println(b);}

}}}The Else If LadderThere is another way of putting ifs together when multipathdecisions are involved. A multipath decision is a chain of ifs inwhich the statement associated with each else is an if. It takes thefollowing general form:

If(condition1)

Page 54: Java and data structure

Java and Data Structures 54IIBSC

Statement1;else if(condition2)

statement2;else if(condition3)

statement3;- - - - - - - - - - - - - - - - - - - - - - - -

else if(condition n)statement-n;

elsedefault-statement;

statement-x;This construct is known as the else if ladder. The conditions areevaluated from the top to down words. As soon as true condition isfound, the statement associated with it is executes and the controlis transferred to the statement-x(skipping the rest o ladder). Whenall the n conditions become false, then the final else containingthe default –statement will be executed. class ElseIfLAdder{

public static void main(String args[]){

int rollNo[]={111, 222,333,444};int marks[]={81,75,43,58};int marks[]={81,75,43,58};for(int i=0;i<rollNo.length;i++){

If(marks>79)System.out.println(rollNo[i]+” Honours”);

else if(marks[i]>59)System.out.println(rollNumber[i] +”I Division”);

elseSystem.out.println(rollNumber[i] +”FAIL”);

}}

}The switch statementJava has a built-in multi way decision statement known as switch.The switch statement tests the value of a given variable against alist of case values and when a match is found, a block of statementsassociated with that case is executed. The general form of theswitch statement is shown below:switch(expression){

Page 55: Java and data structure

switch expr ?

Entry

Block-1

Selection process of the switch statement

True

Statement-x

Block-1

Default Block

Expression=value-2

Expression=value-1

(No match)default

Java and Data Structures 55IIBSC

case value-1: block-1 break;

case value-2: block-2break;

- - - - - -default:

default-blockbreak;

}statement-x;The expression is an integer expression or characters. Value-1,value-2 … . . are constants or constant expressions and are knownas case labels. Each of these values should be unique within aswitch statement. Block-1,block-2. . . are statement lists and maycontain zero or more statements. These is no need to put bracesaround these blocks but case labels end with a colon( : ).

When the switch is executed , the value of the expression issuccessively compared against the values value-1, value-2, . . . ifcase is found whose value matches with the value of the expressionthen the block of statements that follows the case are executed.

The break statement at the end of each block signals the end of aparticular case and causes an exit from the switch statement,transferring the control to the statement-x following the switch.The default is optional case. When present, it will be executed ifthe value of the expression does not match with any of the casevalues. If not present, no action takes place when all matches failand the control goes to the statement-x

Page 56: Java and data structure

Java and Data Structures 56IIBSC

class CityGuide{

public static void main(String args[]){

char choice;System.out.println(“Select your choice”);System.out.println(“MMadras”);System.out.println(“B Bombay”);Sytem.out.println(“CCalcutta”);System.out.print(“Choice - - ->”);System.out.flush( );try{

switch(choice=(char) System.in.read()){

case ‘M’:case ‘m’: System.out.println(“Madras : Booklet

5”); break;

case ‘B’:case ‘b’: System.out.println(“Bombay : Booklet

9”); break;

case ‘C’:case ‘c’: System.out.println(“Calcutta :

Booklet 15”); break;

default: Sytem.out.println(“Invalid Choice(IC)”);

}}catch(Exception e){

System.out.println(“I/O Error”);}

}}The ?: operatorThis operator is combination of ? and :, and takes three operands.This operator is popularly known as the conditional operator. Thegeneral form of use of the conditional operator is as follows:

condition expression ? expression1 : expression2

Page 57: Java and data structure

Test expr ?

Body of the loop

False

True

b)Exit control

Entry

Test expr ?

Entry

Body of the loop

False

a)Entry control

Java and Data Structures 57IIBSC

The conditional expression is evaluated first. IF the result istrue, expression1 is evaluated and is returned as the value of theconditional expression. Otherwise , expression2 is evaluated and itsvalue is returned.

7.Decision Making and LoopingThe process of repeatedly executing a block of statements is knownas looping. The statements in the block may be executed any numberof times, from zero to infinite number. If a loop continues forever,it is called an infinite loop.

Java supports such looping features which enable us to developconcise programs containing repetitive processes without usingunconditional branching statements like go to statement.

In looping , a sequence of statements are executed until someconditions for the termination of the loop are satisfied. A programloop therefore consists of two segments, one known as the body ofthe lop and the other known as the control statement . The controlstatement tests certain conditions and then directs the repeatedexecution of the statements contained in the body of the loop.

Depending on the position of the control statement in the loop,a control structure may be classified either as the entry-controlledloop or as exit –controlled loop. In entry-controlled loop, thecontrol conditions are tested before the start of the loopexecution. If the conditions are not satisfied, then the body of theloop will not be executed. In the case of an exit-controlled loop,the test is performed at the end of the body of the loop andtherefore the body is executed unconditionally for the first time.

The test conditions should be carefully stated in order to performthe desired number of loop executions. It is assumed that the test

Tru

Page 58: Java and data structure

Java and Data Structures 58IIBSC

condition will eventual transfer the control out of the loop. Incase, due to some reason if does not do so, the control sets up aninfinite loop and the body is executed over and over again.A looping process, in general, would include the following foursteps:

1. Setting and initialization of a counter.2. Execution of the statements in the loop.3. Test for a specified condition for execution of the loop.4. Incrementing the counter.

The test may be either to determine whether the loop has beenrepeated the specified number of times or to determine whether aparticular condition has been met with.

The Java language provides for three constructs for performingloop operations. They are

1. while construct2. do construct3. for construct

The While statementThe basic format of the while statement is Initializationwhile(test condition){

Body of the loop}The while is an entry-controlled loop statement. The test conditionis evaluated and if the condition is true, then the body of the loopis executed. After execution of the body, the test condition is onceagain evaluated and if it is true, the body is executed once again.This process of repeated execution of the body continues until thetest condition finally becomes false and the control is transferredout of the loop. On exit, the program continues with the statementimmediately after the body of the loop.The body of the loop may have one or more statements. The braces areneeded only if the body contains two or more statements.Exampleclass WhileTest{

public static void main(String args[]){

StringBuffer string=new StringBuffer();char c;System.out.println(“Enter a string”);try

Page 59: Java and data structure

Java and Data Structures 59IIBSC

{while((c=(char)System.in.read())!=’\n’){

string.append( c);}

}catch(Exception e){

System.out.println(“Error in input”);}System.out.println(“You have entered . . . “);System.out.println(string);

}}The do statementThis takes the formInitializationdo{

Body of the loop}while(test condition);

On reaching the do statement, the program proceeds to evaluatethe body of the loop first. At the end of the loop, the testcondition in the while statement is evaluated. If the condition istrue, the program continues to evaluate the body of the loop onceagain. This process continues as long as the condition is true. Whenthe condition becomes false, the loop will be terminated and thecontrol goes to the statement that appears immediately after thewhile statement.Since the test condition is evaluated at the bottom of the loop, thedo . . . . while construct provides an exit-controlled loop andtherefore the body of the loop is always executed at least once.Printing multiplication table using do - - while loopclass DoWhileTest{

public static void main(String args[]){

int row, column, y;System.out.println(“Multiplication Table\n”);row=1;do{

column=1;do

Page 60: Java and data structure

Java and Data Structures 60IIBSC

{y=row*column;

System.out.print(“ “+y);Column=column+1;

}while(column<=3);System.out.println(“\n”);row = row+1;}while(row<=3);

}}The for statementThe for loop is another entry-controlled loop. The general form ofthe for loop is for(initialization; test condition; increment){

Body of the loop}

The execution of the for statement is as follows:1.Initialization of the control variables is done first, usingassignment statements such as i=1 and count=0. The variables I andcount are known as loop-control variables.

2. The value of the control variable is tested using the testcondition. The test condition is a relational expression, such asi<10 that determines when the loop will exit. If the condition istrue, the body of the loop is executed, otherwise the loop isterminated and the execution continues with the statement thatimmediately follows the loop.

3.When the body of the loop is executed, the control is transferredback to the for statement after evaluating the last statement in theloop.

Now, the control variable is incremented using an assignmentstatement such as i=i+1 and the new value of the control variable isagain tested to see whether it satisfies the loop condition. If thecondition is satisfied, the body of the loop is again executed. Thisprocess continues till the value of the control variable fails tosatisfy the test condition.Consider the following segment of a program

for(x=0; x<=9; x=x+1) { System.out.println(x);}

Page 61: Java and data structure

Java and Data Structures 61IIBSC

This for loop is executed 10 times and prints the digits 0 to 9 inone line. The three sections enclosed within parentheses must beseparated by semicolon.

The for statement allows for negative increments. For example, theloop discussed above can be written as follows:

for(x=9; x>=0; x=x-1) System.out.println(x);

This loop is also executed 10 times, but the output would be from 9to 0 instead of 0 to 9.

Example: computing the power of 2 using for loop.class ForTest{

public static void main(String args[]){

long p; int n; double q;System.out.println(“2 to power –n n 2 to power

n”);p=1;for(n=0; n<10; ++n){

If(n==0) p=1;elsep=p*2;q=1.0/(double)p;System.out.println(“ “+q+” “+n+” “+p);

}}

}Additional Features of for loopMore than one variable can be initialized at a time in the forstatement. for(p=1,n=0; n<17; ++n). Like the initialization section,the increment section may also have more than one part. For example

for(n=1,m=50; n<m, n=n+1, m=m-1){ - - - -- }

is perfectly valid. The multiple arguments in the increment sectionare separated by commas. The third feature is that the testcondition may have any compound relation and the testing need not belimited only to the loop control variable.

Page 62: Java and data structure

Java and Data Structures 62IIBSC

Ex: for(i=1; i<20&&sum<100 ; ++){ - - - }

It is also permissible to use expressions in the assignmentstatements of initialization and increment sections. For example,the statement of the type for(x=(m+n)/2;x>0;x=x/2) is perfectlyvalid. Another unique aspect of for loop is that one or moresections can be omitted in the for statement. the initialization hasbeen done before the for statement and the control variable isincremented inside the loop. In such cases, the sections are leftblank. IF the test condition is not present , the for statement setsup an infinite loop.

Nesting of for loopsNesting of loops, that is , one for statement within another forstatement, is allowed in Java. Similarly, for loops can be nested asfollows: for(i=1; i<=10; ++i){

- - - - -for(j=1;j<10; ++j)

{- Inner loop- }- -outer loop- -

}

The loops should be properly indented so as enable the reader toeasily determine which statements are contained within each forstatement.

The enhanced for loopThis feature helps us to retrieve the array of elements efficientlyrather than using array indexes. We can also use this feature toeliminate the iterators in a for loop and to retrieve the elementsfrom a collection. The enhanced for loop takes the following form:

for(Type Identifier ; Expression) { // statements; }

Where , Type represents the data type or object used; Identifierrefers to the name of a variable ; and Expression is an instance ofthe java.lang.Iterable interface or an array.

int n[3]={72,33,94};for(int k=0; k<=3; k++)

Page 63: Java and data structure

Java and Data Structures 63IIBSC

if(n[k]>50 &&n[k]<100)System.out.println(“The selected value is “+n[k]);

Which is equivalent to the following code:int n[3]={72,33,94};for(int k : n)

if(k>50 &&k<100)System.out.println(“The selected value is “+k);

Jumps in LoopsJava permits a jump from one statement to the end or beginning of aloop as well as a jump out of a loop.

Jumping out of a LoopAn early exit from a loop can be accomplished by using the breakstatement. When break statement is encountered inside a loop, theloop is immediately exited and the program continues with thestatement immediately following the loop. When the loops are nested,the break would only exit from the loop containing it. That is , thebreak will exit only a single loop.

while(){ - - -if(condition) break;

- - }

do{ - - - - - - if(condition) break; - - - - -}while(- - - )

for(- - - -){ - - - - if(error) break;

- - - - }

for(- - - - ){ - - - - - - - - - - for(- - - - -){ -- - - -if(condition) break;

- - - -- }

}

Skipping a part of a loopDuring the loop operations, it may be necessary to skip a part ofthe body of the loop under certain conditions. Java supports thecontinue statement. The continue, as the name implies causes theloop to be continued with the next iteration after skipping anystatements in between. The continue statement tells the compiler.“Skip the following statements and continue with the nextiteration”. The format of the continue statement is simply continue;In while and do loops, continue causes the control to go directly tothe test condition and then to continue the iteration process. Inthe case of for loop, the increment section of the loop is executedbefore the test condition is evaluated.

Page 64: Java and data structure

Java and Data Structures 64IIBSC

while(testcondition){- - - if(- - - -) continue;- - - }

do{- - - - - if(- - - - - )continue; - - - -}while(test condition);

for(initialization;testcondition;increment){- - - - - if(- - - -)continue;-- - - - -}

Labelled loopsIn Java, we can give a label to a block of statements. A label isany valid Java variable name. To give a label to a loop , place itbefore the loop with a colon at the end. Example:Loop1: for(. . . . . .){ - - - -}

Use of continue and break statementclass ContinueBreak{

public static void main(String args[]){LOOP1: for(int i=1; i<100; i++)

{System.out.println(“ “);if(i>=10) break;for(int j=1; j<100;j++){

System.out.print(“*”);if(j= =1) continue LOOP1;

}}System.out.println(“Termination by BREAK”);

}}

8.Classes , Objects and MethodsDefining a classA class is a user –defined data type with a template that serves todefine its properties. Once the class type has been defined, we cancreate “variables” of that type using declarations that are similarto the basic type declarations. In Java, these variables are termedas instances of classes, which are the actual objects. The basicform of a class definition is : class classname [extends super class]

Page 65: Java and data structure

Java and Data Structures 65IIBSC

{[fields declaration; ][ methods declaration;]

}Every thing inside the square brackets is optional. This means thatthe following would be a

valid class definition:class Empty{ }Because the body is empty, this class does not contain anyproperties and therefore cannot do anything. classname andsuperclassname are any valid java identifiers. The keyword extendsindicates that the properties of the superclassname class areextended to the classname class.Fields Declaration Data is encapsulated in a class by placing datafields inside the body of the class definition. These variables arecalled instance variables because they are created whenever anobject of the class is instantiated.

class Rectangle{ int length; int width; }

Methods declaration Methods are declared inside the body of theclass but immediately after the declaration of instance variables.The general form of a method declaration is type methodname(parameter list){

Method body;}Method declarations have four basic parts:

The name of the method(methodname) The type of the value the method returns(type) A list of parameters(parameter-list) The body of the method

The body actually describes the operations to be performed on thedata. Let us consider the Rectangle class again and add a methodgetData() to it.class Rectangle{

int length;int width;void getdata(int x, int y){

length=x;

Page 66: Java and data structure

Action

Declare null

Statement

Rectangle rect1;

Result

rect1

Instantiate

Rectangle object

rect1=new Rectangle(); rect1

Rect1 is a reference to Rectangle object

Creating object references

Java and Data Structures 66IIBSC

width=y;}

}Creating ObjectsAn objects in Java is essentially a block of memory that containsspace to store all the instance variables. Creating an object isalso referred to as instantiating an object.Object in Java are created using the new operator. The new operatorcreates an object of the specified class and returns a reference tothat object. Ex. Creating object of type Rectangle. Rectangle rect1;rect1=new Rectangle(); The first statement declares a variable tohold the object reference and the second one actually assigns theobject reference to the variable. The variable rect1 is now anobject of the Rectangle class.

Both statements can be combined into one as shown below: Rectanglerect1=new Rectangle(); The method Rectangle is the defaultconstructor of the class. We can create any number of objects ofRectangle.

Accessing Class Membersobjectname.variablename=value;objectname.method(parameter-list);Here objectname is the name of the object, variablename is the nameof the instance variable inside the object that we wish to access,methodname is the method that we wish to call, and parameter-list isa comma separated list of “actual values” that must match in typeand number with the parameter list of the methodname declared in theclass. The instance variables of the Rectangle class may be accessedand assigned values as follows:rect1.length = 15;

Page 67: Java and data structure

Java and Data Structures 67IIBSC

rect1.width=10;rect1.getData(15,10);This code creates rect1 object and then passes in the values 15 and10 for the x and y parameters of the method getData.class Rectangle{

int length, 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;Rectangle rect1=new Rectangle();rect1.length=15; rect1.width=10;area1=rect1.length*rect1.width;System.out.println(“Area = “+area1);

}}

ConstructorsJava supports a special type of method , called a constructor, thatenables an object to initialize itself when it is created.Constructors have the same name as the class itself. Secondly, theydo not specify a return type, not even void . This is because theyreturn the instance of the class itself.class Rectangle{

int length; int width;Rectangle(int x, int y){

Length= x; width =y;}int rectArea(){

return(length*width);

Page 68: Java and data structure

Java and Data Structures 68IIBSC

}}class RectangleArea{

public static void main(String args[]){

Rectangle rect1= new Rectangle(15,10);int area1=rect1.rectArea();System.out.println(“Area1 = “+area1);

}}

Methods overloadingIn Java, it is possible to create methods that have the same name,but different parameter lists and different definitions. This iscalled method overloading. Method overloading is used when objectsare required to perform similar tasks but using different inputparameters. When we call a method in an object, java matches up themethod name first and then the number and type of parameters todecide which one of the definitions to execute. This process isknown as polymorphism.class Room{

float length; float breadth;Room(float x, float y){

length=x; breadth=y;}Room(float x){

length=breadth=x;}int area(){

return(length*breadth);}}class OverloadTest{

public static void main(String args[]){

Room room1=new Room(10);Room room2=new Room(15,10);System.out.println(“Room area=”+room1.area());

Page 69: Java and data structure

Java and Data Structures 69IIBSC

System.out.println(“Room area=”+room2.area());}

}

Static MembersA class basically contains two sections. One declares variables andthe other declares methods . These variables and methods are calledinstance variables and instance methods. This is because every timethe class is instantiated, a new copy of each of them is created.They are accessed using the objects(with dot operator).

static int count; static int max(int x, int y);

The members that are declared static as shown above are calledstatic members. Since these members are associated with the classitself rather than individual objects, the static variables andstatic methods are often referred to as class variables and classmethods in order to distinguish them from their counterparts,instance variables and instance methods. Java creates only one copyfor a static variable which can be used even if the class is neveractually instantiated. Like static variables, static methods can becalled without using the objects. They are also available for use byother classes. Java class libraries contain a large number of classmethods. For example, the Math class of Java library defines manystatic methods to perform math operations that can be used in anyprogram. Float x=Math.sqrt(25.0); the method sqrt is a class methoddefined in Math class.class Mathoperation{

static float mul(float x, float y){ return x*y; }static float divide(float x, float y){

return x/y;}

class MathApplication{

public void static main(String args[]){ float a =MathOperation.mul(4.0,5.0);

float b=MathOperation.divide(a,2.0);System.out.println(“b= “+b);

}}

Page 70: Java and data structure

Java and Data Structures 70IIBSC

Static methods have several restrictions: 1. They can only callother static methods. 2.They can only access static data. 3. Theycannot refer to this or super in any way.

Nesting of MethodsA method can be called by using only its name by another method ofthe same class. This is known as nesting of methods.Ex: class Nesting{

int m,n;Nesting(int x, int y){ m=x; n=y; }int largest(){

if(m>=n)return(m);elsereturn(n);

}void display(){

int larger=largest();System .out.println(“Largest value =”+large);

}}class NestingTest{

public static void main(String args[]){ Nesting nest =new Nesting(50,40);

nest.display();}

}

Inheritance :Extending a classJava supports reusability of code. Java classes can be reused inseveral ways. This is basically done by creating new classes,reusing the properties of existing ones. The mechanism of deriving anew class from an old one is called inheritance. The old class isknown as the base class or super class or parent class and the newone is called the subclass or derived class or child class.The inheritance allows subclasses to inherit all the variables andmethods of their parent classes inheritance may take differentforms:

Page 71: Java and data structure

A

B

A

B C D C

BA

Single InheritanceHierarchical inheritanceMultiple inheritance

A

C

B

Multilevel inheritance

Java and Data Structures 71IIBSC

Single inheritance(only one super class) Multiple inheritance(several super classes) Hierarchical inheritance(one super class, many subclasses) Multilevel inheritance(Derived from a derived class).

These forms of inheritance are shown in fig. Java does not directlyimplement multiple inheritance. However, this concept is implementedusing a secondary inheritance path in the form of interfaces.

Defining a subclassA subclass is defined as follows:class subclass extends superclass{

variables declaration;methods declaration;

}The keyword extends signifies that the properties of thesuperclassname are extended to the subclassname. The subclass willnow contain its own variables and methods as well those of thesuperclass. This kind of situation occurs when we want to add somemore properties to an existing class without actually modifying it.class Room{

int length; int breadth; Room(int x, int y){ length=x; breadth=y; }int area(){ return(length*breadth); }

}class BedRoom extends Room{ super(x,y); height=z; }

int volume(){ return(length*breadth*height); }

}class InherTest{

public static void main(String args[]){

Page 72: Java and data structure

A

C

B

Multilevel inheritance

Intermediate superclass

Superclass

Subclass

Father

Grand father

Child

Java and Data Structures 72IIBSC

BedRoom room1=new BedRoom(14,12,10);int area1=room1.area() ;int volume1=room1.volume();System.out.println(“Area1= “+area1);System.out.println(“Volume =”+volume);

}}Subclass constructorA subclass constructor is used to construct the instance variablesof both the subclass and the superclass. The subclass constructoruses the keyword super to invoke the constructor method of thesuperclass. The keyword super is used subject to the followingconditions.

Super may only be used within a subclass constructor method. The call to super constructor must appear as the first

statement within the subclass constructor. The parameters in the super call must match the order and type

of the instance variable declared in the superclass.

Multilevel inheritanceA common requirement in object-oriented programming is the use of aderived class as a super class. Java supports this concept and usesit extensively in building its class library. This concept allows usto build a chain of classes.

class Box{

private double width;private double height;private double depth;Box(double len){

width = height = depth = len;}double volume() {

return width * height * depth;

Page 73: Java and data structure

Java and Data Structures 73IIBSC

}}class BoxWeight extends Box {

double weight; BoxWeight(double len, double m) {

super(len);weight = m;

}}class Shipment extends BoxWeight {

double cost;Shipment(double len, double m, double c){

super(len, m);cost = c;

}}class DemoShipment{

public static void main(String args[]){

Shipment shipment1 = new Shipment(15, 10, 3.41);double vol = shipment1.volume();System.out.println("Volume of shipment1 is " + vol);System.out.println("Weight of shipment1 is "+shipment1.weight);System.out.println("Shipping cost: $" + shipment1.cost);System.out.println();

}} Hierarchical InheritanceAnother interesting application of inheritance is to use it as asupport to the hierarchical design of a program. Many programmingproblems can be cast into a hierarchy where certain features of onelevel are shared by many others below the level.Example 5-2 PersonTest.java import java.text.*; public class PersonTest {

public static void main(String[] args) {

Page 74: Java and data structure

Java and Data Structures 74IIBSC

Person[] people = new Person[2]; people[0] = new Employee("Harry Hacker", 50000); people[1] = new Student("Maria Morris", "computerscience"); for (int i = 0; i < people.length; i++) {

Person p = people[i]; System.out.println(p.getName() + ", " +p.getDescription());

} }

} abstract class Person {

public Person(String n) {

name = n; } public abstract String getDescription(); public String getName() { return name; } private String name;

} class Employee extends Person {

public Employee(String n, double s) {

super(n); salary = s;

} public double getSalary() {

return salary; } public String getDescription() {

return ("An employee with a salary of " +salary); }

} class Student extends Person {

public Student(String n, String m)

Page 75: Java and data structure

Java and Data Structures 75IIBSC

{ super(n); major = m;

} public String getDescription() {

return "a student majoring in " + major; }

}Overriding MethodsMethod inheritance enables us to define and use methods repeatedlyin subclasses without having to define the methods again insubclass.class Super{

int x;Super(int x){ this.x=x; }void display(){ System.out.println(“Super x= “+x); }

}class Sub extends Super{

int y;sub(int x, int y){ super(x); this.y=y; }void display(){ System.out.println(“Super x= “+x);

System.out.println(“Sub y= “+y);}

}class OverrideTest{

public static void main(String args[]){

Sub s1= new Sub(100,200);S1.display();

}}

Final variables and MethodsAll methods and variables can be overridden by default insubclasses. If we wish to prevent the subclasses from overriding the

Page 76: Java and data structure

Java and Data Structures 76IIBSC

members of the superclass, we can declare them as final using thekeyword final as a modifier . Example: final int SIZE=100;

final void showstatus(){ - - - -- -} Making a method final ensures that the functionality defined in thismethod will never be altered in any way. Similarly , the value of afinal variable can never be changed. Final variables, behave likeclass variables and they do not take any space on individual objectsof the class.

Final classesSometimes we may like to prevent a class being further subclassesfor security reasons. A class that cannot be subclassed is a finalclass.final class Aclass{ - - - - -}final class Bclass extends Someclass{ - - - - - } any attempt toinherit these classes will cause an error and the compiler will notallow it. Declaring a class final prevents any unwanted extensionsto the class. It also allows the compiler to perform someoptimizations when a method of a final class is invoked.

Finalizer methodsConstructor is used to initialize an object when it is declared.Java supports a concept called finalization, which is just oppositeto initialization. Java run-time is an automatic garbage collectingsystem. It automatically frees up the memory resources used by theobjects. But objects may hold other non-object resources such asfile descriptors or window system fonts. The garbage collectorcannot free these resources. In order to free these resources wemust use a finalizer method. The finalizer method is simplyfinalize() and can be added to any class. Java calls that methodwhenever it is about to reclaim the space for that object. Thefinalize method should explicitly define the tasks to be performed.

Abstract Methods and ClassesA method must always be redefined in a subclass, thus makingoverriding compulsory. This is done using the modifier keywordabstract in the method definition Ex: abstract class shape{- - -abstract void draw();

- - - }

Page 77: Java and data structure

Java and Data Structures 77IIBSC

When a class contains one or more abstract methods, it should alsobe declared abstract as shown in the example above. While usingabstract classes, we must satisfy the following conditions:

We cannot use abstract classes to instantiate objects directly.For example, Shape s=new Shape() is illegal because shape is anabstract class.

The abstract methods of an abstract class must be defined inits subclass.

We cannot declare abstract constructors or abstract staticmethods.

Methods with varargsVarargs represents variable length arguments in methods. Varargstakes the following form:<access specifier><static> void method-name(object . . . arguments){}In the above syntax, the method contains an argument called varargsin which Object is the type of an argument, ellipsis( . . .) is thekey to varargs and arguments is the name of the variable.For example, consider the following declaration of the method,sample, which contains the same type of arguments. String is usedfor more than arguments.public void sample(String . . . var_name);Where String. . .var_name specifies that we can pass any number ofString arguments to the Sample method.class Exampleprg{

for(String name:person){

System.out.println(“Hello “+name);}

}public static void main(String args[]){

Exampleprg(“John”,”David”,”Suhel”);}}

Visibility ControlThe visibility modifiers are also known as access modifiers. Javaprovides there types of visibility modifiers: public, private andprotected.

Public Access

Page 78: Java and data structure

Java and Data Structures 78IIBSC

Any variable or method is visible to the entire class in which it isdefined. A variable or method declared as public has the widestpossibility and accessible everywhere. public int number; public void sum(){}

Friendly AccessThe difference between the “public “ access and the “Friendly”access is that the public modifier makes fields visible in allclasses, regardless of their packages while the friendly accessmakes fields visible only in the same package, but not in otherpackages.

Protected AccessThe visibility level of a “protected” field lies in between thepublic access and friendly access. That is , the protected modifiermakes the fields visible not only to all classes and subclasses inthe same package but also to subclasses in other packages. Non-subclasses in other packages cannot access the “protected” members.

Private AccessPrivate fields enjoy the highest degree of protection. They areaccessible only with their own class. They cannot be inherited bysubclasses and therefore not accessible in subclasses. A methoddeclared as private behaves like a method declared as final.

Private protected AccessA field can be declared with keyword private and protected togetherlike:

private protected int codeNumber;

This gives a visibility level in between the “protected” access and“private” access. This modifier makes the fields visible in allsubclasses regardless of what package they are in. These fields arenot accessible by other classes in the same package.

Table summarizes the visibility provided by various access modifiers

AccessModifierAccesslocation

public

protected

friendly(default)

privateprotected

private

Same class Yes yes Yes yes YesSubclass in Yes yes Yes yes No

Page 79: Java and data structure

Java and Data Structures 79IIBSC

same packageOther classesin samepackage

Yes yes Yes no No

Subclass inother package

Yes yes No yes No

Non-subclasses inotherpackages

Yes no No no No

9.Arrays , Strings and VectorsArray An array is a group of contiguous or related data items that share acommon name. A particular value is indicated by writing a numbercalled index number or subscript in brackets after the array name.For example salary[10] represents the salary of the 10th employee.While the complete set of values is referred to as an array, theindividual values are called elements. Arrays can be of any variabletype.

One-dimensional ArraysA list of items can be given one variable name using only onesubscript and such a variable is called a single-subscriptedvariable or a one-dimensional array. The subscript can also beginwith number 0. That is x[0] is allowed. For example, if we want torepresent a set of five numbers, say (35,40,20,57,19), by an arrayvariable number, then we may create the variable number as follows

int number[]=new int [5];

and the computer reserves five storage locations as shown below:number[0], number[1],number[2],number[3],number[4].

Creating an ArrayArrays must be declared and created in the computer memory beforethey are used. Creation of an array involves three steps:

1.Declaring the array.2.Creating memory locations3.Putting values into the memory locations.

Declaration of ArraysArrays in Java may be declared in two forms:

Page 80: Java and data structure

Java and Data Structures 80IIBSC

Form1 type arrayname[ ];Form2 type[ ]arrayname;

Examples:int number[ ];float average[ ];int[ ] counter;float[ ] marks;Remember, we do not enter the size of the arrays in the declaration.

Creation of ArraysAfter declaring an array, we need to create it in the memory. Javaallows us to create arrays using new operator only , as shown below:

arrayname = new type[size];

Examples: number = new int[5]; average =new float[10];

These lines create necessary memory locations for the arrays numberand average and designate them as int and float respectively. Now,the variable number refers to an array of 5 integers and averagerefers to an array of 10 floating point values.It is also possible to combine the two steps- declaration andcreation-into one as shown below:

int number[ ] =new int[5];

Initialization of ArraysThe final step is to put values into the array created. This processis known as initialization. This is done using the array subscriptsas shown below: arrayname[subscript]=value;

Example: number[0] =35;

Java create arrays starting with the subscript of 0 and ends with avalue one less than the size specified. We can also initializearrays automatically in the same way as the ordinary variables whenthey are declared, as shown below:

type arrayname[ ] = {list of values};

Page 81: Java and data structure

Java and Data Structures 81IIBSC

The array initialize is a list of values separated by commas andsurrounded by curly braces.

Example: int number[ ]={ 35, 40, 20, 57,19};

Array LengthIn Java, all arrays store the allocated size in a variable namedlength. We can obtain the length of the array a using a.length.Example:

int aSize-a.length;

class NumberSorting{

public static void main(String args[]){

int number[ ]={55,40,80,65,71};int n=number.length;System.out.println(“Given list “);for(int i=0;i<n;i++)

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

for(int j=i+1;j<n;j++){

int t=number[i];number[i]= number[j];number[j]=t;

}}System.out.println(“Sorted list “);for(int i=0;i<n;i++)

System.out.println(number[i]);}

}Two-dimensional ArraysJava allows us to define such tables of items by using twodimensional arrays. Two dimensional arrays are stored in memory asshown in table. As with the single dimensional arrays, eachdimension of the array is indexed from zero to its maximum sizeminus one, the first index selects the row and the second indexselects the column within that row.

[0] [0] [0]

Page 82: Java and data structure

Java and Data Structures 82IIBSC

[0] [1] [2][1][0]

[1][1]

[1][2]

[2][0]

[2][1]

[2][2]

Or creating two-dimensional arrays, we must follow the same steps asthat of simple arrays. We may create a two-dimensional array likethis:

int myArray[ ][ ];myArray=new int [3][3]; orint myArray[ ][ ] =new int[3][3];

This creates a table that can store 9 integer values, three acrossand three down.

class MulTable{

final static int R=20;final static int C=20;public static void main(String args[]){

int p[][]= new int[R][C];System.out.println(“Multiplication Table:”);System.out.println();for(int i=10; i<R;i++){

for(int j=10; j<C;j++){

P[i][j]=i*j;System.out.print(“ “+p[i][j]);

}System.out.println();

}}

}Variable size ArraysJava treats multidimensional array as “arrays of arrays “. It ispossible to declare a two-dimensional array as follows: int x[ ][ ]=new int [3][];

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

Page 83: Java and data structure

Java and Data Structures 83IIBSC

These statements create a two-dimensional array as having differentlengths for each row.

StringsStrings represent a sequence of characters in Java is by using acharacter array .

Ex: char chararray[ ]= new char[4];

In Java, strings are class objects and implemented using two classes, namely, String and StringBuffer. A Java string is an instantiatedobject of the String class. A Java string is not a character arrayand is not NULL terminated. Strings may be declared and created asfollows:

String stringName; StringName = new String(“string”);

Example:String firstName;firstName=new String(“ Osmania”);Like arrays, it is possible to get the length of string using thelength method of the String class. int m=firstName.length();

String MethodsThe string class defines a number of methods that allow us toaccomplish a variety of string manipulation tasks. Method call Task performeds2=s1.toLowerCase; Converts the string s1 to all lowercases2=s1.toUpperCase; Converts the string s1 to all Uppercases2=s1.replace(‘x’,’y’);

Replace all appearances of x with y.

s2=s1.trim(); Remove white spaces at the beginning and endof the string s1

s1.equals(s2); Returns ‘true’ if s1 is equal to s2s1.equalsIgnoreCase(s2)

Returns ‘true’ if s1=s2, ignoring the case ofcharacters

s1.length() Gives the length of s1s1.CharAt(n) Gives nth character of s1s1.compareTo(s2) Returns negative if s1<s2,positive if s1>s2,

and zero if s1 is equal s2s1.concat(s2) Concatenates s1 and s2s1.substring(n) Gives substring starting from nth character

Page 84: Java and data structure

Java and Data Structures 84IIBSC

s1.substring(n,m) Gives substring starting from nth character upto mth

String.ValueOf(p) Creates a string object of the parameter p.p.toString() Creates a string object of the parameter p.p.toString() Creates a string representation of the object

ps1.indexOf(‘x’) Gives the position of the first occurrence of

‘x’ in the string s1s1.indexOf(‘x’,n) Gives the position of ‘x’ that occurs after

nth position in the string s1String.ValueOf(variable)

Converts the parameter value to stringrepresentation.

import java.io.*;class SortString {static String arr[] = { "ram", "sham", "swathi", "manjula", "sunitha", "aaparna", "azar", “sowmya","lakshmi", "ramesh", "sathish", "k.kanth", "anitha", "veena", "jyothi", "sowjanya"};

public static void main(String args[]) {

for(int j = 0; j < arr.length; j++) {

for(int i = j + 1; i < arr.length; i++){

if(arr[i].compareTo(arr[j]) < 0){

String t = arr[j];arr[j] = arr[i];arr[i] = t;

}}

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

System.out.println(arr[i]);}

}String Buffer ClassString Buffer is a peer class of String. While String createsstrings of fixed_length, StringBuffer creates strings of flexiblelength that can be modified in terms of both length and content. Wecan insert characters and substrings in the middle of a string, orappend another string to the end.Method Tasks1.setCharAt(n,’x Modifiers the nth character to x

Page 85: Java and data structure

Java and Data Structures 85IIBSC

’)s1.append(s2) Appends the string s2 to s1 at the ends1.insert(n,s2) Inserts the string s2 at the position n of the

string s1S1.setLength(n) Sets the length of the string s1 on n. if

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

class StringManipulation{

public static void main(String args[]){

StirngBuffer str = new StringBuffer(“Object language”);System.out.println(“Original String :”+str);System.out.println(“Length of string :”+str.length());for(int i=0; i<=str.length();i++){

int p = I +1;System.out.println(“Character at position :” + p + “

is “ +str.charAt(1));}String aString= new String(str.toString());int pos=aString.indexOf(“language”);str.insert(process, “Oriented “);System.out.println(“Modified string :” + str );Str.setCharAt(6, ‘-‘);System.out.println(“String now :”+str);str.append(“improves security “);System.out.print(“Appended string :”+ str);

}}VectorsThe Vector class contained in the java.util package. This class canbe used to create a generic dynamic array known as vector that canhold objects of any type and any number. The objects do not have tobe homogeneous. Arrays can be easily implemented as vectors. Vectorsare created like arrays as follows:

Vector intVect = new Vector();Vector list = new Vector(3);

A vector without size can accommodate an unknown number of items.Even, when a size is specified, this can be overlooked and adifferent number of items may be put into the vector. Remember, incontrast, an array must always have its size specified.

Page 86: Java and data structure

Java and Data Structures 86IIBSC

Vectors possess a number of advantages over arrays.1.It is convenient to use vectors to store objects.2. A vector can be used to store a list of objects that mayvary in size.3.We can add and delete objects from the list as and whenrequired.

A major constraint in using vectors is that we cannot directly storesimple data type in a vector, we can only store objects. Therefore,we need to convert simple types to objects. This can be done usingthe wrapper classes. The vector class supports a number of methodsthat can be used to manipulate the vectors created.

Method Call Task performedlist.addElement(item)

Adds the item specified to the list at theend.

list.elementAt(10) Gives the name of the 10th objectlist.size() Gives the number of objects presentlist.removeElement(item)

Removes the specified item from the list

list.removeElementAt(n)

Removes the item stored in the nth positionof the list

list.removeElements()

Removes allt eh elements in the list

list.copyInto(array) Copies all items from list to arrayList.insertElementAt(item,n)

Inserts the item at nth position

Working with vectors and arraysimport java..util.”;class LanguageVector{

public static void main(String args[]){

Vector list=new Vector(); int length= args.length;for(int i=0 ; i<length; i++){

list.addElement (args[i]);}list.insertElemetnAt(“COBOL”,2);int size=list.size();String listArray[]=new String[size];list.copyInto(listArray);System.out.println(“List of languages”);

Page 87: Java and data structure

Java and Data Structures 87IIBSC

for(int i=0;i<size;i++){

System.out.println(listArray[i]);}

}}

Wrapper ClassesVectors cannot handle primitive data types like int, float, long,char, and double. Primitive data types may be converted into objecttypes by using the wrapper classes contained in the java.langpackage. The simple data types and their corresponding wrapper classtypes.

Wrapper classes for converting simple types

Simple Type Wrapper Classboolean Booleanchar Characterdouble Doubleint Integerlong Long

The wrapper classes have a number of unique methods for handlingprimitive data types and objects. They are listed in the followingtables.

Converting Primitive Numbers to Object Numbers Using ConstructorMethods

Constructor calling Conversion ActionInteger IntVal=newInteger(1);

Primitive integer to Integerobject

Float FloatVal=new Float(f); Primitive float to Floatobject

Double DoubleVal=newDouble(d);

Primitive double to Doubleobject

Long LongVal=new Long(1); Primitive long to Long object

Converting Object Numbers to Primitive Numbers Using typeValue()method

Method Calling Conversion Actionint i=IntVal.intValue(); Object to primitive integer

Page 88: Java and data structure

Java and Data Structures 88IIBSC

floatf=floatVal.floatValue();

Object to primitive float

long l =LongVal.longValue();

Object to primitive long

Doubled=DoubleVal.doubleValue();

Object to primitive double

Converting Numbers to Strings Using to String() Method

Method Calling Conversion Actionstr = Integer.toString(i); Primitive integer to stringstr= Float.toString(f); Primitive float to stringstr=Double.toString(d); Primitive double to stringstr =Long.toString(l); Primitive long to string

Converting String Objects to Numeric Objects Using the Static MethodValueOf()

Method Calling Conversion ActionDoubleVal=Double.Valueof(str);

Converts string to Double object

FloatVal=float.ValueOf(str);

Converts string to Float object

IntVal=Integer.ValueOf(str);

Converts string to Integer object

LongVal=LongValueOf(str);

Converts string to Long object

Converting Numeric Strings to Primitive Numbers Using ParsingMethods

Method Calling Conversion Actioninti=Integer.parseInt(str);

Converts string to primitiveinteger

long l=Long.parseLong(str); Converts string to primitive longimport java.io.*;class Invest{

public static void main(String args[]){

Float p=new Float(0);Float r=new Float(0);

Page 89: Java and data structure

Java and Data Structures 89IIBSC

int n=0;try{

DataInputStream in=new DataInputStream(System.in);System.out.println(“Enter Principal Amount : “);System.out.flush();String pstr=in.readLine();P=Float.valueOf(pstr);System.out.println(“Enter Interest Rate: “);System.out.flush();String istr=in.readLine();r= Float.valueOf(istr);System.out.println(“Enter Number of Years: “);System.out.flush();String nstr=in.readLine();n= Integer.ParseInt(nstr);

} catch(IOException e) {

System.out.println(“I/O Error“);System.exit(1);

} int y=1; float s=p.floatValue(); r=r.floatValue(); while(y<=n)

{s=s*(1+r);y=y+1;

}System.out.println(“Final value = “+s);

}Autoboxing and UnboxingThe autoboxing and unboxing feature to convert primitive datatypesto wrapper class types automatically. The compiler generates acode implicitly to convert primitive type to the correspondingwrapper class type and vice-versa. For example , consider thefollowing statements.double d_object=98.42;double d_primitive =d_object.doubleVAlue();

Using the autoboxing and unboxing feature , we can rewrite the abovecode asdouble d_object=98.42;double d_primitive=d_object;

Page 90: Java and data structure

Java and Data Structures 90IIBSC

The Java compiler provides restrictions to perform the followingconversions:

Convert from null type to any primitive type. Convert to the null type other than the identify conversion. Convert from any class type C to any array type if C is not

object.

Adding two elements from stackimport java.util.Stack;public class autounboxex{

public static void main(Sting args[]){

Stack <Integer>Mystack= new Stack<Integer>();myStack.push(10);myStack.push(20);int stackSum=myStack.pop() +myStack.pop();System.out.println(“The topmost element from the stack

is :+mystack.pop());System.out.println(“The sum of two elements from the

Stack”+stackSum);}

}Enumerated TypesThe enumerated type in Java using the enum keyword. This keyword canbe used similar to the static final constants in the earlier versionof Java.The advantages of using the enumerated type are: Compile-time type safetyWe can use the enum keyword in switch statements.

public class workingdays{

enum Days{

Sundays, Monday, Tuesday, Wednesday, Thursday, Friday,Saturday

}public static void main(String args[]){

for( Days d: Days.values()){

weekend(d);}

Page 91: Java and data structure

Java and Data Structures 91IIBSC

}private static void weekend(Days d){

If(d.equals(Days.Sunday)System.out.println(“value = “ +d + “is a Holiday”);

else System.out.println(“Value =” + d + “is a working

day”);}

}

AnnotationsThe annotations feature is also known as metadata. Metadata isstored in Java class files by the compiler and these class files areused by the JVM or by the program to find the metadata forinteracting with the programming elements. Java contains thefollowing standard annotations:

Annotation Purpose@Deprecated Compiler warns when deprecated java elements are used

in non-deprecated program.@Overrides Compiler generated error when the method uses this

annotation type does not override the methods presentin the super-class.

In addition to the above standard annotations, Java also containssome meta-annotations available in the java.lang.annotation package.The following table provides the meta-annotations:

Meta-annotation

Purpose

@Documented Indicates annotation of this type to bedocumented by Javadoc.

@Inherited Indicates that this type is automaticallyinherited.

@Retention Indicates the extended period using annotationtype.

@Target Indicates to which program element theannotation is applicable.

The declaration of annotation is similar to that of an interface. Weuse the symbol ‘@’ before keyword interface.While using annotations, we need to follow some guidelines:

Page 92: Java and data structure

Java and Data Structures 92IIBSC

Do not use extends clause. It automatically extends the markerinterface java.lang.annotation. Annotation

Do not use any parameter for a method Do not use generic methods Do not use throws clause

An annotation can also be applied to programming elements. Forexample, consider the code in which an annotation is applied to themethods, positive() and negative() of a class, checking:import njunit.annotation.*;public class Checking{

@UnitTest(value=”Test1.Theis test will positive”)public void positive(int no){

assert no>0;}@UnitTest(“Test2. This test will negative”);public void negative(int no){

Assert no<0;}

}

The methods of the AnnotatedElement interface are: IsAnnotationPresent() getAnnotations() getAnnotation() getDeclaredAnnotations()

The classes that implement the AnnotatedElement interface are: java.lang.reflect.accessiblobject java.lang.class java.lang.reflect.constructor java.lang.reflect.field java.lang.reflect.method java.lang.package

10.Interfaces :Multiple InheritanceDefining interfaces An interface is basically a kind of class. Like classes, interfacescontain methods and variables but the difference is that interfacesdefine only abstract methods and final fields. This means thatinterfaces do not specify any code to implement these methods and

Page 93: Java and data structure

Java and Data Structures 93IIBSC

data fields contain only constraints. Therefore , it is theresponsibility of the class that implements an interface to definethe code for implementation of these methods.The syntax for defining an interface is very similar to that fordefining a class. The general forms of an interface definition is:

interface InterfaceName{

Variable declaration;Methods declaration;

}Here , interface is the key word and InterfaceName is any valid Javavariable. Variables are declared as follows:static final type variableName =value;

Note that all variables are declared as constants. Methodsdeclaration will contain only a list of methods without any bodystatements. Example:

return-type methodName1(parameter_list);

Here is an example of an interface definition that contains twovariables and one method:Interface Item{

static final int code =1001;static final String name= “Fan”;void display();

}

Extending InterfacesLike classes, interfaces can also be extended. That is , aninterface can be subinterfaced from other interfaces. The newsubinterface will inherit all the members of the superinterface inthe manner similar to subclasses. This is achieved using the keywordextends as shown below:

interface name2 extends name1{

Body of name2}

Page 94: Java and data structure

Java and Data Structures 94IIBSC

For example, we can put all the constants in one interface and themethods in the other. This will enable us to use the constants inclasses where the methods are not required.

Example:Interface ItemConstants{

int code=1001;string name = “Fan”;

}Interface ItemConstants{

void display();}The interface Item would inherit both the constants code and nameinto it. Note that the variables name and code are declared likesimple variables. It is allowed because all the variables in aninterface are treated as constants although the keywords final andstatic are not present.We can also combine several interfaces together into a singleinterface. Following declarations are valid:Interface ItemConstants{

int code=1001;String name =”Fan”;

}Interface ItemMethods{

void display();}interface Item extends ItemConstants, ItemMethods{

- - -- - --}Implementing InterfacesInterfaces are used as “superclasses” whose properties areinherited by classes. It is therefore necessary to create a classthat inherits the given interface. This is done as follows:

class classname implements interfacename{

Body of classname

Page 95: Java and data structure

Java and Data Structures 95IIBSC

}

Here the class classname “implements” the interface interfacename.A more general form of implementation may look like this: class classname extends superclass implements interface1,interface2, . .

{Body of classname

}

This shows that a class can extend another class whileimplementing interfaces. When a class implements more than oneinterface, they are separated by a comma.

Interface Test.javainterface 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);}

}class interfaceTest{

public static void main(String args[]){

Rectangle rect=new Rectangle();Circle cir =new Circle();Area area;area = rect;System.out.println(“Area of Rectangle = ” +

area.compute(10,20);

Page 96: Java and data structure

Java and Data Structures 96IIBSC

area=cir;System.out.println(“Area of Circle =”+area.compute(10.0));

}}

Accessing Interface VariablesInterface can be used to declare a set of constants that can be usedin different classes. This is similar to creating header files in C++ to contain a large number of constants. Since such interfaces donot contain methods. The constant values will be available to anyclass that implements the interface. The values can b used in anymethod , as part of any variable declaration, or anywhere where wecan use a final value. Example:interface A{

int m=10;int n=50;

}class B implements A{

int x=m;void methodB(int size){

. . . .

. . . .if(size<n). . . . . . . .

}}Implementing multiple inheritanceclass Student{

int rollNumber;void getNumber(int n){

rollNumber=n;}void putNumber(){

System.out.println(“Roll No: “+rollNumber);}class Test extends Student{

float part1,part2;

Page 97: Java and data structure

Java and Data Structures 97IIBSC

void getMarks(float m1,float m2){

part1=m1;part2=m2;

}void putMarks(){

System.out.println(“Marks obtained “);System.out.println(“Part1 = “+part1);System.out.println(“Part2= “+part2);

}}interface Sports{

float sprtWt = 6.0F;void putwt();

}class Results extends Test implements Sports{

float total;public void putWt(){

System.out.println(“Sports Wt = “+sporWt);}void display(){

Total =part1 +part2 +sportWt;putNumber();putMarks();putWt();System.out.println(“Total score =”+total);}

}class Hybrid{

public static void main(String args[]){

Results student1= new Results();student1.getNumber(1234);student1.getMarks(27.5F,33.0F);student1.display();

}}Output:

Page 98: Java and data structure

lang util io awt net applet

Java

Java and Data Structures 98IIBSC

Roll No:1234Marks obtainedPart1 = 27.5Part2 = 33Sports Wt=6Total score =66.5

11. Packages:Putting Classes TogetherPackages act as “containers” for classes. By organizing our classesinto packages we achieve the following benefits:

1. The classes contained in the packages of other programscan be easily reused.

2. In packages, classes can be unique compared with classesin other packages. That is, two classes in two differentpackages can have the same name. They may be referred bytheir fully qualified name, comprising the package nameand the class name.

3. Packages provide a way to “hide” classes thus preventingother programs or packages from accessing classes that aremeant for internal use only.

4. Packages also provide a way for separating “design” from“coding”, First we can design classes and decide theirrelationships, and then we can implement the Java codeneeded for the methods. It is possible to change theimplementation of any method without affecting the rest ofthe design. Java packages are therefore classified into two types. Thefirst category is known as Java API packages and thesecond is known as user defined packages.

Java API PackagesJava API provides a large number of classes grouped into differentpackages according to functionality.

Java System Packages and Their ClassesPackage Name Contentsjava.lang Language support classes. These are classes that

Page 99: Java and data structure

Java

Package containing awt packageawt

ColorGraphicsFont

Images

Package containing classes

Classes containing methods

Java and Data Structures 99IIBSC

Java compiler itself uses and therefore they areautomatically imported. They include classes forprimitive types, strings , math functions, threadsand exceptions.

java.util Language utility classes such as vectors, hashtables, random numbers, date etc.

java.io Input/output support classes. They providefacilities for the input and output of data.

java.awt Set of classes for implementing graphical userinterface. They include classes for windows ,buttons , lists, menus and so on.

Java.net Classes for networking. They include classes forcommunicating with local computers as well as withinternet servers.

java.applet Classes for creating and implementing applets.

Using System PackagesThe packages are organized in hierarchical structure as shown infig. This shows that the Package named java contains the package awt , which in turn containsvarious classes required for implementing graphical user interface.

There are two ways of accessing the classes stored in a package. Thefirst approach is to use the fully qualified class name of the classthat we want to use. This is done by using the package namecontaining the class and then appending the class name to it usingthe dot operator. For example, if we want to refer to the classColor in the awt package, then we may do so as follows:

java.awt.Colour

Page 100: Java and data structure

Java and Data Structures 100IIBSC

we may llike to use many of the classes contained in a package. Wemay achieve this easily as follows:

import packagename.classname;or import packagename.*;

These are known as import statements and must appear at the top ofthe file, before any class declarations, import is a keyword.The first statement allows the specified class in the specifiedpackage to be imported. For example the statement

import java.awt.Color;imports the class Colour and therefore the class name can now bedirectly used in the program. There is no need to use the packagename to qualify the class.The second statement imports every class contained in the specifiedpackage. For example, the statement

import java.awt.*;

will bring all classes of java.awt package.

Naming conventionsPackages begin with lowercase letters. For example, look at thefollowing statement:

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

This statement users a fully qualified class name Math to invoke themethod sqrt(). Note that methods begin with lowercase letters.Consider another example:

java.awt.Points pts[];

This statement declares an array of Point type objects using thefully qualified class name. Every package name must be unique tomake the best use of packages. Duplicate names will cause run-timeerrors.

Creating PackagesWe must first declare the name of the package using the packagekeyword followed by a package name. This must be the first statementin a java source file. Here is an examplepackage firstPackage;

Page 101: Java and data structure

Java and Data Structures 101IIBSC

pulic class FirstClass{

--- - - - -- - -- }

Here the package name is firstPackage. The class FirstClass is nowconsidered a part of this package. Creating our own package involves the following steps:

1.Declare the package at the beginning of a file using the form

package packagename;

2.Define the class that is to be put in the package and declareit public.3. Create a subdirectory where the main source files arestored.4.Store the listing as the classname.java file in thesubdirectory created.5.Compile the file. This creates .class file in thesubdirectory.

Remember that case is significant and therefore the subdirectoryname must match the package name exactly.Java also supports the concept of package hierarchy. This is done byspecifying multiple names in a package statement, separated by dots.Example:

package firstPackage.secondPackage;

This approach allows us to group related classes into a package andthen group related packages into a large package. Remember to storethis package in a subdirectory named firstPackage/secondPackage.A java package file can have more than one class definitions. Insuch cases, only one of the classes may be declared public and thatclass name with .java extension is the source file name. When asource file with more than one class definition is compiled, Javacreates independent .class files for those classes.

Accessing a packageA Java system package can be accessed either using a fully qualifiedclass name or using a shortcut approach through the importstatement. We use the import statement when there are manyreferences to a particular package or the package name is too longand unwieldy.

Page 102: Java and data structure

Java and Data Structures 102IIBSC

The same approaches can be used to access the user-defined packagesas well. The import statement can be used to search a list ofpackages for a particular class. The general form of importstatement for searching a class is as follows:

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

Here package1 is the name of the top level package, package2 is thename of the package that is inside the package1, and so on. We canhave any number of packages in a package hierarchy. Finally, theexplicit classname is specified.

The import statement should appear before any class definitionsin a source file. Multiple import statements are allowed. Thefollowing is an example of importing a particular class:

import firstPackage.secondPAckage.MyClass;

After defining this statement , all the members of the class Myclasscan be directly accessed using the class name or its objectsdirectly without using the package name. We can also use anotherapproach as follows:

import packagename.*;Here, packagename may denote a ingle package or a hierarchy ofpackages.

Using a packagePackage named package1 containing a single class ClassA.

package package1;public class ClassA{

public void diaplayA(){

System.out.println(“Class A”);}

}This source file should be named ClassA.java and stored in thesubdirectory package1 as stated earlier. Now compile this java file.The resultant ClassA.class will be stored in the same directory.

import package1.ClassA;class PackageTest{

Page 103: Java and data structure

Java and Data Structures 103IIBSC

public static void main(String args[]){

ClassA objectA = new ClassA();objectA.display();

}}This listing shows a simple program that imports the class ClassAfrom the package package1. The source file should be saved asPackageTest1.java and then compiled. The source file and thecompiled file would be saved in the directory of which package1 wasa subdirectory. Now we can run the program and obtain the result.When the PackageTest1 program is run, java looks for the filePackageTest1.class and loads it using something called class loader.

Subclassing an imported class

Import package2.ClassB;class ClassC extends ClassB{

int n=20;void displayC(){

System.out.println(“Class C”);System.out.println(“m = “+ m);System.out.println(“n = “+ n);

}}class PackageTest3{

public static void main(String args[]){

ClassC object= new ClassC();objectC.displayB();objectC.displayC();

}}While using packages and inheritance in a program, we should beaware of the visibility restriction imposed by various accessprotection modifiers.

Access Protection

Access modifier public

protected

friendly(default

privateprotect

privateAccess location

Page 104: Java and data structure

Java and Data Structures 104IIBSC

) edSame class yes yes yes yes YesSubclass in same package yes yes Yes yes NoOther classes in samepackage

yes yes yes No No

Subclass in other package yes yes No yes NoNon-subclasses in otherpackages

yes No No No No

Adding a Class to a packageIt is simple to add a class to an existing package. Consider thefollowing package:

package p1;public ClassA{

//body of A}The package p1 contains one public class by name A. Suppose we wantto add another class B to this package . This can be done asfollows:

1.Define the class and make it public.2.Place the package statement

package p1;

Before the class definition as follows:

package p1;public p1;public classB{

//body of B}

3.Store this as B.java file user the directory p.4.Compile B.java file. This will create a B.class file andplace it in the directory p1.Now, the package p1 will contain both the classes A and B. Astatement like

import p1.*;Will import both of them.

Page 105: Java and data structure

Java and Data Structures 105IIBSC

If we want to create a package with multiple public classes in it,we may follow the following steps:

1.Decide the name of the package.2. Create a subdirectory with this name under the directorywhere main source files are stored.3.Create classes that are to be placed in the package inseparate source files and declare the package statement

package packagename;at the top of each source file.4.Switch to the subdirectory created earlier and compile eachsource file. When completed, the package would contain .classfiles of all the source files.

Hiding ClassesWhen we import a package using asterisk(*), all public classes areimported. However, we may prefer to “not import” certain classes.That is, we may like to hide these classes from accessing fromoutside of the package. Such classes should be declared “notpublic”,

Example:package p1;public class X{

//body of X}class Y{

//body of Y}Here, the class Y which is not declared public is hidden fromoutside of the package p1. This class can be seen and used only byother classes in the same package.Now, consider the following code, which imports the package p1 thatcontains classes X and Y

import p1.*;X objectX;Y object;

Page 106: Java and data structure

Java and Data Structures 106IIBSC

Java compiler would generate an error message for this code becausethe class Y, which has not been declared public , is not importedand therefore not available for creating its objects.

Static ImportThis feature eliminates the need of qualifying a static member withthe class name. The static import declaration is similar to that ofimport. We can use the import statement to import classes frompackages and use them without qualifying the package. Similarly, wecan use the static import statement to import static members fromclasses and use them without qualifying the class name. The syntaxfor using the static import feature is :

import static package-name.subpackage-name.calss-name.staticmember-name;orimport static package-name.subpackage-name.class-name.*;

Before introducing the static import feature, we had to use thestatic member with the qualifying class name. For example , considerthe following code that contains the static member PI;

double area_of_circle= Math.PI*radius*radius;

In the above code, PI is the static member of the class, Math. Sothe static member PI is used in the above program with the qualifiedclass name called Math. Also, before implementing the static importfeature, if we use static member in an interface and we need to useit in a class, then we have to implement that interface in theclass.Consider the following code that provides an example of importingthe interface, salary_increment to the class, salary_hike:public interface Salary_increment{

public static final double Manager=0.5;public static final double Clerk=0.25;

}Here , let us assume tht the interface is available in thesubpackage, employee_details of the employee package. If we need toaccess the interface, we can import the interface using the staticimport statement as followis:Import static employee.employee_details.Salary_increment;class Salary_hike{

Page 107: Java and data structure

Class ABC{….……..}

Beginning

Single-Threaded body of execution

End

Java and Data Structures 107IIBSC

public static void main(String args[]){

double manager_salary=Manager*Manager_current_salary;double clerk_salary=Clerk*Clerk_current_salary;. - - -

}}

12.Multithreaded ProgrammingMultithreading is a conceptual programming paradigm where a programis divided into two or more subprograms, which can be implemented atthe same time is parallel.A thread is similar to a program that has a single flow of control.It has a beginning, a body, and an end, and executes commandssequentially. A unique property of Java is its support formultithreading. That is, Java enables us to use multiple flows ofcontrol in developing programs. Each flow of control may be thoughtof as a separate tiny program known as a thread that runs inparallel to others as in fig. A program that contains multiple flowsof control is known as multithreaded program. Fig illustrates a Javaprogram with four threads, one main and three others. The mainthread a actually the main method module, which is designed tocreate and starts the other three threads, namely A, B and C.

Single-threaded program

Page 108: Java and data structure

Main method module

startstartstart

Thread BThread A Thread C

switching switching

Main Thread

Java and Data Structures 108IIBSC

Once initiated by the main thread, the threads A,B and cconcurrently and share the resources jointly. It is like peopleliving in joint families and sharing certain resources among all ofthem. The ability of a language to support multithreads is referredto as concurrency. Since threads in Java are subprograms of a mainapplication program and share the same memory space, they are knownas lightweight threads or lightweight processes.It is important to remember that ‘threads running in parallel’ doesnot really mean that they actually run at the same time . Since allthreads are running on a single processor, the flow of execution isshared between the threads. The java interpreter handles theseitching of control between the threads in such a way that itappears they are running concurrently.Multithreading is a powerful programming tool that makes Javadistinctly different from its fellow programming languages.Multithreading is useful in a number of ways. It enables programmersto do multiple things at one time. They can divide a long programinto threads and execute them in parallel.

A Multithreaded program

Creating ThreadsCreating threads in Java is simple. Threads are implemented in theform of objects that contain a method called run(). The run() methodis the heart and soul of any thread. It makes up the entire body foa thread and is the only method in which the thread’s behavior canbe implemented . A typical run() would appear as follows:

Page 109: Java and data structure

Java and Data Structures 109IIBSC

public void run(){

- - - - -- - - (statements for implementing thread)- - - - -

}The run() method should be invoked by an object of the concernedthread. This can be achieved by creating the thread and initiatingit with the help of another thread method called start().A new thread can be created in two ways.

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

2. By converting a class to a thread: Define a class thatimplements Runnable interface. The Runnable interface has onlyone method, run(), that is to be defined in the method with thecode to be executed by the thread.

Extending the Thread ClassWe can make our class runnable as thread by extending the classjava.lang.Thread. This gives us access to all the thread methodsdirectly. It includes the following steps:

1.Declare the class as extending the Thread class.2. Implement the run() method that is responsible for executingthe sequence of code that the thread will execute.3.Create a thread object and call the start() method toinitiate the thread execution.

Declaring the ClassThe Thread class can be extend as follows:class MyThread extends Thread{

- - - -- - - -

}Now we have a new type of thread MyThreadThe run() method has been inherited by the class MyThread. We haveto override this method in order to implement the code to beexecuted by our thread. The basic implementation of run() will looklike this:

public void run(){

- - -//Thread code here

Page 110: Java and data structure

Java and Data Structures 110IIBSC

}

When we start the new thread, Java calls the thread’s run() method,so it is the run() where all the action takes place.

Starting New ThreadTo actually create and run an instance of our thread class , we mustwrite the following

MyThread aThread= new MyThread();aThread.start();

The first line instantiates a new object of class MyThread. Thisstatement just creates the object. The thread that will run thisobject is not yet running. The thread is in a newborn state.The second line calls the start() method causing the thread to moveinto the runnable state. Then, the Java runtime will schedule thethread to run by invoking its run() method. Now, the thread is saidto be in the running state.

Creating threads using the thread classclass A extends Thread{

public void run(){

for(int i=1;i<=5;i++){

System.out.println(“\t From ThreadA :i=”+i);}System.out.println(“Exit form A”);

}}class B extends Thread{

public void run(){

for(int j=1;j<=5;j++){

System.out.println(“\t From ThreadB:j”+j);}System.out.println(“Exit from B”);

}}class B extends Thread

Page 111: Java and data structure

Java and Data Structures 111IIBSC

{public void run(){

for(int k=1;k<=5;k++){

System.out.println(“\tFrom Thread C:k=”+k);}

System.out.println(“Exit from C”);}

}class ThreadTest{

public static void main(String args[]){

new A().start();new B().start();new C().start();

}}

Stopping and Blocking a ThreadStopping a ThreadWhenever we want to stop a thread from running further, we may do soby calling stop() method, like:

aThread.stop();

This statement causes the thread to move to the dead state. A threadwill also move to the dead state automatically when it reaches theend of its method. The stop() method may be used when the prematuredeath of a thread is desired.

Blocking a ThreadA thread can also be temporarily suspended or blocked from enteringinto the runnable and subsequently running state by using either ofthe following thread methods:sleep(); //blocked for specific timesuspend() //blocked until further orderswait() //blocked until certain condition occursThese methods cause the thread to go into the blocked state. Thethread will return to the runnable state when the specified time iselapsed in the case of sleep(), the resume () method is invoked inthe case of suspend() , and the notify () method is called in thecase of wait().

Page 112: Java and data structure

Newborn

Dead

Blocked

Running Runnable

start

ActiveThread

stop

stop

yield

stop

New Thread

IdleThread

Resume notifySuspend sleep wait

KilledThread

Newborn

Dead

Blocked

Running Runnable

start

ActiveThread

stop

stop

yield

stop

New Thread

IdleThread

Resume notifySuspend sleep wait

KilledThread

Newborn

start stop

Java and Data Structures 112IIBSC

Life Cycle of a ThreadDuring the life time of a thread, there are many states it canenter. They include:1.Newborn state2.Runnable state3.Running state4.Blocked state5.Dead stateA thread is always in one of these five states. It can move from onestate to another via a variety of ways as shown in fig.

State transition diagram of a thread

Newborn stateWhen we create a thread object, the thread is born and is said to bein new born state. The thread is not yet scheduled for running . Atthis state, we can do only one of the following things with it:

Schedule it for running using start() method. Kill it using stop() method.

If scheduled , it moves to the runnable state. If we attempt to useany other method at this stage, an exception will be thrown.

Page 113: Java and data structure

Runnable state Dead state

Scheduling a new born thread

suspend

Running Runnable suspended

resume

yield

Running Thread Runnable Threads

Java and Data Structures 113IIBSC

Runnable stateThe runnable state means that the thread is ready for execution andis waiting for the availability of the processor. That is , thethread has joined the queue of threads that are waiting forexecution. If all threads have equal priority, then they are giventime slots for execution in round robin fashion, i.e, first-com ,first-serve manner. The thread that relinquishes control joins thequeue at the end and again waits for its turn. This process ofassigning time to threads is known as time-slicing.However, if we want a thread of relinquish control to another threadto equal priorty before its turn comes, we can do so by using theyield() method.

Relinquishing control using yield() method.

Running StateRunning means that the processor has given its time to the threadfor its execution. The thread runs until it quit control on its ownor it is preempted by a higher priority thread. A running thread mayquit its control in one of the following situations.1.It has been suspended using suspend() method. A suspend threadcan be revived by using the resume() method. This approach is usefulwhen we want to suspend a thread for some time due to certainreason, but do not want to kill it.

Page 114: Java and data structure

Sleep(t)

Running Runnable suspended

After(t)

wait

Running Runnable Waiting

Notify

Java and Data Structures 114IIBSC

Relinquishing control using suspend() method.

2.It has been made to sleep. We can put a thread to sleep for aspecified time period using the method sleep(time) where time is inmilliseconds. This means that the thread is out of the queue duringthis time period. The thread re-enters the runnable state as soon asthis time period is elapsed.

Relinquishing control using sleep() method.

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

Relinquishing control using wait() method.

Blocked StateA thread is said to be blocked when it is prevented from enteringinto the runnable state and subsequently the running state. Thishappens when the thread is suspended, sleeping, or waiting in orderto satisfy certain requirements. A blocked thread is considered “notrunnable” but not dead and therefore fully qualified to run again.

Dead StateEvery thread has a life cycle. A running thread ends its life whenit has completed executing its run() method. It is a natural death.However, we can kill it by sending the stop message to it at anystate thus causing a premature death to it. A thread can be killed

Page 115: Java and data structure

Java and Data Structures 115IIBSC

as soon it is born, or while it is running , or even when it is in“not runnable” (blocked) condition.

Use of yield(), stop() and sleep() methods

class A extend Thread{

public void run(){

for(int i=1;i<=5;i++){

if(i==1) yield();System.out.println(“\tFrom Thread A : I = ” +i);

}System.out.println(“exit from A”);

}}class B extends Thread{

public void run(){

for(int i=1; i<=5; j++){

System.out.println(“\tFrom Thread B: j=”+j);If(j==3) stop();

}System.out.println(“Exit from B”);

}}class C extends Thread{

public void run(){

for(int k=1; k<=5; k++){

System.out.println(“\tFrom Thread C: k = “+k);if(k==1)try{

Sleep(1000);}catch(Exception e){ }

}

Page 116: Java and data structure

Java and Data Structures 116IIBSC

System.out.println(“Exit from C”);}

}class ThreadMethods{

public static void main(String args[]){

A threadA=new A( );B thread= new B( );C thread= new C( );System.out.println(“Start thread A”);threadA.start( );System.out.println(“Start thread B”);threadB.start( );System.out.println(“Start thread C”);thread.start( );System.out.println(“End of main thread”);

}}

Thread ExceptionsThe call to sleep() method is enclosed in a try block and followedby a catch block. This is necessary because the sleep() methodthrows an exception , which should be caught. If we fail to catchthe exception, program will not compile.Java run system will throwIllegalThreadStateException whenever we attempt to invoke a methodthat a thread cannot handle in the given state. The catch statementmay take one of the following forms:

catch(ThreadDeath e){

- - -//Killed thread }catch(InterruptedException e){

- -//cannot handle it in the current state}catch(IllegalArgumentException e){

--//Illegal method argument}catch(Expection e){

- - -//Any other

Page 117: Java and data structure

Java and Data Structures 117IIBSC

}

Thread PriorityThe threads of the same priority are given equal treatment by theJava scheduler and , therefore , they share the processor on afirst-come, first-server basis.Java permits us to set the priority of a thread using thesetPriority() method as follows:ThreadName.setPriority(intNumber);The intNumer is an integer value to which the thread’s priority isset. The Thread class defines several priority constants:

MIN_PRIORITY=1NORM_PRIORITY=5MAX_PRIORITY=10

The intNumber may assume one of these constants or any value between1 and 10. Thighest priority thread always preempts any lowerpriority threads.

Use of priority in threadsclass A extends Thread{

public void run(){

System.out.println(“threadA started”);for(int i=1; i<=4;i++){

System.out.println(“\tFrom Thread A: i=”+i);}System.out.println(“Exit from A”);

}}class B extends Thread{

public void run(){

Sytem.out.println(“threadsB started”);for(int i=1; i<=4;i++){

System.out.println(“\tFrom Thread B: i=”+i);}System.out.println(“Exit from B”);

}

Page 118: Java and data structure

Java and Data Structures 118IIBSC

}class C extends Thread{

public void run(){

Sytem.out.println(“threadsC started”);for(int i=1; i<=4;i++){

System.out.println(“\tFrom Thread C: i=”+i);}System.out.println(“Exit from C”);

}}class ThreadPriority{

public static void main(String args[]){

A threadA=new A( );B threadB=new B( );C thread=new C();threadC.setPriority(Thread.MAX_PRIORITY);thread.setPriority(threadA.getPriority()+1);threadA.setPriority(Thread.MIN_PRIORITY);System.out.println(“Start thread A”);threadA.start()System.out.println(“Start thread B”);threadB.start()System.out.println(“Start thread C”);threadC.start()System.out.println(“End of main thread”);

}}SynchronizationOne thread may try to read a record from a file while another isstill writing to the same file. Depending on the situation, we mayget strange results. Java enables us to overcome this problem usinga technique known as synchronization.In case of Java, the keyword synchronized helps to solve suchproblems by keeping a watch on such locations. For example, themethod that will read information from a file and the method thatwill update the same file may be declared as synchronized. Example:

synchronized void update(){

Page 119: Java and data structure

Java and Data Structures 119IIBSC

. . .//code here is synchronized}

When we declare a method synchronized , Java creates a “monitor “and hands it over to the thread that calls the method first time. Aslong as the thread holds the key can only open the lock.It is also possible to mark a block of code as synchronized as shownbelow:

synchronized (lock-object) {

…//code here is synchronized}Whenever a thread has completed its work of using synchronizedmethod(or block of code), it will hand over the monitor to the nextthread that is ready to use the same resource.An interesting situation may occur when two or more threads arewaiting to gain control of resource. Due to some reasons , thecondition on which the waiting threads rely on to gain control doesnot happen . this results in what is known as deadlock.

Implementing the ‘Runnable’ InterfaceThe Runnable interface declares the run() method that is requiredfor implementing threads in our program. To do this, we must performthe steps listed below:

1.Declare the class as implementing the Runnable interface.2.Implement the run method.3.Create a thread by defining an object that is instantiatedfrom this “runnable” class as the target of the thread.4.Call the thread’s start() method to run the thread.

Using Runnable interfaceclass X implements Runnable{

public void run(){

for(int i=1;i<=10;i++){

System.out.println(“\tThreadX=”+i);}System.out.println(“End of ThreadX”);

}}class RunnableTest

Page 120: Java and data structure

Java and Data Structures 120IIBSC

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

X runnable =new X();Thread thread=new Thread(runnable);thread.start();System.out.println(“End of main Thread”);

}}

13. Managing Errors and ExceptionsTypes of ErrorsErrors may broadly be classified into two categories:

Compile-time errors Run-time errors

Compile –time ErrorsAll syntax errors will be detected and displayed by the Javacompiler and therefore these errors are known as compile-timeerrors. Whenever the compiler displays an error, it will not createthe .class file. It is therefore necessary that we fix all theerrors before we can successfully compile and run the program.class Error1{

public static void main(String args[]){

System.out.println(“Hello Java!”) //Mising}

}The Java compiler does a nice job of telling us where the errors arein the program. For example , if we have missed the semicolon at theend of print statement.Most of the compile-time errors are due to typing mistakes.Typographical errors are hard to find. We may have to check the codeword by word , or even character by character. The most commonproblems are :

Missing semicolons. Missing(or mismatch of ) brackets in classes and methods. Misspelling of identifier and keywords Missing double quotes in strings Use of undeclared variables Incompatible types in assignments/initialization Bad references to objects Use of =in place of == operator And so on

Page 121: Java and data structure

Java and Data Structures 121IIBSC

Other errors we may encounter are related to directory paths. Anerror such as

Javac : command not found

Means that we have not set the path correctly. We must ensure thatthe path includes the directory where the Java executables arestored.

Run-Time ErrorsSometimes, a program may compile successfully creating the .classfile but may not run properly. Such programs may produce wrongresults due to wrong logic or may terminate due to errors such asstackoverflow. Most common run-time errors are:

Dividing an integer by zero Accessing an element that is out of bounds of an array Trying to store a value into an array of an incompatible class

or type Trying to cast an instance of a class to one of its subclasses Passing a parameter that is not in a valid range or value for a

method Trying to illegally change the state of a thread Attempting to use a negative size for an array Using a null object reference as a legitimate object reference

to access a method or a variable. Converting invalid string to a number Accessing a character that is out of bounds of a string And may more

When such errors are encountered, Java typically generates an errormessage and aborts the program.

Illustration of run-time errorsD Error2

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

int a =10;int b =5;int c =5;int x =a/(b-c);System.out.println(“X = “+x);int y=a/(b+c);

Page 122: Java and data structure

Java and Data Structures 122IIBSC

System.out.println(“Y= “+y);}

}Above program syntactically correct and therefore does not cause anyproblem during compilation . However, while executing it displaysthe following message and stops without executing furtherstatements. Java.lang.ArithmeticException: /by zero At Eror2.main(Error2.java:10)

ExceptionsAn exception is a condition that is caused by a run-time error inthe program. When the Java interpreter encounters an error such asdividing an integer by zero , it creates an exception object andthrows it. If the exception object is not caught and handledproperly, the interpreter will display an error message and willterminate the program. If we want the program to continue with theexecution of the remaining code, then we should try to catch theexception object thrown by the error condition and then display anappropriate message for taking corrective actions. This task isknown as exception handling.The purpose of exception handling mechanism to provide a means todetect and report an “exceptional circumstance” so that appropriateaction can be taken. The mechanism suggests incorporation of aseparate error handling code that performs the following tasks:

1. Find the problem(Hit the exception).2. Inform that an error has occurred(Throw the exception)3. Receive the error information(Catch the exception)4. Take corrective actions(Handle the exception)

The error handling code basically consists of two segments, one todetect errors and to throw exceptions and the other to catchexceptions and to take appropriate actions.When writing programs, we must always be on the lookout for placesin the program where an exception could be generated. Some commonexceptions that we must watch out for catching are listed in Table.

Common Java Exceptions

Exception Type Cause of ExceptionArithmeticException Caused by math errors such as division

by zeroArrayIndexOutOfBoundExcep Caused by bad array indexes

Page 123: Java and data structure

Try BlockStatement that causes an exception

catch BlockStatement that handles the exception

Exception object creator

Exception object handler

Throws exception object

Java and Data Structures 123IIBSC

tionArraStoreException Caused when a program tries to store the

wrong type of data in an arrayFileNotFoundException Caused by an attempt to access a

nonexistent fileIOException Caused by general I/O failures, such as

inability to read from a file.NullPointException Caused when a conversion between strings

and number failsOutOfMemoryException Caused when there’s not enough memory to

allocate a new object.SecurityException Caused when an applet tries to perform

an action not allowed by the browser’ssecurity setting

StackOverFlowException Caused when the system runs out of stackspace

StringIndexOutOfBoundsException

Caused when a program attempts to accessa nonexistent character position in astring

Syntax of Exception Handling CodeThe basic concepts of exception handling are throwing an exceptionand catching it. This is illustrated in fig.

Exception handling mechanismJava uses a keyword try to preface a block of code that is likely tocause an error condition and “throw” an exception. A catch blockdefined by the keyword catch “catches” the exception “throws” by thetry block and handles it appropriately. The catch block is addedimmediately after the try block.

Page 124: Java and data structure

Java and Data Structures 124IIBSC

The following example illustrates the use of simple try and catchstatements:….try{

Statement; //generates an exception}catch(Exception-type e){

Statement; //processes the exception}The try block can have one or more statements that could generate anexception. If any one statement generates an exception , theremaining statements in block are skipped and execution jumps to thecatch block that is placed next to the try block.The catch block too can have one or more statements that arenecessary to process the exception. Remember that every trystatement should be followed by at least one catch statement;otherwise compilation error will occur.The catch statement works like a method definition. The catchstatement is passed a single parameter, which is reference to theexception object thrown. If the catch parameter matches with thetype of exception object, then the exception is caught andstatements in the catch block will be executed. Otherwise , theexception is not caught and the default exception handler will causethe execution to terminate.Using try and catch for exception handlingclass Error3{

public static void main(String args[]){

int a =10;int b =5;int c =5;int x,y;try{

x =a/(b-c); //Exception here}catch(ArithmeticException e)

{System.out.println(“Division by zero “);

}y = a/ (b+c);

Page 125: Java and data structure

Java and Data Structures 125IIBSC

System.out.println(“Y = “+y); }}Multiple Catch StatementsIt is possible to have more than one catch statement in the catchblock as illustrated below:try{

Statement;}catch(Exception-type-1 e){

Statement;}catch(Exception-type-2 e){

Statement;} - - - - - - -- - - - - - -catch(Exception-type-N e){

Statement;}When an exception in a try block is generated, the Java treats themultiple catch statements like cases in a switch statement. Thefirst statement whose parameter matches with the exception objectwill be executed, and the remaining statements will skipped.Exampleclass Error4{

public static void main(String args[]){

int a[ ]={5,10};int b=5;try{

int x=a [2] / b - a[1] ;}catch(ArithmeticException e){

System.out.println(“Division by zero”);}catch(ArrayIndexOutOfBoundsException e)

Page 126: Java and data structure

Java and Data Structures 126IIBSC

{System.out.println(“Array index error”);

}catch(ArrayStoreException e){

System.out.println(“Wrong data type”);}int y = a[1] /a[0];System.out.println(“Y = “+y);

}}

Using Finally StatementJava supports another statement known as finally statement that canbe used to handle an exception that is not caught by any of theprevious catch statements. Finally block can be used to handle anyexception generated within a try block.try{. . . }catch(. . .){

. . .}..finally{. . . .. . . .}When a finally block is defined , this is guaranteed to execute,regardless of whether or not in exception is thrown. As a result, wecan use it to perform certain house-keeping operations such asclosing files and releasing system resources.

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

throw new Thorwable_subclass;

Examples:throw new ArithmenticException();throw new NumberFormatException();

Page 127: Java and data structure

Java and Data Structures 127IIBSC

Throwing our own Exceptions Exampleimport java.lang.Exception;class MyException extends Exception{

MyException(String message){

super(message);}

}class TestMyException{

public static void main(String args[]){

int x =5, y =1000;try{

float z= (float) x / (float)y;if(z < 0.01){throw new MyException(“Number is too small”);

}}catch(MyException e){

System.out.println(“Caught my exception”);System.out.println(e.getMessage());

}finally{

System.out.println(“I am always here”);}

}}Using Exceptions for DebuggingAs we have seen, the exception-handling mechanism can be used tohide errors from rest of the program. It is possible that theprogrammers may misuse this technique for hiding errors rather thatdebugging the code. Exception handling mechanism may be effectivelyused to locate the type and place of errors. Once we identify theerrors, we must try to find out why these errors occur before wecover them up with exception handlers.

14.Applet Programming

Page 128: Java and data structure

Local Applet

Loading local applets

Internet

Remote AppletLocal computer(Client) Remote Computer(Server)

Loading a remote applet

Java and Data Structures 128IIBSC

They can be transported over the Internet from one computer toanother and run using the Applet Viewer or any Web browser thatsupports java. An applet, like any application program, can do manythings for us. It can perform arithmetic operations, displaygraphics , play sounds, accept use input, create animation, and playinteractive games.

Local and Remote AppletsWe can embed applets into Web pages in two ways. One, we can writeour own applets and embed them into web pages. Second, we candownload an applet from a remote computer system and then embed itinto a web page. An applet developed locally and stored in a local system is known asa local applet. When a web page is trying to find a local applet, itdoes not need to use the Internet and therefore the local systemdoes not require the Internet connection. It simply searches thedirectories in the local system and locates and loads the specifiedapplet.A remote applet is that which is developed by someone else andstored on a remote computer connected to the Internet. If our systemis connected to the Internet, we can download the remote applet ontoour system via at the Internet and run it.In order to locate and load a remote applet, we must know theapplet’s address on the Web. This address is known as UniformResource Locator(URL) and must be specified in the applet’s HTMLdocument as the value of the CODEBASE attribute.

Example: CODEBASE=http://www.netserve.com/appletsIn the case of local applets, CODEBASE may be absent or may specifya local directory.

How Applets differ from Applications

Page 129: Java and data structure

Java and Data Structures 129IIBSC

Although both the applets and stand-alone applications are Javaprograms, there are significant differences between them. Appletsare not full-featured programs. They are usually written toaccomplish a small task or a component of a task. Since they areusually designed for use on the Internet, they impose certainlimitations and restrictions in their design.

Applets do not use the main() method for initiating theexecution of the code. Applets, when loaded, automatically callcertain methods of Applet class to start and execute the appletcode.

Unlike stand-alone applications, applets cannot be runindependently. They are run from inside a web page using aspecial feature known as known as HTML tag.

Applets cannot read from or write to the files in the localcomputer.

Applets cannot communicate with other servers on the network. Applet cannot run any program from the local computer. Applets are restricted from using libraries from other

languages such as C or C++.All these restrictions and limitations are placed in the interest ofsecurity of systems. These restrictions ensure that an applet cannotdo any damage to the local system.

Preparing to Write AppletsWhen we might need to use applets1.When we need something dynamic to be included in the display of aweb page. For example, an applet that displays daily sensitivityindex would be useful on a page that lists share prices of variouscompanies or an applet that displays a bar chart would add value toa page that contains data tables.When we require some “flash” outputs. For example, applets thatproduce sounds, animations or some special effects would be usefulwhen displaying certain pages.When we want to create a program and make it available on theInternet for us by others on their computers.The steps involved in developing and testing in applet are:

1. Building an applet code(.java file)2. Creating an executable applet(.class file)3. Designing a Web page using HTML tags.4. Preparing <APPLET> tab.5. Incorporating <APPLET> tag into the web page.6. Creating HTML file.7. Testing the applet code.

Page 130: Java and data structure

Java and Data Structures 130IIBSC

Building Applet CodeThe Applet class which is contained in the java.applet packageprovides life and behavior to the applet through its methods such asinit(), start() and point(). Unlike the applications, where Javacalls the main() method directly to initiate the execution of theprogram, when an applet is loaded, java automatically calls a seriesof applet class methods for starting, running, and stopping theapplet code. The applet class therefore maintains the lifecycle ofan applet. The paint() method of the Applet class, when it is called, actuallydisplays the result of the applet code on the screen. The output maybe text, graphics, or sound. The paint() method, which requires aGraphics object as an argument, is defined as follows:

public void paint(Graphics g)

This requires that the applet code imports the java.awt package thatcontains the Graphics class. All output operations of an applet areperformed using the defined in the Graphics class. An applet codewill have a general format as shown below:import java.awt.*;import java.applet.*;public class appletclassname extends Applet{ . . . . .

public void paint(Graphics g){. . . . .//applet operations code}

}The appletclassname is the main class for the applet. When theapplet is loaded, Java creates an instance of this class, and then aseries of Applet class methods are called on that instance toexecute the code. import java.awt.*;import java.applet.*;public class HelloJAva extends Applet{

public void paint(Graphic g){ g.drawString(“Hello Java”,10,100);}

}The applet contains only one executable statement,

g.drawString(“Hello Java”,10,100);

Page 131: Java and data structure

End

Born

Running Idle

Dead

Begin(Load Applet) Initialization

start()

start()

stop()

stopped

destroy()

Destroyed

Display

Paint()

Exit of Browser

Java and Data Structures 131IIBSC

Which, when executed, draws the stringHello Java At the position 10,100(pixels) of the applet’s reserved space.

Applet Life CycleEvery Java applet inherits a set of default behaviors from theApplet class. As a result, when an applet is loaded, it undergoes aseries of changes in its state as shown in fig. The applet statesinclude:

An applet’s state transition diagram Born on initialization state Running state Idle state Dead or destroyed state

Initialization StateApplet enters the initialization state when it is first loaded. Thisis achieved by calling the init() method of Applet class. The appletis born. At this stage, we may do the following, if required.

Create objects needed by the applet Set up initial values Load images or fonts Set up colors

The initialization occurs only once in the applet’s life cycle.public void init(){……

(Action)…………

Page 132: Java and data structure

Java and Data Structures 132IIBSC

}Running stateApplet enters the running state when the system calls the start()method of Applet Class. This occurs automatically after the appletis initialized. Starting can also occur if the applet is already in‘stopped’(idle) state. For example, we may leave the Web pagecontaining the applet temporarily to another page and return back tothe page. This again starts the applet running. Note that , unlikeinit() method, the start() method may be called more than once. Wemay override the start() method a create a thread to control theapplet.public void start(){………

(Action)…………..}Idle or Stopped StateAn applet becomes idle when it is stopped from running. Stoppingoccurs automatically when we leave the page containing the currentlyrunning applet. We can also do so by calling the stop() methodexplicitly. If we use a thread to run the applet, then we must usestop() method to terminate the thread. We can achieve this byoverriding the stop() method.public void stop(){……………(Action)}

Dead stateAn applet is said to be dead when it is removed from memory. Thisoccurs automatically by invoking the destroy() method when we quitthe browser. Like initialization, destroying stage occurs only oncein the applet’s life cycle. If the applet has created any resources,like threads, we may override the destroy() method to clean up theseresources.public void destroy(){………(Action)}

Display stateApplet moves to the display state whenever it has to perform someoutput operations on the screen. This happens immediately after theapplet enters into the running state. The paint() method is called

Page 133: Java and data structure

Java and Data Structures 133IIBSC

to accomplish this task. Almost every applet will have a paint()method. Like other methods in the life cycle, the default version ofpaint() method does absolutely nothing. We must therefore overridethis method if we want anything to be displayed on the screen.public void paint(Graphics g){………..(Display statements)}Display state is not considered as a part of applet’s life cycle. Infact, the paint() method is defined in the Applet class. It isinherited from the Component class, a super class of Applet.

Creating an Executable AppletExecutable applet is a .class file of the applet, which is obtainedby compiling the source code of the applet. Compiling an applet isexactly the same as compiling an application.

Designing a Web PageTo run Java applet, it is first necessary to have a web page thatreferences that applet. A web page is basically made up of text andHTML tags that can be interpreted by a Web browser or an appletviewer. Like Java source code, it can be prepared using any ASCIItext editor. A web page is also known as HTML page or HTML document.Web pages are stored using a file extension .html. such files arereferred to as HTML files. HTML files should be stored in the samedirectory as the compiled code of the applets. A web page is markedby an opening HTML tab<HTMLL> and closing HTML tag </HTML> and isdivided into the following three major sections.1.Comment section(Optional)2.Head section(Optional)3.Body sectionA web page outline containing these three sections and the openingand closing HTML tags.

Comment SectionThis section contains comments about the web page. It is importantto include comments that tell us what is going on the web page. Acomment line begins with a<! and ends with a> . Web browsers willignore the text enclosed between them.

Head SectionThe head section is defined with a starting <HEAD> tag and a closing</HEAD> tag. This section usually contains a title for the web pageas shown below:

Page 134: Java and data structure

<HTML><!...............................…………………………………………>

<HEAD>

</HEAD>

<BODY>

</BODY>

Title Tag

Applet Tag

Comment Section

Head Section

Body Section

Java and Data Structures 134IIBSC

<HEAD><TITLE> Welcome to Java Applets</TITLE></HEAD>The text enclosed in the tags<TITLE> and <?TITLE> will appear inthe title bar of the web browser when it displays the page. The headsection is also optional.

A web page templateHTML commands usually appear impairs such as <HEAD> and </HEAD> ,and <TITLE> and </TITLE>. A slash(/) in a tag signifies the end ofthat tag section.

Body sectionBody section contains the entire information about the web page andits behavior.<BODY><CENTER><H1>Welcome to the World of Applets</H1></CENTER><BR><APPLET…></APPLET></BODY>

Page 135: Java and data structure

Java and Data Structures 135IIBSC

The body shown above contains instruction to display the message. Welcome to the World of AppletsFollowed by the applet output on the screen. The <CENTER> tagcentered text and <H!> tag causes the text to be of the largestsize.

Applet TagThe <APPLET…>tag supplies the name of the applet to be loaded andtells the browser how much space the applet requires. The ellipsisin the tag <APPLET…> indicates that it contains certain attributesthat must specified. The <APPLET> tag given below specifies theminimum requirements to place the HelloJava applet on the Web page:

<APPLET code =HelloJava.class WIDTH=400 HEIGHT=200> </APPLET>

This HTML code tells the browser to load the compiled Java appletHelloJava.class, which is in the same directory as the HTML file.And also specifies the display area for the applet output as 400pixels width and 200 pixels height.

Adding Applet to HTML fileInsert the <APPLET> tag in the page at the place where the output ofthe applet must appear. Following is the content of the HTML filethat is embedded with the <APPLET> tag of our HelloJava applet.<HTML><HEAD><TITLE>Welcome to Java Applets</TITLE></HEAD><BODY><CENTER><H1>Welcome to the World of Applets</H1></CENTER><BR><CENTER><APPLET CODE=HelloJava.class WIDTH=400 HEIGHT=200></APPLET></CENTER></BODY></HTML>

Running the AppletTo run the applet, we require one of the following tools: 1.Java-enabled Web browser.2.Java applet viewer

Page 136: Java and data structure

Java and Data Structures 136IIBSC

If we use a java –enabled Web browser , we will be able to see theentire web page containing the applet. If we use the appletviewertool, we will only see the applet output. We can use it to run ourapplet as follows:Appletviewer HelloJava.html

More about Applet tagThe syntax of the <APPLET> tag in full form is shown as follows:<APPLET[CODEBASE=codebase_URL][ALT=AppletFileName.class[ALT=alternate_text][NAME=appletinstance_name]WIDTH=pixelsHEIGHT=pixels[ALIGN=alignment][VSPACE=pixels][HSPACE=pixels]>[<PARAM NAME=name1 VALUE=value1>][<PARAM NAME=name2 VALUE=value2>]………….……………[Text to be displayed in the absence of Java]</APPLET>

Attributes of APPLET tag.

Attribute MeaningCODE=AppletFileName.class

Specifies the name of the applet class tobe loaded. That is, the name of thealready- compiled.class file in which theexecutable Java byte code for the applet isstored. This attribute must be specified.

CODEBASE-codebase_URL Specifies the URL of the directory in whichthe applet resides. IF the applet residesin the same directory as the HTML file,then the CODEBASE attribute may be omittedentirely.

WIDTH=pixelsHEIGHT=pixels

These attributes specify the width andheight of the space on the HTML page thatwill be reserved for the applet.

NAME=applet_instance_name

A name for the applet may optionally bespecified so that other applets on the page

Page 137: Java and data structure

Java and Data Structures 137IIBSC

(Optional) may refer to this applet. This facilitatesinter –applet communication.

ALIGN-alignment(optional)

This optional attribute specifies where onthe page the applet will appear. Possiblevalues for alignment are: TOP, BOTTOM,LEFT, RIGHT, MIDDLE, ABSMIDDLE, ABSBOTTOM,TEXTTOP, and BASELINE.

HSPACE=pixels(optional)

Used only when ALIGN is set to LEFT orRIGHT, this attribute specifies the amountof horizontal blank space the browsershould leave surrounding the applet.

VSPACE=pixels(optional)

Used only when some vertical alignment isspecified with the ALIGN attribute (TOP,BOTTOM,etc..) VSPACE specifies the amountof vertical blank space the browser shouldleave surrounding the applet.

ALT-alternate_text Non-Java browsers will dislplay this textwhere the applet would normally go. Thisattribute is optional.

We summarise below the list of things to be done for adding anapplet to a HTML document:1.Insert an <APPLET> tag at an appropriate place in the Web page.2.Specify the name of the applet’s .class file.3.If the .class file is not in the current directory, use thecodebase parameter to specify.

The relative path if file is on the local system, or The Uniform Resource Locator(URL) of the directory containing

the file if it is on a remote computer.4.Specify the space required for display of the applet in terms ofwidth and height in pixels.5. Add any user-defined parameters using <PARAM> tags.6. Add alternate HTML text to be displayed when a non-java browseris used.7.Close the applet declaration with the </APPLET> tag.

Passing Parameters to AppletsPassing parameters to an applet code using <PARAM> tag is somethingsimilar to passing parameters to the main() method using commandline arguments. To set up and handle parameters, we need to do twothings:

1.Include appropriate<PARAM…>tags in the HTML document.2.Provide Code in the applet to parse these parameters.

Page 138: Java and data structure

Java and Data Structures 138IIBSC

Parameters are passed on an applet when it is loaded. We can definethe init() method in the applet to get hold of the parametersdefined in the <PARAM> tags. This is done using the getParameter()method, which takes one string argument representing the name of theparameter and returns a string containing the value of thatparameter.

Applet HelloJava Programimport java.awt.*;import java.applet.*;public class HelloJavaParam extends Applet{

String str;public void init(){

str=getParameter(“string”);if(str==null)

str=”Java”;str=”Hello “+str;

}public void paint(Graphics g){

g.drawString(str,10,100);}

}

The HTML file for HelloJava Program applet

<HTML><HEAD><TITLE>Welcome to Java Applets</TITLE></HEAD><BODY><APPLET CODE= HelloJavaProgram.class WIDTH=400 HEIGHT=200><PARAM NAME=”string” VALUE=”Applet!”></APPLET></BODY>Header ta</HTML>

Aligning the DisplayWe can align the output of the applet using the ALIGN attribute.This attribute can have one of the nine values. LEFT, RIGHT, TOP,TEXT TOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM, ABSBOTTOM. For

Page 139: Java and data structure

Java and Data Structures 139IIBSC

example, ALIGN =left will display the output at the left margin ofthe page.HTML Tags and Their FunctionsTag Function<HTML>…</HTML> Signifies the beginning and end of a HTML

file.<HEAD>…</HEAD> This tag may include details about the Web

page. Usually contains <TITLE> tag within it.<TITLE>…</TITLE> The text contained in it will appear in the

title bar of the browser.<BODY>…</BODY> This tag contains the main text of the web

page. It is the place where the <APPLET> tagis declared.

<H1>…</H1><H1>…<H6> Header tags. Used to display headings. <H1>creates the largest font header, while <H6>creates the smallest one.

<CENTER>…</CENTER> Places the text containing in it at the centreof the page.

<APPLET…> <APPLET>…</APPLET>

<APPLET…> tag declares the applet details asits attributes. May hold optionally user-defined parameters using<PARAM> Tags.

<PARAM…> Supplies user-defined parameters using <PARAM>tag needs to be placed between the <APPLET>and </APPLET>tags. We can use as manydifferent <PARAM> tags as we wish for eachapplet.

<B>…</B> Text between these tags will be displayed inbold type.

<BR> Line break tag. This will skip a line. Doesnot have an end tag.

<P> Paragraph tag. This tag moves us to the nextline and starts a paragraph of text. No endingtag.

<IMG…> This tag declares attributes of an image to bedisplayed.

<HR> Draws a horizontal rule.<A…></A> Anchor tag used to add hyperlink.<FONT…>….</FONT> We can change the color and size of the text

that lies in between <FONT> and </FONT> tagsusing COLOR and SIZE attributes in thetag<FONT..>

<!...> Any text starting with a <! Mark and endingwith a > mark is ignored by the Web browser .

Page 140: Java and data structure

Java and Data Structures 140IIBSC

We may add comments here. A comment tag may beplaced anywhere in a webpage.

Displaying Numerical ValuesIt applets , we can display numerical values by first convertingthem into strings and then using the drawString() method of Graphicsclass. We can do this easily by calling the ValueOf() method ofString class.import java.awt.*;import java.applet.*;public class NumValues extends Applet{

public void paint(Graphics g){

int value1=10;int value2=20;int sum=value1+value2;String s=”Sum: “+String.valueOf(sum);g.drawString(s,100,100);

}}

Getting Input from the UserApplets work in a graphical environment. Therefore, applets treatinputs as text strings. We must first create an area of the screenin which user can type ad edit input items. We can do this by usingthe TextFiled class of the applet package. Once text fields arecreated for receiving input, we can type the values in the fieldsand edit them, if necessary. They need to be converted to the rightform, before they are used in any computations. The results are thenconverted back to strings for display.Import java.awt.*;Import java.applet.*;public class UserIn extends Applet{

TextField text1,text2;public void init(){

text1=new TextField(80);text2=new TextField(8);add(text1);add(text2);text1.setText(“0”);text2.setText(“0”);

Page 141: Java and data structure

Java and Data Structures 141IIBSC

}public void paint(Graphics g){

int x=0,y=0,z=0;String s1,s2,s;g.drawString(“Input a number in each box”,10,50);try{

s1=text1.getText();x=Integer.parseInt(s1);s2=text2.getText();y=Integer.parseInt(s2);

}catch(Exception ex){ }z=x+y;s=String.valueOF(z);g.drawString(“THE SUM IS:”,10,75);g.drawString(s,100,75);public Boolean action(Event event, Object object){

repaint():return true;

}}Run the applet UserIn using the following steps:1.Type and save the program(.java file)2.Compile the applet(.class)3.Write a HTML document(.html file)<html><applet code=UserIn.class width=300 height=200></applet></html>4.Use the appletviewer to display result

V.Data StructuresBubble SortThe bubble sort is notoriously slow, but it's conceptually thesimplest of the sorting techniques.Bubble-Sorting the Baseball PlayersLet's assume there are N players, and the positions they're standingin are numbered from 0 on the left to N– 1 on the right. The bubblesort routine works like this. You start at the left end of the lineand compare the two kids in positions 0 and 1. If the one on theleft (in 0) is taller, you swap them. If the one on the right istaller, you don't do anything. Then you move over one position and

Page 142: Java and data structure

Java and Data Structures 142IIBSC

compare the kids in positions 1 and 2. Again, if the one on the leftis taller, you swap them. This is shown in Figure 3.3.Here are the rules you're following:1. Compare two players.2. If the one on the left is taller, swap them.3. Move one position right.You continue down the line this way until you reach the right end.You have by no means finished sorting the kids, but you do know thatthe tallest kid is on the right. This must be true, because as soonas you encounter the tallest kid, you'll end up swapping him everytime you compare two kids, until eventually he (or she) will reachthe right end of the line. This is why it's called the bubble sort:as the algorithm progresses, the biggest items "bubble up" to thetop end of the array. Figure 3.4 shows the baseball players at theend of the first pass.

Figure 3.3: Bubble sort: beginning of first pass

Figure 3.4: Bubble sort: end of first passAfter this first pass through all the data, you've made N–1comparisons and somewherebetween 0 and N–1 swaps, depending on the initial arrangement of theplayers. The item at the end of the array is sorted and won't bemoved again. Now you go back and start another pass from the leftend of the line. Again you go toward the right, comparing andswapping when appropriate. However, this time you can stop oneplayer short of the end of the line, at position N–2, because youknow the last position, at N–1, already contains the tallest player.This rule could be stated as:4. When you reach the first sorted player, start over at the leftend of the line.

Page 143: Java and data structure

Java and Data Structures 143IIBSC

You continue this process until all the players are in order. Thisis all much harder to describe than it is to demonstrate, so let'swatch the bubbleSort Workshop applet at work.37. Program to implement Bubble Sort.The bubbleSort.java Programclass ArrayBub{private double[] a; // ref to array aprivate int nElems; // number of data itemspublic ArrayBub(int max) // constructor{a = new double[max]; // create the arraynElems = 0; // no items yet}public void insert(double value) // put element into array{a[nElems] = value; // insert itnElems++; // increment size}public void display() // displays array contents{for(int j=0; j<nElems; j++) // for each element,System.out.print(a[j] + " "); // display itSystem.out.println("");}public void bubbleSort(){int out, in;for(out=nElems-1; out>1; out--) // outer loop (backward)for(in=0; in<out; in++) // inner loop (forward)if( a[in] > a[in+1] ) // out of order?{double temp = a[in];a[in] = a[in+1];a[in+1] = temp;}} // end bubbleSort()} // end class ArrayBubclass BubbleSortApp{public static void main(String[] args){int maxSize = 100; // array sizeArrayBub arr; // reference to array

Page 144: Java and data structure

Java and Data Structures 144IIBSC

arr = new ArrayBub(maxSize); // create the arrayarr.insert(77); // insert 10 itemsarr.insert(99);arr.insert(44);arr.insert(55);arr.insert(22);arr.insert(88);arr.insert(11);arr.insert(00);arr.insert(66);arr.insert(33);arr.display(); // display itemsarr.bubbleSort(); // bubble sort themarr.display(); // display them again} // end main()} // end class BubbleSortApp

BubbleSort() method is invoked from main(), the contents of thearray are rearranged into sorted order. The main() routine inserts10 items into the array in random order, displays the array, callsbubbleSort() to sort it, and then displays it again.Here's the output:77 99 44 55 22 88 11 0 66 330 11 22 33 44 55 66 77 88 99

The bubbleSort() method put the smallest item at the beginningof the array (index 0) and the largest item at the end (indexnElems-1). The loop counter out in the outer for loop starts at theend of the array, at nElems-1, and decrements itself each timethrough the loop. The items at indices greater than out are alwayscompletely sorted. The out variable moves left after each pass.The inner loop counter in starts at the beginning of the array andincrements itself each cycle of the inner loop, exiting when itreaches out. Within the inner loop, the two array cells pointed toby in and in+1 are compared and swapped if the one in is largerthan the one in in+1.

Efficiency of the Bubble SortIn general, where N is the number of items in the array, there areN–1 comparisons on the first pass, N–2 on the second, and so on. Theformula for the sum of such a series is (N–1) + (N–2) + (N–3) + ...+ 1 = N*(N–1)/2N*(N–1)/2 is 45 when N is 10. Selection Sort

Page 145: Java and data structure

Java and Data Structures 145IIBSC

The selection sort improves on the bubble sort by reducing thenumber of swaps necessary from O(N2) to O(N). Selection sort on the Baseball PlayersLet's consider the baseball players again. In the selection sort,you can no longer compare only players standing next to each other.Start at the left end of the line of players. Record the leftmostplayer's height in your notebook and throw the magenta towel on theground in front of this person. Then compare the height of the nextplayer to the right with the height in your notebook. If thisplayer is shorter, cross out the height of the first player, andrecord the second player's height instead. Also move the towel,placing it in front of this new "shortest" (for the time being)player. Continue down the row, comparing each player with theminimum. Change the minimum value in your notebook, and move thetowel, whenever you find a shorter player. When you're done, themagenta towel will be in front of the shortest player.Swap this shortest player with the player on the left end of theline. You've now sorted one player. You've made N–1 comparisons, butonly one swap.On the next pass, you do exactly the same thing, except that you cancompletely ignore the player on the left, because this player hasalready been sorted. Thus the algorithm starts the second pass atposition 1 instead of 0. With each succeeding pass, one more playeris sorted and placed on the left, and one less player needs to beconsidered when finding the new minimum. Figure 3.9 shows how thislooks for the first three passes.Figure 3.9: Selection sort on baseball players

36. Program to implement Selection Sort. The selectSort.java Programclass ArraySel{private double[] a; // ref to array a

Page 146: Java and data structure

Java and Data Structures 146IIBSC

private int nElems; // number of data itemspublic ArraySel(int max) // constructor{a = new double[max]; // create the arraynElems = 0; // no items yet}public void insert(double value) // put element into array{a[nElems] = value; // insert itnElems++; // increment size}public void display() // displays array contents{for(int j=0; j<nElems; j++) // for each element,System.out.print(a[j] + " "); // display itSystem.out.println("");}public void selectionSort(){int out, in, min;for(out=0; out<nElems-1; out++) // outer loop{min = out; // minimumfor(in=out+1; in<nElems; in++) // inner loopif(a[in] < a[min] ) // if min greater,min = in; // we have a new minswap(out, min); // swap them} // end for(outer)} // end selectionSort()private void swap(int one, int two){double temp = a[one];a[one] = a[two];a[two] = temp;}} // end class ArraySel

class SelectSortApp{public static void main(String[] args){int maxSize = 100; // array sizeArraySel arr; // reference to arrayarr = new ArraySel(maxSize); // create the array

Page 147: Java and data structure

Java and Data Structures 147IIBSC

arr.insert(77); // insert 10 itemsarr.insert(99);arr.insert(44);arr.insert(55);arr.insert(22);arr.insert(88);arr.insert(11);arr.insert(00);arr.insert(66);arr.insert(33);arr.display(); // display itemsarr.selectionSort(); // selection-sort themarr.display(); // display them again} // end main()} // end class SelectSortAppThe outer loop, with loop variable out, starts at the beginning ofthe array (index 0) andproceeds toward higher indices. The inner loop, with loop variablein, begins at out andlikewise proceeds to the right.

At each new position of in, the elements a[in] and a[min] arecompared. If a[in] issmaller, then min is given the value of in. At the end of the innerloop, min points to theminimum value, and the array elements pointed to by out and min areswapped. The output from selectSort.java is identical to that frombubbleSort.java:77 99 44 55 22 88 11 0 66 330 11 22 33 44 55 66 77 88 99

Efficiency of the Selection SortThe selection sort performs the same number of comparisons as thebubble sort: N*(N–1)/2. For 10 data items, this is 45 comparisons. However, 10 itemsrequire fewer than 10. For large values of N, the comparison timeswill dominate, so we would have to say that the selection sort runsin O(N2) time, just as the bubble sort did. However, it isunquestionably faster because there are so few swaps. For smallervalues of N, it may in fact be considerably faster, especially ifthe swap times are much larger than the comparison times.Insertion SortInsertion sort still executes in O(N2) time, but it's about twice asfast as the bubble sort and somewhat faster than the selection sortin normal situations. It's also not too complex, although it's

Page 148: Java and data structure

Java and Data Structures 148IIBSC

slightly more involved than the bubble and selection sorts. It'soften used as the final stage of more sophisticated sorts, such asquicksort.26. Program to implement insertion sort. The insertSort.java Programclass ArrayIns{private double[] a; // ref to array aprivate int nElems; // number of data itemspublic ArrayIns(int max) // constructor{a = new double[max]; // create the arraynElems = 0; // no items yet}public void insert(double value) // put element into array{a[nElems] = value; // insert itnElems++; // increment size}public void display() // displays array contents{for(int j=0; j<nElems; j++) // for each element,System.out.print(a[j] + " "); // display itSystem.out.println("");}public void insertionSort(){int in, out;for(out=1; out<nElems; out++) // out is dividing line{double temp = a[out]; // remove marked itemin = out; // start shifts at outwhile(in>0 && a[in-1] >= temp) // until one is smaller,{a[in] = a[in-1]; // shift item right,--in; // go left one position}a[in] = temp; // insert marked item} // end for} // end insertionSort()} // end class ArrayIns

class InsertSortApp{

Page 149: Java and data structure

Java and Data Structures 149IIBSC

public static void main(String[] args){int maxSize = 100; // array sizeArrayIns arr; // reference to arrayarr = new ArrayIns(maxSize); // create the arrayarr.insert(77); // insert 10 itemsarr.insert(99);arr.insert(44);arr.insert(55);arr.insert(22);arr.insert(88);arr.insert(11);arr.insert(00);arr.insert(66);arr.insert(33);arr.display(); // display itemsarr.insertionSort(); // insertion-sort themarr.display(); // display them again} // end main()} // end class InsertSortApp

In the outer for loop, out starts at 1 and moves right. Itmarks the leftmost unsorted data. In the inner while loop, in startsat out and moves left, until either temp is smaller than the arrayelement there, or it can't go left any further. Each pass throughthe while loop shifts another sorted element one space right. Here'sthe output from the insertSort.java program77 99 44 55 22 88 11 0 66 330 11 22 33 44 55 66 77 88 99

Efficiency of the Insertion SortHow many comparisons and copies does this algorithm require? On thefirst pass, it compares a maximum of one item. On the second pass,it's a maximum of two items, and so on, up to a maximum of N–1comparisons on the last pass. This is1 + 2 + 3 + ... + N–1 = N*(N–1)/2However, because on each pass an average of only half of the maximumnumber of items are actually compared before the insertion point isfound, we can divide by 2, which gives: N*(N–1)/4

The number of copies is approximately the same as the number ofcomparisons. However, a copy isn't as time-consuming as a swap, sofor random data this algorithm runs twice as fast as the bubble sortand faster than the selection sort.

Stacks and Queues

Page 150: Java and data structure

Java and Data Structures 150IIBSC

Stacks, queues, and priority queues are more abstract entities thanarrays and manyother data storage structures.

StacksA stack allows access to only one data item: the last item inserted.If you remove this item, then you can access the next-to-last iteminserted, and so on. This is a useful capability in many programmingsituations.

Most microprocessors use a stack-based architecture. When amethod is called, its return address and arguments are pushed onto astack, and when it returns they're popped off. The stack operationsare built into the microprocessor.

Some older pocket calculators used a stack-based architecture.Instead of entering arithmetic expressions using parentheses, youpushed intermediate results onto a stack.

Placing a data item on the top of the stack is called pushing it.Removing it from the top of the stack is called popping it. These arethe primary stack operations. A stack is said to be a Last-In-First-Out (LIFO) storage mechanism, because the last item inserted is thefirst one to be removed.27. Program to implement PUSH and POP operations on Stack using array method.Java Code for a Stackimport java.io.*; // for I/Oclass StackX{private int maxSize; // size of stack arrayprivate double[] stackArray;private int top; // top of stackpublic StackX(int s) // constructor{maxSize = s; // set array sizestackArray = new double[maxSize]; // create arraytop = -1; // no items yet}public void push(double j) // put item on top of stack{stackArray[++top] = j; // increment top, insert item}public double pop() // take item from top of stack{return stackArray[top--]; // access item, decrement top}

Page 151: Java and data structure

Java and Data Structures 151IIBSC

public double peek() // peek at top of stack{return stackArray[top];}public boolean isEmpty() // true if stack is empty{return (top == -1);}public boolean isFull() // true if stack is full{return (top == maxSize-1);}} // end class StackXclass StackApp{public static void main(String[] args){StackX theStack = new StackX(10); // make new stacktheStack.push(20); // push items onto stacktheStack.push(40);theStack.push(60);theStack.push(80);while( !theStack.isEmpty() ) // until it's empty,{ // delete item from stackdouble value = theStack.pop();System.out.print(value); // display itSystem.out.print(" ");} // end whileSystem.out.println("");} // end main()} // end class StackAppThe main() method in the StackApp class creates a stack that canhold 10 items, pushes 4 items onto the stack, and then displays allthe items by popping them off the stack until it's empty. Here's theoutput:80 60 40 20

QueuesThe word queue is British for line (the kind you wait in). In computerscience a queue is a data structure that is similar to a stack,except that in a queue the first item inserted is the first to beremoved (FIFO), while in a stack, as we've seen, the last iteminserted is the first to be removed (LIFO). A queue works like theline at the movies.

Page 152: Java and data structure

Java and Data Structures 152IIBSC

There are various queues quietly doing their job in yourcomputer's (or the network's)operating system. There's a printerqueue where print jobs wait for the printer to be available. A queuealso stores keystroke data as you type at the keyboard. 29.Program to implement insert and delete operations on Queue using array method.The Queue.java Programimport java.io.*; // for I/Oclass Queue{private int maxSize;private int[] queArray;private int front;private int rear;private int nItems;public Queue(int s) // constructor{maxSize = s;queArray = new int[maxSize];front = 0;rear = -1;nItems = 0;}public void insert(int j) // put item at rear of queue{if(rear == maxSize-1) // deal with wraparoundrear = -1;queArray[++rear] = j; // increment rear andinsertnItems++; // one more item}public int remove() // take item from front of queue{int temp = queArray[front++]; // get value and incr frontif(front == maxSize) // deal with wraparoundfront = 0;nItems--; // one less itemreturn temp;}public int peekFront() // peek at front of queue{return queArray[front];}public boolean isEmpty() // true if queue is empty

Page 153: Java and data structure

Java and Data Structures 153IIBSC

{return (nItems==0);}public boolean isFull() // true if queue is full{return (nItems==maxSize);}public int size() // number of items in queue{return nItems;}} // end class Queueclass QueueApp{public static void main(String[] args){Queue theQueue = new Queue(5); // queue holds 5 itemstheQueue.insert(10); // insert 4 itemstheQueue.insert(20);theQueue.insert(30);theQueue.insert(40);theQueue.remove(); // remove 3 itemstheQueue.remove(); // (10, 20, 30)theQueue.remove();theQueue.insert(50); // insert 4 more itemstheQueue.insert(60); // (wraps around)theQueue.insert(70);theQueue.insert(80);while( !theQueue.isEmpty() ) // remove and display{ // all itemsint n = theQueue.remove(); // (40, 50, 60, 70, 80)System.out.print(n);System.out.print(" ");}System.out.println("");} // end main()} The Queue Class Without nItemsclass Queue{private int maxSize;private int[] queArray;private int front;private int rear;

Page 154: Java and data structure

Java and Data Structures 154IIBSC

//-------------------------------------------------------------public Queue(int s) // constructor{maxSize = s+1; // array is 1 cell largerqueArray = new int[maxSize]; // than requestedfront = 0;rear = -1;}//-------------------------------------------------------------public void insert(int j) // put item at rear of queue{if(rear == maxSize-1)rear = -1;queArray[++rear] = j;}//-------------------------------------------------------------public int remove() // take item from front of queue{int temp = queArray[front++];if(front == maxSize)front = 0;return temp;}//-------------------------------------------------------------public int peek() // peek at front of queue{return queArray[front];}//-------------------------------------------------------------public boolean isEmpty() // true if queue is empty{return ( rear+1==front || (front+maxSize-1==rear) );}//-------------------------------------------------------------public boolean isFull() // true if queue is full{return ( rear+2==front || (front+maxSize-2==rear) );}//-------------------------------------------------------------public int size() // (assumes queue not empty){if(rear >= front) // contiguous sequencereturn rear-front+1;else // broken sequence

Page 155: Java and data structure

Java and Data Structures 155IIBSC

return (maxSize-front) + (rear+1);}//-------------------------------------------------------------} // end class Queue

DequesA deque is a double-ended queue. You can insert items at either endand delete themfrom either end. The methods might be called insertLeft() andinsertRight(), and removeLeft() and removeRight(). If you restrictyourself to insertLeft() and removeLeft() (or their equivalents onthe right), then the deque acts like a stack. If you restrictyourself to insertLeft() and removeRight() (or the opposite pair),then it acts like a queue.A deque provides a more versatile data structure than either a stackor a queue, and issometimes used in container class libraries to serve both purposes.However, it's not used as often as stacks and queues.32. Program to implement insert and delete operations on Double Ended Queue.import java.io.*; class Queue{

private int maxSize;private int[] queArray;private int front;private int rear;private int nItems;public Queue(int s) {

maxSize = s;queArray = new int[maxSize];front = 0;rear = -1;nItems = 0;

}public void insertRight(int j) {

if(rear == maxSize-1) {

System.out.println("Queue is full");return;

}queArray[++rear] = j;

Page 156: Java and data structure

Java and Data Structures 156IIBSC

nItems++; }public void insertLeft(int j) {

if(front == 0) {

System.out.println("Queue is full");return;

}queArray[--front] = j; nItems++;

}public int removeLeft() {

int temp = queArray[front++]; if(front == maxSize) front = 0;nItems--; return temp;

}public int removeRight() {

int temp = queArray[rear--]; nItems--; return temp;

}

public boolean isEmpty() {

return (nItems==0);}public boolean isFull() {

return (nItems==maxSize);}public int size() {

return nItems;}

} class DeQueue{

public static void main(String[] args)

Page 157: Java and data structure

Java and Data Structures 157IIBSC

{Queue theQueue = new Queue(15); theQueue.insertRight(30);theQueue.insertRight(40);theQueue.insertRight(50); theQueue.insertRight(60); theQueue.insertRight(70);theQueue.insertRight(80);int n=theQueue.removeLeft();System.out.print(n+" "); n=theQueue.removeLeft();System.out.println(n+" ");theQueue.insertLeft(100);theQueue.insertLeft(10);while( !theQueue.isEmpty() ) {

n = theQueue.removeLeft();System.out.print(n+ " ");n = theQueue.removeRight();System.out.print(n+" ");

}System.out.println("");

} }

Priority QueuesA priority queue is a more specialized data structure than a stackor a queue. However, it's a useful tool in a surprising number ofsituations. Like an ordinary queue, a priority queue has a front anda rear, and items are removed from the front. However, in a priorityqueue, items are ordered by key value, so that the item with thelowest key is always at the front. Items are inserted in the properposition to maintain the order.

Also, like ordinary queues, priority queues are used in variousways in certain computer systems. In a preemptive multitaskingoperating system, for example, programs may be placed in a priorityqueue so the highest-priority program is the next one to receive atime-slice that allows it to execute.31.Program to implement insert and delete operations on Priority Queue .Java Code for a Priority Queueimport java.io.*; // for I/Oclass PriorityQ

Page 158: Java and data structure

Java and Data Structures 158IIBSC

{private int maxSize;private double[] queArray;private int nItems;public PriorityQ(int s) // constructor{maxSize = s;queArray = new double[maxSize];nItems = 0;}public void insert(double item) // insert item{int j;if(nItems==0) // if no items,queArray[nItems++] = item; // insert at 0else // if any items,{for(j=nItems-1; j>=0; j--) // start at end,{if( item > queArray[j] ) // if new itemlarger,queArray[j+1] = queArray[j]; // shift upwardelse // if smaller,break; // done shifting} // end forqueArray[j+1] = item; // insert itnItems++;} // end else (nItems > 0)} // end insert()public double remove() // remove minimum item{ return queArray[--nItems]; }public double peekMin() // peek at minimum item{ return queArray[nItems-1]; }public boolean isEmpty() // true if queue is empty{ return (nItems==0); }public boolean isFull() // true if queue is full{ return (nItems == maxSize); }} // end class PriorityQclass PriorityQApp{public static void main(String[] args) throws IOException{PriorityQ thePQ = new PriorityQ(5);thePQ.insert(30);

Page 159: Java and data structure

Java and Data Structures 159IIBSC

thePQ.insert(50);thePQ.insert(10);thePQ.insert(40);thePQ.insert(20);while( !thePQ.isEmpty() ){double item = thePQ.remove();System.out.print(item + " "); // 10, 20, 30, 40, 50} // end whileSystem.out.println("");} // end main()} // end class PriorityQApp

Parsing Arithmetic ExpressionsStacks are used for parsing arithmetic expressions. It's easier forthe algorithm to use a two-step process:1. Transform the arithmetic expression into a different format,called postfix notation.2. Evaluate the postfix expression.

Postfix NotationEveryday arithmetic expressions are written with an operator (+, –, *,or /) placed between two operands (numbers, or symbols that stand fornumbers). This is called infix notation, because the operator iswritten inside the operands. Thus we say 2+2 and 4/7, or, usingletters to stand for numbers, A+B and A/B.In postfix notation (which is also called Reverse Polish Notation,or RPN, because it was invented by a Polish mathematician), theoperator follows the two operands. Thus A+B becomes AB+, and A/Bbecomes AB/.

Table 4.2: Infix and postfix expressionsInfix PostfixA+B–C AB+C–A+B*C ABC*+A*B+C AB*C+A*(B+C) ABC+*A*B+C*D AB*CD*+A+B*(C–D/(E+F)) ABCDEF+/–*+Besides infix and postfix, there's also a prefix notation, in which theoperator is written before the operands: +AB instead of AB+. Translation RulesLet's make the rules for infix-to-postfix translation more explicit.You read items from the infix input string and take the actions

Page 160: Java and data structure

Java and Data Structures 160IIBSC

shown in Table 4.10. These actions are described inpseudocode, ablend of Java and English.In this table, the < and >= symbols referto the operator precedence relationship, not numerical values. TheopThis operator has just been read from the infix input, while theopTop operator has just been popped off the stack.

Table 4.10: Translation rules

Page 161: Java and data structure

Java and Data Structures 161IIBSC

Page 162: Java and data structure

Java and Data Structures 162IIBSC

Java Code to Convert Infix to Postfiximport java.io.*; // for I/Oclass StackX{private int maxSize;private char[] stackArray;private int top;

Page 163: Java and data structure

Java and Data Structures 163IIBSC

public StackX(int s) // constructor{maxSize = s;stackArray = new char[maxSize];top = -1;}

public void push(char j) // put item on top of stack{ stackArray[++top] = j; }

public char pop() // take item from top of stack{ return stackArray[top--]; }

public char peek() // peek at top of stack{ return stackArray[top]; }

public boolean isEmpty() // true if stack is empty{ return (top == -1); }

public int size() // return size{ return top+1; }

public char peekN(int n) // return item at index n{ return stackArray[n]; }

public void displayStack(String s){System.out.print(s);System.out.print("Stack (bottom-->top): ");for(int j=0; j<size(); j++){System.out.print( peekN(j) );System.out.print(' ');}System.out.println("");}} // end class StackX// infix to postfix conversion{private StackX theStack;private String input;private String output = "";public InToPost(String in) // constructor{

Page 164: Java and data structure

Java and Data Structures 164IIBSC

input = in;int stackSize = input.length();theStack = new StackX(stackSize);}public String doTrans() // do translation to postfix{for(int j=0; j<input.length(); j++){char ch = input.charAt(j);theStack.displayStack("For "+ch+" "); // *diagnostic*switch(ch){case '+': // it's + or -case '-':gotOper(ch, 1); // go pop operatorsbreak; // (precedence 1)case '*': // it's * or /case '/':gotOper(ch, 2); // go pop operatorsbreak; // (precedence 2)case '(': // it's a left parentheStack.push(ch); // push itbreak;case ')': // it's a right parengotParen(ch); // go pop operatorsbreak;default: // must be an operandoutput = output + ch; // write it to outputbreak;} // end switch} // end forwhile( !theStack.isEmpty() ) // pop remaining opers{theStack.displayStack("While "); // *diagnostic*output = output + theStack.pop(); // write to output}theStack.displayStack("End "); // *diagnostic*return output; // return postfix} // end doTrans()public void gotOper(char opThis, int prec1){ // got operator from inputwhile( !theStack.isEmpty() ){char opTop = theStack.pop();

Page 165: Java and data structure

Java and Data Structures 165IIBSC

if( opTop == '(' ) // if it's a '('{theStack.push(opTop); // restore '('break;}else // it's an operator{int prec2; // precedence of new opif(opTop=='+' || opTop=='-') // find new op precprec2 = 1;elseprec2 = 2;if(prec2 < prec1) // if prec of new opless{ // than prec of oldtheStack.push(opTop); // save newly-popped opbreak;}else // prec of new not lessoutput = output + opTop; // than prec of old} // end else (it's an operator)} // end whiletheStack.push(opThis); // push new operator} // end gotOp()

public void gotParen(char ch){ // got right paren from inputwhile( !theStack.isEmpty() ){char chx = theStack.pop();if( chx == '(' ) // if popped '('break; // we're doneelse // if popped operatoroutput = output + chx; // output it} // end while} // end popOps()

} // end class InToPostclass InfixApp{public static void main(String[] args) throws IOException{String input, output;while(true)

Page 166: Java and data structure

Java and Data Structures 166IIBSC

{System.out.print("Enter infix: ");System.out.flush();input = getString(); // read a string from kbdif( input.equals("") ) // quit if [Enter]break;// make a translatorInToPost theTrans = new InToPost(input);output = theTrans.doTrans(); // do the translationSystem.out.println("Postfix is " + output + '\n');} // end while} // end main()

public static String getString() throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;}//-------------------------------------------------------------} // end class InfixAppEvaluating Postfix ExpressionsRules for Postfix EvaluationHow do we write a program to reproduce this evaluation process. Usethe rules shown in Table 4.14 to evaluate postfix expressions.

When you're finished, pop the stack to obtain the answer. 33. Program to evaluate postfix expression by using Stack.Java Code to Evaluate Postfix Expressionsimport java.io.*; // for I/Oclass StackX{private int maxSize;private int[] stackArray;

Page 167: Java and data structure

Java and Data Structures 167IIBSC

private int top;

public StackX(int size) // constructor{maxSize = size;stackArray = new int[maxSize];top = -1;}

public void push(int j) // put item on top of stack{ stackArray[++top] = j; }

public int pop() // take item from top of stack{ return stackArray[top--]; }

public int peek() // peek at top of stack{ return stackArray[top]; }

public boolean isEmpty() // true if stack is empty{ return (top == -1); }

public boolean isFull() // true if stack is full{ return (top == maxSize-1); }

public int size() // return size{ return top+1; }

public int peekN(int n) // peek at index n{ return stackArray[n]; }

public void displayStack(String s){System.out.print(s);System.out.print("Stack (bottom-->top): ");for(int j=0; j<size(); j++){System.out.print( peekN(j) );System.out.print(' ');}System.out.println("");}

} // end class StackXclass ParsePost

Page 168: Java and data structure

Java and Data Structures 168IIBSC

{private StackX theStack;private String input;

public ParsePost(String s){ input = s; }

public int doParse(){theStack = new StackX(20); // make new stackchar ch;int j;int num1, num2, interAns;for(j=0; j<input.length(); j++) // for each char,{ch = input.charAt(j); // read from inputtheStack.displayStack(""+ch+" "); // *diagnostic*if(ch >= '0' && ch <= '9') // if it's a numbertheStack.push( (int)(ch-'0') ); // push itelse // it's an operator{num2 = theStack.pop(); // pop operandsnum1 = theStack.pop();switch(ch) // do arithmetic{case '+':interAns = num1 + num2;break;case '-':interAns = num1 - num2;break;case '*':interAns = num1 * num2;break;case '/':interAns = num1 / num2;break;default:interAns = 0;} // end switchtheStack.push(interAns); // push result} // end else} // end forinterAns = theStack.pop(); // get answer

Page 169: Java and data structure

Java and Data Structures 169IIBSC

return interAns;} // end doParse()} // end class ParsePostclass PostfixApp{public static void main(String[] args) throws IOException{String input;int output;while(true){System.out.print("Enter postfix: ");System.out.flush();input = getString(); // read a string from kbdif( input.equals("") ) // quit if [Enter]break; // make a parserParsePost aParser = new ParsePost(input);output = aParser.doParse(); // do the evaluationSystem.out.println("Evaluates to " + output);} // end while} // end main()public static String getString() throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;}} // end class PostfixApp

Linked Lists we saw that arrays had certain disadvantages as data storagestructures. In an unordered array, searching is slow, whereas in anordered array, insertion is slow. In both kinds of arrays deletionis slow. Also, the size of an array can't be changed after it'screated. Linked lists are probably the second most commonly usedgeneral-purpose storage structures after arrays.In a linked list, each data item is embedded in a link. A link is anobject of a class called something like Link. Each link objectcontains a reference (usually called next) to the next link in thelist. A field in the list itself contains a reference to the firstlink.21. Program to create, insert, delete and display operations on single linked list.

Page 170: Java and data structure

Java and Data Structures 170IIBSC

Listing 5.1 The linkList.java Programclass Link{public int iData; // data item (key)public double dData; // data itempublic Link next; // next link in list

public Link(int id, double dd) // constructor{iData = id; // initialize datadData = dd; // ('next' is automatically} // set to null)

public void displayLink() // display ourself{System.out.print("{" + iData + ", " + dData + "} ");}} // end class Linkclass LinkList{private Link first; // ref to first link on list

public LinkList() // constructor{first = null; // no items on list yet}

public boolean isEmpty() // true if list is empty{return (first==null);}

public void insertFirst(int id, double dd){ // make new linkLink newLink = new Link(id, dd);newLink.next = first; // newLink --> old firstfirst = newLink; // first --> newLink}

public Link deleteFirst() { // (assumes list not empty)Link temp = first; // save reference to linkfirst = first.next; // delete it: first-->oldnext

Page 171: Java and data structure

Java and Data Structures 171IIBSC

return temp; // return deleted link}

public void displayList(){System.out.print("List (first-->last): ");Link current = first; // start at beginning of listwhile(current != null) // until end of list,{current.displayLink(); // print datacurrent = current.next; // move to next link}System.out.println("");}

} // end class LinkListclass LinkListApp{public static void main(String[] args){LinkList theList = new LinkList(); // make new listtheList.insertFirst(22, 2.99); // insert four itemstheList.insertFirst(44, 4.99);theList.insertFirst(66, 6.99);theList.insertFirst(88, 8.99);theList.displayList(); // display listwhile( !theList.isEmpty() ) // until it's empty,{Link aLink = theList.deleteFirst(); // delete linkSystem.out.print("Deleted "); // display itaLink.displayLink();System.out.println("");}theList.displayList(); // display list} // end main()} // end class LinkListApp24. Program to split a single link list. class Link{

public int iData;public double dData; public Link next; public Link(int id, double dd) {

Page 172: Java and data structure

Java and Data Structures 172IIBSC

iData = id; dData = dd;

} public void displayLink() {

System.out.print("{" + iData + ", " + dData + "} ");}

} class LinkList{

private Link first;private Link first1;public LinkList(){

first = null;first1= null;

}public boolean isEmpty() {

return (first==null);}public void insertFirst(int id, double dd){

Link newLink = new Link(id, dd);newLink.next = first; first = newLink;

}

public boolean splitList(int i){

Link current=first;while(i!=current.iData){

current=current.next;if(current==null)

return false;}

first1=current.next;current.next=null;return true;

}public void displayList(){

Page 173: Java and data structure

Java and Data Structures 173IIBSC

Link current;if(first1==null){

System.out.print("List (first-->last): ");current = first; while(current != null){

current.displayLink(); current = current.next;

}System.out.println("");

}else{

System.out.print("List1 (first--->last) :");current = first; while(current != null){

current.displayLink(); current = current.next;

}System.out.println("");System.out.print("List2 (first--->last) :");current = first1; while(current != null){

current.displayLink(); current = current.next;

}System.out.println("");

}

}}class SplitLinkedList{

public static void main(String[] args){

LinkList theList = new LinkList();theList.insertFirst(22, 2.99);theList.insertFirst(44, 4.99);theList.insertFirst(66, 6.99);theList.insertFirst(88, 8.99);

Page 174: Java and data structure

Java and Data Structures 174IIBSC

theList.insertFirst(33, 3.65);theList.insertFirst(77, 8.85);theList.insertFirst(55, 9.95);theList.insertFirst(99, 4.65);theList.displayList(); theList.splitList(33);System.out.println("Splited Lists:\n");theList.displayList();

} }

Finding and Deleting Specified LinksOur next example program adds methods to search a linked list for adata item with aspecified key value, and to delete an item with a specified keyvalue.class Link{public int iData; // data item (key)public double dData; // data itempublic Link next; // next link in list

public Link(int id, double dd) // constructor{iData = id;dData = dd;}

public void displayLink() // display ourself{System.out.print("{" + iData + ", " + dData + "} ");}} // end class Linkclass LinkList{private Link first; // ref to first link on list

public LinkList() // constructor{first = null; // no links on list yet}

public void insertFirst(int id, double dd){ // make new link

Page 175: Java and data structure

Java and Data Structures 175IIBSC

Link newLink = new Link(id, dd);newLink.next = first; // it points to old first linkfirst = newLink; // now first points to this}

public Link find(int key) // find link with given key{ // (assumes non-empty list)Link current = first; // start at 'first'while(current.iData != key) // while no match,{if(current.next == null) // if end of list,return null; // didn't find itelse // not end of list,current = current.next; // go to next link}return current; // found it}

public Link delete(int key) // delete link with given key{ // (assumes non-empty list)Link current = first; // search for linkLink previous = first;while(current.iData != key){if(current.next == null)return null; // didn't find itelse{previous = current; // go to next linkcurrent = current.next;}} // found itif(current == first) // if first link,first = first.next; // change firstelse // otherwise,previous.next = current.next; // bypass itreturn current;}

public void displayList() // display the list{System.out.print("List (first-->last): ");Link current = first; // start at beginning of listwhile(current != null) // until end of list,

Page 176: Java and data structure

Java and Data Structures 176IIBSC

{current.displayLink(); // print datacurrent = current.next; // move to next link}System.out.println("");}} // end class LinkListclass LinkList2App{public static void main(String[] args){LinkList theList = new LinkList(); // make listtheList.insertFirst(22, 2.99); // insert 4 itemstheList.insertFirst(44, 4.99);theList.insertFirst(66, 6.99);theList.insertFirst(88, 8.99);theList.displayList(); // display listLink f = theList.find(44); // find itemif( f != null)System.out.println("Found link with key " + f.iData);elseSystem.out.println("Can't find link");Link d = theList.delete(66); // delete itemif( d != null )System.out.println("Deleted link with key " +d.iData);elseSystem.out.println("Can't delete link");theList.displayList(); // display list} // end main()} // end class LinkList2App

Double-Ended ListsA double-ended list is similar to an ordinary linked list, but ithas one additional feature: a reference to the last link as well asto the first. Figure 5.9 shows what this looks like.

Figure 5.9: A double-ended list

Page 177: Java and data structure

Java and Data Structures 177IIBSC

The reference to the last link permits you to insert a new linkdirectly at the end of the list as well as at the beginning. Ofcourse you can insert a new link at the end of an ordinary single-ended list by iterating through the entire list until you reach theend, but this is inefficient. Access to the end of the list as well as the beginning makes thedouble-ended list suitable for certain situations that a single-ended list can't handle efficiently. One such situation isimplementing a queue; we'll see how this works in the next section.Listing 5.3 The firstLastList.java Programclass Link{public double dData; // data itempublic Link next; // next link in list

public Link(double d) // constructor{ dData = d; }

public void displayLink() // display this link{ System.out.print(dData + " "); }

} // end class Linkclass FirstLastList{private Link first; // ref to first linkprivate Link last; // ref to last link

public FirstLastList() // constructor{first = null; // no links on list yetlast = null;}

public boolean isEmpty() // true if no links{ return first==null; }

public void insertFirst(double dd) // insert at front oflist{Link newLink = new Link(dd); // make new linkif( isEmpty() ) // if empty list,last = newLink; // newLink <-- lastnewLink.next = first; // newLink --> old firstfirst = newLink; // first --> newLink

Page 178: Java and data structure

Java and Data Structures 178IIBSC

}

public void insertLast(double dd) // insert at end of list{Link newLink = new Link(dd); // make new linkif( isEmpty() ) // if empty list,first = newLink; // first --> newLinkelselast.next = newLink; // old last --> newLinklast = newLink; // newLink <-- last}

public double deleteFirst() // delete first link{ // (assumes non-empty list)double temp = first.dData; // save the dataif(first.next == null) // if only one itemlast = null; // null <-- lastfirst = first.next; // first --> old nextreturn temp;}

public void displayList(){System.out.print("List (first-->last): ");Link current = first; // start at beginningwhile(current != null) // until end of list,{current.displayLink(); // print datacurrent = current.next; // move to next link}System.out.println("");}

} // end class FirstLastListclass FirstLastApp{public static void main(String[] args){ // make a new listFirstLastList theList = new FirstLastList();theList.insertFirst(22); // insert at fronttheList.insertFirst(44);theList.insertFirst(66);theList.insertLast(11); // insert at reartheList.insertLast(33);

Page 179: Java and data structure

Java and Data Structures 179IIBSC

theList.insertLast(55);theList.displayList(); // display the listtheList.deleteFirst(); // delete first two itemstheList.deleteFirst();theList.displayList(); // display again} // end main()} // end class FirstLastApp

Abstract Data TypesIn this section we'll shift gears and discuss a topic that's moregeneral than linked lists:Abstract Data Types (ADTs). What is an ADT? Roughly speaking, it's away of looking at a data structure: focusing on what it does, andignoring how it does it.Stacks and queues are examples of ADTs. We've already seen that bothstacks and queues can be implemented using arrays. Before we returnto a discussion of ADTs, let's see how stacks and queues can beimplemented using linked lists. This will demonstrate the "abstract"nature of stacks and queues: how they can be considered separatelyfrom their implementation.28.Program to implement PUSH and POP operations on Stack using Linked List method.A Stack Implemented by a Linked Listimport java.io.*; // for I/Oclass Link{public double dData; // data itempublic Link next; // next link in list

public Link(double dd) // constructor{ dData = dd; }

public void displayLink() // display ourself{ System.out.print(dData + " "); }} // end class Linkclass LinkList{private Link first; // ref to first item on list

public LinkList() // constructor{ first = null; } // no items on list yet

public boolean isEmpty() // true if list is empty{ return (first==null); }

Page 180: Java and data structure

Java and Data Structures 180IIBSC

public void insertFirst(double dd) // insert at start of list{ // make new linkLink newLink = new Link(dd);newLink.next = first; // newLink --> old firstfirst = newLink; // first --> newLink}

public double deleteFirst() // delete first item{ // (assumes list not empty)Link temp = first; // save reference to linkfirst = first.next; // delete it: first-->old nextreturn temp.dData; // return deleted link}

public void displayList(){Link current = first; // start at beginning of listwhile(current != null) // until end of list,{current.displayLink(); // print datacurrent = current.next; // move to next link}System.out.println("");}} // end class LinkListclass LinkStack{private LinkList theList;

public LinkStack() // constructor{theList = new LinkList();}public void push(double j) // put item on top of stack{theList.insertFirst(j);}

public double pop() // take item from top ofstack{return theList.deleteFirst();}

Page 181: Java and data structure

Java and Data Structures 181IIBSC

public boolean isEmpty() // true if stack is empty{return ( theList.isEmpty() );}

public void displayStack(){System.out.print("Stack (top-->bottom): ");theList.displayList();}

} // end class LinkStackclass LinkStackApp{public static void main(String[] args) throws IOException{LinkStack theStack = new LinkStack(); // make stacktheStack.push(20); // push itemstheStack.push(40);theStack.displayStack(); // display stacktheStack.push(60); // push itemstheStack.push(80);theStack.displayStack(); // display stacktheStack.pop(); // pop itemstheStack.pop();theStack.displayStack(); // display stack} // end main()} // end class LinkStackApp

A Queue Implemented by a Linked ListHere's a similar example of an ADT implemented with a linked list.Listing 5.5 shows a queue implemented as a double-ended linked list.30.Program to implement insert and delete operations on Queue using Linked List method.Listing 5.5 The linkQueue() Programimport java.io.*; // for I/Oclass Link{public double dData; // data itempublic Link next; // next link in list

public Link(double d) // constructor{ dData = d; }

Page 182: Java and data structure

Java and Data Structures 182IIBSC

public void displayLink() // display this link{ System.out.print(dData + " "); }

} // end class Linkclass FirstLastList{private Link first; // ref to first itemprivate Link last; // ref to last item

public FirstLastList() // constructor{first = null; // no items on list yetlast = null;}

public boolean isEmpty() // true if no links{ return first==null; }

public void insertLast(double dd) // insert at end of list{Link newLink = new Link(dd); // make new linkif( isEmpty() ) // if empty list,first = newLink; // first --> newLinkelselast.next = newLink; // old last --> newLinklast = newLink; // newLink <-- last}

public double deleteFirst() // delete first link{ // (assumes non-emptylist)double temp = first.dData;if(first.next == null) // if only one itemlast = null; // null <-- lastfirst = first.next; // first --> old nextreturn temp;}

public void displayList(){Link current = first; // start at beginningwhile(current != null) // until end of list,{current.displayLink(); // print data

Page 183: Java and data structure

Java and Data Structures 183IIBSC

current = current.next; // move to next link}System.out.println("");}

} // end class FirstLastListclass LinkQueue{private FirstLastList theList;

public LinkQueue() // constructor{theList = new FirstLastList(); // make a 2-ended list}

public boolean isEmpty() // true if queue is empty{return theList.isEmpty();}

public void insert(double j) // insert, rear of queue{theList.insertLast(j);}

public double remove() // remove, front of queue{return theList.deleteFirst();}

public void displayQueue(){System.out.print("Queue (front-->rear): ");theList.displayList();}} // end class LinkQueueclass LinkQueueApp{public static void main(String[] args) throws IOException{LinkQueue theQueue = new LinkQueue();theQueue.insert(20); // insert itemstheQueue.insert(40);theQueue.displayQueue(); // display queue

Page 184: Java and data structure

Java and Data Structures 184IIBSC

theQueue.insert(60); // insert itemstheQueue.insert(80);theQueue.displayQueue(); // display queuetheQueue.remove(); // remove itemstheQueue.remove();theQueue.displayQueue(); // display queue} // end main()} // end class LinkQueueApp

23.Program to create, insert, delete and display operations on circularsingle linked list.class Link{

public int iData;public double dData; public Link next; public Link(int id, double dd) {

iData = id; dData = dd;

} public void displayLink() {

System.out.print("{" + iData + ", " + dData + "} ");}

} class LinkList{

private Link first; private Link last;public LinkList(){

first = null; last=null;

}public boolean isEmpty(){

return(first==null&&last==null);}public void insertFirst(int id, double dd){

Link newLink = new Link(id, dd);if(isEmpty()){

Page 185: Java and data structure

Java and Data Structures 185IIBSC

newLink.next = first; first = newLink;last=newLink;

}else{

newLink.next = first; first = newLink; last.next=first;

}}public Link deleteFirst() {

Link temp = first; if(first==last){

first=null;last=null;

}else{

first = first.next;last.next=first;

}return temp;

}public void displayList(){

System.out.print("List (first-->last): ");first.displayLink();Link current = first.next; while(current != first){

current.displayLink(); current = current.next;

}System.out.println("");

}

}class CircularLinkedList{

Page 186: Java and data structure

Java and Data Structures 186IIBSC

public static void main(String[] args){

LinkList theList = new LinkList();theList.insertFirst(22, 2.99);theList.insertFirst(44, 4.99);theList.insertFirst(66, 6.99);theList.insertFirst(88, 8.99);theList.displayList(); while(!theList.isEmpty()){

Link aLink = theList.deleteFirst(); System.out.print("Deleted "); aLink.displayLink();System.out.println("");

}

} }

Data Types and Abstraction

Data TypesA primitive type, you're actually referring to two things: a dataitem with certain characteristics, and permissible operations onthat data. create your own data types using classes. Some of thesedata types represent numerical quantities that are used in wayssimilar to primitive types. In fact, any class represents a datatype, in the sense that a class comprises data (fields) andpermissible operations on that data (methods).

AbstractionIn object-oriented programming, then, an abstract data type is aclass considered without regard to its implementation. The meaningof abstract data type is further extended when it's applied to datastructures like stacks and queues. As with any class, it means thedata and the operations that can be performed on it, but in thiscontext even the fundamentals of how the data is stored becomeinvisible to the user. Users not only don't know how the methodswork, they also don't know what structure is used to store the data.

The Interface

Page 187: Java and data structure

Java and Data Structures 187IIBSC

An ADT specification is often called an interface. It's what the classuser sees; usually its public methods. In a stack class, push() andpop() and similar methods form the interface.

ADT ListsNow that we know what an abstract data type is, we can mentionanother one: the list. A list (sometimes called a linear list) is agroup of items arranged in a linear order. That is, they're lined upin a certain way, like beads on a string or houses on a street.Lists support certain fundamental operations. You can insert anitem, delete an item, and usually read an item from a specifiedlocation (the third item, say). Don't confuse the ADT list with the linked list we've beendiscussing in this chapter. A list is defined by its interface: thespecific methods used to interact with it. This interface can beimplemented by various structures, including arrays and linkedlists. The list is an abstraction of such data structures.

ADTs as a Design ToolThe ADT concept is a useful aid in the software design process. Ifyou need to store data,start by considering the operations that needto be performed on that data. Do you need access to the last iteminserted? The first one? An item with a specified key? An item in acertain position? Answering such questions leads to the definitionof an ADT. Only after the ADT is completely defined should you worryabout the details of how to represent the data and how to code themethods that access the data.By decoupling the specification of the ADT from the implementationdetails, you can simplify the design process. You also make iteasier to change the implementation at some future time. If theusers relate only to the ADT interface, you should be able to changethe implementation without "breaking" the user's code.Of course, once the ADT has been designed, the underlying datastructure must be carefully chosen to make the specified operationsas efficient as possible. If you need random access to element N,for example, then the linked-list representation isn't so goodbecause random access isn't an efficient operation for a linkedlist. You'd be better off with an array.Sorted Lists In a sorted list, the items are arranged in sorted order by keyvalue. Deletion is often limited to the smallest (or the largest)item in the list, which is at the start of the list, althoughsometimes find() and delete() methods, which search through the listfor specified links, are used as well. The advantages of a sorted

Page 188: Java and data structure

Java and Data Structures 188IIBSC

list over a sorted array are speed of insertion and the fact that alist can expand to fill available memory, while an array is limitedto a fixed size. However, a sorted list is somewhat more difficultto implement than a sorted array. The sortedList.java Program import java.io.*; // for I/O class Link {

public double dData; // data item public Link next; // next link in list

public Link(double dd) // constructor {

dData = dd; } public void displayLink() // display this link {

System.out.print(dData + " "); } } // end class Link class SortedList {

private Link first; // ref to first item on list public SortedList() // constructor {

first = null; } public boolean isEmpty() // true if no links

{ return (first==null);

} public void insert(double key) // insert in order

{ Link newLink = new Link(key); // make new link Link previous = null; // start at first Link current = first;

// until end of list, while(current != null && key > current.dData) {

previous = current; current = current.next; // go to next

item } if(previous==null) // at beginning

of list

Page 189: Java and data structure

Java and Data Structures 189IIBSC

first = newLink; // first -->newLink else // not at

beginning previous.next = newLink; // old prev

--> newLink newLink.next = current; // newLink --> old

currnt } // end insert public Link remove() // return & delete first link { // (assumes non-empty list) Link temp = first; // save first first = first.next; // delete first

return temp; // return value } public void displayList() { System.out.print("List (first-->last): "); Link current = first; // start at beginning of list while(current != null) // until end of list, {

current.displayLink(); // print data current = current.next; // move to next link

} System.out.println("");

} } // end class SortedList class SortedListApp {

public static void main(String[] args) {

SortedList theSortedList = new SortedList(); theSortedList.insert(20); // insert 2 items

theSortedList.insert(40); theSortedList.displayList(); // display list theSortedList.insert(10); // insert 3 more items

theSortedList.insert(30); theSortedList.insert(50); theSortedList.displayList(); // display list

theSortedList.remove(); // remove an item theSortedList.displayList(); // display list

} // end main() } // end class SortedListApp Doubly Linked Lists

Page 190: Java and data structure

Java and Data Structures 190IIBSC

The doubly linked list provides this capability. It allows you totraverse backward as well as forward through the list. 22. Program to create, insert, delete and display operations on double linked list.The doublyLinked.java Program class Link { public double dData; // data item public Link next; // next link in list public Link previous; // previous link in list public Link(double d) // constructor {

dData = d; }

public void displayLink() // display this link {

System.out.print(dData + " "); }

} // end class Link class DoublyLinkedList {

private Link first; // ref to first item private Link last; // ref to last item public DoublyLinkedList() // constructor

{ first = null; // no items on list

yet last = null;

} public boolean isEmpty() // true if no links

{ return first==null;

} public void insertFirst(double dd) // insert at front oflist

{ Link newLink = new Link(dd); // make new link if( isEmpty() ) // if empty list,

last = newLink; // newLink <--last else

first.previous = newLink; // newLink <--old first

Page 191: Java and data structure

Java and Data Structures 191IIBSC

newLink.next = first; // newLink --> old first- 183 -

first = newLink; // first --> newLink } public void insertLast(double dd) // insert at end of list { Link newLink = new Link(dd); // make new link

if( isEmpty() ) // if empty list, first = newLink; // first -->

newLink else

{ last.next = newLink; // old last -->newLink

newLink.previous = last; // old last <--newLink

} last = newLink; // newLink <-- last

} public Link deleteFirst() // delete first link { Link temp = first;

if(first.next == null) // if only one item last = null; // null <-- last

else first.next.previous = null; // null <-- old

next first = first.next; // first --> old next return temp;

} public Link deleteLast() // delete last link { Link temp = last;

if(first.next == null) // if only one item first = null; // first --> null else last.previous.next = null; // old previous -->

null last = last.previous; // old previous <-- last return temp;

} public boolean insertAfter(double key, double dd) { Link current = first; // start at beginning

Page 192: Java and data structure

Java and Data Structures 192IIBSC

while(current.dData != key) // until match isfound,

{ current = current.next; // move to nextlink

if(current == null) return false; // didn't find

it }

Link newLink = new Link(dd); // make new link if(current==last) // if lastlink, {

newLink.next = null; // newLink --> null last = newLink; // newLink <-- last

} else // not last link,

{ newLink.next = current.next; // newLink --> old

next current.next.previous = newLink; }

newLink.previous = current; // old current <--newLink

current.next = newLink; // old current --> newLink return true; // found it, did

insertion } public Link deleteKey(double key) // delete item w/ givenkey { Link current = first; // start atbeginning

while(current.dData != key) // until match isfound,

{ current = current.next; // move to next

link if(current == null)

return null; // didn't findit

} if(current==first) // found it; first

item?

Page 193: Java and data structure

Java and Data Structures 193IIBSC

first = current.next; // first --> oldnext else // not first

current.previous.next = current.next; if(current==last) // last item?

last = current.previous; // old previous<-- last

else// old previous <-- old next

current.next.previous = current.previous; return current; // return value

} public void displayForward() { System.out.print("List (first-->last): ");

Link current = first; // start at beginning while(current != null) // until end of

list, {

current.displayLink(); // display data current = current.next; // move to next

link }

System.out.println(""); } public void displayBackward() { System.out.print("List (last-->first): "); Link current = last; // start at end while(current != null) // until start oflist, {

current.displayLink(); // display data current = current.previous; // move to previous

link } System.out.println("");

} } // end class DoublyLinkedList class DoublyLinkedApp {

public static void main(String[] args) {

DoublyLinkedList theList = new DoublyLinkedList();

Page 194: Java and data structure

Java and Data Structures 194IIBSC

theList.insertFirst(22); // insert at front theList.insertFirst(44); theList.insertFirst(66); theList.insertLast(11); // insert at rear theList.insertLast(33); theList.insertLast(55); theList.displayForward(); // display list

forward theList.displayBackward(); // display list

backward theList.deleteFirst(); // delete first item theList.deleteLast(); // delete last item theList.deleteKey(11); // delete item with

key 11 theList.displayForward(); // display list

forward theList.insertAfter(22, 77); // insert 77 after

22 theList.insertAfter(33, 88); // insert 88 after

33 theList.displayForward(); // display list

forward } // end main() } // end class DoublyLinkedApp

Quicksort Quicksort is undoubtedly the most popular sorting algorithm, and forgood reason: in the majority of situations, it's the fastest,operating in O(N*logN) time. (This is only true for internal or in-memory sorting; for sorting data in disk files other methods may bebetter.) The code for a basic recursive quicksort method is fairlysimple. Here's an example: public void recQuickSort(int left, int right) {

if(right-left <= 0) // if size is 1, return; // it's already sorted

else // size is 2 or larger { // partition range

int partition = partitionIt(left, right); recQuickSort(left, partition-1); // sort left side recQuickSort(partition+1, right); // sort right

side }

}

Page 195: Java and data structure

Java and Data Structures 195IIBSC

As you can see, there are three basic steps: 1. Partition the array or subarray into left (smaller keys) andright (larger keys) groups. 2. Call ourselves to sort the left group. 3. Call ourselves again to sort the right group. After a partition, all the items in the left subarray are smallerthan all those on the right. If we then sort the left subarray andsort the right subarray, the entire array will be sorted. The arguments to the recQuickSort() method determine the left andright ends of thearray (or subarray) it's supposed to sort. Themethod first checks whether this array consists of only one element.If so, the array is by definition already sorted, and the methodreturns immediately. This is the base case in the recursion process. If the array has two or more cells, the algorithm calls thepartitionIt() method, to partition it. This method returns the index number of thepartition: the left element in the right (larger keys) subarray. Thepartition marks the boundary between the subarrays. This is shown in Figure 7.8.

Once the array is partitioned, recQuickSort() calls itselfrecursively, once for the left part of its array, from left topartition-1, and once for the right part, from partition+1 to right. Note that the data item at the index partitionis not included in either of the recursive calls. Choosing a Pivot Value

The pivot value should be the key value of an actual data item;this item is called the pivot.

You can pick a data item to be the pivot more or less atrandom. For simplicity, let's say we always pick the item onthe right end of the subarray being partitioned.

Page 196: Java and data structure

Java and Data Structures 196IIBSC

After the partition, if the pivot is inserted at the boundarybetween the left and right subarrays, it will be in its finalsorted position.

This last point may sound unlikely, but remember that, because thepivot's key value is used to partition the array, then following thepartition the left subarray holds items smaller than the pivot, andthe right subarray holds items larger. The pivot starts out on theright, but if it could somehow be placed between these twosubarrays, it would be in the right place; that is, in its finalsorted position

Therefore, to simplify inserting the pivot in its proper place, wecan simply swap the pivot (36) and the left item in the rightsubarray, which is 63. This places the pivot in its proper positionbetween the left and right groups. The 63 is switched to the rightend, but because it remains in the right (larger) group, thepartitioning is undisturbed. This is shown in Figure 7.10.

Figure 7.10: Swapping the pivot Once it's swapped into the partition's locaFiguretion, the pivot isin its final resting place. All subsequent activity will take place

Page 197: Java and data structure

Java and Data Structures 197IIBSC

on one side of it or on the other, but the pivot itself won't bemoved (or indeed even accessed) again. 39. Program to implement Quick Sort. Listing 7.3 The quickSort1.java Program class ArrayIns { private double[] theArray; // ref to array theArray

private int nElems; // number of data items public ArrayIns(int max) // constructor {

theArray = new double[max]; // create thearray

nElems = 0; // no items yet } public void insert(double value) // put element into array {

theArray[nElems] = value; // insert it nElems++; // increment

size } public void display() // displays array

contents {

System.out.print("A="); for(int j=0; j<nElems; j++) // for each

element, System.out.print(theArray[j] + " "); //

display it System.out.println("");

} public void quickSort() {

recQuickSort(0, nElems-1); } public void recQuickSort(int left, int right)

{ if(right-left <= 0) // if size <= 1,

return; // alreadysorted else // size is 2 or

larger {

double pivot = theArray[right]; //rightmost item

Page 198: Java and data structure

Java and Data Structures 198IIBSC

int partition = partitionIt(left, right,pivot);

recQuickSort(left, partition-1); // sortleft side

recQuickSort(partition+1, right); // sortright side }

} // end recQuickSort() public int partitionIt(int left, int right, double pivot)

{ int leftPtr = left-1; // left (after

++) int rightPtr = right; // right-1 (after

--) while(true) {

while(theArray[++leftPtr]<pivot);// findsmaller item

while(rightPtr > 0 && theArray[--rightPtr] > pivot);

if(leftPtr >= rightPtr) // ifpointers cross,

break; //partition done else // not

crossed, so swap(leftPtr, rightPtr); // swap

elements } // end while(true) swap(leftPtr, right); // restore

pivot return leftPtr; // return

pivot location } // end partitionIt() public void swap(int dex1, int dex2) // swap two elements { double temp = theArray[dex1]; // A into temp

theArray[dex1] = theArray[dex2]; // B into A theArray[dex2] = temp; // temp into B

} // end swap( } // end class ArrayIns class QuickSort1App { public static void main(String[] args)

Page 199: Java and data structure

Java and Data Structures 199IIBSC

{ int maxSize = 16; // array size ArrayIns arr; arr = new ArrayIns(maxSize); // create array for(int j=0; j<maxSize; j++) // fill array with

{ // randomnumbers

double n = (int)(java.lang.Math.random()*99);

arr.insert(n); } arr.display(); // display items arr.quickSort(); // quicksort them

- 263 - arr.display(); // display them

again } // end main()

} // end class QuickSort1App What Is a Tree?A tree consists of nodes connected by edges.How Do Binary Trees Work? Let's see how to carry out the common binary-tree operations offinding a node with a given key, inserting a new node, traversingthe tree, and deleting a node. The Node ClassFirst, we need a class of node objects. These objects contain thedata representing the objects being stored (employees in an employeedatabase, for example) and also references to each of the node's twochildren. Here's how that looks: class Node {

int iData; // data used as key value float fData; // other data node leftChild; // this node's left child node rightChild; // this node's right child public void displayNode() {

// (body) } } Traversing the Tree Traversing a tree means visiting each node in a specified order. Onereason for this is that traversal is not particularly fast. But

Page 200: Java and data structure

Java and Data Structures 200IIBSC

traversing a tree is useful in some circumstances. There are threesimple ways to traverse a tree. They're called preorder, inorder,and postorder. The order most commonly used for binary search treesis inorder. Inorder Traversal An inorder traversal of a binary search tree will cause all thenodes to be visited in ascending order, based on their key values.If you want to create a sorted list of the data in a binary tree,this is one way to do it. The simplest way to carry out a traversalis the use of recursion (discussed in Chapter 6, "Recursion"). A recursive method to traverse the entire tree iscalled with a node as an argument. Initially, this node is the root.The method needs to do only three things: 1. Call itself to traverse the node's left subtree 2. Visit the node 3. Call itself to traverse the node's right subtree Remember that visiting a node means doing something to it:displaying it, writing it to a file, or whatever. Traversals workwith any binary tree, not just with binary search trees. Thetraversal mechanism doesn't pay any attention to the key values ofthe nodes; it only concerns itself with whether a node has children.34.Program to construct Binary Search Tree and implement tree traversingtechniques.class Node { int iData; double dData; Node leftChild; Node rightChild; public void displayNode() { System.out.println("("+iData+" , "+dData+")"); } } class BSTree{Node root;public BSTree(){

root=null;}

Page 201: Java and data structure

Java and Data Structures 201IIBSC

public Node insert(int id, double dd){ Node newNode = new Node(); newNode.iData = id; newNode.dData = dd; if(root==null) root = newNode; else {

Node current = root; Node parent; while(true) { parent = current; if(id < current.iData) { current = current.leftChild;

if(current == null) { parent.leftChild = newNode;

return root; }

} else { current = current.rightChild;

if(current == null) {

parent.rightChild = newNode; return root;

} } } }

return root; } public void inOrder(Node root) {

Node localRoot=root;

Page 202: Java and data structure

Java and Data Structures 202IIBSC

if(localRoot!= null) {

inOrder(localRoot.leftChild); localRoot.displayNode(); inOrder(localRoot.rightChild);

} } public void preOrder(Node root) {

Node localRoot=root;

if(localRoot!= null) {

localRoot.displayNode(); preOrder(localRoot.leftChild);

preOrder(localRoot.rightChild); } }public void postOrder(Node root) {

Node localRoot=root;

if(localRoot!= null) {

postOrder(localRoot.leftChild); postOrder(localRoot.rightChild);

localRoot.displayNode(); } } }class BSearchTree { public static void main(String[] args) { Node root=null;

Page 203: Java and data structure

Java and Data Structures 203IIBSC

BSTree theTree = new BSTree(); root=theTree.insert(50, 1.5); root=theTree.insert(25, 1.7); root=theTree.insert(75, 1.9);

root=theTree.insert(60, 2.4);root=theTree.insert(40, 3.4);root=theTree.insert(35, 4.1);

System.out.println("Inorder Traversing:\n");theTree.inOrder(root);System.out.println("preorder Traversing:\n");theTree.preOrder(root);

System.out.println("postorder Traversing:\n");theTree.postOrder(root);

} }

Finding Maximum and Minimum Values Incidentally, we should note how easy it is to find the maximum andminimum values in a binary search tree. For the minimum, go to theleft child of the root; then go to the left child of that child, andso on, until you come to a node that has no left child. This node isthe minimum. Here's some code that returns the node with the minimum key value: public Node minimum() // returns node with minimum key value {

Node current, last; current = root; // start at root while(current != null) // until the bottom, {

last = current; // remember node current = current.leftChild; // go to left child

} return last;

} For the maximum value in the tree, follow the same procedure but gofrom right child to right child until you find a node with no rightchild. This node is the maximum. The code the same except that thelast statement in the loop is current = current.rightChild; // go to right child

Page 204: Java and data structure

Java and Data Structures 204IIBSC

The Efficiency of Binary Trees Thus the time needed to carry out the common tree operations isproportional to the base-2 log of N. In Big-O notation we say suchoperations take O(logN) time. If the tree isn't full, analysis isdifficult. We can say that for a tree with a given number of levels,average search times will be shorter for the non-full tree than thefull tree because fewer searches will proceed to lower levels. Thusa tree provides high efficiency for all the common data-storageoperations. Traversing is not as fast as the other operations.However, traversals are probably not very commonly carried out in atypical large database. They're more appropriate when a tree is usedas an aid to parsing algebraic or similar expressions, which areprobably not too long anyway.the number of comparisons for a binary search was approximatelyequal to the base-2 logarithm of the number of cells in the array.Here, if we call the number of nodes in the first column N, and thenumber of levels in the second column L, then we can say that N is 1less than 2 raised to the power L, or N = 2L – 1 Adding 1 to both sides of the equation, we have N+1 = 2L

This is equivalent to L = log2(N+1)

Thus the time needed to carry out the common tree operations isproportional to the base-2 log of N. In Big-O notation we say suchoperations take O(logN) time. If the tree isn't full, analysis isdifficult. We can say that for a tree with a given number of levels,average search times will be shorter for the non-full tree than thefull tree because fewer searches will proceed to lower levels.Compare the tree to the other data-storage structures we'vediscussed so far. In an unordered array or a linked list containing1,000,000 items, it would take you on the average 500,000comparisons to find the one you wanted. But in a tree of 1,000,000items, it takes 20 (or fewer) comparisons. In an ordered array you can find an item equally quickly, butinserting an item requires, on the average, moving 500,000 items.Inserting an item in a tree with 1,000,000 items requires 20 orfewer comparisons, plus a small amount of time to connect the item.Similarly, deleting an item from a 1,000,000-item array requiresmoving an average of 500,000 items, while deleting an item from a1,000,000-node tree requires 20 or fewer comparisons to find theitem, plus (possibly) a few more comparisons to find its successor,plus a short time to disconnect the item and connect its successor.

Page 205: Java and data structure

Java and Data Structures 205IIBSC

Thus a tree provides high efficiency for all the common data-storageoperations. Traversing is not as fast as the other operations.However, traversals are probably not very commonly carried out in atypical large database. They're more appropriate when a tree is usedas an aid to parsing algebraic or similar expressions, which areprobably not too long anyway.

Trees Represented as Arrays Our code examples are based on the idea that a tree's edges arerepresented by leftChild and rightChild references in each node.However, there's a completely different way to represent a tree:with an array. In the array approach, the nodes are stored in anarray and are not linked by references. The position of the node inthe array corresponds to its position in the tree. The node at index0 is the root, the node at index 1 is the root's left child, and soon, progressing from left to right along each level of the tree.This is shown in Figure.

Every position in the tree, whether it represents an existing nodeor not, corresponds to a cell in the array. Adding a node at a givenposition in the tree means inserting the node into the equivalentcell in the array. Cells representing tree positions with no nodesare filled with zero or null. With this scheme, a node's children and parent can be found byapplying some simple arithmetic to the node's index number in thearray. If a node's index number is index, then this node's

Page 206: Java and data structure

Java and Data Structures 206IIBSC

left child is 2*index + 1 its right child is

2*index + 2 and its parent is (index-1) / 2

(where the '/' character indicates integer division with noremainder). You can check this out by looking at the figure. In mostsituations, representing a tree with an array isn't very efficient.Unfilled nodes and deleted nodes leave holes in the array, wastingmemory. Even worse, when deletion of a node involves movingsubtrees, every node in the subtree must be moved to its newlocation in the array, which is time-consuming in large trees. However, if deletions aren't allowed, then the array representationmay be useful, especially if obtaining memory for each nodedynamically is, for some reason, too time-consuming. The arrayrepresentation may also be useful in special situations. The tree inthe Workshop applet, for example, is represented internally as anarray to make it easy to map the nodes from the array to fixedlocations on the screen display.35. Program to delete a leaf node from binary search tree.class Node { int iData; double dData; Node leftChild; Node rightChild; public void displayNode() { System.out.println("("+iData+" , "+dData+")"); } } class BSTree{

Node root;public BSTree(){

root=null;

}public Node insert(int id, double dd){

Node newNode = new Node();

newNode.iData = id;

Page 207: Java and data structure

Java and Data Structures 207IIBSC

newNode.dData = dd; if(root==null)

root = newNode; else

{ Node current = root; Node parent; while(true) { parent = current; if(id < current.iData) { current = current.leftChild;

if(current == null) { parent.leftChild = newNode;

return root; }

} else { current = current.rightChild;

if(current == null) {

parent.rightChild = newNode; return root;

} } } }

return root; } public void deleteLeafNode(Node localRoot,Node parent) {

if(localRoot!=null){

if(localRoot.leftChild==null&&localRoot.rightChild==null){

System.out.println("Deleted Node = "+"("+localRoot.iData+" , "+localRoot.dData+ ")");

if(parent.leftChild==localRoot)

Page 208: Java and data structure

Java and Data Structures 208IIBSC

parent.leftChild=null;else

parent.rightChild=null;}deleteLeafNode(localRoot.leftChild,localRoot);deleteLeafNode(localRoot.rightChild,localRoot);

}

} public void inOrder(Node localRoot)

{

if(localRoot!= null) {

inOrder(localRoot.leftChild); localRoot.displayNode(); inOrder(localRoot.rightChild);

}

}

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

Node root=null;BSTree theTree = new BSTree();

root=theTree.insert(50, 1.5); root=theTree.insert(25, 1.7);

root=theTree.insert(75, 1.9); root=theTree.insert(60, 2.4);root=theTree.insert(40, 3.4);root=theTree.insert(35, 4.1);root=theTree.insert(65,1.2);

System.out.println("Inorder Traversing:\n");theTree.inOrder(root);theTree.deleteLeafNode(root,root);theTree.inOrder(root);

} }

Page 209: Java and data structure

Java and Data Structures 209IIBSC

40. Program to Find number of Leaf nodes and Non-Leaf nodes in Binary Search Tree.class Node { int iData; double dData; Node leftChild; Node rightChild; public void displayNode() { System.out.println("("+iData+" , "+dData+")"); } } class BSTree{

Node root;public int count;public int leafcount;public BSTree(){

root=null;count=0;leafcount=0;

}public Node insert(int id, double dd){

Node newNode = new Node();

newNode.iData = id; newNode.dData = dd; if(root==null)

root = newNode; else

{ Node current = root; Node parent; while(true) { parent = current; if(id < current.iData) { current = current.leftChild;

if(current == null) {

Page 210: Java and data structure

Java and Data Structures 210IIBSC

parent.leftChild = newNode; return root;

} } else { current = current.rightChild;

if(current == null) {

parent.rightChild = newNode; return root;

} } } }

return root; } public void nodecount(Node localRoot) {

if(localRoot!=null){

if(localRoot.leftChild==null&&localRoot.rightChild==null)leafcount++;

elsecount++;

nodecount(localRoot.leftChild);nodecount(localRoot.rightChild);

}

} public void inOrder(Node localRoot)

{if(localRoot!= null)

{ inOrder(localRoot.leftChild); localRoot.displayNode(); inOrder(localRoot.rightChild);

} } }class BSearchTreeNodeCount

Page 211: Java and data structure

Java and Data Structures 211IIBSC

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

Node root=null;BSTree theTree = new BSTree();

root=theTree.insert(50, 1.5); root=theTree.insert(25, 1.7);

root=theTree.insert(75, 1.9); root=theTree.insert(60, 2.4);root=theTree.insert(40, 3.4);root=theTree.insert(35, 4.1);root=theTree.insert(65,1.2);

System.out.println("Inorder Traversing:\n");theTree.inOrder(root);theTree.nodecount(root);System.out.println("Non leaf Node Count =

"+theTree.count);System.out.println("Leaf Node Count =

"+theTree.leafcount); }

} Introduction to Graphs Graphs are data structures rather like trees. In fact, in amathematical sense, a tree is a kind of graph. In computerprogramming, however, graphs are used in different ways than trees. For example, nodes in a graph may represent cities, while edges mayrepresent airline flight routes between the cities. Another moreabstract example is a graph representing the individual tasksnecessary to complete a project. In the graph, nodes may representtasks, while directed edges (with an arrow at one end) indicatewhich task must be completed before another. In both cases, theshape of the graph arises from the specific real-world situation.In graphs, nodes are called vertices (the singular is vertex). Treesare more closely associated with computer science. Definitions

Page 212: Java and data structure

Java and Data Structures 212IIBSC

In the graph, The circles are vertices, and the lines are edges. Thevertices are usually labeled in some way—often, as shown here, withletters of the alphabet. Each edge is bounded by the two vertices atits ends. The graph doesn't attempt to reflect the geographicalpositions shown on the map; it shows only the relationships of thevertices and the edges—that is, which edges are connected to whichvertex. It doesn't concern itself with physical distances ordirections. Also, one edge may represent several different routenumbers.

Adjacency Two vertices are said to be adjacent to one another if they areconnected by a single edge. The vertices adjacent to a given vertexare sometimes said to be its neighbors.

Paths A path is a sequence of edges. There can be more than one pathbetween two vertices.

Connected Graphs A graph is said to be connected if there is at least one path fromevery vertex to every other vertex. A non-connected graph consistsof several connected components. Directed and Weighted Graphs Non-directed graphs means that the edge don't have a direction; youcan go either way on them. Thus you can go from vertex A to vertexB, or from vertex B to vertex A, with equal ease. (This modelsfreeways appropriately, because you can usually go either way on afreeway.) However, graphs are often used to model situations inwhich you can go in only one direction along an edge; from A to Bbut not from B to A, as on a one-way street. Such a graph is said tobe directed. The allowed direction is typically shown with anarrowhead a the end of the edge.

Page 213: Java and data structure

Java and Data Structures 213IIBSC

In some graphs, edges are given a weight, a number that canrepresent the physical distance between two vertices, or the time ittakes to get from one vertex to another, or how much it costs totravel from vertex to vertex (on airline routes, for example). Suchgraphs are called weighted graphs.

Two methods are commonly used for graphs: the adjacency matrix andthe adjacency list.

Vertices In a very abstract graph program you could simply number thevertices 0 to N–1 (where N is the number of vertices). In mostsituations, however, a vertex represents some real-world object, andthe object must be described using data items. If a vertexrepresents a city in an airline route simulation, for example, itmay need to store the name of the city, its altitude, its location,and other such information. Thus it's usually convenient torepresent a vertex by an object of a vertex class. class Vertex {

public char label; // label (e.g. 'A') public boolean wasVisited;

public Vertex(char lab) // constructor {

label = lab; wasVisited = false;

} } // end class Vertex

The Adjacency Matrix An adjacency matrix is a two-dimensional array in which the elementsindicate whether an edge is present between two vertices. If a graphhas N vertices, the adjacency matrix is an NxN array. Table 13.1shows the adjacency matrix for the graph in Figure 13.2-a.

Page 214: Java and data structure

Java and Data Structures 214IIBSC

The vertices are used as headings for both rows and columns. An edgebetween two vertices is indicated by a 1; the absence of an edge is a 0. (Youcould also use Boolean true/false values.) As you can see, vertex Ais adjacent to all three other vertices, B is adjacent to A and D, Cis adjacent only to A, and D is adjacent to A and B. In thisexample, the "connection" of a vertex to itself is indicated by 0,so the diagonal from upper-left to lower-right, A-A to D-D, which iscalled the identity diagonal, is all 0s. The entries on the identitydiagonal don't convey any real information, so you can equally wellput 1s along it, if that's more convenient in your program.

The Adjacency List The other way to represent edges is with an adjacency list. The listin adjacency list refers to a linked list, "Recursion." Actually, an adjacency listis an array of lists (or a list of lists). Each individual listshows what vertices a given vertex is adjacent to. Table 13.2 showsthe adjacency lists for the graph of Figure 13.2-a.

Each link in the list is a vertex. The adjacency list shows whichvertices are adjacent to—that is, one edge away from—a given vertex,not paths from vertex to vertex.

Page 215: Java and data structure

Java and Data Structures 215IIBSC

SearchesThere are two common approaches to searching a graph: depth-firstsearch (DFS) and breadth-first search (BFS). Both will eventuallyreach all connected vertices. The difference is that the depth-first search is implemented with astack, whereas the breadth-first search is implemented with a queue.

Depth-First Search The depth-first search uses a stack to remember where it should gowhen it reaches a dead end. We'll discuss the idea behind the depth-first search in relation to Figure 13.5. The numbers in this figureshow the order in which the vertices are visited.

To carry out the depth-first search, you pick a starting point—inthis case, vertex A. You then do three things: visit this vertex,push it onto a stack so you can remember it, and mark it so youwon't visit it again. Next you go to any vertex adjacent to A that hasn't yet beenvisited. We'll assume the vertices are selected in alphabeticalorder, so that brings up B. You visit B, mark it, and push it on thestack. go to an adjacent vertex that hasn't been visited, and pushit on the stack. We can call this process Rule 1.

Rule 2: If you can't follow Rule 1, then, if possible, pop a vertexoff the stack. Following this rule, you pop H off the stack, which brings you backto F. F has no unvisited adjacent vertices, so you pop it. Ditto B. Now only A isleft on the stack. A, however, does have unvisited adjacent vertices, so you visit thenext one, C. But C is the end of the line again, so you pop it andyou're back to A. You visit D, G, and I, and then pop them all whenyou reach the dead end at I. Now you're back to A. You visit E, andagain you're back to A. This time, however, A has no unvisitedneighbors, so we pop it off the stack.

Page 216: Java and data structure

Java and Data Structures 216IIBSC

Table 13.3 shows how the stack looks in the various stages of thisprocess, as applied to Figure 13.5. Table 13.3: Stack Contents During Depth-First Search

The contents of the stack is the route you took from the startingvertex to get where you are. As you move away from the startingvertex, you push vertices as you go. As you move back toward thestarting vertex, you pop them. The order in which you visit thevertices is ABFHCDGIE. You might say that the depth-first search algorithm likes to get asfar away from the starting point as quickly as possible, and returns only when itreaches a dead end. If you use the term depth to mean the distancefrom starting point, you can see where the name depth-first searchcomes from.

Page 217: Java and data structure

Java and Data Structures 217IIBSC

Breadth-First Search In the breadth-first search, on the other hand, the algorithm likesto stay as close as possible to the starting point. It visits allthe vertices adjacent to the starting vertex, and only then goesfurther afield. This kind of search is implemented using a queueinstead of a stack.

Figure 13.9 shows the same graph as Figure 13.5, but here thebreadth-first search is used. Again, the numbers indicate the orderin which the vertices are visited. A is the starting vertex, so youvisit it and make it the current vertex. Then you follow these rules: Rule 1: Visit the next unvisited vertex (if there is one) that'sadjacent to the current vertex, mark it, and insert it into thequeue.

Rule 2: If you can't carry out Rule 1 because there are no moreunvisited vertices, remove a vertex from the queue (if possible) and make it the currentvertex. Rule 3: If you can't carry out Rule 2 because the queue is empty,you're finished.

Thus you first visit all the vertices adjacent to A, inserting eachone into the queue as you visit it. Now you've visited A, B, C, D,and E. At this point the queue (from front to rear) contains BCDE.

Page 218: Java and data structure

Java and Data Structures 218IIBSC

There are no more unvisited vertices adjacent to A, so you remove Bfrom the queue and look for vertices adjacent to B, so you remove Cfrom the queue. It has no adjacent unvisited adjacent vertices, soyou remove D and visit G. D has no more adjacent unvisited vertices,so you remove E. Now the queue is FG. You remove F and visit H, andthen you remove G and visit I. Now the queue is HI, but when you'veremoved each of these and found no adjacent unvisited vertices, thequeue is empty, so you're finished. Table 13.4 shows this sequence. Table 13.4: Queue Contents During Breadth-First Search

At each moment, the queue contains the vertices that have beenvisited but whose neighbors have not yet been fully explored. (Contrast this with thedepth-first search, where the contents of the stack is the route you took from thestarting point to the current vertex.) The nodes are visited in theorder ABCDEFGHI.Minimum Spanning Trees

Page 219: Java and data structure

Java and Data Structures 219IIBSC

A graph with the minimum number of edges necessary to connect thevertices. For example, Figure 13.10-a shows five vertices with anexcessive number of edges, while Figure 13.10-b shows the same vertices with the minimum numberof edges necessary to connect them. This constitutes a minimum spanning tree.There are many possible minimum spanning trees for a given set ofvertices. Figure 13.10-b shows edges AB, BC, CD, and DE, but edgesAC, CE, ED, and DB would do just as well. The arithmetically inclined will note that the number ofedges E in a minimum spanning tree is always one less than the number of vertices V: E = V – 1 Remember that we're not worried here about the length of the edges.We're not trying to find a minimum physical length, just the minimumnumber of edges. The algorithm for creating the minimum spanning tree is almostidentical to that used for searching. It can be based on either thedepth-first search or the breadth-first search. In our example we'lluse the depth-first-search. It turns out that by executing thedepth-first search and recording the edges you've traveled to makethe search, you automatically create a minimum spanning tree. Theonly difference between the minimum spanning tree method mst(),which we'll see in a moment, and the depth-first search methoddfs(), which we saw earlier, is that mst(must somehow record theedges traveled.Topological Sorting with Directed Graphs Topological sorting is another operation that can be modeled withgraphs. It's useful in situations in which items or events must bearranged in a specific order.

Directed Graphs As the figure shows, a graph can represent this sort of arrangement.However, the graph needs a feature we haven't seen before: The edgesneed to have a direction.

Page 220: Java and data structure

Java and Data Structures 220IIBSC

When this is the case, the graph is called a directed graph. In adirected graph you can only proceed one way along an edge. Thedifference between a non-directed graph and a directed graph is thean edge in a directed graph has only one entry in the adjacencymatrix. Figure 13.12 shows a small directed graph; Table 13.5 showsits adjacency matrix. Table 13.5: Adjacency Matrix for Small Directed Graph

Each edge is represented by a single 1. The row labels show wherethe edge starts, and the column labels show where it ends. Thus, theedge from A to B is represented by a single 1 at row A column B. Ifthe directed edge were reversed so that it went from B to A, therewould be a 1 at row B column A instead. For a non-directed graph, as we noted earlier, half of theadjacency matrix mirrors the other half, so half the cells areredundant. However, for a weighted graph, every cell in theadjacency matrix conveys unique information. For a directed graph, the method that adds an edge thus needs only asingle statement, public void addEdge(int start, int end) // directed graph { adjMat[start][end] = 1; } instead of the two statements required in a non-directed graph. If you use the adjacency-list approach to represent your graph, thenA has B in its list but—unlike a non-directed graph—B does not have A in its list. Topological Sorting

Page 221: Java and data structure

Java and Data Structures 221IIBSC

Imagine that you make a list of all the courses necessary for yourdegree, using Figure 13.11 as your input data. You then arrange thecourses in the order you need to take them. Obtaining your degree isthe last item on the list, which might look like this:BAEDGCFH Arranged this way, the graph is said to be topologically sorted. Anycourse you must take before some other course occurs before it inthe list. Actually, many possible orderings would satisfy the courseprerequisites. You could take the English courses C and F first, forexample: CFBAEDGH This also satisfies all the prerequisites. There are many otherpossible orderings as well. When you use an algorithm to generate atopological sort, the approach you take and the details of the codedetermine which of various valid sortings are generated. Topological sorting can model other situations besides courseprerequisites. Job scheduling is an example. Modeling job schedules with graphs is called critical pathanalysis. A weighted graph can be used, which allows the graph toinclude the time necessary to complete different tasks in a project.The graph can then tell you such things as the minimum timenecessary to complete the project. 1.Write a java program to determine the sum of the following harmonic series for a given value of 'n'. 1+ ½ + ⅓ + …………..+ 1/n. class Series{public static void main(String args[]){

int a,i;double s=0.0;

Page 222: Java and data structure

Java and Data Structures 222IIBSC

char b;System.out.println("Enter a Number");System.out.flush();try{

b=(char)System.in.read();a=(int)(b-'0');for(i=1;i<=a;i++)s+=(double)(1.0/(double)i);System.out.println("Series="+s);

}catch(Exception e){

System.out.println("I/O Error");}

}}

2.Write a program to perform the following operations on string throughinteractive input.(a) Sort given Strings in alphabetical order. import java.io.*;class SortString {static String arr[] = {"ram", "sham", "swathi", "manjula", "sunitha", "aaparna", "azar", "sowmya","lakshmi", "ramesh", "sathish", "k.kanth", "anitha", "veena", "jyothi", "sowjanya"};public static void main(String args[]) {

for(int j = 0; j < arr.length; j++) {

for(int i = j + 1; i < arr.length; i++){

if(arr[i].compareTo(arr[j]) < 0){

String t = arr[j];arr[j] = arr[i];arr[i] = t;

}}

Page 223: Java and data structure

Java and Data Structures 223IIBSC

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

System.out.println(arr[i]);}}b)Check whether one String is Sub String of another String or not.import java.io.*;public class FindSubString {public static void main(String[] args) throws IOException{

System.out.println("Enter cost price");System.out.flush();String text1 = getString();int costprice=Integer.ParseInt(text1);System.out.println("Enter searchstring");System.out.flush();String sub = getString();

index = text.indexOf(sub); if(index!=-1)

System.out.println("position of "+sub+" : "+index);else

System.out.println(sub+" not available in given text");} public static String getString() throws IOException{

InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;

}}

c)Convert the Strings to uppercase.import java.io.*;public class ToUpperCase

Page 224: Java and data structure

Java and Data Structures 224IIBSC

{public static void main(String[] args) throws IOException{

int Count = 0; int index = -1;

System.out.println("Enter text");System.out.flush();String text = getString();System.out.println("Entered Text :"+text);System.out.println("Entered Text in

uppercase :"+text.toUpperCase());} public static String getString() throws IOException{

InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;

}}3.Write a program to simulate on-line shopping.import java.io.*;class Shopping{public static void main(String as[]) throws Exception{

int i=0,x,op,sum=0,m;String con="";int a[]=new int[10];int n[]=new int[10];String s[]={"Self Confidence -book(Rs.200)","My Experiments with

truth(Rs. 100)", "Java Apoorva book(Rs. 150)", "Java Complete Reference(Rs. 300)"};

InputStreamReader isr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(isr);do{

Page 225: Java and data structure

Java and Data Structures 225IIBSC

System.out.println("Select Items from the list:\n");System.out.println(" 1.Self Confidence -book\tRs.200");System.out.println(" 2.My Experiments with truth\tRs.100");System.out.println(" 3.Java Apoorva book\tRs.150");System.out.println(" 4.Java Complete Reference\tRs.300");System.out.println("\nSelect the Item number:");x=Integer.parseInt(br.readLine());if(x<1 || x>4) continue;a[i]=x;System.out.println("Enter quantity:");n[i]=Integer.parseInt(br.readLine());i++;System.out.println("Add more Items?(y,n):");con=br.readLine();

} while(con.equals("y"));m=i; // number of itemsSystem.out.println("\n 1. Check out \n 2. Cancel the order \n");System.out.println("Enter option:");op=Integer.parseInt(br.readLine());if(op==1){

System.out.println("==========================================");System.out.println("\nItem\tQuantity");

System.out.println("==========================================");for(i=0;i<m;i++){

if(a[i]==1)sum=sum+n[i]*200;

else if(a[i]==2)sum=sum+n[i]*100;

else if(a[i]==3)sum=sum+n[i]*150;

else if(a[i]==4)sum=sum+n[i]*300;

System.out.println("\n"+s[a[i]]+"\t"+n[i]);}

Page 226: Java and data structure

Java and Data Structures 226IIBSC

System.out.println("==========================================");System.out.println("\nTotal Bill:"+sum);

System.out.println("==========================================");}

}

}4.Write a program to identify a duplicate value in vector.class DuplicateValueInVector{public static void main(String args[]){

int i,j;int[] a={1,22,4,55,22,7,8,9,1,4,12,6,5,10,11};for(i=0;i<a.length-1;i++){

for(j=i+1;j<a.length;j++)if(a[i]==a[j])

System.out.println("duplicate value in vector is "+a[i]);

}}

}5.Create two threads such that one of the thread print even no's and other prints odd no's up to a given range.class MyThread extends Thread{Int initval, finalval;MyThread(int iv, int fv){initval=iv;finalval=fv;start();}public void run(){for(int i=initval;i<=finalval;i+=2){

Page 227: Java and data structure

Java and Data Structures 227IIBSC

System.out.println(i);try{Thread.sleep(1000);}catch(Exception e){}}}}class ThreadTest{public static void main(String as[]){MyThread t1=new MyThread(1,6);MyThread t2=new MyThread(2,6);}}

6.Define an exception called "Marks Out of Bound" Exception, that is thrown if the entered marks are greater than 100.class MyException extends Exception {

public String toString(){

return "Marks Out of Bound ";}}class MarksException{static void compute(int a) throws MyException {

if(a > 100)throw new MyException();

System.out.println("Normal exit");}public static void main(String args[]) {

try{

compute(70);

Page 228: Java and data structure

Java and Data Structures 228IIBSC

compute(150);

}catch (MyException e) {

System.out.println("Caught " + e);}

}}7.Write a Java program to shuffle the list elements using all the possible permutations.class ShuffleList{public static void main(String as[]){

char s[]={'a','b','c'};int i,j,k,n=s.length;/* number of for loops should match with number of character i.e

here ‘3’ */for(i=0;ifor(j=0;jfor(k=0;kif(i!=j && j!=k && i!=k)System.out.println(s[i]+","+s[j]+","+s[k]);

}}8.Create a package called "Arithmetic" that contains methods to deal all arithmetic operations. Also, write a program to use the package.package arithmetic;public class Math{int sum(int a, int b){

return(a+b);}int dif(int a, int b){

return(a-b);}int mul(int a, int b)

Page 229: Java and data structure

Java and Data Structures 229IIBSC

{return(a*b);

}int div(int a, int b){

return(a/b);}int mod(int a, int b){

return(a%b);}}import arthmetic.*;class ArithmeticOp{public static void main(String args[]){

Math a=new Math();int x=40;int y=10;int z;z=a.sum(x,y);System.out.println("Sum of "+x+","+y+" = "+z);z=a.dif(x,y);System.out.println("Difference of "+x+","+y+" = "+z);z=a.div(x,y);System.out.println("Division of "+x+","+y+" = "+z);z=a.mul(x,y);System.out.println("Multiplication of "+x+","+y+" = "+z);z=a.mod(x,y);System.out.println("Modulus of "+x+","+y+" = "+z);

}}9.Write an Applet program to design a simple calculator.mport java.applet.*;import java.awt.*;import java.awt.event.*;public class Calc extends Applet implements ActionListener{String cmd[]={"+","-","*","/","=","C"};int pv=0;String op="";

Page 230: Java and data structure

Java and Data Structures 230IIBSC

Button b[]=new Button[16];TextField t1=new TextField(10);public void init(){setLayout(new BorderLayout());add(t1,"North");t1.setText("0");Panel p=new Panel();p.setLayout(new GridLayout(4,4));for(int i=0;i<16;i++){if(i<10)b[i]=new Button(String.valueOf(i));elseb[i]=new Button(cmd[i%10]);b[i].setFont(new Font("Arial",Font.BOLD,25));p.add(b[i]);add(p,"Center");b[i].addActionListener(this); }}public void actionPerformed(ActionEvent ae){int res=0;String cap=ae.getActionCommand();int cv=Integer.parseInt(t1.getText());if(cap.equals("C")){t1.setText("0");pv=0;cv=0;res=0;op="";}else if(cap.equals("=")){res=0;if(op=="+")res=pv+cv;else if(op=="-")res=pv-cv;else if(op=="*")res=pv*cv;else if(op=="/")res=pv/cv;

Page 231: Java and data structure

Java and Data Structures 231IIBSC

t1.setText(String.valueOf(res)); }else if(cap.equals("+")||cap.equals("-")||cap.equals("*")||cap.equals("/")){pv=cv;op=cap;t1.setText("0");}else{int v=cv*10+Integer.parseInt(cap);t1.setText(String.valueOf(v));}}}10.Write a program to read a text and count all the occurrences of a given word. Also, display their positions.public class CountWords {public static void main(String[] args){ String text = "To be or not to be, that is the question;" + " Whether 'this nobler in the mind to suffer" + " the slings and arrows of outrageous fortune," + " or to take arms against a sea of troubles," + " and by opposing end them?";

int andCount = 0; int theCount = 0; int index = -1; String andStr = "and"; String theStr = "the";

// Search forwards for "and" index = text.indexOf(andStr);

if(index!=-1)System.out.println("and position : "+index);while(index >= 0)

Page 232: Java and data structure

Java and Data Structures 232IIBSC

{ ++andCount; index += andStr.length();

index = text.indexOf(andStr, index); if(index!=-1) System.out.println("and position : "+index);

} // Search backwards for "the"

index = text.lastIndexOf(theStr); // Find last 'the'if(index!=-1)System.out.println("the position : "+index);while(index >= 0) { ++theCount; index -= theStr.length(); index = text.lastIndexOf(theStr, index); if(index!=-1) System.out.println("the position : "+index);

}System.out.println("The text contains " + andCount + " ands\n"

+ "The text contains " + theCount + " thes"); }}11.Write an applet illustrating sequence of events in an applet.import java.awt.*;import java.applet.*;public class EventsSequence extends Applet{String msg;public void init(){setBackground(Color.blue);setForeground(Color.red);msg+= "Inside init()--";}public void start(){msg+= "Inside start()--";}public void stop()

Page 233: Java and data structure

Java and Data Structures 233IIBSC

{msg+= "Inside stop()--";}public void destroy(){msg+= "Inside destroy()--";}public void paint(Graphics g){msg+="Inside paint()";g.drawString(msg, 10,30);}}Adding Applet to HTML file<HTML><HEAD><TITLE> WELCOME TO JAVA APPLET </TITLE></HEAD><BODY><CENTER><H1> Welcome to the World of Applets</H1></CENTER><APPLET CODE=EventsSequence.class” WIDTH=400 HEIGHT=200></APPLET></CENTER></BODY></HTML>12.Illustrate the method of overriding in Java.class Super{int x;Super(int x){

this.x=x; }void display(){

System.out.println("Super x=" +x); }}

Page 234: Java and data structure

Java and Data Structures 234IIBSC

class Sub extends Super{int y;public Sub(int x, int y){

super(x);this.y=y;

}void display(){

System.out.println("Super x=" +x);System.out.println("Sub y=" +y);

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

Sub s1= new Sub(100,200);s1.display();

}}13.Write a program to fill elements into a list. Also, copy them in reverse order into other list.class ReverseList{public static void main(String args[]){int i,j;int[] list={1,22,4,55,22,7,8,9,1,4,12,6,5,10,11};int size=list.length;int reverselist[]=new int[size];for(i=list.length-1,j=0;i>=0;i--,j++)reverselist[j]=list[i];System.out.println("Availablelist:");for(j=0;j<list.length;j++)System.out.print(" "+list[j]);System.out.println("\n ReverseList:");for(j=0;j<reverselist.length;j++)System.out.print(" "+reverselist[j]);

Page 235: Java and data structure

Java and Data Structures 235IIBSC

}}14.Write an interactive program to accept name of person and validate it. If the name contains any numeric value throw an exception "Invalid Name".import java.lang.Exception;import java.lang.String;import java.io.*;class InvalidNameException extends Exception{InvalidNameException (String message){

super(message);}}class CheckName {public static void validName(String s){

try{

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

char ch=s.charAt(i);if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z')|| ch=='

'){ }elsethrow new InvalidNameException ("Inavalid Name...!

Please Check Your Name ");}

}catch(Exception e){

System.out.println(e);}

}}Class NameValidation {

Page 236: Java and data structure

Java and Data Structures 236IIBSC

public static void main(String[] args) throws Exception{

DataInputStream din=new DataInputStream(System.in);String name;System.out.print(" Enter Name : ");CheckName.validName(din.readLine());

}}15. Write an applet program to insert the text at the specified position.Import java.awt.*;Import java.applet.*;public class HelloJava extends Applet{public void paint(Graphics g){

g.drawString(“Hello Java”,10,100);}}Adding Applet to HTML file<HTML><HEAD><TITLE> WELCOME TO JAVA APPLET </TITLE></HEAD><BODY><CENTER><H1> Welcome to the World of Applets</H1></CENTER><APPLET CODE=HelloJava” WIDTH=200 HEIGHT=200></APPLET></CENTER></BODY></HTML>16.Prompt for the cost price and selling price of an article and display the profit (or) loss percentage.import java.io.*;public class percentage{public static void main(String args[])throws IOException{

Page 237: Java and data structure

Java and Data Structures 237IIBSC

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));double cp,sp;System.out.print("Enter cost price of an article:");cp=Double.parseDouble(br.readLine());System.out.print("Enter selling price of an article:");sp=Double.parseDouble(br.readLine());if(sp-cp>0){System.out.println("profit:"+(sp-cp));System.out.println("profit percentage:"+(((sp-cp)/cp)*100)+"%");}else if(sp-cp<0){System.out.println("loss:"+(cp-sp));System.out.println("loss percentage:"+(((cp-sp)/cp)*100)+"%");}else{System.out.println("No profit and No Loss");}}}

17.Create an anonymous array in Java.import java.io.*;import java.util.*;class Anonymous1{public static void printList(int a[]){

for(int i=0;i<a.length;i++)System.out.println(a[i]);

}public static void main(String args[]){ printList(new int[]{1,2,3,4,5,6,7,8,9,10});}}18.Create a font animation application that change the colors of text as and when prompted.

import java.awt.*;import java.awt.event.*;import java.applet.*;import java.lang.*;

Page 238: Java and data structure

Java and Data Structures 238IIBSC

import javax.swing.JPanel;

/*<applet code="TextFieldDemo" width=380 height=150></applet>*/public class F extends Applet implements ActionListener{final Font f = new Font("SansSerif", Font.BOLD, 18);TextField text;Color color=Color.black;public void init() {

Label textc = new Label("Color: ", Label.RIGHT);text = new TextField(12);add(textc);add(text);text.addActionListener(this);

}public void actionPerformed(ActionEvent ae) {

repaint();}public void paint(Graphics g){

g.setFont(f);g.setColor(color);switch(g.getText()){

case '1':color=Color.blue; break;

case '2':color=Color.red;}g.setColor(color);g.drawString("Font color " , 6, 60);

}}19.Write an interactive program to wish the user at different hours of the day.import java.util.*;

Page 239: Java and data structure

Java and Data Structures 239IIBSC

public class WishUser{public static void main(String[] args){ Calendar calendar = new GregorianCalendar(); String s; int hour = calendar.get(Calendar.HOUR); if(hour<=12) s = "Good Morning"; else if(hour<=15) s = "Good After Noon"; else if(hour<=18)

s="Good Evening"; else

s="Good Night"; System.out.println("Hello "+s);}}20.Simulate the library information system i.e. maintain the list of books and borrower's details. import java.io.*;class Library{public static void main(String as[]) throws Exception

{int i=0,x,m;String con="";int a[]=new int[10];String name[]=new String[10];String s[]={"Self Confidence ","My Experiments with truth","Java Apoorva book","Java Complete Reference"};InputStreamReader isr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(isr);do{System.out.println("Select Books from the list:\n");System.out.println(" 0.Programming in C");System.out.println(" 1. Programming with Java");System.out.println(" 2.Web Programming");System.out.println(" 3.Database Systems");System.out.println("\nSelect the book number:");

Page 240: Java and data structure

Java and Data Structures 240IIBSC

x=Integer.parseInt(br.readLine());if(x<1 || x>4) continue;a[i]=x;System.out.println("Enter your name:");name[i]=br.readLine();i++;System.out.println("Continue?(y,n):");con=br.readLine();}while(con.equals("y"));m=i; // number of borrowersSystem.out.println("==========================================");System.out.println("\nName \t Book borrowed");System.out.println("=========================================");for(i=0;i<m;i++)</m;i++){ System.out.println(name[i]+"\t"+s[a[i]]);} System.out.println("==========================================");} }Short Questions

1. What are web browsers?2. Define terms:3. i)Data abstraction ii)Polymorphism4. What is message communication.5. List few benefits of OOP.6. What is the task fi the main method in a java program?7. What are the command line arguments?8. Why do we need the import statement?9. Explain terinary operator with an example.10. Explain the if-else if ladder.11. Differenciate between break and continue.12. Write a program to illustrate enumerated types.13. Distinguish between a class and an object.14. List and compare access modifiers in java.15. How to give values to variables?16. When do we declare method of class abstract?17. When do we declare a method or class final?18. Explain processing of “hiding classes”.19. How are interfaces similar to classes?20. How does string class differ from string buffer class?21. What is static import ? How is it useful.22. What are symbolic constants?23. Write a program to explain vectors.24. What is a vecotor?How is it different from an array?25. List few java API packages.

Page 241: Java and data structure

Java and Data Structures 241IIBSC

26. List the benefits by organizing our classes into packages.27. Define interfaces.28. Explain thread synchronization.29. What are the two methods to stop threads?30. What is the purpose of ‘catch’ block?31. How many catch blocks can we use with one try block?32. List some common types of exceptions that might occur in

java.33. What is a finally block?Give examples.34. Write attributes of applet tag.35. Define various sections of a web page.36. Why do applet classes need to be declared as public?37. Differentiate between Queue and circular queue?38. What are the applications of stack?39. Define directed graph.40. Define minimum spanning tree.41. Define Binary Tree.42. Differentiate directed graph from undirected graph.43. Explain selection sort with an example.44. Explain insertion sort with an example.45. How do dequeue differ form circular queue?46.