Professional Documents
Culture Documents
BSIT - 42
Java Programming
Kuvempu University
In col l aborati on w i th
II
First Edition : May 2005 Second Edition : December 2010 Third Edition : May 2012
No Part of this Book may be reproduced in any form or by any means without the written permission from Universal Education Trust, Bangalore.
All Product names and company names mentioned herein are the property of their respective owners.
NOT FOR SALE For personal use of Kuvempu University IT - Programme Students only.
Corrections & Suggestions for Improvement of Study material are invited by Universal Education Trust, Bangalore. E-mail : info@uetb.org
Printed at :
III
JAVA PROGRAMMING
(BSIT - 42)
: Contributing Authors :
IV
BLANK PAGE
V
a
Preface
rogramming languages, paradigms and practices do not survive very long. Methods and technologies applied yesterday become out-of-date today. This rapid rate of change makes programming an exciting task.
Java is a fine example for the above statements. In a decade or so, it has grown from a concept into one of the most dominant computer language. Java has gone through many revisions. It has grown into a technology. It has many new and innovative features. Each innovation in language design has been driven by the need to solve a fundamental problem that the preceding languages could not solve. Java is no exception. When the history of computer languages is written, it will be said that B led to C, C evolved into C++ and C++ set the stage to Java. Java is a blend of best elements of its rich heritage combined with innovative concepts required by its unique environment. Java is inherited from C and C++. Java derives its syntax from C. Its object oriented features are influenced by C++. Development of Java technology has its roots in the process of refinement and adaptation that has been occurring in programming languages for the past three decades. Whenever a programming language is designed, trade offs like ease-of-use versus power, safety versus efficiency and rigidity versus extensibility are often made. C++ fitted the bill. However, the World Wide Web (WWW) and the Internet drove the language evolution forward and Java arrived. The Internet helped catapult Java to the forefront programming and Java had a profound effect on Internet. The reason is that Java expands the universe of objects that can move about freely in cyberspace. Java addresses serious problem of security and portability in Internet. Javas magic is the byte code, which makes it platform independent. All these features make it a compulsory subject in various courses of engineering. This Revised study material covers all aspects of Java programming language with large number of
VI
illustrative examples which will help the students to enhance their skills in programming. It begins with basics including such things as data types, control statements classes and arrays. In the latter part, we discuss Javas exception handling mechanism, packages, multithreading and interfaces. We are very much thankful to the authorities of Universal Education Trust, Bangalore for providing this opportunity to prepare the study material on Java.. Finally we thank the Principal and Management of J.N.N College of Engineering, Shimoga for providing the facilities. Suggestions regarding the improvement of this material are welcome. Dr. S.N Jagadeesha Ravindra. S B.J Sandesh
VII
a
Contents
Chapter 1 THE HISTORY OF JAVA 1.1 1.2 Introduction ..................................................................................... What is JAVA Technology ................................................................ 1.2.1 Primary Goals of Java Technology........................................ 1.3 Applets & Application ....................................................................... 1.4 The history of JAVA ......................................................................... 1.5 Basic Features in JAVA.................................................................... 1.6 How JAVA differ from C & C++...................................................... 1.7 JAVA & Internet.............................................................................. 1.8 Java Development Kit(JDK).............................................................. 1.9 Java Standard Library(JSL)............................................................... 1.10 How will JAVA Technology change my life ?...................................... 1.11 Summary.......................................................................................... 1 1 2 2 2 3 5 7 8 8 8 9 10
Chapter 2 FUNDAMENTALS OF OBJECT ORIENTED PROGRAMMING 2.1 2.2 2.3 2.4 2.5 2.5 Introduction....................................................................................... Programming Approaches................................................................. What is Object-Oriented Programming............................................... Advantages of OOP........................................................................... Applications ..................................................................................... Summary.......................................................................................... 11 11 12 15 18 19 19
VIII
Chapter 3 OVERVIEW OF JAVA LANGUAGE 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 Introduction...................................................................................... Simple JAVA Program....................................................................... JAVA Program Structure................................................................... Implementing a JAVA Program.......................................................... More of JAVA.................................................................................. JAVA virtual machine........................................................................ JAVA Tokens................................................................................... Summary.......................................................................................... 21 21 22 24 26 27 28 29 31
Chapter 4 CONSTANTS, VARIABLES AND DATA TYPES 4.1 4.2 4.3 4.4 4.5 4.6 4.7 Introduction...................................................................................... Constants......................................................................................... Data types........................................................................................ Variables.......................................................................................... Scope of Variables............................................................................ Type Casting.................................................................................... Summary.......................................................................................... 32 32 32 35 38 40 40 43
Chapter 5 OPERATORS AND EXPRESSIONS 5.1 5.2 Introduction...................................................................................... Arithmetic Operators......................................................................... 5.2.1. Integer Arithmetic............................................................... 5.2.2. Real Arithmetic................................................................... 5.2.3 Mixed-Mode Arithmetic................................................ 5.2.4 String Concatenation.................................................... 5.2.5 Multiplication and Division in Java................................. Assignment Operators...................................................................... Relational Operators......................................................................... Logical Operators............................................................................. Increment and Decrement Operator................................................... Conditional Operator.......................................................................... 45 45 46 46 47 48 49 49 50 51 54 55 57
IX
5.8 Bit-wise Operator............................................................................. 5.8.1 Shift and Logical Operators................................................. 5.8.2 Dot Operator...................................................................... 5.8.3 Type-Casting...................................................................... 5.8.4 Arithmetic Expressions....................................................... 5.8.5 Precedence of Arithmetic Operators.................................... 5.8.6 Operator Precedence and Associativity................................. 5.9 Mathematical Functions..................................................................... 5.10 Summary.......................................................................................... 58 58 61 61 61 61 63 64 68
Chapter 6 DECISION MAKING AND BRANCHING 6.1 6.2 Introduction...................................................................................... Decision Making With If Statement...................................................... 6.2.1 Simple IF Statement............................................................ 6.2.2 The IFELSE Statement.................................................... 6.2.3 Simple IF...ELSE Statements............................................... 6.2.4 The ELSE IF Ladder........................................................... Switch Statement ............................................................................. The ?: Operator in JAVA.................................................................... Summary.......................................................................................... 71 71 71 72 74 76 78 81 85 86
Chapter 7 LOOPING 7.1 7.2 7.3 7.4 Introduction...................................................................................... The While Loop................................................................................ Do Statement.................................................................................... For Statement................................................................................... 7.4.1. Additional Features of the for loop........................................ 7.4.2. Nested for loops.................................................................. Continue and Break Statements in JAVA............................................ Summary.......................................................................................... 88 88 89 90 92 96 97 100 103
7.5 7.6
X
8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 Introduction...................................................................................... Classes............................................................................................. 8.2.1 Variables and Methods........................................................ Adding Variables to Class.................................................................... Introduction to Objects........................................................................ Defining Methods .............................................................................. Inheritance: Extending Classes.......................................................... Advanced class Features .................................................................. Summary.......................................................................................... 105 105 106 109 116 122 127 132 137
Chapter 9 ARRAYS AND STRINGS 9.1 9.2 9.3 Introduction...................................................................................... One-dimensional array....................................................................... Creating an Array............................................................................... 9.3.1. Declaration of Array............................................................ 9.3.2 Initialization of Array............................................................ Primitive and reference data types...................................................... Two dimensional array........................................................................ Strings in Java................................................................................... 9.6.1. Constructors....................................................................... 9.6.2. String Methods................................................................... Summary.......................................................................................... 139 139 139 140 141 141 146 147 151 152 154 161
9.7
Chapter 10 MULTITHREADING 10.1 Introduction....................................................................................... 10.2 Thread Fundamentals......................................................................... 10.2.1. Advantages of Multithreading over Multitasking process........ 10.3 The Java Thread Model..................................................................... 10.3.1. Thread States: Life Cycle of a Thread.................................. 10.3.2. Context Switching............................................................... 10.4 Main thread....................................................................................... 10.5 Naming the threads........................................................................... 10.5.1 THE getName METHOD................................................... 10.5.2 THE setName METHOD................................................... 163 163 164 165 165 166 167 167 167 168 168
XI
10.6 Creating threads............................................................................... 10.6.1 Extending the Thread Class.................................................. 10.6.2 Implementing the Run() Method........................................... 10.6.3 Starting New Thread........................................................... 10.6.4 Implementing The Runnable Interface................................ 10.7 Synchronization................................................................................ 10.8 Messaging........................................................................................ 10.9 Summary.......................................................................................... 154 169 170 170 171 173 174 174
Chapter 11 PACKAGES & INTERFACES 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 Introduction...................................................................................... Creating Packages ........................................................................... Procedure to create our own package................................................ Accessing a Package........................................................................ Using a Package.............................................................................. Access Protection............................................................................. Adding a class to a Package.............................................................. Interfaces......................................................................................... Summary.......................................................................................... 175 175 176 176 177 177 178 179 180 184
Chapter 12 EXCEPTION HANDLING 12.1 12.2 12.3 12.4 12.5 Introduction...................................................................................... Exception ......................................................................................... Exception class hierarchy................................................................... Uncaught Exceptions......................................................................... Exception Methods............................................................................ 12.5.1 Throw................................................................................ 12.5.2 Catch ................................................................................ 12.5.3 Try..................................................................................... 12.5.4 Finally................................................................................. 12.5.5 Using Try In Exception Handling.......................................... 12.5.6 Using Catch In Exception Handling...................................... 12.5.7 Using Finally In Exception Handling...................................... 12.6 Summary.......................................................................................... 185 185 186 187 188 189 189 189 189 190 190 191 191 194
XII
Chapter 13 MANAGING INPUT /OUTPUT 13.1 13.2 13.3 13.4 13.5 13.6 13.7 Introduction....................................................................................... Concept of Streams........................................................................... Stream Classes................................................................................. Reading Characters........................................................................... Reading Strings................................................................................. Writing Console Output...................................................................... Summary.......................................................................................... References....................................................................................... 196 196 197 199 199 201 204 205 206
Chapter 1
Th e Hist o r y o f JAVA
OBJECTIVES
Define the Java technology Describe the processes java technology uses that make it cross-platform and how this makes it different from the other programming languages List two essential components of java technology List the software needed to write the java program List the reasons that make java technology Superior than programming languages
1.1 INTRODUCTION
Software industry is witnessing change. Change is the most critical aspect of software development and management. New tools and approaches are announced very frequently. Important issues addressed by software engineers are maintainability, reusability, portability security, and integrity and user friendliness. Java technology is yet another answer in this direction.
The Java programming language is designed to meet the challenges of application development in the context of heterogeneous, network-wide distributed environments. Paramount among these challenges is secure delivery of applications that consume the minimum of system resources, can run on any hardware and software platform, and can be extended dynamically. Java Technology is a Programming language, development environment, application environment, and deployment environment.The syntax of Java programming language is similar to C++ syntax. Java can be used to create all kinds of applications that can be created using any conventional programming language. Java is usually mentioned in the context of World Wide Web (WWW) browsers that are capable of running programs called applets. Applets are programs written in Java that reside on WWW servers. Applets are usually small in size to minimize download and are invoked by a HTML web page. Java applications are standalone programs that do not require a web browser to execute. As a deployment environment, Java technology provides the programmer with a large suite of tools - a compiler, an interpreter, a document generator, a class file packaging tool and so on.
Provides an easy to use language by avoiding pitfalls of other languages and enables users to create clear and streamlined code. Provides an interpreted environment for improved speed of development and code portability Provides a way for programs to run more than one thread of activity. Furnishes better security
An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applets code is transferred to your system and executed by the browsers Java Virtual Machine (JVM). Applications : An application is a program that runs on a single machine or over a network. In-fact, java can be used to develop programs for all kinds of applications. For example Hot Java itself is a java application program.
Applets are different form the applications and are not self-contained programs. They are like application fragments and are typically small programs. Applets find uses that includes displaying graphics, animated text, Loading URLs and doing calculations. Applets runs within a browser. Applets have built in feature for internet such as security. For example, they are Inspected for viruses.
Year 1991
Development
Stealth Project (as named by Scott McNealy) brainstorming meeting in Aspen with Bill Joy, Andy Bechtolsheim, Wayne Rosing, Mike Sheridan, James Gosling and Patrick Naughton.
Gosling starts working on the Oak interpreter, which, several years later
(following a trademark search), is renamed Java.
1993
The development team, now incorporated as First Person, focuses on interactive television after learning about Time Warners RFP for its interactive cable TV trial in Orlando, FL.
1994
NCSA Mosaic 1.0, the first graphical browser for the Internet, is released Liveoak project started. Designed by Bill Joy to use Oak for a big small operating system project. Jonathon Payne and Naughton start writing Web Runner, a Mosaic-like browser later renamed HotJava
V an Hoff implements Java compiler in Java. (Gosling had previously implemented it in C.)
1995
Sun formally announces Java and HotJava at SunWorld 95 Netscape announces its intention to license Java for use in Netscape browser. Sun and Netscape announce Javascript, a scripting language based on the Java language which is designed to be accessible to non-programmers. Java developed itself not only as a leader in internet programming but also as a general purpose object oriented programming language. Sun releases Java Development Kit 1.0 Sun releases Java Development Kit 1.1 Sun releases Java 2 version 1.2of Software Development Kit (SDK 1.2) Sun releases java 2 Platform standard edition(J2SE) and Enterprise edition(J2EE) Sun releases J2SE with SDK 1.3 Sun releases J2SE with SDK 1.4 Sun releases J2SE with JDK 5.0 (instead of JDK 1.5). Also known as J2SE 5.0 Sun releases J2SE 6.0 Dolphin project begins in august 2006 The current version is J2SE 6 update 22
expected to release in mid Java 8 in 2012 Future Java Java77is is expected to release in2011. mid 2011.Java 8 in 2012
Simple, Object-oriented Distributed interpreted Robust Secure Architecture neutral Portable Multi-threaded Dynamic
Simple
Most programmers working these days use C, and most programmers doing object-oriented programming use C++. Java is designed as closely to C++ as possible in order to make the system more comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ .
Object-Oriented
Like C++, Java is an object-oriented language. Object-oriented languages allow the programmer to organize a program, so that it closely models the real world in structure and in the interactions among its components.
Distributed
Java was built with the Internet and Web in mind. As do most other languages, Java includes pre-built components or libraries that provide important additional capabilities beyond the language itself. However, Javas standard libraries specifically include network-aware units that greatly facilitate writing Internet applications.
6
Interpreted
Javas executable files are composed of bytecodes that are instructions and data relating to a hypothetical computer called the Java virtual machine. Each machine that runs a Java program uses a small program, known as the Java run-time system, to execute the Java bytecodes in your program. This design is what makes it possible to run the same program on a Macintosh, a Sun, and a PC.
Robust
Java contains features that make the task of writing robust software easier. In Java programs, exceptions can be detected and handled according to instructions written by the programmer, often allowing software to keep working in the face of unexpected problems.
Secure
One of the potential errors of the Internet is the possibility of security breaches viruses that infect your computer, or hackers who take advantage of a software glitch to invade your personal cyberspace and make off with confidential information. Applets, which are Java programs automatically downloaded when a Web page is displayed, are subject to a number of limitations that are designed to reduce the chance that simply viewing someones page might result in harm to your system or data. No such system is absolutely reliable and none will ever be; but Java represents the state-of-the-art in reducing the chances of a disaster.
Architecture Neutral
Javas bytecodes are designed to be read and interpretedin exactly the same manneron any computer hardware or operating system that supports a Java run-time. No translation or conversion is necessary.
Portable
Java programs contain no implementation-dependent aspects, so the result of executing a series of Java bytecodes should always be the same no matter on what system they are executed. Moreover, the Java run-time system itself, though it is written in C, is written in a way that simplifies porting the Java runtime to a new computer system.
High Performance
A typical problem with interpreted languages is that they are somewhat less efficient than compiled languages. A program written by use of an interpreted language may run 20 to 100 times slower than the same program written by use of a compiled language.
Java aims at overcoming this problem through the use of a technique known as just-in-time compilation. A just-in-time compiler is an interpreter that remembers the machine code sequences it executes corresponding to the input bytecodes. Having figured out the proper machine code sequence once, it doesnt have to figure it out again if the same code is executed. Instead, it retrieves the memorized sequences and executes them straight away. Studies have suggested that just-in-time compilation may make interpretation of Java bytecodes almost as efficient as native execution of machine-language code. Developing multithreaded applications in C or C++ can be agony, because these languages lack standard support for operations necessary to create and control threads. Java includes support for multithreaded applications as part of its basic library.
Dynamic
Javas program units, classes, are loaded dynamically (when needed) by the Java run-time system. Loaded classes are then dynamically linked with existing classes to form an integrated unit. The lengthy link-and-load step required by third-generation programming languages is eliminated.
Java does not have a preprocessor, and as such, does not have macros like #define. Constants can be created by using the final modifier when declaring class and instance variables. Java does not have template classes as in C++. Java does not include Cs const keyword or the ability to pass by const reference explicitly. Java classes are singly inherited, with some multiple-inheritance features provided through interfaces. All functions must be methods. There are no functions that are not tied to classes. The goto keyword does not exist in Java (its a reserved word, but currently unimplemented). You can, however, use labeled breaks and continues to break out of and continue executing complex switch or loop constructs. Java does not use pointers Java doesnt contain the data types: struct, union, enum.
Internet users can use java to create applet programs and run them locally using a java enabled browsers such as hotjava. They can also use a java enabled browser to download an applet located on a computer anywhere in the internet and run it on their local computer. Internet users can also set up their websites containing java applets that could be used by other remote users of the Internet.
Web browsers
A web browser or Internet browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier (URI) and may be a web page, image, video, or other piece of content. Hyperlinks present in resources enable users to easily navigate their browsers to related resources. Although browsers are primarily intended to access the World Wide Web, they can also be used to access information provided by Web servers in private networks or files in file systems. Some browsers can also be used to save information resources to file systems. Web browsers are used to navigate through the information found on the net. Browsers allow us to retrieve the information from the internet and display it using the hypertext markup language(HTML). Hotjava, Netscape navigator and Internet explorer are some popular web browsers.
Applet viewer for viewing java applets. Enables us to run java applets Javac (javac compiler): translates java source code to byte code Java (java interpreter): runs applets and applications by reading and interpreting byte code Javap (java disassembler): converts byte code file into program description. Javah (for c header files):produces leader files for use with native network Javadoc(for creating html documents):creates html format documentation from java source file Jdb(java debugger)
interface(API). These classes and methods are grouped into several functional packages. Most commonly used packages are:
Language support packages :A collection of classes and methods required for implementing basic features of java. Utilities packages: A group of classes that provide utility functions such as date and time functions Input / Output package: collection of classes required for input/output manipulation. Networking package: Set of classes for communicating for other computers is a internet. Awt package: Collections of classes that implement platform independent GUI. Applet package: Collection of classes that allows to create java applets.
Get started quickly: Although the Java programming language is a powerful object-oriented language, its easy to learn, especially for programmers already familiar with C or C++. Write less code: Comparisons of program metrics (class counts, method counts, and so on) suggest that a program written in the Java programming language can be four times smaller than the same program written in C++. Write better code: The Java programming language encourages good coding practices, and automatic garbage collection helps you avoid memory leaks. Its object orientation, its JavaBeansTM component architecture, and its wide-ranging, easily extendible API let you reuse existing, tested code and introduce fewer bugs. Develop programs more quickly: The Java programming language is simpler than C++, and as such, your development time could be up to twice as fast when writing in it. Your programs will also require fewer lines of code. Avoid platform dependencies: You can keep your program portable by avoiding the use of libraries written in other languages. Write once, run anywhere: Because applications written in the Java programming language are compiled into machine-independent bytecodes, they run consistently on any Java platform. Distribute software more easily: With Java Web Start software, users will be able to launch your applications with a single click of the mouse. An automatic version check at startup ensures
10
that users are always up to date with the latest version of your software. If an update is available, the Java Web Start software will automatically update their installation.
1.11 SUMMARY
Java is a pure object oriented language introduced by sun Microsystems. In this chapter, we have introduced an overview of java history and its salient features. It has many characteristics that make it suitable for Internet programming. Fundamental differences between Java and c++ have also been discussed. Various tools and environment required for implementation of java programs have also been included.
EXERCISES
1. 2. 3. 4. 5. 6. 7. Why is Java known as platform-neutral language? How is Java more secured than other languages? What is multithreading? How does it improve the performance of JAVA? List at least seven major differences between C and Java. How is Java strongly associated with the Internet? What is Hypertext Markup Language? Describe its role in the implementation of Java applets. List out primary goals of Java Technology?
Chapter 2
OBJECTIVES
Identify various programming approaches Define object-oriented paradigm Discuss different features of OOP Lists the advantages and disadvantages of OOP
2.1 INTRODUCTION
Object-Oriented Programming (OOP) is a programming paradigm that uses objects data structures consisting of data fields and methods together with their interactions to design applications and computer programs. OOP is an approach to program organization and development which attempts to eliminate some of the pitfalls of conventional programming methods by incorporating the best of structured programming methods with several new concepts. It is a new way of organizing and developing and has nothing to do with any particular language. Programming techniques may include features such as encapsulation, data abstraction, modularity, polymorphism, and inheritance. Many modern programming languages now support OOP.
11
12
Before learning the oops concepts, we will see some of the features of programming approaches as mentioned below
Unstructured Programming
Usually, people start learning programming by writing small and simple programs consisting only of one main program. Here main program stands for a sequence of commands or statements, which modify data, which is global throughout the program. We can illustrate this as shown in Fig.2.1
Fig. 2.1: Unstructured programming. The main program directly operates on global data.
Procedural Programming
Procedural programming can sometimes be used as a synonym for imperative programming (specifying the steps the program must take to reach the desired state), With procedural programming you are able to combine returning sequences of statements into one single place. A procedure call is used to invoke the procedure. After the sequence is processed, flow of control proceeds right after the position where the call was made (Fig.2.2).
13
Fig. 2.2: Execution of procedures. After processing flow of controls proceed where the call was made.
With introducing parameters as well as procedures of procedures (sub procedures) programs can now be written more structured and error free. For example, if a procedure is correct, every time it is used it produces correct results. Consequently, in cases of errors you can narrow down your search to those places, which are not proven to be correct. Now a program can be viewed as a sequence of procedure calls. The main program is responsible to pass data to the individual calls, the data is processed by the procedures and, once the program has finished, the resulting data is presented. Thus, the flow of data can be illustrated as a hierarchical graph, a tree, as shown in Fig. 2.3 for a program with no sub procedures.
The main program coordinates calls to procedures and hands over appropriate data as parameters.
Modular Programming
Modular programming is a software design technique that increases the extent to which software is composed of separate, interchangeable components, called modules. Conceptually, modules represent a separation of concerns, and improve maintainability by enforcing logical boundaries between components. Modules are typically incorporated into the program through interfaces. A module interface expresses the
14
elements that are provided and required by the module. The elements defined in the interface are detectable by other modules. The implementation contains the working code that corresponds to the elements declared in the interface. A program therefore no longer consists of only one single part. It is now divided into several smaller parts which interact through procedure calls and which form the whole program (Fig.2.4).
The main program coordinates calls to procedures in separate modules and hands over appropriate data as parameters. Each module can have its own data. This allows each module to manage an internal state, which is modified by calls to procedures of this module. However, there is only one state per module and each module exists at most once in the whole program.
Object-Oriented Programming
In object oriented programming, a complex system is decomposed in accordance to the key abstractions of the problem. Rather than decomposing the problems into steps, we identify objects, which are delivered directly from the vocabulary of the problem domain. we view the world (problem domain) as a set of autonomous agents that collaborate to perform some higher level behavior. Each object in the solution embodies its own unique behavior and each one models some object in the real world. The object is simply a tangible entity that exhibits some well defined behavior. Objects do things we ask them to perform what they do by sending the messages. OOP paradigm helps us to organize the inherent complexities of software systems.
15
Definition
It is a method of implementation in which programs are organized as co-operative collection of objects, each of which represents an instance of some class and whose classes all members of a hierarchy of classes united in inheritance relationships.
16
A set of variables and functions used to describe an object is a class. A Class is a template for an object, a user-defined data type that contains variables, properties, and methods. A class defines the abstract characteristics of a thing (object), including its characteristics (its attributes, fields or properties) and the things it can do (behaviors) or methods, operations or features). A class is the blueprint from which individual objects are created. Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context. Also, the code for a class should be relatively self-contained (generally using encapsulation). Collectively, the properties and methods defined by a class are called members. A class defines the structure and behavior (data and code) that will be shared by a set of objects. Each object of a given class contains the structure and behavior defined by the class, as if it were stamped out of a mould in the shape of a class. A class is a logical construct, an object has physical reality. When you create a class, you will specify the code and data that will constitute that class. Collectively, these elements are called the members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods, which define the use of the membervariables. For example, you might have a Tree class that describes the features of all trees (has leaves and roots, grows, creates chlorophyll). The Tree class serves as an abstract model for the concept of a tree-to reach out and grab, or interact with, or cut down a tree you have to have a concrete instance of that tree. Of course, once you have a tree class, you can create lots of different instances of that tree, and each different tree instance can have different features (short, tall, bushy, drops leaves in Autumn), while still behaving like and being immediately recognizable as a tree.
17
An instance of a class is another word for an actual object. The instance is the actual object created at run-time. If class is the general representation of an object, an instance is its concrete representation. So what, precisely, is the difference between an instance and an object? Nothing, really. Object is the more general term, but both instances and objects are the concrete representation of a class. In fact, the terms instance and object are often used interchangeably in OOP language. An instance of a tree and a tree object are both the same thing.
Abstraction
Abstraction is simplifying complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem. Abstraction - the act or process of leaving out of consideration one or more qualities of a complex object so as to attend to others. Solving a problem with objects requires you to build the objects tailored to your solution. We choose to ignore its inessential details, dealing instead with the generalized and idealized model of the object.
Encapsulation
The ability to provide users with a well-defined interface to a set of functions in a way, which hides their internal workings. In object oriented programming, the technique of keeping together data structures and the methods (procedures) which act on them. The easiest way to think of encapsulation is to reference phones. There are many different types of phones, which consumers can purchase today. All of the phones used today will communicate with each other through a standard interface. A phone made by GE can be used to call a phone made by Panasonic for example. Although their internal implementation may be different their public interface is the same. This is the idea of encapsulation.
Information Hiding
It is a process of hiding all the secrets of an object that do not contribute to its essential characteristics. Typically, the structure of an object is hidden as well as the implementation of the methods.
Inheritance
Inheritance in object oriented programming means that a class of objects can inherit properties from another class of objects. When inheritance occurs, one class is then referred to as the parent class or superclass or base class. In turn, these serve as a pattern for a derived class or subclass. Inheritance is an important concept since it allows reuse of class definition without requiring major code changes. Inheritance can mean just reusing code, or can mean that you have used a whole class of object with all its variables and functions. Why not reuse an existing class that has behaviors similar to what you need in a new program?
18
For example, the bike is a part of the class two wheelers, which is again a part of class vehicle as shown in following Fig. 2.7
Polymorphism
It is a key concept in object-oriented programming. Poly means many...morph means change (or form). Many changes of form or changes of form by many. Polymorphism is simply a name given to an action that is performed by similar objects. Polymorphism allows a common data-gathering message to be sent to each class and allows each subclass object to respond to a message format in an appropriate manner to its own properties. Polymorphism encourages something we call extendibility. In other words, an object or a class can have its uses extended.
Message passing
In an object based world the only way for anything to happen is by objects communicating with each other and acting on the results. This communication is called message passing and involves one object sending a message to another and (possibly) receiving a result.
19
Reusability Elimination of redundant code and use of existing classes through inheritance. Thus provides economy of expression.
Easy mapping. Object in the problem domain can be directly mapped to the objects in the program.
Scalability. Can be easily upgraded from small programs to large programs. Object oriented systems are also resilient to change and evolves over time in a better way.
2.5 APPLICATIONS
OOP can be used for such diverse applications as Real-time systems, simulation and modeling, Artificial Intelligence and Expert systems parallel programming and Neural networks, Decision support systems, Office automation systems and others.
2.6 SUMMARY
In this chapter, various programming approaches followed since the computers were invented has been discussed. How OOP evolved as a powerful programming concept has been explained. The basic concepts of object oriented programming namely classes, objects, encapsulation, inheritance, and polymorphism have been introduced. Benefits and applications of OOP approach have been discussed briefly.
EXERCISES
1. 2. What is object-oriented programming? How is it different from the procedure-oriented programming? How are data and methods organized in an object-oriented program?
20
3. 4.
What are unique advantages of an object-oriented programming paradigm? Distinguish between the following terms: a) b) c) d) Objects and classes Data abstraction and data encapsulation Inheritance and polymorphism Dynamic binding and message passing
5. 6. 7.
Describe inheritance as applied to OOP. List a few areas of application of OOP technology. State whether the following statements are TRUE or FALSE. a) b) In conventional, procedure-oriented programming, all data are shared by all functions. The main emphasis of procedure-oriented programming is on algorithms rather than on data.
c) One of the striking feature of object-oriented programming is the division of programs into objects that represent real-world entities. d) e) f) g) h) i) j) Wrapping up of data of different types into a single unit is known as encapsulation. One problem with OOP is that once a class is created, it can never be changed. Inheritance means the ability to reuse the data values of one object by other objects. Polymorphism is extensively used in implementing inheritance. Object-oriented programs are executed much faster than conventional programs. Object-oriented systems can scale up better from small to large. Object-oriented approach cannot be used to create databases.
Chapter 3
OBJECTIVES
Define stand-alone applications and applets Write a simple java program Explain the java program structure Create, compile, run a java program Differentiate between a compiler and java virtual machine
3.1 INTRODUCTION
Java is a general-purpose, object-oriented programming language. We can develop two types of Java programs : * Stand-alone applications * Web applets They are implemented as shown in the Figure 3.1.
21
22
Stand-alone applications
Stand-alone applications are program written in JAVA to carry out certain tasks on a stand-alone local computer. Java program involves two steps : 1. Compiling source code into bytecode using javac compiler 2. Executing the bytecode program using java interpreter
Web applets
Applets are small Java programs developed for Internet applications. An applet located on a distant computer (Server) can be downloaded via Internet and executed on a local computer(Client) using a Java-capable browser.
Java Source
Java Interpreter
Output
Output
23
public class ExampleOne { public static void main (string [ ] args) { System.out.println(Welcome to the World of Java); } } It is worth spending time that you need to become comfortable with the frame work or this sample, the pieces will recur in all applications. First and the foremost, Java is case sensitive. If you made any mistake in capitalization (such as typing Main instead of main), the program will not run. Now lets look at the source code line by line. The keyword public is called an access modifier these modifiers control the level of access other parts of a program have to this code. Java is a true object-oriented language and therefore, The keyword class reminds you that everything in java program lives inside a class. Following the keyword class is the name of the class ExampleOne. In Java, the class definition begins with a call to the main ( ) method. Similar to a C or C++ environment, the execution of all Java applications begins with a call to the main ( ) method. An interpreter is guided by the main ( ) method in determining the position from which byte code should be interpreted. A program can contain various classes. However, only one of these needs, to contain the main ( ) method. In the main ( ) method, all the components that make up the main ( ) method are specified within a second set of braces. The entire body of the main ( ) method is contained within these braces. The main ( ) method body ends with the first brace, and the second brace ends the class definition.
Blocks of code
Java allows two or more logically inseparable statements to be grouped into blocks of code. A block of code is specified within the main ( ) method body and is contained within braces. A block of code can be referred to as a subset of the main ( ) method.
24
statement begins with System.out. This is a constant that represents the default output mode, which in this case is the screen. The constant helps to read and display the data in a Java program. The output is generated using the built-in println( ) method. The string that is assigned to the println( ) method is displayed when the statement is executed. In the example displayed on the screen, the output generated is the text
25
Suggested Optional Optional Optional Optional Essential
Documentation Section Package Statement Import Statements Interface Statements Class Definitions Main Method Class { Main Method Definition }
Documentation Section
The documentation section comprises a set of comment lines giving the name of the program , the author and other details. Java also uses comment /***/ known as documentation comment.
Package Statement
The first statement allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here belong to this package. Eg : package student;
Import Statement
The next thing after a package statement (but before any class definitions) may be a number of import statements. This is similar to the #include statement in C. Example : import student.test; This statement instructs the interpreter to load the test class contained in the package student.
Interface Statements
An interface is like a class but includes a group of method declarations. This is also an optional section and is used only when we wish to implement the multiple inheritance feature in the program.
Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential elements of a Java program.
26
We need to use the Java interpreter to run a stand-alone program. At the command prompt, type
Java filename
Now, the interpreter looks for the main method in the program and begins execution from there. When executed, our program displays the following:
Hello World!
27
28
Sample program with multiple classes
class Room { float length; float breadth; void getdata (float a, float b) { length = a; breadth = b; } }
class RoomArea { public static void main (String [ ] args) { float area; Room room1 = new Room (); // Creates an object room1 room1. getdata (14, 10); area = room1.length * room1.breadth; system.out.println(Area = +area); } } The above program defines two classes Room and RoomArea. The Room class defines two variables and one method to assign values to these variables. The class RoomArea contains the main method that initiates the execution.
29
The virtual machine code is not machine specific. This machine specific code (known as machine code) is generated by the Java interpreter by acting as an intermediary between the virtual machine and the real machine Interpreter is different for different machines.
Identifiers
Identifiers are used for naming classes, methods, variables, objects, labels, package and interfaces in a program. Java identifiers follow the following rules: 1. They can have alphabets, digits, and the underscore and dollar sign characters. 2. They must not begin with a digit 3. Uppercase and lowercase letters are distinct. 4. They can be of any length. Examples: Average, sum, Batch_strength
30
Keywords
Keywords are an essential part of a language definition. They implement specific features of the language. Java language has reserved 60 words as keywords. The following table lists the keywords. These keywords have specific meaning in Java; we cannot use them as names for variables, classes, methods. All keywords are to be written in lower case letters. Since Java is case-sensitive.
Java Keywords
boolean Case cast Const* continue Else extends Float For If implements Int interface Null** operator* Protected public Static super Threadsafe* throw Try var* * Reserved for future use
Abstract
break catch default false** future* import long outer* rest* switch throws void
byte char do final generic* inner* native package return synchronization transient volatile
byvalue* class double finally goto* instanceof new private short this true** while
Literals
Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are:
Integer literals Floating-point literals Character literals String literals Boolean literals
Operators
An operator is a symbol that takes one or more arguments and operates on them to produce a result.
31
3.8 SUMMARY
In this chapter, we have discussed a simple application program to familiarize the readers with basic java structure and syntax. The basics of java language and steps involved in creating and executing a java application program has also been presented.
EXERCISES
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Describe the structure of a typical Java program. What is the task of the main method in a Java program? What is a token? List the various types of tokens supported by Java. Why cant we use a keyword as a variable name? Enumerate the rules for creating identifiers in Java. What are the conventions followed in Java for naming identifiers? Give examples. Explain println statement in Java with an example? Why main method in Java is declared as static? What is Applet? Explain with a simple example how to create, compile and run a program in Java? Write a program in java to calculate the area of a circle. Write a program in java to calculate the perimeter of a rectangle.
Chapter 4
Co n st an t s, Var i ab le s An d Dat at y p e s
OBJECTIVES
Define java constants and variables Describe their representation inside computer Discuss data type conversion Discuss what is typecasting
4.1 INTRODUCTION
A programming language is developed to process certain kinds of data consisting of numbers, characters and strings and to provide useful output known as information. The task of processing data is accomplished by executing a sequence of instructions constituting a program. Constants in Java refer to fixed values that do not change during the execution of a program
4.2 CONSTANTS
Integer Constant
Integer constants may be decimal or hexadecimal. Decimal constants are written as ordinary integers
32
33
with no decimal point using the digits 0 through 9.. They can range in magnitude from negative to positive 231 - 1 (approximately two billion). Constants larger than these permissible magnitudes will produce unpredictable results. Leading plus or minus signs are permitted, as are leading zeros. Valid examples of decimal integer constants are 1 ,-45, 377849 ,-1999999999,0 ,12 , -45 , 078 , +99 An octal integer constant consists of any combination of digits from the set of 0 through 7 with a leading 0. Some examples are 037 ,0 0435,0551
Real Constants
Quantities are represented by numbers containing fractional parts like 17.548. Such numbers are called real (or floating point) constants. A real number may also be expressed in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. E2 means multiply by 102. The general form is:
Mantissa
exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer with an optional plus or minus sign. The letter e separating the mantissa and the exponent can be written in either lowercase or uppercase Further examples of real constants are 3.14159 ,-8.92E-45 ,0.0001724 ,8.95e294, 0.0 -12.0 3E4 4e+5 +12.3e-45
Character Constants
A character constant consists of a single character enclosed in single quotes. Control characters can be placed in character constants by a # character followed by an integer constant (decimal or hexadecimal) corresponding to the desired ASCII value.. Valid examples of character constants are a 1 ; #10 #$1A A character constant has the char type.
String Constants
A string constant consists of zero or more characters enclosed in double quotes, as in
34
ab Hello! A line...
If the string is two or more characters, it can be enclosed in single quotes instead of double quotes: ab is the same as ab If there is only one character in the string and you enclose it in single quotes, it will be taken as a character constant rather than a string constant. This causes no problems
Value bits: 0/1 6 0/1 5 0/1 4 0/1 3 0/1 2 0/1 1 0/1 0* Value in each bit Index of each bit
35
Value bits:
0/1 3
0/1 2
0/1 1
0/1 0*
Fig. 4.2 Determining Number of Possible Values, and Range of Values, for a Value
Primitive (Intrinsic)
Non-Primitive (Derived)
Numeric
Non-numeric
Classes
Arrays
Integer
Floating-point
Character
Boolean
Interface
36
Integer Types
Integer types can hold whole numbers such as 123,-96,and 5639. The size of the values that can be stored depends on the integer data type we choose. Java supports four types of integers. Byte, short, int, and long. Java does not support the concept of unsigned types and therefore all Java values are signed, meaning they can be positive or negative. The different integer types along with their range and length are given in Table.4.1.
Type Byte Short Int Long Length Range Inclusive -128 to 127 -32,768 to 32,767 -2,147,483,648 to 2,147,483,648 9,223,372,036854,775,808 to 9,223,372,036854,775,808
Table 4.1. Integer Types
Length
Range Inclusive
4 bytes 8 Byte
When you specify a literal value for a float, put a capital F(float) to the right of the value to explicitly state that it is a float, not a double. Literal values for floating point types are assumed to be doubles unless you specify otherwise, using the F.
Character Type
Another data type you need to store and manipulate is single-character information. The primitive type used for storing a single character is char. Most computer languages use the American Standard Code for Information Interchange (ASCII), an 8-bit character set that has an entry for every English character and punctuation mark, numbers and so on. The Java programming language uses a 16-bit character set called Unicode that can store all the necessary displayable characters from the vast majority of languages used in the modern world. Your programs can therefore be written so that they will work and display the correct language for countries. Unicode contains a subset of ASCII (the first 128 characters)
37
38 4.4 VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. * average * height * total_height * classStrength As mentioned earlier, variable names may consist of alphabets, digits, the underscore ( _ ) and dollar characters, subject to the following conditions: 1. They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Total is not same as total or TOTAL. 3. It should not be a keyword. 4. White space is not allowed. 5. Variable names can be of any length.
Declaration of variables
In Java, variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler. Declaration does three things: 1. It tells the compiler what the variable name is. 2. It specifies what type of data the variable will hold. 3. The place of declaration (in the program) decides the scope of the variable. A variable must be declared before it is used in the program. A variable can be used to store a value of any data type. That is, the name has nothing to do with the type. Java allows any properly formed variable to have any declared data type. The declaration statement defines the type of variable. The general form of declaration of a variable is :
39
Variables are separated by commas. A declaration statement must end with a semicolon. Some valid declaration are: int count; float x,y; double pi; byte b; char c1, c2, c3;
Assignment Statement
A simple method of giving value to a variable is through the assignment statement as follows:
VariableName = value;
For example initialValue = 0; finalvalue = 100; yes = x; we can also string assignment expressions as shown below: x = y = z = 0; It is also possible to assign a value to a variable at the time of its declaration. This takes the form:
40
The process of giving initial values to variables is known as the initialization. The ones that are not initialized are automatically set to zero. The following are valid Java statements:
float x, y, z; int m = 5, n = 10; int m, n = 10; // declares three float variables // declares and initializes two int variables // declares m and n initializes n
41
42
//Convert from boolean to char. c = (char)(t?1':0'); System.out.println (Value of c after conversion: + c); c = (char) (t? 1:0); System.out.println (Value of c after conversion in unicode: + c); //Convert from boolean to long. l = (long) (t? 1:0); System.out.println(Value of l after conversion : + l); //Convert from boolean to float. f = (float) (t? 1:0); System.out.println (Value of f after conversion: + f); //Convert from boolean to double. d = (double) (t? 1:0); System.out.println (Value of d after conversion: + d); //Convert from boolean to String. g = String.valueOf (t); System.out.println (Value of g after conversion: + g); g = (String) (t?1":0"); System.out.println (Value of g after conversion: + g); int sum = (int)(b + i + l + d + f); System.out.println (Value of sum after conversion: + sum); } } Output Values of all the variables like t = true b =2 s = 100 c =C i =200 l = 24000 f =3.14 d =5.3E-14 g = string
43
1 1 1 1 0 1 1.0 1.0 true 1 5
Value of Value of Value of Value of Value of Value of Value of Value of Value of Value of Value of
t b s c I l f d g g sum
after conversion : after conversion : after conversion : after conversion : after conversion in Unicode: after conversion : after conversion : after conversion : after conversion : after conversion : after conversion :
4.7 SUMMARY
Java constants and variables, and their representation inside the computer have been described in this chapter. Way and means of declaring and initializing java variables has also been presented. We have also discussed how data type conversions is achieved in java.
EXERCISES
1. 2. 3. 4. 5. 6. What is a Constant? What is a variable? List the eight basic data types used in Java. Give examples. What is scope of a variable. What is type casting? Why is it required in programming? Which of the following are invalid constants and why.
n1+n2 N$ Total-Marks
44
8. Find errors, if any, in the following declaration statements: int x; float length, height; double = p,q; character c1; final int total; final pi = 3.142; long int m; 9.
Write a program to determine the sum of the following harmonic series for a given value of n: 1+1/2 + 1/3+ ..+1/n The value of n should be given interactively through the keyboard.
10.
Write a program to convert the given temperature into Celsius using the following conversion formula F-32 C= And display the values in a tabular form. 1.8 Write a program to read the price of an item in decimal form (like 75.95) and print the output in paise (like 7595 paise)
11.
Chapter 5
Op er at o r s An d Exp r essio n s
OBJECTIVES
Use rich set of operator that java provides Write mathematical and logical expression in java Understand manipulation of data and variables Describe type conversions and order of precedence of operators Conclude that java types are of fixed size and machine independent
5.1 INTRODUCTION
Java supports a rich set of operations. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations they usually form a part of mathematical or logical operations. Java operators can be classified into number categories, namely: Arithmetic operators, relational operators, logical operators ,assignment operators ,Increment and decrement operators,conditional operators,bit wise operators,special operators
45
Java provides all the basic arithmetic operators. They are listed in the following table 5.1. The basic operators in Java are:
Operator + * / %
Explanation adds two numbers subtracts two numbers multiplies two numbers divides two numbers Modulo operator (rest of integer division)
There are five basic arithmetic operators in Java: addition (+), subtraction (-), multiplication (*), division (/) and modulus (%). All operators can be used with all primitive numeric types (char, byte, short, int, long, float and double). In addition any two numeric types can be combined (mixed mode arithmetic). Although the operators can be used with any numeric type, Java actually only does arithmetic with the types int, long, float and double. Therefore, the following rules are used to first convert both operands into one of these four types: 1. If either operand is a double then the other is converted to double. 2. if either operand is a float then the other is converted to float. 3. if either operand is a long then the other is converted to a long. 4. both are converted to int.
47
x / y, when x and y are integer types, gives the result division of x and y after truncating the divisor. This operation is called the integer division. For modulo division, the sign of the result is always the sign of the first operand (the dividend). That is - 20 % 3 = -2 - 20 % -3 = -2 20 % -3 = 2 (when the module division is defined as: x%y=x-(x/y)*y, where x/y is the integer division)
48
double fa=1+1; double fb=a*3; double fc=b/4; double fd=c-a; double fe= -d; System.out.println(fa = +fa); System.out.println(fb = +fb); System.out.println(fc= +fc); System.out.println(fd = +fd); System.out.println(fe= +fe); } }
Result
Integer Arithmetic a=2 b=6 c=1 d=-1 e=1 Floating point arithmetic fa=2.0 fb=6.0 fc=1.5 fd=-0.5 fe=0.5
49
50
Floats and doubles are multiplied and divided in exactly the same way. When faced with an inexact integer division, Java rounds the result down. For instance dividing 10 by 3 produces 3. Class modulus { public static void main(string args[ ]) { int x=42; double y=42.3; System.out.println(x mod 10 = + x%10); System.out.println(x mod 10= +y%10); } } Result: X mod 10 = 2 X mod 10 = 2.3
v op= exp;
Java also provides several short cut assignment operators that allow you to perform an arithmetic, logical, or bitwise operation and an assignment operation all with one operator. Suppose we wanted to add a number to a variable and assign the result back into the variable, like this: i = i + 2; You can shorten this statement using the short cut operator +=. i += 2; The two previous lines of code are equivalent. This table 5.2 lists the shortcut assignment operators and their lengthy equivalents:
51
Normal way Short way (example) X=X+1 X++ X=X1 X-X=X*2 X*=2 X=X/3 X/=3 X=X+5 X+=5 X=X-4 X-=4
Table 5.2 Shortcut assignment operators
Returns t r ue if op1 is greater than op2 op1 >= op2 op1 is greater than or equal to op2 Op1 < op2 op1 is less than op2 Op1 <= op2 op1 is less than or equal to op2 Op1 == op2 op1 and op2 are equal Op1 ! = op2 op1 and op2 are not equal
Table 5.3 Relational operators
52
A simple relational expression contains only one relational operator and is of the following form.
ae -1 relation al operator ae - 2
Ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or combination of them. Below table 5.4 shows some examples of simple relational expressions and their values.
Expression 15. 6 <= 20 9.5 < - 10 -20 >= 0 10 < 7 + 8 a+b == c+d Value TRUE FALSE FALSE TRUE TRUE
* Only if the sum of values of a and b is equal to the sum of values of c and d. The following program demonstrates the Relational Operators import java.io.*; class RelationalOperator { public static int val1; public static int val2; public static void main(int val1, int val2) { val1=val1; val2=val2; } public int Equal() { if(val1 == val2) { System.out.println(both are equal); } if(val1!=val2) { System.out.println(both are notequal); } if(val1<val2) {
53
System.out.println(Value1 is less then values2);
if(val1 > val2) { System.out.println(val1+ is greater then + val2); } return(0); } public static void main(String arg[ ]) { try { RelationalOperator relationalOperator = new RelationalOperator(); BufferedReader object = new BufferedReader(newInputStreamReader(System.in)); System.out.println(Enter the number1); relationalOperator.val1= Integer.parseInt(object.readLine()); System.out.println(Enter the number2); relationalOperator.val2= Integer.parseInt(object.readLine()); int equal=relationalOperator.Equal(); } catch(Exception e){} } } Output Case 1; Enter number 1: 12 Enter Number 2; 12 Both are equal Case 2: Enter number 1: 12
54
Enter Number 2; 4 Both are not equal 12 is greater than 4
Returns t r ue if op1 and op2 are both t r ue either op1 or op2 is t r ue op is f al se.
Following table 5.6 gives the false and true conditions for the && and || operations when applied on two operands op1 and op2.
Op-1 True True False False op-2 True False True False op-1 && op-2 True False False False op-1 || op-2 True True True False
&& is logical and. && combines two boolean values and returns a boolean which is true if and only if both of its operands are true. For instance
55
boolean b; b = 3 > 2 && 5 < 7; // b is true b = 2 > 3 && 5 < 7; // b is now false || is logical or. || combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true. For instance boolean b; b = 3 > 2 || 5 < 7; // b is true b = 2 > 3 || 5 < 7; // b is still true b = 2 > 3 || 5 > 7; // now b is false The last logic operator is ! which means not. It reverses the value of a boolean expression. Thus if b is true !b is false. If b is false !b is true. boolean b; b = !(3 > 2); // b is false b = !(2 > 3); // b is true These operators allow you to test multiple conditions more easily. For instance the previous example can now be written as if (x == 2 && y != 2) { System.out.println(Both conditions are true.);}
56
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statement as m = 5; y = m++; Then, the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. On the other hand, a postfix operator first assigns the value to the variable on left and then increments the operand. Table 5.7 illustrates the use of increment and decrement operators
Operator Purpose Pre-Increment ++ Post-Increment Pre-Decrement -Post-Decrement Syntax Example
j=++i int i=6 int j=++i; i is 7 ,j is 7 int i=6; int j=i++; i is 7,j is 6 int i=6; int j=--i; i is 5, j is 5 int i=6; int j=i--; i is 5, j is 6
j=i++
j=--i
j=i--
The following programs illustrates the working of increment and decrement operators class incdec { public static void main(string args[ ]) { int a = 3; int b = 4; int c; int d; c = ++b; d = a++; c++; system.out.println(a= +a); system.out.println(b= +b); system.out.println(c= +c); system.out.println(d= +d); } }
57
Result a b c d
=4 =5 =6 =3
Class incr01 { public static void main(String[ ] args) { int x = 5, X = 5, y = 5, Y = 5; system.out.println (x = + x ); system.out.println(X = + X ); system.out.println(x + X++ = + (x + X++) ); system.out.println(X = + X ); system.out.println(); system.out.println (y = + y); system.out.println (Y = + Y); system.out.println (y + ++Y = + (y + ++Y)); system.out.println (Y = + Y); } } The output from this Java application follows: x=5 X=5 x + X++ = 10 x=6 y=5 Y=5 y + ++Y = 11 Y=6
58
exp1 ? exp2 : exp3
Where exp1, exp2 and exp3 are expressions. The operator ?: works as follows: exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and becomes the value of the conditional expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the conditional expressions. Note that only one of the expressions (either exp2 or exp3) is evaluated. For example, consider the following statements : a = 20; b = 26; x = (a > b) ? a : b; In this example, x will be assigned the value of b. This can be achieved using the if.else statement as follows: if (a > b) x = a; else x = b;
5.8
BITWISE OPERATORS
Operator Use
>> << >>> op1 >> o p2 op1 << op2 op1 >>> op2
shift bits of op1 left by distance op2 shift bits of op1 right by distance
op2
(unsigned)
Table 5.7 Shift operators in java
59
Each shift operator shifts the bits of the left-hand operand over by the number of positions indicated by the right-hand operand. The shift occurs in the direction indicated by the operator itself. For example, the following statement shifts the bits of the integer 13 to the right by one position: 13 >> 1; The binary representation of the number 13 is 1101. The result of the shift operation is 1101 shifted to the right by one position110 or 6 in decimal. Note that the bit farthest to the right falls off the end into the bit bucket. The Java programming language also provides these four operators that perform logical functions on their operands:
Operator Use
& | ^ ~ op1 & op2 op1 | op2
The & operation performs the logical and function on each parallel pair of bits in each operand. The and function sets the resulting bit to 1 if both operands are 1, as shown in this following table:
op1 op2
0 0 1 1
0 1 0 1
Result 0 0 0 1
Suppose you were to and the values 12 and 13: 12 & 13 The result of this operation is 12. Why? Well, the binary representation of 12 is 1100, and the binary representation of 13 is 1101. The and function sets the resulting bit to 1 if both operand bits are 1, otherwise, the resulting bit is 0. So, if you line up the two operands and perform the and function, you can see that the two high-order bits (the two bits farthest to the left of each number) of each operand are 1. Thus the resulting bit in the result is also 1. The low-order bits evaluate to 0 because either one or both bits in the operands are 0: 1101 & 1100 1100
60
The | operator performs the inclusive or operation and ^ performs the exclusive or operation. Inclusive or means that if either of the two bits are 1 then the result is 1. The following table shows the results of your inclusive or operations:
op1 op2
0 0 1 1
0 1 0 1
Result 0 1 1 1
Exclusive or means that if the two operand bits are different the result is 1, otherwise the result is 0. The following table shows the results of your exclusive or operation.
op1 op2
0 0 1 1
0 1 0 1
Result 0 1 1 0
And finally, the complement operator inverts the value of each bit of the operand: if the operand bit is 1 the result is 0 and if the operand bit is 0 the result is 1. Once you have a boolean value, either stored in a variable representing a primitive boolean value (e.g. boolean done = false;) or as the result of an expression involving a relational operator (e.g. x < y) then you can combine these boolean values using the logical operators. Java provides four logical operators: and, (&) or, (|) exclusive or, (^) and not (!). The meaning of these operators is given by the following rules:
x & y is true if both x AND y are true and false otherwise. x | y is true if either x OR y (or both) is true and false otherwise. x ^ y is true if exactly one of x OR y is true and false otherwise. ! x is true is x is false and false otherwise.
For example if you wanted to check that a person in a database was an adult but not a senior citizen you could check if their age was greater than or equal to 18 and their age was less than or equal to 65.
61
5.8.3 Type-Casting
Casting means assigning a value of one type to a variable of another type If the two types are compatible, the java technology performs the conversation Automatically. For example, an int value can always be assigned to a long Variable. Where information would be lost in an assignment ,the compiler requires that you confirm the assignment with a typecast. This can be done ,for example , bysqueezing a long value into an int variable. Explicit casting is done like this: Long bigvalue= 99L Int small= (int) (bigvalue); The desired target type is placed in parentheses and used as a prefix to the expression that must be modified.
Algebraic Expression a b-c (m+n)(x+y) Ab/c 3x2 +2x+1 X /+cy Java Expression a*b-c (m+n)*(x+y) a*b/c 3*x*x+2*x+1 x/y+c
62
High priority Low priority * / % + -
The basic evaluation procedure includes two left-to-right passes through the expressions. During the first pass, the high priority operators (if any) are applied as they are encountered. During the second pass, the low priority operators (if any) are applied as they are encountered. Consider the following evaluation statement: x = a-b/3+c*2-1 When a=9, b=12 and c=3, the statement becomes x = 9-12/3+3*2-1 and is evaluated as follows:
First pass
Step1 : x = 9-4+3*2-1 Step2: x = 9-4+6-1 (12/3 evaluated) (3*2 evaluated)
Second pass
Step3 : x = 5+6-1 Step4: x = 11-1 Step5: x = 10 (9-4 evaluated) (5+6 evaluated) (11-1 evaluated)
However, the order of evaluation can be changed by introducing parenthesis into an expression. Consider the same expression with parenthesis as shown below: 9-12/ (3+3) * (2-1) Whenever the parenthesis are used, the expressions within parenthesis assume highest priority. If two or more sets of parenthesis appear one after another as shown above, the expression contained in the leftmost set is evaluated first and the right-most in the last. Given below are the new steps.
First pass
Step1 : Step2: 9-12/6*(2-1) 9-12/6*1
Second pass
Step3 : Step4: 9-2*1 9-2
Third pass
Step5: 7
63
Right to left
Left to right
4 5
Left to right
Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left
7 8 9 10 11 12 13 14
Mathematical functions such as cos, sqrt, log, etc, are frequently used in analysis of real-life problems. Java supports these basic math functions through Math class defined in the the java.lang package. The following table lists the math functions defined in the Math class. These functions should be used as follows: Math.function_name( ) Example double y = Math. Sqrt(x);
Mathematical Functions
Functions Sin (x) Cos (x) Tan (x) Asin (y) Acos (y) Atan(y) Atan2(x,y) pow(x,y) exp(x) log(x) sqrt(x) ceil(x) floor(x) rint(x) abs(x) max(a,b) min(a,b) Action Returns the sine of the angle x in radians Returns the cosine of the angle x in radians Returns the cosine of the angle x in radians Returns the angle whose sine is y Returns the angle whose cosine is y Returns the angle whose tangent is y Returns the angle whose tangent isx/y
Returns x raised to y (x ) x Returns e raised to x (e )
y
Returns the natural logarithm of x Returns the square root of x R etur ns th e sm al lest w h o le n um b er g reater than or equal to x. (Rounding up) R etu r ns th e l arg est w h o le n um ber g r eater than or equal to x. (Rounding down) Returns the truncated value of x. Returns the absolute value of x. Returns the maximum of a and b. Returns the minimum of a and b.
Note : x and y are double type parameters. And b may be ints, longs, floats and doubles. An example program that exercises most of the routines in java.lang.Math. public class MathLibraryExample { public static void main(String[] args) { int i = 7; int j = -9; double x = 72.3;
65
double y = 0.34; System.out.println(i is + i); System.out.println(j is + j); System.out.println(x is + x); System.out.println(y is + y); // The absolute value of a number is equal to the number if the number is positive //or zero and equal to the negative of the number if the number is negative. System.out.println(| + i + | is + Math.abs(i)); System.out.println(| + j + | is + Math.abs(j)); System.out.println(| + x + | is + Math.abs(x)); System.out.println(| + y + | is + Math.abs(y)); // Truncating and Rounding functions. You can round off a floating point number // to the nearest integer with round() System.out.println(x + is approximately + Math.round(x)); System.out.println(y + is approximately + Math.round(y)); // The ceiling of a number is the smallest integer greater than or equal to the //number. Every integer is its own ceiling. System.out.println(The ceiling of + i + is + Math.ceil(i)); System.out.println(The ceiling of + j + is + Math.ceil(j)); System.out.println(The ceiling of + x + is + Math.ceil(x)); System.out.println(The ceiling of + y + is + Math.ceil(y)); // The floor of a number is the largest integer less than or equal to the number. // Every integer is its own floor. System.out.println(The floor of + i + is + Math.floor(i)); System.out.println(The floor of + j + is + Math.floor(j)); System.out.println(The floor of + x + is + Math.floor(x)); System.out.println(The floor of + y + is + Math.floor(y)); // Comparison operators min() returns the smaller of the two arguments you pass it System.out.println(min( + i + , + j + ) is + Math.min(i,j)); System.out.println(min( + x + , + y + ) is + Math.min(x,y)); System.out.println(min( + i + , + x + ) is + Math.min(i,x)); System.out.println(min( + y + , + j + ) is + Math.min(y,j));
66
// Theres a corresponding max() method that returns the larger of two numbers System.out.println(max( + i + , + j + ) is + Math.max(i,j)); System.out.println(max( + x + , + y + ) is + Math.max(x,y)); System.out.println(max( + i + , + x + ) is + Math.max(i,x)); System.out.println(max( + y + , + j + ) is + Math.max(y,j)); // The Math library defines a couple of useful constants: System.out.println(Pi is + Math.PI); System.out.println(e is + Math.E); // Trigonometric methodsAll arguments are given in radians // Convert a 45 degree angle to radians double angle = 45.0 * 2.0 * Math.PI/360.0; System.out.println(cos( + angle + ) is + Math.cos(angle)); System.out.println(sin( + angle + ) is + Math.sin(angle)); // Inverse Trigonometric methods All values are returned as radians double value = 0.707; System.out.println(acos( + value + ) is + Math.acos(value)); System.out.println(asin( + value + ) is + Math.asin(value)); System.out.println(atan( + value + ) is + Math.atan(value)); // Exponential and Logarithmic Methods. exp (a) returns e (2.71828...) raised // to the power of a. System.out.println(exp(1.0) is + Math.exp(1.0)); System.out.println(exp(10.0) is + Math.exp(10.0)); System.out.println(exp(0.0) is + Math.exp(0.0)); // log(a) returns the natural logarithm (base e) of a. System.out.println(log(1.0) is + Math.log(1.0)); System.out.println(log(10.0) is + Math.log(10.0)); System.out.println(log(Math.E) is + Math.log(Math.E)); // pow(x, y) returns the x raised to the yth power. System.out.println(pow(2.0, 2.0) is + Math.pow(2.0,2.0)); System.out.println(pow(10.0, 3.5) is + Math.pow(10.0,3.5)); System.out.println(pow(8, -1) is + Math.pow(8,-1));
67
// sqrt(x) returns the square root of x. for (i=0; i < 10; i++) { System.out.println (The square root of + i + is + Math.sqrt(i)); } // Finally theres one Random method that returns a pseudo-random number // between 0.0 and 1.0; System.out.println(Heres one random number: + Math.random()); System.out.println(Heres another random number: + Math.random()); } } Output i is 7 j is -9 x is 72.3 y is 0.34 |7| is 7 |-9| is 9 |72.3| is 72.3 |0.34| is 0.34 72.3 is approximately 72 0.34 is approximately 0 The ceiling of 7 is 7 The ceiling of -9 is -9 The ceiling of 72.3 is 73 The ceiling of 0.34 is 1 The floor of 7 is 7 The floor of -9 is -9 The floor of 72.3 is 72 The floor of 0.34 is 0 min(7,-9) is -9 min(72.3,0.34) is 0.34 min(7,72.3) is 7 min(0.34,-9) is -9 max(7,-9) is 7 max(72.3,0.34) is 72.3
68
max(7,72.3) is 72.3 max(0.34,-9) is 0.34 Pi is 3.14159 e is 2.71828 cos(0.785398) is 0.707107 sin(0.785398) is 0.707107 acos(0.707) is 0.785549 asin(0.707) is 0.785247 atan(0.707) is 0.615409 exp(1.0) is 2.71828 exp(10.0) is 22026.5 exp(0.0) is 1 log(1.0) is 0 log(10.0) is 2.30259 log(Math.E) is 1 pow(2.0, 2.0) is 4 pow(10.0, 3.5) is 3162.28 pow(8, -1) is 0.125 The square root of 0 is 0 The square root of 1 is 1 The square root of 2 is 1.41421 The square root of 3 is 1.73205 The square root of 4 is 2 The square root of 5 is 2.23607 The square root of 6 is 2.44949 The square root of 7 is 2.64575 The square root of 8 is 2.82843 The square root of 9 is 3 Heres one random number: 0.820582 Heres another random number: 0.866157
5.10 SUMMARY
In this chapter, we have discussed all the operators in java and their usage in expressions. We have highlighted the type conversions and order of precedence While evaluating expressions simple programs are presented to demonstrate use of different type expressions operators It should be noted that all java types are of fixed size and are machine independent.
69
EXERCISES
1. Which of the following arithmetic expressions are valid?
a) 25/3 % 2 b) +9/4 + 5 c) 7.5 % 3 d) 14 % 3 + 7 % 2 e) 14 % 3 f) 15.25 + -5.0 g) (5/3) * 3 + 5 % 3 h) 21 % (int) 4.5
Identify unnecessary parenthesis in the following arithmetic expressions. a) b) c) d) (x-(y/5)+z) % 8) + 25 ((x-y) * p) + q (m*n) + (-x/y) x/(3*y)
Find errors, if any, in the following assignment statements and rectify them. e) f) g) h) e) f) x = y = z = 0.5, 2.0 5.75; m = ++a * 5; y = sqrt(100); p * x/y; s = /5; a = b++ -c * 2
Determine the value of each of the following logical expressions if a=5, b=10 and c=-6 a) b) c) d) e) a>b && a<c a<b && a>c a==c || b>a b>15 && c<0 || a>0 (a/2.0 == 0.0 && b/2.0 != 0.0) || c< 0.0
The straight-line method of computing the early depreciation of the value of an item is given by Purchase price Salvage value Depreciation = Years of service Write a program to determine the salvage value of an item when the purchase price, years of service, and the annual depreciation are given.
The total distance traveled by a vehicle in t seconds is given by Distance = ut + (at 2)/2 Where u is the initial velocity (metres per second), a is the acceleration (metres per second). Write a
70
program to evaluate the distance traveled at regular intervals of time, given the values of u and a. The program should provide the flexibility to the user to select his own time intervals and repeat the calculations for different values of u and a. In inventory management, the Economic Order Quality for a single item is given by
Write a program to compute EOQ and TBO, given demand rate (items per unit time), setup costs (per order), and the holding cost(per item per unit time).
Chapter 6
fter going through this chapter, you will be able to understand the
6.1 INTRODUCTION
Java language possesses decision making capabilities and supports the following statements known as control or decision-making statements.
71
72
if (test expression) { statement block; }
It allows the computer to evaluate the expression first and then , depending on whether the value of the expression (relation or condition) is true (non-zero) or false (zero), it transfers the control to a particular statement. This point of program has two paths to follow , one for the true condition and the other for the false condition. The if statement may be implemented in different forms depending on the complexity of the conditions to be tested.
73
The following program using simple if statement finds the greatest of two numbers. Example : // Program to find the greatest of two numbers public class Greater { public static void main(String [ ] args) { int x=10,y=20; if (x > y) { System.out.println(x + is greater than + y); } if(y>x) { System.out.println(y + is greater than + x); } System.out.println(); } }
74
The example used for simple if statements is rewritten in the following using the if else statement //program to find the greatest of two numbers
75
public class Greater { public static void main(String [ ] args) { int x=10,y=20; if (x > y) { System.out.println(x + is greater than + y); } else { System.out.println(y + is greater than + x); } System.out.println( ); } In the following we write a simple program to find whether the given number is odd or even public class OddOrEven{ public static void main(String [ ] args) { int number = 25; /* determine whether the number is odd or even and print a message to the screen. */ System.out.println(); if (number % 2 == 0) { System.out.println(number + is even.); } else { System.out.println(number + is odd.); } System.out.println(); } }
76
If the condition-1 is false statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x.
Example: To find the greatest of two numbers public class Greater { public static void main(String [ ] args) { int x,y; x = 10; y = 10; /* determine which number is the greater of the two and display the greater number on the screen.*/ System.out.println( ); if (x > y) { System.out.println(x + " is greater than " + y); }
77
else if (x == y) { System.out.println("The two numbers are equal."); } else { System.out.println(y + " is greater than " + x); } System.out.println(); } }
Point to Note
This program uses an if - else if - else construct. The if part is evaluated first. If the boolean expression evaluates to true, the statements between the first set of brackets are executed. If the if part evaluates to false, the boolean expression in the else if part is evaluated. If this is true, the statements between the second set of brackets are executed. If the else if part evaluates to false, the statements between the third set of brackets (the else part) are executed. In the following, we demonstrate if the year is leap year or not public class DetermineLeapYearExample { public static void main(String[ ] args) { //year we want to check int year = 2004; //if year is divisible by 4, it is a leap year if (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)) System.out.println(Year + year + is a leap year); els e System.out.println(Year + year + is not a leap year); } } Output of the example would be Year 2004 is a leap year
There is another way of putting ifs together when multi path decisions are involved. A multi path decision is a chain of ifs in which the statement associated with each else is an if. It takes the following general form:(Fig. 6.4)
This construct is known as the else if ladder. The conditions are evaluated from the top (of the ladder), downwards. As soon as a true condition is found, the statement associated with is executed and the control is transferred to the statement x (skipping the rest of the ladder). When all the n conditions become false, then the final else containing the default statement will be executed. The flowchart is given in Fig. 6.5
79
Example : Let us consider an example of grading the students in an academic institution. The grading is done according to the following rules: Average marks Grade 80-100 Honours 60- 79 First Division 50- 59 Second Division 40- 49 Third Division 0- 39 Fail This grading can be done using the else if ladder follows: if (marks > 79)
80
grade = Honours; else if (marks >59) grade = First Division; else if (marks > 49) grade = Second Division; else if(marks > 39) grade = Third division; else grade = Fail;
Java program
Class grade( ) { public static void main(String[ ] args) { int testscore = 76; char grade; if (testscore >= 79) { grade = Honours; } else if (testscore >= 59) { grade = First division; } else if (testscore >= 49) { grade = second division; } else if (testscore >= 39) { grade = Third division; } else { grade = Fail; } System.out.println(Grade = + grade); } }
81
The output from this program is: Grade = First division You may have noticed that the value of testscore can satisfy more than one of the expressions in the compound if statement: 76 >= 59 and 76 >= 60. However, as the runtime system processes a compound if statement such as this one, once a condition is satisfied, the appropriate statements are executed (grade = First division;), and control passes out of the if statement without evaluating the remaining conditions.
A switch statement has the form: switch (expression) { case 1: statements-1 break; case 2: statements-2 break; . . // (more cases) . case N: statements-N break; default: // optional default case } // end of switch statement The statements are technically optional. The effect of a
is to make
82
The break statements are technically optional. The effect of a break is to make the computer jump to the end of the switch statement. If you leave out the break statement, the computer will just forge ahead after completing one case and will execute the statements associated with the next case label. This is rarely what you want, but it is legal. However, that inside a subroutine, the break statement is sometimes replaced by a return statement. In a nutshell, - switch statement is convenient for handling multiple if-else cases - need to use single value as decision variable - need to identify code to be executed for each case - essential to end each case with break command can use default for all cases not specifically labeled. The case statement is diagrammatically shown in Fig. 6.6
The following example illustrates how case statements are executed if break is not used to terminate the execution of the statements.
83
public class FreeFlowingSwitchExample { public static void main(String[] args) { int i=0; switch(i) { case 0: System.out.println(i is 0); case 1: System.out.println(i is 1); case 2: System.out.println(i is 2); default: System.out.println(Free flowing switch example!); } } } Output would be i is 0 i is 1 i is 2 Free flowing switch example! public class FreeFlowingSwitchExample { public static void main(String[] args) { int i=0; switch(i) { case 0: System.out.println(i is 0); case 1: System.out.println(i is 1); case 2: System.out.println(i is 2); default: System.out.println(Free flowing switch example!);
84
} } } Output would be i is 0 i is 1 i is 2 Free flowing switch example!
The switch statement evaluates its expression, in this case the value of month, and executes the appropriate case statement. Thus, the output of the program is: August. Of course, you could implement this by using an if statement: Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use, based on readability and other factors. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer value. Also, the value provided to each case statement must be unique. Another point of interest in the switch statement is the break statement after each case. Each break statement terminates the enclosing switch statement, and the flow of control continues with the first statement following the switch block. The break statements are necessary because without them, the case statements fall through. That is, without an explicit break, control will flow sequentially through subsequent case statements.
85
case 1: System.out.println(i is 0, j is 1); break ; default: System.out.println(nested default case!!);
86 6.5 SUMMARY
In this chapter, we discussed the features of the following selection statements. Available in java: If statement, switch,conditional operator. Several applications of these statements have been presented. We also discussed how these can be used to solve problems. These concepts are useful in developing complex systems. Control execution is an important tool.
EXERCISES
1. Determine whether the following are true or false; a) b) c) d) e) 2. 3. When if statements are nested, the last else gets associated with the nearest if without an else. One if can have more than one else clause. A switch statement can always be replaced by a series of if.else statements A switch expression can be of any type. A program stops its execution when a break statement is encountered.
In what ways does a switch statement differ from an if statement? Find errors, if any, in each of the following segments; a) b) if (x+y = z && y > 0) if (code>1); a = b+c else a= 0 c) if (p < 0) || (q < 0)
4.
Rewrite each of the following without using compound relations: a) if (grade < = 59 && grade >=50) second = second + 1 b) if (number > 100 && number < 0) System.out.print(Out of range); Else
87
Sum = sum + number; c) if ((M1>60 && M2>60 || T >200) y=1; else y=0; 5. Write a program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7. 6. Given a list of marks ranging from 0 to 100, write a program to compute and print the number of students who have obtained marks a) b) c) d) in the range 81 to 100, in the range 61 to 80, in the range 41 to 60, and in the range 0 to 40.
The program should use a minimum number of if statements. 8. A cloth showroom has announced the following seasonal discounts on purchase of items:
Chapter 7
LOOPING
OBJECTIVES
fter going through this chapter, you will be able to write simple programs using the following loop constructs
7.1 INTRODUCTION
In looping, a sequence of statements are executed until some condition for the termination of the loop is satisfied. A program loop therefore consists of two segments , first the body of the loop and other is control Statement. The control statements test certain conditions and then makes the repeated execution of the statements contained in the block. There are two types of loops. They are pre-test loop and post-test loop. In pre-test loop the control variable is tested prior to the start of each iteration whereas in post-test loops the control variable is tested at the end of each iteration (Fig. 7.1.). From an efficiency point of view, the advantage is that ,we can reduce the number of tests required provided that we know that the loop must be exercised at least once. If there is a possibility that the loop should not be exercised at all then a post-test loop will not be appropriate (a pre-test loop will be required instead).
88
Chapter 7 - Looping
89
90
Chapter 7 - Looping
All the variables used in the condition of the while statement must be initialized before the while loop. The values of the variables used in the condition must be changed in the loop body. Otherwise, the condition may always remain true and the loop may never terminate. You change the values of the variables by performing arithmetic operations on the variables. You can write a single statement or multiple statements in the loop body. Multiple statements should be enclosed within braces. Otherwise, the code may generate an unexpected output. Before the loop body is executed, the condition of the while statement is evaluated. Only when the condition evaluates to true is the loop body executed. Therefore, the while loop is also called the top tested loop. After the loop body is executed, the condition is evaluated again. The sequence of evaluating the condition and executing the loop body continues until the condition becomes false.
Example: class numbers { public static void main(String args[ ]) { int n=0; int num=5; while(n<=num) { sysytem.out.printfln(n); n++; } } }
7.3 DO STATEMENT
Similar to the while statement, the do-while statement is a loop statement provided by Java. The statement helps to perform certain repetitive actions depending on a condition. The major difference between the do-while statement and the while statement is that in the while statement, the loop body is executed only when the condition stated in the statement is true. In contrast, in the do-while loop, the loop body is executed at least once, regardless of the condition evaluating to true or false. After the loop body is executed once, the condition in the do-while statement is checked. If the condition evaluates to true, the loop body is executed repeatedly until the condition becomes false. Therefore, the do-while loop is also called the bottom tested loop.
91
You can use the do-while loop in situations where an action must be performed at least once without evaluating the condition. Syntax and flowchart of the do while statement is shown in Fig. 7.3
Example 1: Ex://program to print the numbers form 1 to 5 Class numbers { public static void main(String [ ] args) { int n=0; int num=5; do { sysytem.out.printfln(n); n++; } while(n<=5); } }
92
Example 2: // Program to print the Fibonacci numbers from 1 to 50 Class Fibonacci { public static void main( string [ ] args) { int loopCounter =0; int fib1=0 int fib2=1; int tempTerm; do { if (loopCounter == 0) System.out.print(fib1 + ); else { if (loopCounter == 1) System.out.print(fib2 + ); else { tempTerm = fib1 + fib2; fib1 = fib2; fib2 = tempTerm; System.out.print(fib2 + ); } } loopCounter ++; } while (loopCounter <= 50); system.out.println(); } }
Chapter 7 - Looping
93
specified condition becomes false. The syntax of the for statement is for (initialization expression; test condition; update expressions) { statement1; statement2; } The for statement starts with the for keyword. This statement has three elements enclosed within parentheses. The first element of the for statement is initialization expressions. The initialization expressions element is an assignment statement. The assignment is done only once before the for statement begins execution. The second element, test condition, is evaluated before each iteration of the for statement. This element determines whether the execution of the for loop should continue or terminate. Update expressions is the third element in the for statement. This element changes the values of the variables used in the test condition. Update expressions are executed at the end of each iteration after the loop body is executed. The elements of a for statement are separated by semicolons. Example: //the program display a number form 2 to 10 class displaynumber { public static void main(stsring args[ ]) { for ( j = 2; j <= 10; j++ ) system.print(output, i = %d, j); } }
94
Chapter 7 - Looping
In the for loop(Fig. 7.4.), first variable j is initialized to 2. Next, the value of j is compared with 10. If the test condition is true, the value of j is displayed on the screen. Next, the value of j is incremented by one. After the value of j is incremented, the test condition is evaluated again. If the test condition evaluates to true, the print function is executed again. If the test condition evaluates to false, the flow of control comes out of the for loop. Example 2: // The program displays even numbers between 2 and 10 Class EvenNum { public static void main (string [ ] args) { int j, k; for (j =2, k= 0; j<=10; j++) { k = j /2; if (k = =0) system.out.println(j); } } } Similarities between for and while loops are illustrated in Fig. 7.5
Fig. 7.5 Flow charts showing similarities between for and while statements
95
This Java example shows how to input the number from console and check if the number is a palindrome number or not. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class InputPalindromeNumberExample { public static void main(String[] args) { System.out.println(Enter the number to check..); int number = 0; try { //take input from console BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//parse the line into int number = Integer.parseInt(br.readLine()); } catch(NumberFormatException ne) { System.out.println(Invalid input: + ne); System.exit(0); } catch(IOException ioe) { System.out.println(I/O Error: + ioe); System.exit(0); } System.out.println(Number is + number); int n = number; int reversedNumber = 0; int temp=0;
96
//reverse the number while(n > 0){ temp = n % 10; n = n / 10; reversedNumber = reversedNumber * 10 + temp; if(number == reversedNumber) System.out.println(number + is a palindrome number); e lse System.out.println(number + is not a palindrome number); } Output is Enter the number to check.. 121 Number is 121 121 is a palindrome number
Chapter 7 - Looping
The for loop has several capabilities that are not found in other loop constructs. For example more than one variable can be initialized at a time in the for statement. For example, i=1; for (j=0; j<10; j++) Can be rewritten as for (i=1,j=0; j<10; j++)
Like the initialization section, the increment section may also have more than two parts. For Example Class comma { public static void main (string [ ] args) { int i, j; for(i=1 , j=4; i<j ; i++, j) { system.out.println(i= +i);
97
system.out.println(j= +j); } }
The test condition in the for loop may have any compound relation and the testing need not be limited only to the loop control variable For example sum=0; for(i=1,i<20 && sum<100;i++) { } The loop uses a compound test condition with the control variable I and external variable sum.
In for
loop it is permissible to use expression in the initialization and the increment parts
98
Example: class NestedFor { public static void main (String [ ] args) { for (int i = 0; i<5; i++) { for (int j = 1; j<=i; j++) { system.out.print(*); } system.out.println(i); } } } Output 0 *1 **2 ***3 ****4
Chapter 7 - Looping
This Java example shows how to generate a pyramid of numbers for given number using for loop example. import java.io.BufferedReader; import java.io.InputStreamReader; public class GeneratePyramidExample { public static void main (String[] args) throws Exception BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in)); System.out.println(Enter Number:); int as= Integer.parseInt (keyboard.readLine()); System.out.println(Enter X:); int x= Integer.parseInt (keyboard.readLine()); int y = 0; for(int i=0; i<= as ;i++) {
99
for(int j=1; j <= i ; j++) { System.out.print(y + \t ); y = y + x; } System.out.println(); } } Output Enter Number: 5 Enter X: 1 0 1 2 3 4 5 6 7 8 10 11 12 Enter Number: 5 Enter X: 2 0 2 6 12 20
9 13
14
4 8 14 22
10 16 24
18 26
28
Fibonacci Series Java Example using for loop public class JavaFibonacciSeriesExample { public static void main(String[ ] args) { //number of elements to generate in a series int limit = 20; long[ ] series = new long[limit]; //create first 2 series elements series[0] = 0; series[1] = 1; //create the Fibonacci series and store it in an array
100
for(int i=2; i < limit; i++) { series[i] = series[i-1] + series[i-2]; } //print the Fibonacci series numbers System.out.println(Fibonacci Series upto + limit); for(int i=0; i< limit; i++) { System.out.print(series[i] + ); } } } Fibonacci Series upto 20 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Chapter 7 - Looping
101
{ k = j /2; if (k !=0) continue; else system.out.println( j+ , is an even number); } } } The continue statement causes the flow of control to move to the condition part of the while and dowhile loops. In the case of the for statement, the continue statement causes the flow of control to move to the update expressions part of the for statement before moving to the test condition part. This example shows how to use java continue statement to skip the iteration of the loop. public class JavaContinueExample { public static void main(String[] args) { int intArray[] = new int[]{1,2,3,4,5}; System.out.println(All numbers except for 3 are :); for(int i=0; i < intArray.length; i++) { if(intArray[i] == 3) continue; els e System.out.println(intArray[i]); } } } Output would be: All numbers except for 3 are : 1 2 4 5
102
Class Breakloop { public static void main(string [ ] args) { for(int i=0; i<00; i++) { if (i == 10) break; system.out.println(i =:+i); } system.out.prinln(loop complete); } }
Chapter 7 - Looping
In several instances, such as an error or incorrect input from the user, it may be necessary for the flow of control to exit from a loop statement. To accomplish this, Java provides a jump statement called break. The break statement forces the control to come out from a:
After the control moves out of a switch statement or various loop statements, it moves to the statement after the loop statement or the switch statement. Exiting from a loop with a break statement is shown in Fig. 7.7.
103
7.6 SUMMARY
We have covered the loops, continue and break statements in this chapter. Following loop structures were discussed While structure do structure for structure These are useful in developing concise, compact and structured programs. Break and Continue statements are used to jump or skip out of a loop whenever the need arises.
104
EXERCISES :
1. Compare in terms of their functions, the following pairs of statements: (a) while and do..while. (b) while and for (c) break and continue. 2. 3. Write a program to compute the sum of the digits of a given integer number Given a number, write a program using while loop ti reverse the digits of the number . For examples, the number is 12345 should be written as 54321 4.
Chapter 7 - Looping
Analyze each of the program segments that follow and determine how many times the body of each loop will be executed.
a). x = 5; y = 50; while(x <= y) { x = y / x; . . } int il for (i=0; i<=5; i= i+2/3) { . . } b). m = 1; do { m = m + 2; } while (m < 10) int m = 10; int n= 7; while ( m % n >= 0) { .. m = m + 1; n = n + 2; .. }
c).
d).
Chapter 8
OBJECTIVES
define a class create objects add methods to classes extend or reuse a class write application programs
8.1 INTRODUCTION
Java is a true object oriented language and hence all java programs have classes as their underlying structure. Anything we wish to represent in java program must be encapsulated in a class . Class defines the state and behavior of objects . classes create objects. Objects use methods to communicate between them.
8.2 CLASSES
Class is a template that defines a particular type of object. Classes contain all the features of a BSIT 42 JAVA Programming
105
106
particular set of objects. We can use the class definition to create objects of that of class type, that is, to create objects that incorporate all the features belonging to that class. An instance of a class is another word for an actual object. If the class is the general representation of an object, then an instance is its concrete representation.
Syntax of the class declaration class classname { member variable declarations; method declarations; }
Example: You might perhaps define a motorcycle class that describes the features of all motorcycles (has color, make, engineon etc..). The motorcycle class serves as an abstract model for the concept of a motorcycle-to interact with each type of motorcycle ,we should have a concrete instance of that motorcycle. Of course once you have a motorcycle class we can create lots of different instances of that motorcycle. Different motorcycles can have different features .
Variables
Variables are the data types that store data items that typically differentiate one object of the class from another. They are also referred to as data members of a class. Every class you write in Java is generally made up of two components: attributes and behavior. Lets consider an object to define a motorcycle. Attributes are the individual things that differentiate one object from another and determine the state, appearance, or other qualities of that object. The attributes of our motorcycle might include:
color: red, green, silver, brown. make: Honda, BMW, Bultaco. engineOn: true, false.
107
Attributes are defined by variables, in fact, you can consider them because each instance of a class can have different values for its variables, each variable is called an instance variable.
Instance variables
Each object of the class will have its own copy of each of the instance variables that appear in the class definition. Each object will have its own values for each instance variable. The name instance variable originates from the fact that an object is an instance or an occurrence of a class and the values stored in the instance variables for the object differentiate the object from others of the same class type. An instance variable is declared within the class definition in the usual way, with a type name and a variable name, and can have an initial value specified. Instance variables define the attributes of an object. The class defines the type of the attribute, and each instance stores its own value for that attribute
Class variables
A given class will only have one copy of each of its class variables, and these will be shared between all the objects of the class. The class variables exist even if no objects of the class have been created. They belong to the class, and they can be referenced by any object or class, not just instances of that class. If the value of a class variable is changed, the new value is available in all the objects of the class. This is quite different from instance variables where changing a value for one object does not affect the values in other objects. A class variable must be declared using the keyword static preceding the type name. Look at the following diagram (Fig 8.1), which illustrates the difference between the two: This shows a schematic of a class Sphere with one class variable
Fig. 8.1 Difference between the class variables and instance variables
108
Methods
These define the operations you can perform for the classso they determine what you can do to, or with, objects of the class. Methods typically operate on the fieldsthe variables of the class. A classs behavior determines what instances of that class do when asked to by another class or object. Behavior is the only way that objects can have anything done to them. Our motorcycle class might well have the following behavior:
To define an objects behavior you create methods. Methods are functions defined inside classes that operate on instances of those classes The methods in a class definition are named, self-contained blocks of code that typically operate on the variables that appear in the class definition. /* This Java class example describes how class is defined and being used */ public class JavaClassExample { private String name; public void setName(String n) { name = n; } public String getName() { return name; } } public static void main(String [ ] args) { JavaClassExample javaClassExample = new JavaClassExample(); javaClassExample.setName(Visitor); System.out.println(Hello + javaClassExample.getName()); }
109
OUTPUT of the above given Java Class Example would be : Hello Visitor
In the above examples Class box contains three double type variables. Class account contains three different types of variables each for acc_no , name and balance. Class motorcycle contains a variables to show the make,color and engine_on, a Boolean variable defined to check whether the engine is on or off.
110
have to have parameters specified. A method that does not require any information to be passed to it when it is executed has an empty pair of parentheses after the name. Return-Type method _name (parameter- list) { Method-body; }
The body of the method Example 1: Class box { double width; double height; double length; void getdata ( double x, double y, double z) { width = x; height = y; length = z;
111
} double volume( ) { return(width*height*length); } } Example 2: class Sphere { static final double PI = 3.14; // Class variable that has a fixed value static int count = 0; // Class variable to count objects // Instance variables double radius; double xCenter; double yCenter; double zCenter;
// Static method to report the number of objects created static int getCount ( ) { return count; } // Instance method to calculate volume double volume ( ) { return 4.0/3.0*PI*radius*radius*radius; } There are two varieties of methodsinstance methods and class methods. You can execute class methods even when no objects of a class exist, whereas instance methods can only be executed in relation to a particular object, so if no objects exist, there are no instance methods to be executed. Again, like class variables, class methods are declared using the keyword static so they are sometimes referred to as static methods.
112
Since class methods can be executed when there are no objects in existence, they cannot refer to instance variables.. In fact the Java compiler wont let you try. If you reference an instance variable in the code for a class method, it wont compileyoull just get an error message. The method main(), where execution of a Java application starts, must always be declared as static, as you have seen. The reason for this should be apparent by now. Before an application starts execution, no objects exist, so in order to start execution, you need a method that is executable even though there are no objectsa static method therefore. Note that, although instance methods are specific to objects of a class, there is only one copy of an instance method in memory that is shared by all objects of the class, as it would be extremely expensive to replicate all the instance methods for each object. There is a special mechanism that ensures that, each time you call a method the codes executes in a manner that is specific to an object. You can access program code when you do not have an instance of a particular object available. A method that is marked using the keyword static can be used in this way and is called a class method. Methods that are static can be accessed using the class name rather than a reference to an object, as follows: public class ClassMethod { public static int getNumber ( ) { } } public class UseMethod { // Call the method using the classname int x = ClassMethod.getNumber ( ); ... }
113
valuethat is methods declared with a return type other than voidmust always finish by executing a return statement that returns a value of the appropriate type. Note, though, that you can put several return statements within a method if the logic requires this. If a method does not return a value, you can just use the keyword return by itself to end execution of the method: return; // Return from a method Note that, for methods that do not return a value, falling through the closing brace enclosing the body of the method is equivalent to executing a return statement
A parameter has a name and appears in the parameter list in the definition of a method. A parameter defines the type of value that can be passed to the method, and the name that is used to reference it within the code for the method. An argument is a value that is passed to a method when it is executed, and the value of the argument is referenced by the parameter name during execution of the method.
Fig. 8.2 parameter passing and returning a value from the method
114
Here we have the definition of a method Add( ). This can only appear within the definition of a class, but the rest of the class definition has been omitted so as not to clutter up the diagram. You can see that the method has two parameters, value1, and value2, both of which are of type double, that are used to refer to the arguments 3.0 and 5.0 respectively within the body of the method. Since this method has not been defined as static, you can only call it for an object of the class. We call Add( ) in our example for the object, obj. When you call the method from another method (from main( ) in this case, but it could be from some other method), the values of the arguments passed are the initial values assigned to the corresponding parameters. You can use any expression you like for an argument when you call a method, as long as the value it produces is of the same type as the corresponding parameter in the definition of the method. With our method Add( ), both parameters are of type double, so both argument values must always be of type double. The method Add( ) declares the variable result, which only exists within the body of the method. The variable is created each time you execute the method and it is destroyed when execution of the method ends. All the variables that you declare within the body of a method are local to the method, and are only around while the method is being executed. Variables declared within a method are called local variables because they are local to the method. Local variables are not initialized automatically. If you want your local variables to have initial values you must supply the initial value when you declare them. This Java Factorial Example shows how to calculate factorial of a given number public class NumberFactorial { public static void main(String[] args) { int number = 5; int factorial = number; for(int i =(number - 1); i > 1; i) { factorial = factorial * i; } System.out.println(Factorial of a number is + factorial); } } Output of the Factorial program would be Factorial of a number is 120 This Following example shows how to swap two numbers public class SwapElementsExample {
115
public static void main(String[] args) { int num1 = 10; int num2 = 20; System.out.println(Before Swapping); System.out.println(Value of num1 is : + num1); System.out.println(Value of num2 is : +num2); swap(num1, num2); } private static void swap(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; System.out.println(After Swapping); System.out.println(Value of num1 is : + num1); System.out.println(Value of num2 is : +num2); } } Output of Swap Numbers example would be Before Swapping Value of num1 is: 10 Value of num2 is: 20 After Swapping Value of num1 is: 20 Value of num2 is: 10 Program to swap two numbers without using the third variable public class SwapElementsWithoutThirdVariableExample { public static void main(String[ ] args) { int num1 = 10; int num2 = 20; System.out.println(Before Swapping); System.out.println(Value of num1 is : + num1); System.out.println(Value of num2 is : +num2); //add both the numbers and assign it to first num1 = num1 + num2;
116
num2 = num1 - num2; num1 = num1 - num2;
System.out.println(After Swapping); System.out.println(Value of num1 is : + num1); System.out.println(Value of num2 is : +num2); } } Output of Swap Numbers example would be Before Swapping Value of num1 is: 10 Value of num2 is: 20 After Swapping Value of num1 is: 20 Value of num2 is: 10
Creating a object
An object in java is a block of memory that contains a space to store all the instance variables. Creating an object is referred to as instantiating an object. The creating object to a class is two-step Process. 1. decleare a variable of class type. This variable does not define an object instead it is a simply a variable that can refer to an object. 2. physical copy of the object is created and assigned to that variable.
New operator
The object in java is created using the new operator. The new operator dynamically allocates memory for an object and returns a reference to it. This reference is stored in the variable declared.
117
Example: Box mybox Mybox = new Box( ) / / declare a reference to an object of the class //allocate a box object
The first line declares mybox as a reference to an object of type box. After the line executes, mybox contains the value null, which indicates that it does not point to the object. The next line allocates an actual object and assigns a reference to mybox. Mybox holds the memory address of the actual box object. Both objects can be combined into one single statement. Box mybox = new Box( ); We can create any number of box objects Box mybox1= new Box( ); Box mybox2=new Box( ); When the above statement is executed each object has its own copy of the instance variables of its class. If any changes are made to the variables of one object, it will have no effect on variables of other.
118
Accessing a class members
The members of the class can be accessed using the following form Objectname.variablename; Objectname.methodname(parameter-list); Here objectname is the name of the object, variablename is the name of the Instance variable inside the object that we wish to access, method name is the Method that we wish to call, and parameter list is a comma separated list of actual values that must match in type and number with the parameter list of the method name declared in the class. Example: For the class Box in the above example we can write the main method and access the methods of the class as follows. class Boxarea { public static void main(String [ ] args) { double v1,v2; Box b1= new Box( ); Box b2 = new Box( ); b1.width=2; b1.height=4; b1.length=8; b2.getdata(5,10,15); v1=b1.volume(); v2=b2.volume(); System.out.println(The volume1is = +v1); System.out.println(The volume2 is= +v2); } } Output The volume is = 64 The volume is = 750
Constructors
The central player in object initialization is the constructor. In Java, constructors are similar to methods,
119
but they are not methods. Like a method, a constructor has a set of parameters and a body of code. Unlike methods, however, constructors have no return type. Like methods, you can give access specifiers to constructors, but unlike methods, constructors with public, protected, or package access are not inherited by subclasses. (Also, instead of determining the ability to invoke a method, the access level of a constructor determines the ability to instantiate an object.) In class definitions, constructor methods stand apart from other instance methods in two ways:
Constructor-method names are the same as the name of the class. Constructor methods return new class instances; no return type is specified explicitly To define a zero-parameter constructor for the Box class, you would write the following:
No return type specified Constructor name is the same as class name public Box( ) { ... }
In the following program, the Box class definition includes a constructor method that assigns the value 10 to all the instance variables in box instances. class box { double width; double height; double depth; public box( ) { width=10; height=10; depth=10; } double volume( ) { return(width*height*depth); } } Because it uses the new definition of the box class introduced, the following main method does not need to assign values to the instance variables:
120
Class boxvolume { // Define main public static void main (string [ ] args) { Box b = new Box( ); double vol; vol = b.volume( ); system.out.println (volume is ,+vol); } } Result Volume is 1000.00
Now, suppose that you want to provide values for the length, width, and height instance variables when you create certain box instances. You should define a constructor with three parameters: Constructor with three parameters: class box { double width; double height; double depth; public box( ) { width=10; height=10; depth=10; } public box(double a, double b, double c) { width =a; height=b; depth=c; } double volume( ) { return (width*height*depth); } }
121
Note that the constructor for three parameters, like the one for zero parameters, is named for the class in which it appears. To tell Java to use the three-parameter constructor, blocking the involvement of the zeroparameter constructor, you modify the box creation statement: Declare b to be a variable of class box Use argument list with three arguments
Box b = new Box(5 ,5,10); The arguments dictate that initialization is to be done with the three-parameter constructor; it is not to be done with the zero-parameter constructor The following program uses both the zero-parameter constructor and the three-parameter constructor class boxvolume { // Define main: public static void main (String [ ] argv) { Box b1 = new Box(); Box b2 = new Box(5, 5, 10); System.out.println(The first box volume is + b1.volume()); System.out.println(The second box volume is + b2.volume()); } } Result The first box volume is 1000.00 The second box volume is 250.00 If you do not define any constructors, Java defines a do-nothing default constructor for you. The default constructor is a zero-parameter constructor The this keyword: Sometimes a method will need to refer to the object that invoked it. To allow this java defines the this keyword. This can be used inside any method to refer to the current object. ,i.e .,this is always a reference to the object on which the method was invoked. Example 1: Box (double a, double b, double c)
122
{ this.width=a; this.height=b; this.depth=c; }
Example 2: public class Class2 { String name; int age; public Class2( ) { name = Rahul; age = 39; } public void printName( ) { System.out.println( The name of this object is + name ); } } public class Class3 { String name; int age; public Class3 (String name, int age ) { this.name = name; this.age = age; } public void printName( ) { System.out.println( The name of this object is + name ); } }
123
modifier(s) return-type method-name (parameter-list) { statement-list } e.g. public void chooseOption(String m) { option = m; } public String getOption() { return(option); }
Defining classes
The basic syntax for defining a class in Java is class class-name { data-declarations constructors methods } Example : Class Student { String name; int mark; String option; Student(String nm) { name=nm; } public void setMark(int m)
124
{ mark = m; } public int getMark( ) { return(mark); } public void chooseOption(String m) { option = m; } public String getOption( ) { return(option); } } //Student
125
For example: void add(int x,int y) ... void add(int x, int y, int z) .. void add(double x, double y) When you write code to call one of above methods, the appropriate one is chosen according to the type of argument or arguments that you supply. Two rules apply to overloaded methods: 1. The return type of the methods can be different, but the argument lists of overloaded methods must differ. 2. The argument lists of the calling statement must differ enough to allow unambiguous determination of the proper method to call. Demonstration of method overloading Class overload { int add(int a , int b) { return (a+b); } //overload add for three integer parameters int add(int a , int b , int c) { return (a+b+c); } //overload add for two double parameters double add(double a , double b) { return (a+b); } // overload add for three double type parameters double add(double a, double b , double c)
126
{ return (a+b+c); } }
From the main method we can call the add method which is in class add. The add method is selected form the four depending on the number and type of the parameter passed to the method. Ob.add(2,3) Ob.add(2,3,4) Ob.add(3.0,4.0) Ob.add(3.0,4.0,5.0) Example 2: class Overload void show (int x) { system.out.println(The value is +x); } void show (int a,int b) { int c = a*b; system.out.println(The value is +c); } public static void main (String [ ] args) { Overload over = new Overload( ); over.show(50); over.show(60,70); } Output The value is 50 The value is 4200 // calls the add method with two integer parameter //calls the add method with three integer parameters //calls the add method with two double type parameters //calls the add method with three double type parameters.
127
Defining a subclass
A subclass is defined as follows Class subclass extends superclass { Variables declaration; Methods declaration; } The keyword extends signifies that the properties of superclassname are extended to the subclassname. The subclass will now contain its own variables and methods as well those of the superclass. This kind of situation occurs when we want to add some more properties to existing class without actually modifying it In the following example we have a base class called book which consists of name of the book, id of the book and a method to display. Further we want to add variable author name to the book with existing properties so we have created a derived class book1 in which we will add the variable author and a method to display the author. Now this derived class will contain the properties of the base class including its own property. import java.io.*; //super class declaration class book { String name; int id; void showsuper( ) { system.out.println(the id and name of the book is : +id+ } }
+name);
128
class book1 extends book { String author; void showderived( ) { System.out.println(the author name is: +author); } } class simpleinhertence { public static void main(String [] args) { book superob=new book( ); book1 subobj = new book1( ); superob.id=10; superob.name=java; system.out.println(the contents of super object is); superob.showsuper( ); system.out.println( ); subobj.id=20; subobj.name=c programming; subobj.author=Balaguruswamy; System.out.println(the contents of the subobj:); subobj.showsuper( ); subobj.showderived( ); } }
Result
The contents if super object is The id and name of the book is: 10 java The contents of the subobj: The id and name of the book is : 20 c programming The autor name is: Swamy As you see, the subclass book1 includes all the members of its superclass, book. This is why subob can access the id and name and call showsuper.
129
Even though book is a superclass of book1 it is also a completely independent stand-alone class. Being a superclass for a subclass does not mean that superclass cannot be used by itself. The general form of class declaration that inherits the a superclass is shown here: Class subclass-name extends superclass-name { body of the class }
130
class C extends B { void display() { System.out.println(C); } public static void main(String[] args) { A a = new A(); a.get(5,6); a.Show(); } } Java does not support multiple Inheritance
Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface. In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.
Subclass constructors
A subclass can call constructor method defined by its superclass by use of the Following form of super The super is java keyword. As the name suggest super is used to access the members of the super class. It is used for two purposes in java. The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class. The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command. super(param-list); Here parameter_list specifies any parameters needed by the constructors in the superclass. Super( ) must always be the first statement executed inside a subclass constructors.
131
To see how the super is used, consider our previous example class box. Now create a boxweight class which extends the box class with variable weight in it. Now define a constructor boxweight, this constructor calls super ( ) with parameters w,h,d this causes the box constructor to be called ,which initializes width,height and depth using these values. Boxweight no longer initializes these values itself. It only needs to initialize the value unique to it. ,i.e ,weight version of the boxweight class Class boxweight extends box { double weight; boxweight(double w, double h, double d, double m) { super (w,h,d); weight=m; } }
Method Overriding
In the class hierarchy, when a method in a subclass has the same name and type signature as method in the superclass, then the method in the subclass is said to override the method in superclass. class Book { //super class defined String name = JAVA PROGRAMMING; int id = 34567; void show ( ) { system.out.println( Book name is +name); system.out.println( Book id is +id); } } Save this file as book.java and compile. This is our Base Class class Book1 extends Book { // This is the subclass String author = micheal janson; void show ( ) { System.out.println( Book name is +name); System.out.println( Book id is +id);
132
System.out.println( The author name is +author); } public static void main(String args[ ] ) { Book1 x = new Book1( ); x.show(); } } Save this file as book1.java.This is our derived class. Compile and execute the derived file. You can see the three outputs. Note that the first two print statements in the derived class is inherited from book class (Base Class). We have not declared the variables in them in the derived class Methods in the derived class can have same name as that of the base class. If you are having one base class called book and two derived class called book1 and book2 and if you use same methods in all the three classes, then the last derived class method is executed although there are methods with similar names in all the former classes. This concept in Java is called as Method Overriding. If you want to display the details of base class and that of derived class in the above context, then super keyword is used in each derived classes after the method definition.
Class Attributes
Sometimes it is desirable to have a variable that is shared among all instances of a class. For Example this can be used as the basis for communication between instances or to keep track of the number of instaces that have been created We can achieve this effect by making the variable with the keyword static .such variable is sometimes called a class variable to distinguish it from a member of instance variable, which is not shared. public class Count { private int serialNumber; public static int counter=0; public count()
133
{ counter++; seraialNumber=counter; } } In this example, every object that is created is assigned a unique serial number, starting at 1 and counting upwards. The variable counter is shared among all instances, so when the constructor of one object increments counter, the next object to be created receives the incremented value. A static variable is similar in some ways to global variable in other languages. The java programming language does not have global as such, but a static variable is a single variable accessible form any instance of a class. If static variable is not marked as private, you can access it from outside the class. To do this, you do not need an instance of a class, you can refer to it through the class name. public class otherclass { public void incrementNumber() { Count.counter++; } }
Class Methods
Static method can be accessed without creating a instance of a particular object. a method that is marked as static method using the keyword static which is shown in the following diagram. public class Count { private int serialNumber; public static int counter=0; public static int getTotalCount() { return counter; } public count() { counter++; seraialNumber=counter;
134
} }
We should access the methods that are static using the class name rather than an object reference, as follows: Public class TestCounter { Public staic void main(String [ ] args) { System.out.println(Number of counter is + Count.getTotalCount()); Count count1=new Count(); System.out.println(Number of counter is + Count.getTotalCount()); } The output of the Test Counter program is: Number of counter is 0 Number of counter is 1
135
Any attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring a class final prevents any unwanted extensions to the class. It also allows the compiler to perform some optimizations when a method of final class is invoked.
Finalizer methods
We have seen that a constructor method is used to initialize an object when it is declared. this process is known as initialization. Similarly, java supports a concept called finalization, which is just opposite to initialization. We know that java run time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non-object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources. In order to free these resources we must use a finalizer method. This is similar to destructors in C++. The finalizer method is simply finalize( ) and can be added to any class. Java calls that method whenever it is about to reclaim the space for that object. The finalize method should explicitly define the tasks to be performed.
136
We cannot use abstract classes to instantiate objects directly. For example, Shape s =new shape ( ); Is illegal because shape is an abstract class. The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.
Access Modifiers
Access to variables and methods in Java classes is accomplished through access modifiers. Access modifiers define varying levels of access between class members and other objects. Access modifiers are declared immediately before the type of a member variable or the return type of a method. There are four access modifiers
The default access modifier specifies that only classes in the same file or package have access to a classs variables and methods. There is no actual keyword for declaring the default access modifier; it is applied by default in the absence of any other modifier. For example, in our MotorMain program all the variables and methods in the MotorCycle class had default access because no access modifiers were specified. The class MotorMain could however see and use all these variables and methods because the two classes are part of the same file (and hence the same default package). The public access modifier specifies that class variables and methods are accessible to anyone, both inside and outside the class. This means that public class members have global visibility and can be accessed by any other object. For example: if you declared the variable named x as public int x = 20; , then the value of x will be visible to all the other classes of the same program. public int count; public Boolean isActive; The protected access modifier specifies that class members are accessible only to methods in that class and subclasses (dont worry we deal with subclasses later) of that class. This is same, as Public but it will give more protection than the public. If Protected is used then all the methods and attributes of the base class will be available to all its derived classes Protected int count; Protected Boolean isActive; The private access modifier is the most restrictive; it specifies that class members are accessible only
137
by the class in which they are defined. this means that no other class has access to private class members. For example: private int y = 100; means the value of y will be visible only to the class it is defined. If you try to access the variable in other classes then the compiler will return an error.
8.8 SUMMARY
In this chapter, we have discussed classes, objects and methods which are the basic components used in java programming we have discussed in detail
How to define a class How to create objects How to add methods to classes How to reuse a class and How to write application programs
Concepts discussed here provide the basics for writing both stand alone application programs and applets.
EXERCISES
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. What is class? How does it accomplish data hiding? How do classes help us to organize our programs? What are objects? How are they created from a class? How is a method defined? When do we declare a member of a class static? What is a constructor? What are its special properties? How do we invoke a constructor? What is inheritance and how does it help us create new classes quickly? Describe different forms of inheritance with examples. Design a class to represent a bank account. Include the following member: Data members
138
Methods
To assign initial values To deposit an amount To withdraw an amount after checking balance To display the name and balance
11.
Assume that a bank maintains two kinds of account for its customers, one called savings account and the other current account. The savings account provides compound interest and withdrawal facilities but no cheque book facility. The current account provides cheque book facility but no interest. Current account holders should also maintain a minimum balance and if the balance falls below this level, a service charge is imposed. Create a class Account that stores customer name, account number and the type of account. From this derive the classes Curr-acct and Sav-acct to make them more specific to their requirements. Include the necessary methods in order to achieve the following tasks: i. ii. iii. iv. v. Accept deposit from a customer and update the balance. Display the balance. Compute and deposit interest. Permit withdrawal and update the balance. Check for the minimum balance, impose penalty, if necessary and update the balance. Do not use any constructors. Use methods to initialize the class members.
Chapter 9
Ar r ay s An d St r in g s
OBJECTIVES
What is an array in Java How arrays are used What is a string How to use string classes
9.1 INTRODUCTION
An array is a sequence of logically related data items. It is a kind of row made of boxes, with each box holding a value. The number associated with each box is the index of the item. Each box can be accessed by, first box, second box, third box, and so on, till the nth box. The first box, or the lowest bound of an array is always zero, that means, the first item in an array is always at position zero of that array. Position in an array is called index. So the third item in an array would be at index 2 (0, 1,2);
139
140
One-dimensional array is a data structure which allows a collective name to be given to a group of elements which all have the same type. An individual element of an array is identified by its own unique index (or subscript). The indices will be consecutive integers running from a start value to a finish value, (Fig 9.1).
An array element is one of the values within an array and is accessed by its position within the array In Java, arrays can be of a single type like integers, Strings, float, double and so on. For example, consider the following two statements. int array = new int [5] means array is assigned 5 memory locations in the computer (Fig. 9.2). int comp[ ] = {10,20,30}; means the variable comp is assigned the values 10,20,30 Reserve five storage locations as shown below
141
142
Diagrammatically this can be represented as follows:
The number of elements in the array must be specified by an integer constant or an integer expression. The numbering of the indices of an array commence at zero. Thus an n element array will have indices ranging from 0 to n-1. The elements of the array will be assigned the default value associated with the data type of the array elements.
In the example above the data type is numeric so the default value is zero and it is a ten element array so the subscripts run from 0 to 9. We illustrate how storage can be allocated and initialized to specific values by example. The following example declares and initializes an array which holds the number of days in each of the twelve months of the year. Int [ ] daysInMonth = {31,28,31,30,31,30.31,31,30,31,30,31}; This allocates space for a twelve element array called daysInMonth and initializes the elements in order so that the element with index 0 holds 31, the element with index 1 holds 28, etc. Note that the function new is not required when initializing an array in this way. When an array is initialized like this its size is set to the number of values that are contained within the curly brackets. Thus the array daysInMonth has size 12.
143
Alternatively allocation and initialization could have been separated from declaration as follows: Int [ ] daysInMonth; daysInMonth = new int[ ] {31,28,31,30,31,30.31,31,30,31,30,31};
type[ ] A;
Declares A as an array variable of type. No storage allocated for the elements of A. Reference variable for A holds null.
Declares A as an array variable of type and allocates storage to store size array elements. These elements are initialized to the default value for the type. The reference variable for A points to the allocated storage.
Declares A as an array variable and allocates storage of size equal to the number of values. This storage is initialized to the given values.
A = new type[size];
Allocates storage for the array A sufficient for size elements of type. Elements initialized to default values for type. A must have previously been declared as an array variable.
144
Allocates storage of size equal to the number of values and initializes it to the default values for type. A must have previously been declared as an array variable. String as an array: A string variable is, in reality, an array. So, if we have var myname = Rahul; then myname[0] has R, myname[1] has a, and so on. In a similar way, we can initialize every index position of an array. For instance: var myname = new Array(5); //In this way we declare an array. myname[0 ]= R; myname[1] = a; myname[2] = h; myname[3] = u; myname[4] = l; //It seems we have just filled till the index 4, but the dimension //can be any number, as long as you dont try to assign //a value to an index that does not exist. //The following for(){} loop displays the array. for(n=0; n<5; n++) { System.out.println( myname[n]); System.out.println(); } }
Output
R a h u l
145
146
This java example shows how to create a List from an array of type Object using asList method of Arrays class. import java.util.Arrays; import java.util.List; import java.util.Iterator; public class CreateListFromObjectArrayExample { public static void main(String[ ] args) { String[ ] strArray = new String[ ]{Object,Array,Converted,To,List}; List list = Arrays.asList(strArray); Iterator itr = list.iterator(); System.out.println(List created from an Array of type Object contains,); while (itr.hasNext()) System.out.println(itr.next()); } } List created from an Array of type Object contains, Object Array Converted To List
147
Similarly when a reference variable is declared memory space sufficient to hold a reference is allocated to it. This memory is assigned the value null to indicate that as yet there is no information associated with this reference variable. Only when the reference variable is initialized will space be allocated for the actual information associated with the variable and the reference be updated to reference this space.
The rectangular matrices have usually the following form: Int a [ ][ ]=new int [3][4]; This declaration specifies that the matrix created have 3 rows and 4 columns. The index number for columns and rows starts at 0. The elements from the first row are at the next positions (A [0][0], a [0][1], a [0][2] and a [0][3]) Elements from the second row are at the next positions: (A [1][0], a [1][1], a [1][2] and a [1][3].) and elements from the third row are at the next positions: (A [2][0], a [2][1], a [2][2] ski a [2][3].). To find out the no of rows in a matrix: M=a. length; To find out the length of the first row N1=a [0]. Length; To find out the length of the second row: N2=a [1]. Length; Two-dimensional arrays are objects. A variable such as myArray is a reference to a 2D array object. The declaration
148
Int [ ][ ] my Array;
Says that my Array can hold a reference to a 2D array of int. without any further initialization, it will start out holding null. The declaration int[ ][ ] myArray = new int[3][5] ; Says that myArray can hold a reference to a 2D array of int, creates an array object of 3 rows and 5 columns, and puts the reference in myArray. All the elements of the array are initialized to zero. The declaration int[ ][ ] myArray = { {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0} }; does exactly the same thing as the previous declaration (and would not ordinarily be used.) The declaration int[ ][ ] myArray = { {8,1,2,2,9}, {1,9,4,0,3}, {0,3,0,0,7} }; Creates an array of the same dimensions (same number of rows and columns) as the previous array and initializes the elements to specific values.
149
myArray[1] = x ; myArray[2] = y ; // 4.
150
2D Array of int
The following program creates a 2D array of int that implements the gradeTable example. Details about declaring and constructing 2D arrays will be explained later.
Col 1 0 99 90 88 61 93 50 43
1 42 91 61 89 73 65 98
2 74 72 74 82 75 92 78
3 83 88 89 98 78 87 56
4 100 95 96 93 99 94 99
class gradeExample { public static void main( String[] arg ) { // declare and construct a 2D array
int[ ][ ] gradeTable = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99}} system.out.println(grade 0,0: + gradeTable[0][0]); system.out.println(grade 2,4: + gradeTable[2][4]); gradeTable[5][3] = 99 ; int sum = gradeTable[0][1] + gradeTable[0][2] ; system.out.println( sum: + sum ); } }
151
The declaration of gradeTable uses an initializer list as a short-cut way to create a 2D array object and place values into it. The list contains 7 rows each separated by a comma; each row is a list of values. In Java, a table may be implemented as a 2D array. Each slot of the array is a variable that can hold a value and works like any variable. As with one dimensional arrays, every slot in a 2D array is of the same type. The type can be a primitive type or an object reference type. Important: Each slot of the array is specified with a row and column number, in that order. Say that gradeTable is a 2D array of int, and that (conceptually, at least) it looks like the table to the left. Then, gradeTable[ 0 ][ 1 ] gradeTable[ 3 ][ 4 ] gradeTable[ 6 ][ 2 ] // holds 42 // holds 93 // holds 78
The subscripted variables are used in assignment statements and arithmetic expressions just like any variable: gradeTable[ 0 ][ 1 ] = 33 ; // puts a 33 into row 0 column 1. gradeTable[ 3 ][ 4 ]++ ; // increments the value at row 3 column 4.
152
Because instances of the class String are so common Java provides a short hand to achieve the above as shown in Table 2.
9.6.1. Constructors
The default constructor takes a single string constant as its only argument. String myString = new String( Hello World );
You may use the shorthand notation, familiar to many other programming languages, which invokes the same String() constructor. String myString = Hello World;
Example 1: class StringEx1 { public static void main(String[] args) { char data[] = {J,a,v,a}; String name = new String(data); System.out.println(name); } }
Example 2: class StringEx2 { public static void main(String[ ] args) { String name = Java System.out.println(name); } } Output : Java
153
Strings in Java are objects. As with any object, we work with strings by means of reference variables. However, strings are a little unusual in that the compiler knows more about strings than other types of objects and allows us to do some things with strings that are not possible with other objects. One simple example of this is shown in the following code fragment: 1 .String str = Hello; 2 .System.out.println(str);//output the string In line 1 we are creating a new object, but we havent used the new operator. The reason for this is that the compiler automatically creates the necessary String objects to represent the string literals used in a program (like Hello here). What we have after line 1 is the usual situation with references to objects, which we can picture as shown in the following figure.
If we now execute the statement: str = Wells; we get the picture as shown in the Fig. 9.7.
The question is now: what happens to the original string (containing Hello)?. The answer is that it is now out of the reach of our program, as there is no longer any reference variable that refers to it. As such it is referred to as garbage: memory that our program was using to store an object but which is no longer required. Most languages that support dynamic memory allocation like this require that the programmer keeps track of the memory being used. Thus it is the programmers responsibility to ensure that the program deallocates the memory used by an object once it is no longer required. This is a notorious source of programming errors in many programming languages, not least C++. Fortunately for us, Java has a very powerful and useful feature called automatic garbage collection. The Java run-time system keeps track of the references to the objects that the program is using and will automatically
154
reclaim any memory that is no longer being used by the program (such as that being used by the Hello object above). Another important fact to bear in mind with Java strings is that they are immutable. This means that the contents of the object cannot be changed after the object has been created. To put it another way: it is impossible to edit or modify a string object in Java. Of course, it is possible to make a String reference variable refer to another object with different contents, but the original object is never changed.
compareTo( )
Often, it is not enough to simply know whether two strings are identical. For sorting applications, we need to know which is less than, equalto, or greater than the next.The string method compareTo( ) serves this purpose. It has the general form int compareTo(String str) Value value less than zero greater than zero zero Meaning the invoking string is less than str the invoking string is greater than str the two string are equal
155
String s2=Hello; String s3=bye; System.out.println(COMPARE STRINGS); // The compareTo method System.out.println(s1 + equals + s2 + -> +s1.eqals(s2)); System.out.println(s1 + equals + s3 + -> + s1.eqals(s3)); // Using the compareTo method within an if-else statement if (name1.compareTo(name2)==0) System.out.println(the same); else System.out.println(not the same); } } The difference between equals and == The equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares what an object points to, rather than the pointer itself. The == operator compares whether two objects are exactly the same object, meaning that they reference the same spot in memory, NOT that the values of the parameters of the object are the same. So if you declare String s1 = This is a String.; String s2 = s1; It is assured that (s1 == s2) is true, since s1 and s2 reference the same String at the same location in memory. However, if you had: String s1 = new String(This is a String.); String s2 = new String(This is a String.); It is assured that (s1 == s2) is NOT true, since you created two different Strings using the new operator, and they definitely do not reference the same object, even though the contents of the String are the same. The equals() method, on the other hand, does the operation you probably intend to do, comparing the contents of the two strings and seeing if they match. Usually you will want use the equals method.
156
Class stringDemo { public static void main(String args[]) { /* Compare two Strings */ String firstString = Java programming; String secondString = Java programming; System.out.println((firstString == secondString)); /* returns true */ /* Compare two Strings */ firstString = new String(Java programming); secondString = new String(Java programming); System.out.println((firstString== secondString)); /* returns false */ System.out.println((firstString.equals(secondString)); /* returns true */ } } The results in line 11 and 13 are predictable. Line 11 returns false, because we are comparing two different object instances, and they arent the same. The variables firstString and secondString point to two different objects in memory. So in order to test if the strings inside the String object are the same, we must use the equals method(line13). But what about the true result of line 5? Here we see some compiler optimazation at work. Because the secondString variable contains the same string as the firstString variable, the compiler already assumes both variables can point to the same space in memory. And because both variables point to the same memory space, the comparison returns true. But we cannot rely on this process for other objects, so try to use the equals method, when comparing objects. charAT( ) To extract a single character from the string. We can refer directly to an individual character via the charAt() method. It has the general form Char chatAt(int where) Here where is the index of the character that we want to obtain. ChatAt( ) returns the character at the specified location
String length
The length of a string is the number of characters that it contains. To obtain this value call a length method int length();
157
class strCmp { public static void main (String args[ ]) { String str = Hello; String str2 = Java; System.out.println (str.equals(str2)); // false System.out.println (str.compareTo(str2)); // a negative number, str is less than str2 System.out.println (str.charAt(0)); // H, i.e. char is position 0 System.out.println (str.length() + str2.length()); // 5 + 4 = 9 } }
i.e.
158
Output First String : Sachin Second String : Tendulkar Concatenated : Sachin Tendulkar
Conversions
toLowerCase( ) returns a newly minted string identical to the original, but with all upper case characters cast to lower case. toUpperCase( ) returns a newly minted string identical to the original, but with all lower case characters cast to upper case.
Replace method
The replace method is used to replace each occurrence of the first argument in a string with the second argument the general form of the replace method is String replace(char original, char replacement) Here the original specifies the character to be replaced by character specified by replacement Substring method The subString method is used to create new instances of the class String from existing instances. The new string is specified by giving the required index range within the existing string string substring(int startIndex) This returns the sub string that starts at startIndex and runs to the end of the invoking string. string substring(int start Index, int endIndex) This returns the substring that starts at startindex and runs through endIndex-1; This Java String Replace example describes how replace method of java String class can be used to replace character or substring can be replaced by new one. public class JavaStringReplaceExample { public static void main(String args[ ]) { String str=Replace Region; System.out.println( str.replace( R,A ) ); System.out.println( str.replaceFirst(Re, Ra) );
159
System.out.println( str.replaceAll(Re, Ra) ); } } OUTPUT Aeplace Aegion Raplace Region Raplace Ragion
Trim method
The trim method returns a copy of the invoking string from which any leading and trailing white space has been removed. It has the general form String trim ( ); class altStr { public static void main (String args[ ]) { String str = Hello; String str2 = Java; str = str.toUpperCase(); str2 = str2.toLowerCase(); System.out.println (str); // HELLO System.out.println (str2);// java str = str.concat(str2); // str now equals HELLO java System.out.println (str); str = str.trim(); // str now equals HELLOjava System.out.println (str); str = str.substring (5,str.length()); // str = java System.out.println (str); str = str.replace (a, i); // str = jivi System.out.println (str); } } Program to Convert String to Character Array Example public class StringToCharacterArrayExample { public static void main(String args[]) { String strOrig = Hello World; char [] stringArray;
160
stringArray = strOrig.toCharArray(); for(int index=0; index < stringArray.length; index++) System.out.print(stringArray[index]); } } Output Hello World Search a word within a String object using indexOf method. public class SearchStringExample { public static void main(String[] args) { String strOrig = Hello world Hello World; int intIndex = strOrig.indexOf(Hello); if(intIndex == - 1) { system.out.println(Hello not found); } else { System.out.println(Found Hello at index + intIndex); }
int positionIndex = strOrig.indexOf(Hello,11); System.out.println(Index of Hello after 11 is + positionIndex); int lastIndex = strOrig.lastIndexOf(Hello); System.out.println(Last occurrence of Hello is at index + lastIndex); } } Output Found Hello at index 0 Index of Hello after 11 is 12 Last occurrence of Hello is at index 12
161
9.7 SUMMARY
In this chapter, two important java data structures namely arrays and strings were discussed we learnt arrays and their usage, and , strings and their usuage. Some examples to illustrate where these structures can be used was also highlighted.
EXERCISES
1. 2. 3. What is an array? Why are arrays easier to use compared to a bunch of related variables? Write a statement to declare and instantiate an array to hold marks obtained by students in different subjects in a class. Assume that there are up to 60 students in a class and there are 8 subjects. Find errors, if any, in the following code segments: int m; int x[ ] =int [10]; int [ ] y =int [11]; for (m=1;m<=10; ++m) x[m]=y[m]=m; x=y=new int[20]; for (m=0 ; m<10; ++m) system.out.println(x[m]) 5. An election is contested by 5 candidates. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count. In case, a number read is outside the range 1 to 5, the ballot should be considered as a spoilt ballot and the program should also count the number of spoilt ballots. Two matrices that have the same number of rows and columns can be multiplied to produce a third matrix. Consider the following two matrices.
4.
6.
The product of A and B is a third matrix C of size b by n where each element of C is given by the following equation. Write a program that will read the values of elements of A and B and produce the product matrix C.
162
7. 8. How does String class differ from the StringBuffer class? Explain about : 1. 2. 9. Comparision of two strings Concatenation of two strings
10. 11.
Write a program to split a string into multiple java string objects Write a program to remove a leading thread and trailing space from string using trim method of java string class
Chapter 10
M u l t i t h r e ad i n g
OBJECTIVES
10.1 INTRODUCTION
It is nice if we can do one thing at a time and do it well. However, this is not the way the world works. For example, the human body performs a variety of operations in parallel or concurrently. Similarly, all of the senses seeing, touching, smelling, hearing etc., can occur concurrently. Computers, too perform operations concurrently. A computer can concurrently compile a program, print a file and receive e-mail over a network. Most programming languages do not help programmers to specify concurrent activities. They generally provide a simple set of control structures that allow programmers to perform one action at a time. Among popular, general purpose programming languages Java is unique in that it provides concurrency primitives. The programmer specifies that applications contain threads of execution. Each thread earmarks a portion of program that can be executed concurrently with other threads. This capability of Java language is called multithreading. This facility is not available in C and C++ on which Java is based. BSIT 42 JAVA Programming
163
164
Examples of concurrent programming:
Chapter 10 - Multithreading
When programs download large files of audio or video clips from WWW, one need not wait until the entire clip is downloaded before starting the playback. He can put multiple threads to work. In C and C++, the responsibility of reclaiming dynamically allocated memory rests with the programmer. However, Java provides a garbage collector thread that reclaims dynamically allocated memory automatically.
Processes
A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Processes are often seen as synonymous with programs or applications. However, what the user sees as a single application may in fact be a set of cooperating processes. To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets. IPC is used not just for communication between processes on the same system, but processes on different systems.
Threads
Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads exist within a process every process has at least one. Threads share the processs resources, including memory and open files. This makes for efficient, but potentially problematic, communication.
165
Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread or several, if you count system threads that do things like memory management and signal handling. But from the application programmers point of view, you start with just one thread, called the main thread. To summarize
A process is a program executing within its own address space. A thread is a single stream of execution within a process.
Thread is the smallest unit of dispatchable code and is a sequence of code executing within a process. Threads cannot execute on their own; they require a parent process to run. Within each process , there are a variety of threads executing. For example, Word may have a thread in the background automatically checking the spelling of what is being written, while another thread may be automatically saving changes to the document. Like Word, each application (process) can be running many threads that are performing a number of tasks. The significance here is that threads are always associated with a particular process.
Chapter 10 - Multithreading
Thread exists in several states. A thread just created is in the born state. When the threads start method is called, it enters the runnable (ready) state. Then the system assigns a processor to the thread. A thread enters the dead state when its run method completes or terminates for any reason. When a sleep method is called in a running thread, that thread becomes ready after the designated sleep time expires. Even if a processor is available, sleeping thread can not use it. A running thread can enter a blocked state. For example, when thread issues an input/output request.A blocked thread becomes ready when the I/O is completed. When a running thread calls wait, the thread enters a waiting state for the particular object on which wait was called. A thread in the waiting state for a particular object becomes ready on a call to notify issued by another thread associated with that object. A thread enters the dead state when its run method is either completed or throws an uncaught exception.Fig 10.1 depicts the state transition diagram of a thread.
167
A thread can voluntarily relinquish control When this happens all other threads are examined and the highest priority thread that is in runnable state is given to C.P.U.
A thread can be preempted by a higher priority thread. A lower priority thread that does not yield the processor is simply preempted. This is called preemptive multitasking.
It is the thread from which other child threads will be created It must be the last thread to finish execution. When the main thread stops, the program terminates.
Chapter 10 - Multithreading
You can query a thread for its name using the getName method. getName returns the name associated with the thread object, as in the following example: System.out.println(The name of this thread is + myThread.getName()); The output is: The name of this thread is first thread A thread can also query for its own name in the same way: System.out.println(My name is + this.getName());
169
} catch(InterruptedException e) { System.out.println(Main Thread Interrupted); } } } Current thread : Thread[main,5,main] After name change:Thread[My Thread,5,main] 5 4 3 2 1
Chapter 10 - Multithreading
The run() method has been inherited by the class MyThread.We have to override this mehthod in order to implement the code to be executed by our thread.The basic implementation of run() will be as follows Public void run() { ----------------------------------------} when we start the new thread, java calls the threads run() method.where all the action takes place.
171
172
} } class RunnableTest { public static void main(String args[]) { X runnable = new X(); Thread threadX = new Thread(runnable); ThreadX.start(); System.out.println(End of main Thread); } } Output of the program End of the main Thread ThreadX: 1 ThreadX: 2 ThreadX: 3 ThreadX 4 ThreadX: 5 Program to create New Thread Using Java Runnable Interface public class CreateThreadRunnableExample implements Runnable { public void run() {
Chapter 10 - Multithreading
for(int i=0; i < 5; i++) { System.out.println(Child Thread : + i); try { Thread.sleep(50); } catch(InterruptedException ie) { System.out.println(Child thread interrupted! + ie); } }
173
System.out.println(Child thread finished!); } public static void main(String[ ] args) { Thread t = new Thread(new CreateThreadRunnableExample(), My Thread); t.start(); for(int i=0; i < 5; i++) { System.out.println(Main thread : + i); try { Thread.sleep(100); } catch(InterruptedException ie) { System.out.println(Child thread interrupted! + ie); } } System.out.println(Main thread finished!); } } Typical output of this thread example would be Main thread: 0 Child Thread: 0 Main thread: 1 Main thread: 2 Child Thread: 2 Child Thread: 3 Main thread: 3 Main thread: 4 Child Thread: 4 Child thread finished! Main thread finished!
10.7 SYNCHRONIZATION
Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
174
Chapter 10 - Multithreading
Thread Interference describes how errors are introduced when multiple threads access shared data. Interference happens when two operations, running in different threads, but acting on the same data, interleave. This means that the two operations consist of multiple steps, and the sequences of steps overlap. Memory Consistency Errors describes errors that result from inconsistent views of shared memory. The key to avoiding memory consistency errors is understanding the happens-before relationship Multithreading introduces a synchronous behavior in programs. There is a need to enforce synchronicity when it is necessary. For example, if two threads are to communicate and share a data structure, there is a need to avoid conflict between them. That is, a thread must be prevented from writing data while the other thread is reading the data. To overcome this problem, Java implements a model of interprocess communication called monitor. The monitor is a control mechanism that can hold only one thread at a time. Once a thread enters a monitor, all other threads have to wait until that exits from the monitor.
10.8 MESSAGING
After we divide our program into separate threads, we need a method by which the threads communicate with each other. In Java, two or more threads can talk to each other, via calls to predefined methods that all objects have.
10.9 SUMMARY
A thread is a single line of execution within program. Multiple threads can run concurrently in a single program. A thread is created either by subclass in thread class or implementing a runnable interface. Careful application of multithreading will improve the execution speed of java programs.
EXERCISES
1. 2. 3. 4. 5. 6. What is a Thread? Distinguish between Multiprocessing and Multithreading? Describe the life cycle of a Thread? What is Synchronization? Why do we use it? How a thread is created? Write a program to implement the set name method of a thread class.
Chapter 11
Pack ag e s & In t e r f ac e s
OBJECTIVES
Create a package Add more classes to a package Access contents of a package Use java system packages
11.1 INTRODUCTION
A package is a grouping of related types providing access protection and name space management. Packages are containers for classes that are used to keep the class name space compartmentalized. For example, a package allows us to create a class named list, which we can store in our own package without concern that it will collide with some other class named list stored elsewhere. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions. Packages, a concept similar to class libraries in other languages helps in achieving the reusability. Packages are Javas way of grouping a variety of classes and/or interfaces together. The grouping is done according to functionality. By organizing the classes into packages, we get the following benefits. 1. Classes contained in packages of other programs can be reused.
175
176
2. Two classes in two different packages can have the same name. 3. Packages provide a way to hide classes. 4. Designing is separated from coding by use of packages. This is achieved by first designing classes and their relationship and then implementing the Java code needed for methods.
// class definition
Here the package name is first package. The class First class now a part of the package. The listing would be saved as a file called Firstclass.java. It is located in a directory named firstpackage. When the source file is compiled, Java will create a class file and store it in the same directory.
Package Packagename;
2. Define the class that is to be put in the package and declare it public. 3. Create a subdirectory under the directory where the main source file are stored.
177
4. Store the listing as the classname.java file in subdirectory. 5. Compile the file. This creates .class file in subdirectory. As stated earlier, Java also supports the concept of package hierarchy. Specifying multiple names in a package statement separated by periods does this. The general form of a multileveled package statement is shown here Package pkg1 [pkg2 [pkg3]]; For example, a package declared as Package java.awt.image; needs to be stored in java/awt/image, java/awt/image or java:awt:image on UNIX, windows or Macintosh file system.
178
Package package 1; Public class Class A; { Public void display A( ) { System.out.println(class A); } }
This source file should be named classA.Java. It is stored in subdirectory package1. This Java file is compiled. Resultant is classA.class. This will be stored in the same subdirectory. Now consider the listing import package1.classA; class packageTest1 { public Static Void main(String args[ ] ) { class A object A = new class A( ); object A.displayA( ); } } The above is a simple program that imports the class.calssA from package1. The source file should be saved as PackageTest1.Java and then compiled. The source file and the compiled file should be saved in the directory of which package1 is a subdirectory. Now, the program can be run to obtain the results.
179
Subclasses in different packages Classes that are neither in the same package nor subclass.
The three access specifiers private, public and protected provide a variety of ways to produce many levels of access required. Table No.11.1 sums up the interaction.
Private Yes No No No No No modifier Yes Yes Yes No No Protected Yes Yes Yes Yes No Public Yes Yes Yes Yes Yes
Same class Same Package Subclass Same Package Non-Subclass Different Package Subclass Different Package Non-Subclass
180
//body of B }
3. Store this as B.Java file under the directory P1. 4. Compile B.java file and creates B.class file. Place it in the directory P1. Now package P1 contains both the classes A and B.
11.8 INTERFACE
We have discussed about classes and how they can be inherited by other class in chapeter 8. Java does not support multiple inheritence. ,i.e, classes in java canot have more than one superclass. However, most of the real life applications require the use of multiple inheritence where by a class inherits methods and properties from several distinct classes. Java provides an alternate approach called interfaces to support the concept of multiple inheritence. interfaces are syntactically similar to classes but they lack instance variables, and their methods are declared without any body. In practice, we can define interfaces which dont make assumptions about how they are implemented.once it is defined, any number of classes can implement an inferface. Also one class can implement any number of interfaces. An interface only defines a methods name, return type, and arguments. It does not include executable code or point to a particular method. Think of an interface as a template of structure.
Declaring an Interface
An interface is declared in much the same manner as a class, but instead uses the interface keyword instead of the class keyword: Interface InterfaceName { Variables decleration; Mehods decleration; } The interface body is declared between the curly braces. The body of an interface consists of declarations for variables and methods.
Modifiers
The same modifiers-public and default-available to classes can be applied to an interfaces declaration. The default is nonpublic, which means accessible by any member of a given package. Most interfaces are
181
public because interfaces are the only means to share variable and method definitions between different packages. Here is an example of a public interface declaration: public interface AnInterface { ... //body of interface } Variables and methods declared inside an interface also have modifiers associated with them. However, the modifiers are limited to particular combinations for variables and methods. Modifiers for variables are limited to one specific set: public static final. In other words, variables declared in interfaces can only function as constants. Public static final are the default modifiers. It is not necessary to declare the modifiers explicitly, but it makes the code more self-documenting. Trying to assign other modifiers such as protected results in a compile-time error. Here are examples of variable declarations: public static final float pie = 3.14159; public static final String = The quick brown fox; Modifiers for methods are limited to one specific set as public abstract, meaning that methods declared inside an interface can only be abstract. These are the default modifiers for methods. It is not necessary to declare them explicitly, but once again, it makes the code easier to read. Trying to assign other modifiers, such as protected, results in a compile-time error. Here are example interface method declarations: public abstract boolean isBlack(Color); public abstract boolean isBlack(String); public abstract StringBuffer promptForName(String); As you can see in this example, overloaded methods can be declared in an interface just as in a class. An entire interface based on these examples follows: public interface MyInterface { public static final int smtpSocket = 25; public static final float pie = 3.14159; public static final String = The quick brown fox; public abstract boolean isBlack(Color); public abstract boolean isBlack(String); public abstract StringBuffer promptForName(String); }
182
Interfaces also can extend other interfaces, just as classes can extend other classes, using the extends keyword. In the following code, the interface AnInterface declares a variable named theAnswer: public interface AnInterface { public static final int theAnswer = 42; } public interface MyInterface extends AnInterface { public static final int smtpSocket = 25; public static final float pie = 3.14159; public static final String = The quick brown fox; public abstract boolean isBlack(Color); public abstract boolean isBlack(String); public abstract StringBuffer promptForName(String); } The interface MyInterface specifies that it extends AnInterface. This means that any classes that use MyInterface will have access to not only the variables and methods declared in MyInterface, but also those in AnInterface. You can also list multiple interfaces after the extends keyword. Multiple, possibly disparate, interfaces can be combined into a logical whole if desired, as in the following: public interface MyInterface extends Interface1, Interface2 { body of interface }
Implementing interfaces
Interfaces are used as uperclasses whose properties are inherited by classes. It is therefore necessary to create Class classname implements Interfacename { body of classname; } Here the class classname implements the interface interfacename.A more gerneral form of implementation may lool lilke this
183
Class classname extends superclass implements interface1,interface2 { body of the classname } this shows that a class can extend another class while implementing interfaces. When the class implements more than one interface,they are seperated by a comma. The implementation of interfaces can take various form as shown in the following example //interface Test.java interface Area { final static float pi=3.14F; float compute(float x, float y) } class Rectangle implements Area { pulbic 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 staic void main(String args[ ]) { Rectangle rect = new Rectangle(); Circle cir = new Circle(); Area area; //interface object area = rect
184
System.out.println(Area of rectangle = +area.compute(10,20)); area = cir; System.out.println(Area of circle = + area.compute(10,0); } } The output is as follows: Area of rectangle = 200 Area of circle = 314
11.9 SUMMARY
Java has several levels of hierarchy for code organization, the highest of which is the package. Packages are javas way of grouping a variety of classes and /or interfaces together. In this chapter, we learnt how to create a package , to add more classes to a package, to access the contents of the package, to use java packages and also about interfaces. Interfaces provide the facility of multiple inheritence required in real life applications.
EXERCISES
1. 2. 3. 4. 5. What is package? Write a procedure to create your own package. How do we design a package Discuss various levels of access protection available for packages and their implications Define Interface. How multiple inheritance can be implemented using interfaces?
Chapter 12
OBJECTIVES
Errors and types of errors in a program What exceptions are How to throw system exceptions How to catch and handle different types of exceptions
12.1 INTRODUCTION
We make mistakes while developing and typing a program. A mistake may lead to an error causing the program to produce unexpected results. An error may even cause the system to cause hence, it is important to detect and manage properly all the possible error conditions in a program so that the program will run properly during execution. There are two types of errors , namely,compile-time error and run-time errors compile time errors are all syntax errors detected and displayed by the java compiler. Whenever the compiler displays an error, it will not create the .class file.Hence it is necessary to fix all the errors before we can successfully compile and run the program. Most of the compile time errors are due to typing mistake. The most commom errors are,missing semicolons, missing /mismatch of brackets in classes and methods,wrong spelling of identifiers and keywords, missing double quotes in strings, use of undeclared variables, incompatible types in assignments /initialization and so on. BSIT 42 JAVA Programming
185
186
A program may compile successfully creating the .class file. However, it may not run properly. Such programs produce wrong results due to wrong logic or may terminate due to errors. Most common run time errors are dividing the interger by zero, accessing an element that is out of the bounds of the array, 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 the thread etc., when these errors are encountered java generates an error message and aborts the program.
12.2 EXCEPTION
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the programs instructions. An exception is a run time error. Most of the computer languages do not support exception handling. Errors must be checked and handled manually. This is cumbersome and troublesome. Java provides the facility of exception handling and avoids the above problems. By this run time error management becomes easy. A Java exception is an object that describes an error condition that has occurred in a piece of code. When an error or an exceptional condition arises, an object representing that exception is created and is thrown in the method that caused the error. The method may handle the exception itself or pass it on. In this way, the exception is caught and processed. Exceptions thrown by Java relate to fundamental errors that violate the rules of the language. Five key words try, catch, throw, throws and finally are used to manage exception handling in Java. The programmer encloses in a try block the code that may generate an exception . The try block is immediately followed by a zero or more catch blocks. Each catch block specifies the type of exception it can catch and contains an exception handler. After the last catch block, an optional finally block provides code that always executes regardless of whether or not an exception occurs. If there are no catch blocks following a try block, the finally block is required. When an exception is thrown, program control leaves the try block and catch blocks are searched for an appropriate handler. If the type of thrown exception matches the parameter type in one of the catch blocks, the code for that catch block is executed. If no exception are thrown in the try block, the exception handlers for that block are skipped and the program resumes execution after the last catch block. If a finally block appears after the last catch block, it is executed regardless of whether or not an exception is thrown. A throws clause specifies the exceptions a method throws. An exceptions can be thrown from the statements in a method or from a method thrown from a method called directly or indirectly from the try block. The point at which throw is executed is called a throw point.
187
Object Throwable Exception IO Exception Arithmetic Exception Arrays store Exception Illegal argument Exception Index out of bound Exception Null pointer Exception Runtime Exception File not found End of file Exception Error
Runtime exceptions (subclasses of the class RuntimeException) such as ArrayIndexOutofBounds, SecurityException, or NullPointerException. Other exceptions such as EOFException and MalformedURLException.
Runtime exceptions usually occur because of code that isnt very robust. An ArrayIndexOutofBounds exception, for example, should never be thrown if youre properly checking to make sure your code doesnt extend past the end of an array. NullPointerException exceptions wont happen if you dont try to reference the values of a variable that doesnt actually hold an object. If your program is causing runtime exceptions under any circumstances whatsoever, you should be fixing those problems before you even begin to deal with exception management. The final group of exceptions is the most interesting because these are the exceptions that indicate that something very strange and out of control is happening. EOFExceptions, for example, happen when youre reading from a file and the file ends before you expect it to. MalformedURLExceptions happen when a URL isnt in the right format (perhaps your user typed it wrong). This group includes exceptions that you yourself create to signal unusual cases that may occur in your own programs. Exceptions are arranged in a hierarchy like other classes, where the Exception superclasses are more
188
general errors, and subclasses are more specific errors. This organization will become more important to you as you deal with exceptions in your own code. Most of the exception classes are part of the java.lang package (including Throwable, Exception, and RuntimeException). But many of the other packages define other exceptions, and those exceptions are used throughout the class library. For example, the java.io package defines a general exception class called IOException, which is subclassed not only in the java.io package for input and output exceptions (EOFException, FileNotFoundException), but also in the java.net classes for networking exceptions such as MalFormedURLException
189
12.5.1 Throw
Understanding exception handling in Java requires that you learn some new terminology. The first concept you need to grasp is that of throwing an exception, Javas name for causing an exception to be generated. For example, say a method was written to read a file. If the method could not read the file because the file did not exist, this would generate an IOException. In Java terminology, it is said that the method threw an IOException.
12.5.2 Catch
The next term to learn in Java exception handling is catch. An exception catch is code that realizes the exception has occurred and deals with it appropriately. In Java terms, you say a thrown exception gets caught. In the case of the IOException thrown because of the nonexistent file, the catch statement writes an error message to the screen stating that the specified file does not exist. It then allows the user to try entering a different filename if the first was incorrect, or it may exit. In Java terminology, the IOException was caught.
12.5.3 Try
try is the Java exception-handling term that means a Java program is going to try to execute a block of code that might generate (throw) an exception. The try is a way of telling the compiler that some attempt will be made to deal with at least some of the exceptions generated by the block of code.
The finally statement is used to specify the action to take if none of the previous catch statements specifically deals with the situation. It is similar to the default part of a switch statement. finally is the big net that catches everything that falls out of the exception-handling statement.
191
If any one statement generates an exception, the remaining statements in the block are skipped and execution continues with the first statement following the try construct, which must be a catch or finally statement. This is an important point to remember. It is an easy way to determine which block of code should be skipped if an error occurs.
192
As with the catch statement, a finally block must follow immediately after a try or other catch statement or a compilation error results. A finally statement acts like a default case in a switch statement if it follows a series of catch statements. Anything that was not explicitly matched by an earlier catch statement is caught by the finally statement. A finally statement cannot be followed by another catch or finally statement or a compilation error will result. Because finally catches everything. Additional statements would never be executed in any case Solved EX1: class Exc2 { public static void main(String args[]) { int d,a; try { d=0; a = 42/d; System.out.println(this will not be printed); } catch(ArithmeticException e) { System.out.println(Division by zero); } System.out.println(after the catch statement); } } This program generates the following output: Division by Zero. After Catch statement Notice that the call println() inside the try block is never executed. once an exception is thrown, program control transfers out of the try block into the catch block thus the line this will not be printed. is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
193
normally program terminates with error message when an exception is thrown,after its loop has executed for four times. This program produces following output: Rahul Mohan Madan Java.lang.ArrayIndexOutOfBoundsException : 3 At array.main(array.java:9) The following example is a rewrite of the main() method from previous example. the exception generated in the eariler version is caught and the array index is reset, allowing the program to continue.
194
int i = 0; string names[]={ Rahul , Mohan , Madan}; While(i<4) { try { System.out.println(names[i]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(Re-setting the index value); i=-1; } finally { System.out.println(this is always printed); } i++; } } } Rahul this is always printed Mohan this is always printed Madan this is always printed Re-setting index value This is always printed
12.6 SUMMARY
We commit both sytactic and semantic errors while writing a program sytactic errors are detected during compile time. Some of the run time errors can be managed using exception handling. In this chapter, we have discussed what exceptions are, how to throw system exceptions, how to catch and handle different types of exceptions.
195
EXERCISES
1. 2. 3. 4. 5. 6. 7. What is an exception? How do we define a try block? How do we define a catch block? How many catch blocks can we use with one try block? What is a finally block? When and how is it used? Give a suitable example? Why does the compiler complain about interrupted exception when I try to use threads.sleep method What is The Difference Between A Runtime Exception and a plain exception why dont runtime exceptions have to be declared.
Chapter 13
Man ag in g In p u t / Ou t p u t
OBJECTIVE
Understand the Stream Classes Print( ) and Println( ) statements Reading of characters & strings Writing into the console output.
13.1 INTRODUCTION
As you know, all Java programs automatically import the java.lang package. This package defines a class called System, which encapsulates several aspects of the run-time environment. System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. However, these streams may be redirected to any compatible I/O device. System.in is an object of type InputStream, System.out and System.err are objects of type PrintStream. These are byte streams, even though they typically are used to read and write characters from and to the console. As you will see, you can wrap these within character-based streams, if desired.
196
197
The preceding chapters have been using System.out in their examples. You can use System.err in much the same way. As explained in the next section, use of System.in is a little more complicated. In Java, console input is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here. BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); After this statement executes, br is a character-based stream that is linked to the console through System.in.
198
Keyboard Mouse Input
Output
Screen Printer
Memory
Disk
Java Program
Memory
Disk Network
Network
A stream in Java is a path along which data flows (like a river or a pipe along which water flows). It has a source (of data) and a destination (for that data) as depicted in Fig. 13.2. Both the source and the destination may be physical devices or programs or other streams in the same program.
Source Valve connecting the source and the stream
Stream
Destination
The concept of sending data from one stream to another (like one pipe feeding into another pipe) has made streams in Java a powerful tool for file processing. We can build a complex file processing sequence using a series of simple stream operations. This feature can be used to filter data along the pipelining of streams so that we obtain data in a desired format. For example, we can use one stream to get raw data in binary format and then use another stream to convert it to integers. Java streams are classified into two basic types, namely, input stream and output stream. An input stream extracts (i.e. reads) data from the source (file) and sends it to the program. Similarly, an output
199
stream takes data from the program and sends (i.e. writes) it to destination (file). Figure illustrates the use of input and output streams. The program connects and opens an input stream on the data source and then reads the data serially and writes data out serially. In both the cases, the program does not know the details of end points (i.e. source and destination).
200
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns 1 when the end of the stream is encountered. As you can see, it can throw an IOException. The following program demonstrates read( ) by reading characters from the console until the user types a q:
Java Stream Classes
Character Stream
Classes
Reader Classes
Writer Classes
Memory
File
Pipe
Memory
File
Pipe
//use a bufferedreader to read characters from the console Import java.io.*; Class BRRead
201
{ Public static void main(string [ ] args) Throws IOException { Char c; BufferedReader br = new BufferedReader (InputStreamReader(System.in)); System.out.println(Enter characters, q to quit); //read characters do { C=(char) br.read(); System.out.println( c); } While (c!=q); } } Here is a sample run: Enter characters, q, to quit. 123abcq 1 2 3 a b c q This output may look a little different from what you expected, because System.in is line buffered, by default. This means that no input is actually passed to the program until you press ENTER. As you can guess, this does not make read( ) particularly valuable for interactive, console input.
202
As you can see, it returns a String object.
The following program demonstrates BufferedReader and the readLine( ) method; the program reads and display lines of text until you enter the word stop: // Read a string from console using a BufferedReader. Import java.io.*; Class BRReadLines { Public staic void main(String args[ ]) Throws IOException { // Create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println(Enter lines of text); System.out.println(Enter stop to quit); do { Str = br.readLine( ); System.out.println(str); } while (!str.equals(stop)); } } The next example creates a tiny text editor. It creates an array of String objects and then reads in lines of text, storing each line in the array. It will read up to 100 lines or until you enter stop. It uses a BufferedReader to read from the console. // A tiny editor. import java.io.*; class TinyEdit { public staic void main(String args[ ]) throws IOException
203
{ // Create a BufferedReader using System.in BufferedReader br = new BufferedReader(newinputStreamReader(System.in)); String str[ ] = new String[100]; System.out.println(Enter lines of text); System.out.println(Enter stop to quit); for (int i=0;i<100;i++) { str[ i ] = br.readline( ); if (str[ i ] .equals (stop)) break; } System.out.println(\nHere is your file:); // display the lines for (int i=0;i<100;i++) { if (str[ i ] .equals (stop)) break; System.out.println(str[ I ]); } } } Here is a sample run: Enter lines of text. Enter stop to quit. This is line one. This is line two. Java makes working with strings easy. Just create String objects. Stop Here is your file: This is line one. This is line two. Java makes working with strings easy. Just create String objects.
Console output is most easily accomplished with print( ) and println( ), described earlier, which are used in most of the examples in this book. These methods are defined by the class PrintStream (which is the type of the object referenced by System.out). Even though System.out is a byte stream, using it for simple program output is still acceptable. However, a character-based alternative is described in the next section. Because PrintStream is an output stream derived from OutputStream, it also implements the lowlevel method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here: Void write(int byteval) throws IOException This method writes to the file the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write( ) to output the character A followed by a newline to the screen. //Demonstrate System.out.write( ). class writedemo { public static void main(string args[ ]) { int b; b = a ; System.out.write(b); System.out.write(\n); } } You will not often use write( ) to perform console output(lthough doing so might be useful in some situation), because print( ) and println( ) are substantially easier to use. Program to shows how to read a Java char primitive value from file using readChar method of Java DataInputStream class. import java.io.*; public class ReadCharFromFile { public static void main(String[ ] args) { String strFilePath = C://FileIO//readChar.txt;
205
try { FileInputStream fin = new FileInputStream(strFilePath); DataInputStream din = new DataInputStream(fin); char ch = din.readChar(); System.out.println(Char : + ch); din.close(); } catch(FileNotFoundException fe) { System.out.println(FileNotFoundException : + fe); } catch(IOException ioe) { System.out.println(IOException : + ioe); } } }
13.7 SUMMARY
In this chapter, we have discussed how to manage inputs and outputs. How to read characters, strings, and usage of print( ) and println( ) statements have been discussed. After going through this chapter, you will be able to
EXERCISES
1. 2. 3. 4. What is a file? Why do we require files to store data? What is a stream? How id the concept of streams used in Java? What are input and output streams? Explain them with illustrations? What is a stream class? How are the stream classes classified?
206
REFERENCES
1. 2. 3. 4. 5. 6 7 JAVATM- HOW TO PROGRAM, Deitel and Deital, Pearson Education Third Edition, 1999. JAVATM- 2, The Complete Reference, Patrick Naughton and Herbert Schildt, Tata Mc.Graw-Hill Third Edition, 1999. JAVATM- Programming Langauage, Sun Educational Services, Student Guides, April 2000. Programming with JAVA, Jogh R Hubbard, Mc.Graw-Hill, 1999. Programming with JAVA, E. Balaguruswamy. Flanagan.D Java in a Nutshell,OReilly & Assosiates, 1996. www.java.sun.com