You are on page 1of 218

KUVEMPU UNIVERSITY

INFORMATION TECHNOLOGY PROGRAMMES


Bachelor of Science in Information Technology - B.Sc. (IT) Master of Science in Information Technology - M.Sc. (IT)

B.Sc.(IT) - 4th Semester

BSIT - 42

Java Programming

Directorate of Distance Education

Kuvempu University

Shankaraghatta, Shimoga District, Karnataka

In col l aborati on w i th

Universal Education Trust


Banga l ore

II

Titles in this Volume : BSIT - 42 Java Programming

Prepared by UNIVERSAL EDUCATION TRUST (UET) Bangalore

First Edition : May 2005 Second Edition : December 2010 Third Edition : May 2012

Copyright by UNIVERSAL EDUCATION TRUST, Bangalore All rights reserved

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 :

Pragathi Print Communications


Bangalore - 20 Ph : 080-23340100

III

JAVA PROGRAMMING
(BSIT - 42)

: Contributing Authors :

Dr. S.N. Jagadeesha, M.E., Ph.D


Professor and Head Department of Computer Science & Engineering JNN College of Engineering Shimoga

Ravindra. S, M.Tech. (Networking & Internet Engg)


Lecturer Department of Computer Science & Engineering Jawaharlal Nehru National College of Engineering Shimoga

B.J. Sandesh, M.Tech., (CS&E)


Lecturer Department of Information Science & Engineering PES School of Engineering Bangalore

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

5.3 5.4 5.5 5.6 5.7

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

6.3 6.4 6.5

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

Chapter 8 CLASSES OBJECTS AND METHODS 105

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.4 9.5 9.6

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

pon completion of this chapter, you will be able to :

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.

BSIT 42 JAVA Programming

2 1.2 WHAT IS JAVA TECHNOLOGY?

Chapter 1 - The History of JAVA

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.

1.2.1 Primary Goals of Java Technology

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

The above goals are achieved by the following features


The java virtual machine Garbage collection Code security

1.3 APPLETS & APPLICATION


Java technologys first use was on internet. However ,it has rapidly grown into a general purpose, complex programming language. It is used as the language for creating a large applications.

BSIT 42 JAVA Programming

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.

1.4 THE HISTORY OF JAVA


At first glance, it may appear that Java was developed specifically for the World Wide Web. However, interestingly enough, Java was developed independently of the web, and went through several stages of metamorphosis before reaching its current status of de facto programming language for the World Wide Web. Below is a brief history of Java since its infancy to its current state. In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton (formerly the project leader of Suns Open Windows user environment), and several other individuals met in Aspen to discuss the ideas for the Stealth Project. The goal of the Stealth Project was to do research in the area of application of computers in the consumer electronics market. The vision of the project was to develop smart consumer electronic devices that could all be centrally controlled and programmed from a handheldremote-control-like device. Gosling began with C++, but soon after he was convinced that C++ was inadequate for this particular project. His extensions and modifications to C++ (also know as C++ ++ ), were the first step towards the development of an independent language that would fit the project objectives. He named the language Oak while staring at an oak tree outside his office window!. The name Oak was later dismissed due to a patent search, which determined that the name was copyrighted and used for another programming language and renamed Oak as Java . The major milestones in the development of java technology are listed in Table 1.1

Chapter 1 - The History of JAVA

Important Years in Java history

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

1996 1997 1998 1999 2000 2002 2004 2006 2010

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

Table 1.1 Major milestones

BSIT 42 JAVA Programming

1.5 BASIC FEATURES IN JAVA


The Java programming language is a high level language that can be characterized by all of the following buzz words. The fundamental forces that necessitates the invention of Java are Portability and Security . Other factors also play an important role in modeling the final form of the Java language. Lets briefly examine each of these words, with a view to better understanding what makes Java tick.

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

Chapter 1 - The History of JAVA

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.

BSIT 42 JAVA Programming

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.

1.6 HOW JAVA DIFFERS FROM C AND C++


To build a better language. Java was improved on C++. It has changed and improved upon the powerful and difficult C++ features. The following are the differences from C and C++ that exist in Java:

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.

8 1.7 JAVA & INTERNET

Chapter 1 - The History of JAVA

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.

1.8 JAVA DEVELOPMENT KIT(JDK)


JDK comes with a collection of tools that are used for developing and running a java programs. They include

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)

1.9 JAVA STANDARD LIBRARY (JSL)


It is a collection of hundreds of classes and methods. This is also known as application programming

BSIT 42 JAVA Programming

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.

1.10 HOW WILL JAVA TECHNOLOGY CHANGE MY LIFE?


We believe that Java technology will help you do the following:

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

Chapter 1 - The History of JAVA

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

Fu n d am en t als Of Ob ject Or ien t ed Pr o g r am m i n g

OBJECTIVES

fter going through this chapter you will be able to :

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.

BSIT 42 JAVA Programming

11

12

Chapter 2 - Fundamentals of Object Oriented

Before learning the oops concepts, we will see some of the features of programming approaches as mentioned below

2.2 PROGRAMMING APPROACHES


Computer programming (often shortened to programming or coding) is the process of designing, writing, testing, debugging / troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language. The code may be a modification of an existing source or something completely new. The purpose of programming is to create a program that exhibits a certain desired behaviour (customization). The process of writing source code often requires expertise in many different subjects, including knowledge of the application domain, specialized algorithms and formal logic. Since from the invention of computers many programming approaches have been tried for various applications. These include unstructured programming, procedural programming, modular programming and object oriented programming.

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).

BSIT 42 JAVA Programming

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.

Fig. 2.3: Procedural programming

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

Chapter 2 - Fundamentals of Object Oriented

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).

Fig. 2.4: Modular programming

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.

BSIT 42 JAVA Programming

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.

Fig. 2.5. Object Oriented Programming

Objects of the program interact by sending messages to each other.

2.3 WHAT IS OBJECT-ORIENTED PROGRAMMING?


Object-oriented programming derives from the way we think about day-to-day objects such as telephones, cars, etc. Programmers just like to use words like encapsulation and inheritance to confuse the average person when talking about object-oriented programming. The concept is actually quite simple since we can relate physical objects to understand how the process actually works.

Objects and Classes


Objects are key to understanding object-oriented technology. Object is a physical entity which represents a person, vehicle or a conceptual entity (thing in existence) like bank account, company etc.

16

Chapter 2 - Fundamentals of Object Oriented

Fig. 2.6 Representation of a class with object and fields

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.

BSIT 42 JAVA Programming

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

Chapter 2 - Fundamentals of Object Oriented

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

Fig. 2.7 Inheritance in java

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.

2.4 ADVANTAGES OF OOP


OOP offers several advantages to both the program designer and the user. The important advantages are,

BSIT 42 JAVA Programming

19

Reusability Elimination of redundant code and use of existing classes through inheritance. Thus provides economy of expression.

Modularity. Programs can be the built from standard working modules.

Security. Principle of information hiding helps programmer to build secure programs.

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.

Easy management Easy management of software complexity.

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.

Chapter 2 - Fundamentals of Object Oriented

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

Over v ie w Of JAVA Lan g u ag e

OBJECTIVES

fter completing this chapter, you will be able to :

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.

BSIT 42 JAVA Programming

21

22
Stand-alone applications

Chapter 3 - Overview of JAVA Language

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 Compiler Applet Type Application T ype

Java Enabled Web Browser

Java Interpreter

Output

Output

Fig. 3.1Two ways of using Java

3.2 SIMPLE JAVA PROGRAM


Here is a simple program that prints a line of text as output

BSIT 42 JAVA Programming

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.

Keyword Static and Void


You specify that the main ( ) method can be called without instantiating a particular instance of a class. The keyword static helps you do this. This is necessary because the main ( ) method is called by the Java interpreter before any objects are created. After specifying the keyword static, you specify the void keyword. This keyword indicates to the compiler that, the main ( ) method does not return a value.

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.

Println statements in Java


Notice that the main( ) method body also contains a statement for generating a specified output. The

24

Chapter 3 - Overview of JAVA Language

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

Welcome to the world of Java


There is a difference between the println ( ) method and the print ( ) method. a. When the println ( ) method is specified, the string parameters for the method are displayed. The output is followed by a new line. b. In the case of the print ( ) method, the string parameters are displayed but the output is not followed by a new line. To Compile and execute the code 1. Save the source code with the extension .java appended to the class name. ExampleOne.java 2. launch the source code by issuing the command javac ExampleOne.java 3. Execute by issuing the command Java ExampleOne 4. Check the output Welcome to the world of Java

3.3 JAVA PROGRAM STRUCTURE


As we have seen in the previous example, a Java program may contain many classes of which only one class defines a main method. Classes contain data members and methods that operate on the data members of the class. Methods may contain data type declarations and executable statements. To write a Java program, we first define classes and then put them together. A Java program may contain one or more sections as shown in the Fig.3.2.

BSIT 42 JAVA Programming

25
Suggested Optional Optional Optional Optional Essential

Documentation Section Package Statement Import Statements Interface Statements Class Definitions Main Method Class { Main Method Definition }

Fig. 3.2 General Structure of a Java program

Documentation Section
The documentation section comprises a set of comment lines giving the name of the program , the author and other details. 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.

Main Method Class


Since every Java stand-alone program requires a main method as its starting point, this class is the essential part of a Java program. A simple Java program may contain only this part. The main method creates objects of various classes and establishes communications between them.

26

Chapter 3 - Overview of JAVA Language

3.4 IMPLEMENTING A JAVA PROGRAM


Implementation of a Java application program involves a series of steps. They include creating the program , compiling the program, running the program

Creating the program


We can create a program using any text editor and we must save this program in the file called filename. Java where filename is the name of the class which includes the main method.

Compiling the program


To compile the program, we must run the Java compiler Javac with the name of the source file on the command line Javac filename.Java. Javac compiler creates a file called filename.class containing the byte codes of the program.

Fig. 3.3 Implementations of Java Program

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!

BSIT 42 JAVA Programming

27

3.5 MORE OF JAVA


Assume that we would like to compute and print the number is even or odd. /* Even Odd Number Example This Java Even Odd Number Example shows how to check if the given number is even or odd. */ public class FindEvenOrOddNumber { public static void main(String[] args) { //create an array of 10 numbers int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10}; for(int i=0; i < numbers.length; i++) { /* use modulus operator to check if the number is even or odd. If we divide any number by 2 and reminder is 0 then the number is even, otherwise it is odd.*/ if(numbers[i]%2 == 0) System.out.println(numbers[i] + is even number.); Else System.out.println(numbers[i] + is odd number.); } } } /*Output of the program would be 1 is odd number. 2 is even number. 3 is odd number. 4 is even number. 5 is odd number. 6 is even number. 7 is odd number. 8 is even number. 9 is odd number. 10 is even number. */

28
Sample program with multiple classes
class Room { float length; float breadth; void getdata (float a, float b) { length = a; breadth = b; } }

Chapter 3 - Overview of JAVA Language

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.

3.6 JAVA VIRTUAL MACHINE


All language compilers translate source code into machine code for a specific computer. Java compiler produces an intermediate code known as bytecode for a machine that does not exist. This machine is called the Java Virtual Machine and it exists only inside the computer memory. The process of compiling a Java program into bytecode which is also referred to as virtual machine code.

BSIT 42 JAVA Programming

29

Fig. 3.4 Process of Compilation

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.

3.7 JAVA TOKENS


Java Language includes four types of tokens. They are:

Identifiers Reserved Keywords Literals Operators

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

Chapter 3 - Overview of JAVA Language

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.

BSIT 42 JAVA Programming

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

fter going through this chapter, you will be able to :

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

Chapter 4 - Overview of JAVA Language

BSIT 42 JAVA Programming

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...

Chapter 4 - Overview of JAVA Language

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

Computer Data Storage


All software and data are stored and manipulated within the computer in bits. Values are calculated by multiplying 2 to the power of the number of bits: 28,216, and so on. * 21 = 1 * 22 = (2 * 2) = 4, and * 24 = (2 * 2 * 2 * 2) = 16 The Java programming language uses various data types to store different number of bits. Each type is based on 2 multiplied to a power equaling the number of bits. An 8-bit number has 28 possible values, or 256. The highest possible value of a number is: (2 to the power of [number of bits 1] 1 is subtracted at the end because zero is counted as positive. This is illustrated in Fig.4.1. and how to calculate the base 10 value of binary data in Fig.4.2.
Sign Bit: 0/1 7 -/+ values * Numbering of the bits starts at 0
Fig. 4.1 Determining Number of Possible Values, and Range of Values, for a Value

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

2 * 2 * 2 * 2 * 2 * 2 * 2 = -128 or 127 256 possible

BSIT 42 JAVA Programming

35
Value bits:

Sign Bit: 0/1 7 -/+ values 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

2 * 2 * 2 * 2 * 2 * 2 * 2 = -128 or 127 256 possible

* Numbering of the bits starts at 0

Fig. 4.2 Determining Number of Possible Values, and Range of Values, for a Value

4.3 DATA TYPES


Every variable in Java has a data type. Data types specify the size and), The various data types supported by Java are illustrated in Fig.4.3.

Data Types in Java

Primitive (Intrinsic)

Non-Primitive (Derived)

Numeric

Non-numeric

Classes

Arrays

Integer

Floating-point

Character

Boolean

Interface

Fig. 4.3 Data Types in Java

36
Integer Types

Chapter 4 - Overview of JAVA Language

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

1 Byte 2 Byte 4 Byte 8 Byte

Floating Point Types


There are two types for floating point numbers, float and double. They are used to store number with values to the right of the decimal point. Table.4.2 lists the floating point types with a few examples.

Type Float Double

Length

Range Inclusive

4 bytes 8 Byte

Approximately 3.40282347E+38F Approximately 1.79769313486231570E+308


Table.4.2 Floating Point Types

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)

BSIT 42 JAVA Programming

37

Java Boolean Example


/* This Java Example shows how to declare and use Java primitive Boolean variable*/ public class JavaBooleanExample { public static void main(String[ ] args) { boolean b1 = true; boolean b2 = false; boolean b3 = (10 > 2)? true :false; System.out.println(Value of boolean variable b1 is : + b1); System.out.println(Value of boolean variable b2 is : + b2); System.out.println(Value of boolean variable b3 is : + b3); } } Output would be Value of Boolean variable b1 is: true Value of Boolean variable b2 is: false Value of Boolean variable b3 is: true /* This Java Example shows how to declare and use Java primitive char variable */ public class JavaCharExample { public static void main(String[ ] args) { char ch1 = a; char ch2 = 65; /* ASCII code of A*/ System.out.println(Value of char variable ch1 is : + ch1); System.out.println(Value of char variable ch2 is : + ch2); } } Output would be Value of char variable ch1 is :a Value of char variable ch2 is :A

38 4.4 VARIABLES

Chapter 4 - Overview of JAVA Language

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 :

t ype variable1, variable 2,., variable N;

BSIT 42 JAVA Programming

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;

Giving values to variables


A variable must be given a value after it has been declared but before it is used in an expression. This can be achieved in two ways: 1. By using an assignment statement 2. By using a read statement

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:

type VariableName = Value;

Examples int char double finalValue yes total = 100; = X; = 75.36;

40

Chapter 4 - Overview of JAVA Language

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

4.5 SCOPE OF VARIABLES


Java variables are actually classified into three kinds: * Instance Variables * Class variables, and * Local variables Instance and class variables are declared inside a class. Instance variables are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each object. On the other hand, class variables are global to a class and belong to the entire set of objects that class creates. Variables declared and used inside methods are called local variables. They are called so because they are not available for use outside the method definition. Local variables can also be declared inside program blocks that are defined between an opening brace { and a closing brace }. These variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leaves a block, all the variables in the block will cease to exist. The area of the program where the variable is accessible (i.e., usable) is called its scope.

4.6 TYPE CASTING


The process of converting one data type to another is called casting.

Type variable1 = (type) variable2;


Examples Int m = 50;

BSIT 40 42 JAVA Programming

41

Byte n = (byte)m; Long distance = (long)m;

Program to demonstrate type casting of data types


public class conversion { public static void main(String[ ] args) { boolean t = true; byte b = 2; short s = 100; char c = C; int i = 200; long l = 24000; float f = 3.14f; double d = 0.000000000000053; String g = string; System.out.println(Value of all the variables like); System.out.println(t = + t ); System.out.println(b = + b ); System.out.println(s = + s ); System.out.println (c = + c); System.out.println (i = + i); System.out.println (l = + l); System.out.println (f = + f); System.out.println (d = + d ); System.out.println (g = + g ); System.out.println ( ); //Convert from boolean to byte. b = (byte) (t? 1:0); System.out.println (Value of b after conversion: + b); //Convert from boolean to short. s = (short) (t? 1:0); System.out.println (Value of s after conversion : + s); //Convert from boolean to int. i = (int) (t? 1:0); System.out.println (Value of i after conversion: + i);

42

Chapter 4 - Overview of JAVA Language

//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

BSIT 42 JAVA Programming

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.

0.001 +100 -45.6


7.

5 * 1.5 75.45E-2 -1.4e(+4)

RS 75.50 15.75 0.000001234

Which of the following are invalid variable names and why?

minimum doubles float

first.Name 3rd-row Sum Total

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.

Chapter 4 - Overview of JAVA Language

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

fter going through this chapter, you will be able to

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

BSIT 42 JAVA Programming

45

46 5.2 ARITHMETIC OPERATORS

Chapter 5 - Operators And Expressions

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)

Example x =1+ 2 x =7-4 x =4* 5 x = 21 / 3 x = 17 % 3 //x = 2

Table 5.1 Java arithmatic operators

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.

5.2.1 Integer Arithmetic


When both the operands in a single arithmetic expression such as x+y are integers, the expression is called an integer expression, and the operation is called integer arithmetic. Integer arithmetic always yields an integer value. In the following examples, if x and y are integers, then for x=12 and y=5 we get the following results: xy = 7 x + y = 17 x * y = 60 x / y = 2 (decimal part truncated) x % y = 2 (remainder of integer division)

BSIT 42 JAVA Programming

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)

5.2.2 Real Arithmetic


A arithmetic operation involving only real operands is called real arithmetic. A real operand may assume values either in decimal or exponential form. Modulus operator can also be applied to floating point data. The following program demonstrates the arithmetic operators. It also illustrates the difference between floating point division and integer division. Example Class basicEx { public static void main(String args[]) { System.out.pritln(Integer Arthamatic); Int a=1+1; Int b=a*3; Int c=b/4; Int d=c-a; Int e= -d; System.out.println(a = +a); System.out.println(b = +b); System.out.println(c= +c); System.out.println(d = +d); System.out.println(e= +e); System.out.pritln(\nfloating point Arthamatic);

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); } }

Chapter 5 - Operators And Expressions

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

5.2.3 Mixed-Mode Arithmetic


When one of the operands is real and the other is integer, the expression is known as mixed-mode arithmetic expression. If either operand is of the real type, then the other operand is converted to real and the real arithmetic is performed. The result will be a real Value. For example 25/10.0 produces the result 1.5 whereas 25/10 produces the result 2 More about mixed operations will be discussed later when we deal with the evaluation of expressions.

BSIT 42 JAVA Programming

49

5.2.4 String Concatenation


The plus sign, +, is used for numeric addition and it is also used to perform String concatenation if one of the operands is a String (i.e. an instance of the standard Java class String). This is the only operator that operates on non-primitive types. Because String manipulation is so prevalent in most computer programs, the Java designers decided to treat the String class special giving it this operator . If one or both operands of a + operator is a String then the other is coverted to a String and the result of the operation is a new String that contains the characters from both strings concatenated together with the characters from the left operand preceding the characters from the right operand.

5.2.5 Multiplication and Division in Java


Of course Java can also do multiplication and division. Since most keyboards dont have the times and division symbols you learned in grammar school, Java uses * to mean multiplication and / to mean division. The syntax is straightforward as shown below. class MultiplyDivide { public static void main (String args[]) { int i = 10; int j = 2; System.out.println(i is + i); System.out.println(j is + j); int k = i/j; System.out.println(i/j is + k); k = i * j; System.out.println(i * j is + k); } } Heres the result: % javac MultiplyDivide.java % java MultiplyDivide i is 10 j is 2 i/j is 5 i * j is 20

50

Chapter 5 - Operators And Expressions

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

5.3 ASSIGNMENT OPERATORS


Assignment operators are used to assign the value of an expression to a variable. We have seen the usual assignment operator, =. In addition, Java has a set of shorthand assignment operators which are used in the form

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:

BSIT 42 JAVA Programming

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

5.4 RELATIONAL OPERATORS


We often compare two quantities, and depending on their relation, take certain decisions. For examples, we may compare the age of two persons, or the price of two items, and so on. These comparisons can be done with the help of relational operators. For Example a < b or x < 20 where < denotes less than Containing a relational operator is termed as a relational expressions. The value of relational expressions is either true or false. For example, if x=10, then x < 30 is true while 20 < x is false. Java supports six relational operators in all. These operators and their meaning are as shown the below table 5.3.

Operator Use > Op1 > op2


>= < <= == !=

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

Chapter 5 - Operators And Expressions

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

Table 5.4 simple relational expressions and their values

* 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) {

BSIT 42 JAVA Programming

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

Chapter 5 - Operators And Expressions

5.5 LOGICAL OPERATORS


A relational operator compares two values and determines the relationship between them. For example, != returns true if the two operands are unequal. This table summarizes Javas relational operators: Relational operators often are used with the conditional operators to construct more complex decisionmaking expressions. One such operator is &&, which performs the boolean and operation. For example, you can use two different relational operators along with && to determine if both relationships are true. The && operator will return true only if both operands are true. the left-hand operand for && is false and the return value of && can be determined without evaluating the right-hand operand. In such a case, Java will not evaluate the right-hand operand. The operator & is similar to && if both of its operands are of boolean type. However, & always evaluates both of its operands and returns true if both are true. Likewise, | is similar to || if both of its operands are boolean. This operator always evaluates both of its operands and returns false if they are both false. The following table 5.5 shows the logical operators
Operator Use Op1 && op2 &&
|| ! op1 | | op2 ! op

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.

Table 5.5 Logical operation

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

Table 5.6: Usage of && and || operatore

&& 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

BSIT 42 JAVA Programming

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

5.6 INCREMENT AND DECREMENT OPERATORS


Java has two very useful operator like increment and decrement operator ++ and The operator ++ adds 1 to the operand while subtracts 1. Both are unary operators and are used in the following form: ++m; or m++; m or m; ++m is equivalent to m = m + 1; (or m += 1;) m; is equivalent to m = m 1; (or m -= 1;) We use the increment and decrement operators extensively in for and while loops. Consider the following: m=5; y = ++m;

56

Chapter 5 - Operators And Expressions

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--

Table 5.7 Usage of increment and decrement operators

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); } }

BSIT 42 JAVA Programming

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

5.7 CONDITIONAL OPERATOR


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

58
exp1 ? exp2 : exp3

Chapter 5 - Operators And Expressions

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

5.8.1 Shift and Logical Operators


A shift operator allows you to perform bit manipulation on data. The table 5.8 summarizes the shift operators available in the Java programming language.

Operator Use
>> << >>> op1 >> o p2 op1 << op2 op1 >>> op2

Operation shift bits of op1 right by distance


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

BSIT 42 JAVA Programming

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

op1 ^ op2 ~op2

Operation bitwise and bitwise or bitwise xor bitwise complement

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

Chapter 5 - Operators And Expressions

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.

BSIT 42 JAVA Programming

61

5.8.2 Dot Operator


The dot operator(.) is used to access the instance variables and methods of class objects. Examples: person1.age person1.salary() // Reference to the variable age // Reference to the method salary()

It is also used to access classes and sub-packages from a package.

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

5.8.4 Arithmetic Expressions


An arithmetic expression is a combination of variables, constant, and operators arranged as per the syntax of the language. Java can handle any complex mathematical expressions. Some of the examples of Java expressions are shown in the below table. Remember that Java does not have an operator for exponentiation.

5.8.5 Precedence of Arithmetic Operators


An arithmetic expression without any parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in Java:

62
High priority Low priority * / % + -

Chapter 5 - Operators And Expressions

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

BSIT 42 JAVA Programming

63

5.8.6 Operator Precedence and Associativity


Each operator in Java has a precedence associated with it. This precedence is used to determine how an expression involving more than one operator is evaluated. There are distinct levels of precedence and an operator may belong to one of the levels. The operators at the higher level of precedence are evaluated first. The operators of the same precedence are evaluated either from left to right or from right to left, depending on the level. This is known as the associatively property of an operator. The following table 5.8 provides a complete list of operators, their precedence levels, and their rules of association.
Operator . () [] ++ -! ~ (type) * / % + << >> >>> < <= > >= Instance of == != & ^ | && || ?: = Op= Description Member selection Function call Array element reference Unary minus Increment Decrement Logical Negation Ones Compliment Casting Multiplication Division Modulus Addition Subtraction Left shift Right shift Right shift with zero fill Less than Less than or equal to Greater than Greater than or Equal to Type comparison Equality Inequality bitwise and bitwise x or bitwise or Logical and Logical or Conditional operator Assignment operator Shorthand assignment Associativity Rank Left to right 1

Right to left

Left to right

Left to right 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

Table 5.8: List of operators & there precedence levels

64 5.9 MATHEMATICAL FUNCTIONS

Chapter 5 - Operators And Expressions

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;

BSIT 42 JAVA Programming

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

Chapter 5 - Operators And Expressions

// 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));

BSIT 42 JAVA Programming

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

Chapter 5 - Operators And Expressions

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.

BSIT 42 JAVA Programming

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

Chapter 5 - Operators And Expressions

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

and the optimal Time Between Orders

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

Decisio n Making an d Bran ch in g Ob ject ives

fter going through this chapter, you will be able to understand the

If statement Switch statement Conditional operator statement and their applications

6.1 INTRODUCTION
Java language possesses decision making capabilities and supports the following statements known as control or decision-making statements.

if statement switch statement Conditional operator statement

6.2 DECISION MAKING WITH IF STATEMENT


The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. It takes the following form: BSIT 42 JAVA Programming

71

72
if (test expression) { statement block; }

Chapter 6 - Decision Making and Branching Objectives

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.

Simple if statement if...else statement Nested if...else statement else if ladder

6.2.1 Simple If Statement


The general form of a simple if statement is if (test expression) { statement-block; } statement-x; The statement-block may be a single statement or a group of statements. If the test expression is true, the statement-block will be executed; otherwise the statement-block will be skipped and the execution will jump to statement-x, remember, when the condition is true both the statement-block and the statementx are executed in sequence. The flowchart is depicted in Fig. 6.1

BSIT 42 JAVA Programming

73

Fig. 6.1 Flow-chart for simple if statement

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

Chapter 6 - Decision Making and Branching Objectives

6.2.2 THE IFELSE STATEMENT


The if....else statement is an extension of the simple if statement. The general form is if (test expression) { True-block statement(s) } else { False-block statement(s) } statement-x If the test expression is true , then the true-block statement(s), immediately following the if statement are executed; otherwise the false-block statement(s) executed. In either case, either true-block or falseblock will be executed. The flowchart for if-else statement is given in Fig. 6.2

Fig. 6.2 Flow chart for the if-else statement

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

BSIT 42 JAVA Programming

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

Chapter 6 - Decision Making and Branching Objectives

6.2.3 Simple If...Else Statements


When a series of decisions are involved, we may have to use more than one if.....else statement in nested form as follows:

Fig. 6.3 Nesting of IF-ELSE Statements

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); }

BSIT 42 JAVA Programming

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

78 6.2.4 The Else If Ladder

Chapter 6 - Decision Making and Branching Objectives

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)

Fig. 6.4 General form of else-if ladder

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

BSIT 42 JAVA Programming

79

Fig. 6.5 Flowchart for the else-if ladder

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;

Chapter 6 - Decision Making and Branching Objectives

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); } }

BSIT 42 JAVA Programming

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.

6.3 SWITCH STATEMENT


The second branching statement in Java is the switch statement, which is introduced in this section. The switch is used far less often than the if statement, but it is sometimes useful for expressing a certain type of multi-way branch. A switch statement allows you to test the value of an expression and, depending on that value, to jump to some location within the switch statement. The expression must be either integer-valued or charactervalued. It cannot be a String or a real number. The positions that you can jump to are marked with case labels that take the form: case constant This marks the position the computer jumps to when the expression evaluates to the given constant. As the final case in a switch statement you can, optionally, use the label default:, which provides a default jump point that is used when the value of the expression is not listed in any case label. A switch statement has the form:

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

Chapter 6 - Decision Making and Branching Objectives

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

Fig. 6.6 Selection process of the Switch Statement

The following example illustrates how case statements are executed if break is not used to terminate the execution of the statements.

BSIT 42 JAVA Programming

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!

Chapter 6 - Decision Making and Branching Objectives

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.

The following example illustrates Nested switch statements


public class NestedSwitchExample { public static void main(String[] args) { int i = 0; int j = 1; switch(i) { case 0: switch(j) { case 0: System.out.println(i is 0, j is 0); break ;

BSIT 42 JAVA Programming

85
case 1: System.out.println(i is 0, j is 1); break ; default: System.out.println(nested default case!!);

} break ; default: System.out.println(No matching case found!!); } } } Output would be, i is 0, j is 1

6.4 THE ? : OPERATOR IN JAVA


The value of a variable often depends on whether a particular boolean expression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the maximum of two quantities. In Java you might write if (a > b) { max = a; } else { max = b; } Setting a single variable to one of two states based on a single condition is such a common use of ifelse that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this: max = (a > b) ? a : b; (a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.

86 6.5 SUMMARY

Chapter 6 - Decision Making and Branching Objectives

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

BSIT 42 JAVA Programming

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:

Purchase Amount 0-100 101-200 201-300 Above 300

Mill Cloth 5.0% 7.5% 10.0%

Discount Handloom Items 5.0% 7.5% 10.0% 15.0%

Chapter 7

LOOPING

OBJECTIVES

fter going through this chapter, you will be able to write simple programs using the following loop constructs

While loop do loop for loop, continue and break statements

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

BSIT 42 JAVA Programming

89

Fig. 7.1 Distinction between pre-test and post-test loops

7.2 THE WHILE LOOP


To perform an action repeatedly, Java provides certain loop statements. One of the loop statements is the while statement. The while statement contains a condition and a loop body. The condition is enclosed within parentheses. The syntax and the flow diagram are given in Fig 7.2

Fig. 7.2. Syntax and flow diagram of while loop

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.

BSIT 42 JAVA Programming

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

Fig. 7.3: Syntax and Flow-chart of do-while statement

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

7.4 FOR STATEMENTS


To manage iterative actions, Java provides the for statement as an efficient alternative to the while statement. The for statement creates a loop in which a set of statements is repeatedly executed until the

BSIT 42 JAVA Programming

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); } }

Fig. 7.4. Flow-chart for the For loop

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

BSIT 42 JAVA Programming

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

7.4.1. Additional Features of the for loop

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);

BSIT 42 JAVA Programming

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

For example for(x=(m+n)/2;x>0;x=x/2)

7.4.2. Nested for loops


Nesting of loop i.e., One for statement within another for statement is allowed in java and is illustrated in Fig. 7.6.
for (i=1; i<10;i++) { ----------------------------------------------------------for (j=0; j<10;j++) { ----------------------------------------------------------} ------------------------------------------------------------}

Fig. 7.6 Nested for loops

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++) {

BSIT 42 JAVA Programming

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

7.5 CONTINUE AND BREAK STATEMENTS IN JAVA


In certain situations, it may be necessary for the flow of control to exit a loop statement and start the next iteration of the loop statement. An example of such a situation is a password verification program where the user is given three chances to enter the correct password. If the user enters an incorrect password, the counter variable in the program is incremented and the control is returned to the start of the loop statement. This saves time because the remaining statements in the loop will not be executed. For this purpose, Java provides the continue statement. The continue statement stops the current iteration of a loop and immediately starts the next iteration of the same loop. When the current iteration of a loop stops, the statements after the continue statement in the loop are not executed. The continue statement is written as continue;. You can use the continue statement in the while, do-while, and for statements but not in the switch statement. Use of continue statements is illustrated in the following program. // The program displays all even numbers between 1 and 20 class EvenNum20 { public static void main (string [ ] args) { int j,k; for (j =1, k= 0; j<=20; j++)

BSIT 42 JAVA Programming

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

Break statement in Java:


By using break, we can force immediate termination of loop, by passing the Conditional expression and any remaining code in the body of the loop. When a Break statement is encountered inside the loop, the loop is terminated and program control resumes the next statement following the loop.

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:

switch statement while loop do-while loop for loop

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.

BSIT 42 JAVA Programming

103

The break statement is written as break;

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

Classes Ob ject s An d Met h o d s

OBJECTIVES

fter going through this chapter, you will be able to

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

Chapter 8 - Classes Objects And Methods

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 .

8.2.1 Variables and Methods


In essence a class definition is very simple. There are just two kinds of things that you can include in a class definition:

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.

BSIT 42 JAVA Programming

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

Chapter 8 - Classes Objects And 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:

Start the engine Stop the engine Speed up Change gear

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()); }

BSIT 42 JAVA Programming

109

OUTPUT of the above given Java Class Example would be : Hello Visitor

8.3 ADDING VARIABLE TO CLASS


class class _name { variables name; }

Class box { double width; double height; double length; }

Class Account { int acc_no; string name; float balance; }

Class motorcycle { string make; string color; Boolean engine_on }

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.

Adding methods to class


A method is a self-contained block of code that has a name, and has the property that it is reusable i.e the same method can be executed from as many different points in a program as you require When we specify the return type for a method, you are defining the type for the value that will be returned by the method when we execute it. The method must always return a value of this type. To define a method that does not return a value, you specify the return type as void The parameters to a method appear in its definition between parentheses following the method name. These specify what information is to be passed to the method when you execute it. Your methods do not

110

Chapter 8 - Classes Objects And Methods

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;

BSIT 42 JAVA Programming

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;

// Radius of a sphere // 3D coordinates // of the center // of a sphere

// 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.

// Return current object count

112

Chapter 8 - Classes Objects And Methods

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 ( ); ... }

Returning from a Method


To return a value from a method when its execution is complete you use a return statement, for example: return return_value; // Return a value from a method After executing the return statement, the program continues from the point where the method was called. The value, return_value, that is returned by the method, can be any expression that produces a value of the type specified for the return value in the declaration of the method. Methods that return a

BSIT 42 JAVA Programming

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

The Parameter List


The parameter list appears between the parentheses following the method name. This specifies the type of each value that can be passed as an argument to the method, and the variable name that is to be used in the body of the method to refer to each value passed. The difference between a parameter and an argument is sometimes confusing because people often, incorrectly, use them interchangeably. We will try to differentiate them consistently, as follows:

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

Chapter 8 - Classes Objects And Methods

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 {

BSIT 42 JAVA Programming

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;

Chapter 8 - Classes Objects And Methods

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

8.4 INTRODUCTION TO OBJECTS


Objects are at the heart of object-oriented technology. If we think of an object in the real world such as a car then we can describe a car by its state and its behavior. The state of the car includes the current speed, the type of transmission, whether it is two-wheel or four-wheel drive, whether the lights are on, the current gear etc.. The behavior of a car includes turning, braking and accelerating. As with real-world objects, software objects have state and behavior. In programming terms the state of an object is determined by its data (variables); the behavior by its methods. Thus a software object combines data and methods into one unit.

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.

BSIT 42 JAVA Programming

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

Chapter 8 - Classes Objects And Methods

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,

BSIT 42 JAVA Programming

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

Chapter 8 - Classes Objects And Methods

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); } }

BSIT 42 JAVA Programming

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; }

Chapter 8 - Classes Objects And Methods

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 ); } }

8.5 DEFINING METHODS


A method is a group of programming language statements that are given a name. A method is associated with a particular class. The syntax of a method is

BSIT 42 JAVA Programming

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

Chapter 8 - Classes Objects And Methods

Creating Instances and sending messages to objects


Instances of a class are created using new. Messages can be sent to an object to ask that object to perform a particular action, e.g. s1.setMark(70). class TestStudent { public static void main(String [ ] args) { Student s1=new Student(fred); s1.setMark(70); int m= s1.getMark(); s1.chooseOption(java); system.out.println(Option is + s1.getOption()); system.out.println(Mark is + m); } //main } //TestStudent

Overloading the Methods


Java, along with several other programming languages, allows you to reuse a method name for more than one method. In some circumstances, you might want to write several methods in the same class that do basically the same job with different arguments. (Compare to overriding methods.)

BSIT 42 JAVA Programming

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); } }

Chapter 8 - Classes Objects And Methods

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.

BSIT 42 JAVA Programming

127

8.6 INHERITANCE: EXTENDING CLASSES


So far we have dealt with single class programs. We will declare class and then write statements according to each program. The properties of each class is available to that class only. Inheritance refers to the properties of a class being available to other classes as well. The original class is called Base Class and Derived classes are classes created from the existing class (Base Class). It will have all the features of the base class. The concept of Inheritance is very important in Object oriented programming languages. It simplifies code writing thus making programs easier to maintain and debug. It allows reusability of the code

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

Chapter 8 - Classes Objects And Methods

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.

BSIT 42 JAVA Programming

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 }

Multi Level Inheritance


It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for its parent class and this parent class works as the child class for its just above ( parent ) class. Multilevel inheritance can go up to any number of level. class A { int x; int y; int get(int p, int q) { x=p; y=q; return(0); } void Show() { System.out.println(x); } }

class B extends A { void Showb() { System.out.println(B); } }

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

Chapter 8 - Classes Objects And Methods

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.

BSIT 42 JAVA Programming

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

Chapter 8 - Classes Objects And Methods

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.

8.7 ADVANCED CLASS FEATURES


Static Keyword
Static keyword is used to declare members(attributes, mehods, and inner classes) that are associated with the class rather than the instance of the class.

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()

BSIT 42 JAVA Programming

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
} }

Chapter 8 - Classes Objects And Methods

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

The Final Keyword


Final variable and methods All methods and variables can be overridden by default in subclasses. If we wish to prevent the subclasses from overriding the members of the superclass, we can declare them as final using the keyword final as a modifier. Example: final int size = 100; final void showstatus( ) {} Making a method final ensures that the functionality defined in this method will never be altered in any way. Similarly, the value of a final variable can never be changed. Final variables, behave like class variables, and they do not take any space on individual objects of the class. Final classes Sometimes we may like to prevent a class being further sub classed for security reasons. A class that cannot be subclassed is called a final class. This is achieved in java using the keyword final as follows. final class aclass {..} final class bclass extends someclass {}

BSIT 42 JAVA Programming

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.

Abstract methods and classes


An abstract class is a class that is declared abstractit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon) We have seen that by making a method final we ensure that the method is not redefined in a subclass. That is, the method can never be subclassed. Java allows us to do something that is exactly opposite to this. That is, we can indicate that a method must always be redefined in a subclass, thus making overriding compulsory. This is done using the modifier keyword abstract in the method definition. example: abstract class shape .. abstract void draw(); ...... .. When a class contains one or more abstract methods, it should also be declared abstract as shown in the example above. While using abstract classes, we must satisfy the following conditions:

136

Chapter 8 - Classes Objects And Methods

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 Public Protected Private

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

BSIT 42 JAVA Programming

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

Name of the depositor

138

Chapter 8 - Classes Objects And Methods

Account Number Type of account Balance amount in the account

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

fter going through this chapter, you will be able to answer

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);

9.2 ONE-DIMENSIONAL ARRAY


A list of items can be given one variable name using only one Subscript. And such a variable is called a single-subscripted variable or a one dimensional array. BSIT 42 JAVA Programming

139

140

Chapter 9 - Arrays And Strings

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).

Fig. 9.1 One dimensional array

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

Array[0] Array[1] Array[2] Array[3] Array[4]


Fig. 9.2 Memory allocation for an array

9.3 CREATING AN ARRAY


Like any other variables, arrays must be declared and created in a computer memory before they are used. Creation of array involves three steps.

Declare the array

BSIT 42 JAVA Programming

141

Create memory locations Put values into the memory locations

9.3.1. Declaration of Array


To declare an array we must indicate the type of the components and the name we wish to give the array. Arrays in java can be declared in the following form Form 1 Type arrayname[ ]; Form 2 Type[ ] arrayname; For example to declare an array called intarray, elements are integers and would require the declaration: int intarray[ ]; or int [ ] intarray; The square brackets [ ] indicate that this is an array declaration and hence is defining a reference variable. After this declaration the memory location holding the reference associated with intarray will hold null and no memory will have been allocated to hold the elements of the array.

9.3.2 Initialization of Array


Once the array has been declared it must be initialized before it can be used. Initializing an array specifies the number of elements that are in the array and allocates memory space for these elements. It is also possible to initialize the elements of the array. The new statement is used to specify the number of elements in the array and to allocate space for the elements. Thus to set the size of the array intarray declared above to be 10 and allocate space for its elements would require: Intarray = new int[10]; Or both the statement can be combined into one statement as follows int intarray [] = new int[10];

142
Diagrammatically this can be represented as follows:

Chapter 9 - Arrays And Strings

Fig. 9.3 Setting the size of an array

There are three important points to note in the above:

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.

BSIT 42 JAVA Programming

143

The effect of this declaration and initialization is illustrated in Fig. 9.4.

Fig. 9.4 Array formation for days in month

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};

Summary of declaring and initializing the array

type[ ] A;

Declares A as an array variable of type. No storage allocated for the elements of A. Reference variable for A holds null.

type[ ] A = new type[size];

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.

type[ ] A = { value, value, .... , value};

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.

A = new type[]{ value, value, .... , value};

144

Chapter 9 - Arrays And Strings

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

BSIT 42 JAVA Programming

145

Accessing a size of the array


Associated with an array is a variable which holds the number of elements in the array. This variable is called length and is accessed by adding. Length to the array name. Thus given the array declaration: int [ ] arrayOfInt = new int [20] The length of the array is given by arrayOfInt.length Thus to set the each element of the array example equal to its index we could write the code for ( int i = 0; i < arrayOfInt.length; i++) arrayOfInt [i]= i; Example: public class ArrayDemo { public static void main(String[ ] args) { int[] anArray; // declare an array of integer anArray = new int[10]; // create an array of integers // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) { anArray[i] = i; system.out.print (anArray[i] + ); } System.out.println(); } } Output : 0 1 2 3 4 5 6 7 8 9

146

Chapter 9 - Arrays And Strings

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

9.4 PRIMITIVE AND REFERENCE DATA TYPES


Data types fall into two categories namely: primitive and reference. You have already seen the primitive types Boolean, char, int and double. A variable of primitive type contains a single value of the appropriate size and format for its type. For example a variable of type int contains an integer occupying four bytes. In contrast the value stored in memory for a reference variable is a reference to the actual value or set of values represented by the variable. This reference is not the actual information itself but is a pointer to where the information can be found. For example, a persons address furnishes a way to find them but is not the actual person. When a primitive variable is declared, memory space is allocated for it, however no value is assigned to that memory space until the variable is initialized.

BSIT 42 JAVA Programming

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.

9.5 TWODIMENSIONAL ARRAY


A two-dimensional array is a sequence where the elements are themselves sequences. Each sequence represents one row of the matrix. The rows of the matrix may have different dimensions, therefore matrices are not necessarily rectangulars.

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;

Chapter 9 - Arrays And Strings

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.

Implementation of two-dimensional array


A two dimensional array is implemented as an array of one dimensional arrays. This is not as awful as you might think. It is an extension of what you already know about one dimensional arrays of objects. The declaration int[ ][ ] myArray; // 1. declares a variable myArray which in the future may refer to an array object. Each slot of the array may be a reference to an int[ ] object (but so far there are no arrays.) At this point, nothing has been said about the number of rows or columns. To create an array of 3 rows do this: myArray = new int[3][ ] ; // 2. Now myArray refers to an array object. The array object has 3 slots (elements.) Each slot may refer (in the future) to an array of int. However none of the slots yet refer to an object. They are initialized to null. One way to create row 0 is this: myArray[0] = new int[3] ; // 3. This creates a 1D array object and puts its reference in slot 0 of myArray. The elements of the 1D array are initialized to 0. A previously constructed 1D array can be assigned to a row: int[ ] x = {0, 2}; int[ ] y = {0, 1, 2, 3, 4} ;

BSIT 42 JAVA Programming

149

myArray[1] = x ; myArray[2] = y ; // 4.

Fig. 9.5. Creation of two dimensional array

150
2D Array of int

Chapter 9 - Arrays And Strings

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

Row 0 1 2 3 4 5 6 Grade table

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 ); } }

BSIT 42 JAVA Programming

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.

int value = (gradeTable[ 6 ][ 2 ] + 2) / 2 ; // puts 40 into value

9.6 STRINGS IN JAVA


A special kind of array is the string which is essentially an array whose elements are of the type char. Thus the string: java can be thought of as the character array:{j, a, v, a}.The need for string data items in computer programming is so frequent that many programming languages provided a predefined string type. Java, while remaining with the concept of a string being an array of characters, does not do this; instead it provides a predefined class called String. We use this in the same manner that we might use any other predefined class. For example we might declare an instance of the String class as follows: String name = new String(); However, in Java, instances of the class string are always constants, i.e. there value is fixed on construction. Thus to assign a value to the instance name we must do this when it is created. Consider the code given in program 1. Here we have created a 4 element array, called data of characters. We then used this array as the argument for the String constructor to create a (constant) data item called name which has the value java which is itself a character array.

152

Chapter 9 - Arrays And Strings

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

BSIT 42 JAVA Programming

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.

Fig. 9.6 A reference to a String object.

If we now execute the statement: str = Wells; we get the picture as shown in the Fig. 9.7.

Fig. 9.7 A reference to a String object after assignment

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

Chapter 9 - Arrays And Strings

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.

9.6.2. String Methods


The string class includes several methods that compares strings. Equals( ) method: To compare two strings for equality, use equals(). It has the general form: Boolean equals(object str); Here, str is the string object being compared with the invoking String object. It returns true if the string contains the same characters in the same order and false Otherwise.

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

Class equalsdemo { public static void main(String args[ ]) { String s1=Hello;

BSIT 42 JAVA Programming

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

Chapter 9 - Arrays And Strings

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();

BSIT 42 JAVA Programming

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.

Concatenation of two strings


String manipulation is something we do quite often in our applications . One of the simplest methods to concatenate two Strings is by using the + operator. To append String s2 to s1 we simply use: s1 += s2 But Java provides more ways for concatenating Strings. The String class contains a instance method named concat(String s). To add a new String to a existing String we would code something like this: s1.concat(s2); public class Test { public static void main(String arg[ ]) { //defining two strings and printing them out String s1 = new String(sachin); String s2 = new String(tendulkar); System.out.println(First String: + s1); System.out.println(Second String: + s2); //adding the second string to the first and printing result s1 = s1.concat(s2); System.out.println(Concatenated: + s1); } }

158
Output First String : Sachin Second String : Tendulkar Concatenated : Sachin Tendulkar

Chapter 9 - Arrays And Strings

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) );

BSIT 42 JAVA Programming

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

Chapter 9 - Arrays And Strings

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

BSIT 42 JAVA Programming

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

Chapter 9 - Arrays And Strings

Explain the methods : 1. 2. 3. Trim Substring Length

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

fter going through this chapter, you will be able to

Define a thread Creation of a thread Describe the usefulness of thread

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.

10.2 THREAD FUNDAMENTALS


In concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important. A computer system normally has many active processes and threads. This is true even in systems that only have a single execution core, and thus only have one thread actually executing at any given moment. Processing time for a single core is shared among processes and threads through an OS feature called time slicing. Its becoming more and more common for computer systems to have multiple processors or processors with multiple execution cores. This greatly enhances a systems capacity for concurrent execution of processes and threads but concurrency is possible even on simple systems, without multiple processors or execution cores.

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.

BSIT 42 JAVA Programming

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.

10.2.1 Advantages of Multithreading over Multitasking process


Processes are heavy weight tasks and require their own separate address space. Inter process communication is expensive and limited context switching from one process to other is costly. On the other hand, threads are light weight and share the same address space. Inter-thread communication is inexpensive. Context switching from one thread to the other is at low cost.

10.3 THE JAVA THREAD MODEL


Single threaded systems use an approach called an event loop with polling. In this model, a single thread of control runs in an infinite loop, polling a single event queue to decide what to do next. Once this polling mechanism returns with, say, a signal that a network file is ready to be read, then the event loop dispatches control to the appropriate event handler. Until this event handler returns nothing else can happen. This wastes CPU time. The benefit of Javas multithreading is that the main loop/polling mechanism is eliminated. One thread can pause without stopping other parts of the program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere. When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run.

166 10.3.1 Thread States: Life Cycle Of A Thread

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.

Fig. 10.1 State Transition diagram of a Thread

BSIT 42 JAVA Programming

167

10.3.2. Context Switching


A thread is assigned a priority that determines how that thread should be treated with respect to others. Thread priorities are integers that specify the relative priority of one thread to another. Every Java thread has a priority in the range Thread.MIN PRIORITY (a constant of 1) and Thread.MAX PRIORITY (a constant of 10). By default, each thread is given priority Thread.NORM-PRIORITY (a constant of 5). Each new thread inherits the priority of the thread that creates it. Thread priority is used to decide when to switch from one running thread to the next. This is called a context switch. The rules for context switching are simple.

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.

10.4 MAIN THREAD


When a java program starts, one thread begins running immediately. This is usually called the main thread of the program, because it is the one that is executed when the program begins. The main thread is important for two reasons:

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.

The main thread is controlled through a Thread object.

10.5 NAMING THE THREADS


Names can consist of any valid Java string. Naming the threads help to distinguish one thread from another and enables a parent process to query a thread for its name. A thread can be assigned a name at creation time or at any point thereafter. Threads can also be renamed at any time. To assign a name to a thread at creation time, use a Thread constructor that accepts a string as an additional argument, for ex., Thread myThread = new Thread(this ,first thread); In this example, the thread is instantiated by new operator and assigned a name first thread.

168 10.5.1 THE getName METHOD

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());

10.5.2 THE setName METHOD


You can set or change a thread name after creation using the setName method. The parent process, the thread itself, or any other method that has access to the thread object can do this. Following is an example of changing a thread name using setName: myThread.setName(second thread); This example changes the name of the thread from first thread to second thread. Example: class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println(Current thread : + t); t.setName(MyThread); System.out.println(After name change: +t); try { for(int n=5;n>0;n) { System.out.print(n); Thread.sleep(1000); }

BSIT 42 JAVA Programming

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

10.6 CREATING THREADS


To create classes that make use of threads, you can extend the class Thread or implement the interface Runnable. Both yield the same result. By implementing Runnable, existing classes can be converted to threads without having to change the classes on which they are based.

10.6.1 Extending the Thread Class


We can make our class runnable as a thread by extending the class java.lang.Thread. This gives us access to all the thread methods directly.It includes the following steps 1. Declere the class extending the Thread class 2. Implement the run method that executes the sequence of code that the thread will execute. 3. create the thread object and call the start method to initiate the thread execution Declaring the class: The thread class can be extended as follows Class MyThread extends Thread { ----------------------------------------} Now we have a new type of thread MyThread

170 10.6.2 Implementing the Run() Method

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.

10.6.3 Starting New Thread


To actually create and run an instance of our thread class, we must write the following MyThread aThread = new MyThread(); AThread.start(); The first line instantiates a new object of class MyThread. This statement just creates the object. The thread that will run this object is not yet running. The thread is in the newborn state. The second line calls the start() method causing the thread to move into the runnable state. The java runtime will schedule the thread to run by invoking its run() method. Now the thread is said to be in the running state. Class A extends Thread{ public void run(){ for(int i=1; i<=5;i++) { System.out.println(\t from Thread A : i= +i); } System.out.println(Exit from A); } }

BSIT 42 JAVA Programming

171

class ThreadTest{ public static void main(String args[]) { new A().start(); } }

10.6.4 Implementing The Runnable Interface


We can create threads in two ways: one by using the extended Thread class and another by implementing the runnable interface. We have already discussed in detail how the thread class is used for creating and running the threads. In this section, we shall see how to make use of the Runnable interface to implement threads. The Runnable interface declares run() method that is required for implementing threads in our program. This is done as follows: 1. Declare the class as implementing the Runnable interface. 2. Implement the run() method. 3. Create a thread by defining an object that is instantiated form this runnable class as the target of the thread. 4. Call the threads start() method to run the thread Following program illustartrates the implementation of the above steps. In main method , we first create an instance of x and then pass this instance as the initial value of the object threadX(an object of Thread class).Whenever ,the new thread threadx starts up, its run() method calls the run() method of the target object supplied to it. Here the target object is runnable. Class x implemtns Runnable { public void run() { for(int i=1; I<=5 i++) { System.out.println(\t threadX: +I); } System.out.println(End of ThreadX);

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); } }

BSIT 42 JAVA Programming

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

fter going through this chapter, you will be able to

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.

BSIT 42 JAVA Programming

175

176

Chapter 11 - Packages & Interfaces

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.

11.2 CREATING PACKAGES


Creating a package is quite easy. First declare the name of the package using the package key word followed by a package name. This statement defines a name space in which classes are stored. It is followed by package definition. Here is an example. Package first package // package declaration

Public class First class { }

// 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.

11.3 PROCEDURE TO CREATE OUR OWN PACKAGE


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

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.

BSIT 42 JAVA Programming

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.

11.4 ACCESSING A PACKAGE


A Java system package can be accessed either using a fully qualified class name or through the import statement. Import statement is used when 1. There are too many references to a particular package 2. When the package name is too long. The general form of import statement for searching a class is as follows import package 1[package 2] [package 3], class name; where package1 is the name of the top level package, package2 is the name of package inside package1 and so on. Finally, class name is specified explicitly. Example : import firstPackage.SecondPackage.Myclass ; Alternative Approach : import.Package.*; In the above statement, Packagename can denote a single package or a hierarchy of packages. The star(*) indicates that the compiler should search this entire package hierarchy. We can access all classes contained in the above package directly.

11.5 USING A PACKAGE


We now consider a few examples which will use classes from other packages. The following listing shows a package named package1 containing a single class class A.

178
Package package 1; Public class Class A; { Public void display A( ) { System.out.println(class A); } }

Chapter 11 - Packages & Interfaces

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.

11.6 ACCESS PROTECTION


Classes and packages are both means of encapsulation. Both contain the name space, scope of variables and methods. Packages act as containers of classes and other subordinate packages. Classes act as containers for data and methods. The class is Javas smallest unit of abstraction. Because of interplay between classes and packages, Java addresses four categories of visibility for class members.

Subclasses in the same package Non subclasses in the same package

BSIT 42 JAVA Programming

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

Table 11.1 Class Member Access

11.7 ADDING A CLASS TO A PACKAGE


It is simple to add a class to an existing package. Consider the following package Package P1; Public classA { //body of A } The package P1 contains one public class by name. Suppose we want to add another class B to this package. This can be done as follows. 1. Define the class and make it public. 2. Place the package statement Package P1. Before the class definition Package P1 Public class B {

180
//body of B }

Chapter 11 - Packages & Interfaces

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

BSIT 42 JAVA Programming

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

Chapter 11 - Packages & Interfaces

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

BSIT 42 JAVA Programming

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

Chapter 11 - Packages & Interfaces

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

Excep t io n Han d lin g

OBJECTIVES

fter going through this chapter, you will be able to understand

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

Chapter 12 - Exception Handling

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.

BSIT 42 JAVA Programming

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

Exceptions are represented in Java by instances of the exception class.

12.3 THE EXCEPTION CLASS HIERARCHY.


The class Exception is more interesting. Subclasses of Exception fall into two general groups:

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

Chapter 12 - Exception Handling

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

12.4 UNCAUGHT EXCEPTIONS


Before you learn how to handle exceptions in your program, it is useful to see what happens when you dont handle them. This small program includes an expression that intentionally causes a divide-by-zero error. class Exce0 { public static void main(String args[]) { int d=0; int a=42/d; } } When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. In this example, We havent supplied any exception handlers of our own, so exception caught by the default handler provided by the java run time systems. Any exception that is not caught by your program will be ultimately be processed by the default handler. This default handler displays the string describing the exception, prints the stack trace from point at which the exception occurred and terminates the program. This program produces this output: Java.lang.ArithmeticException: / by Zero At Exc0.main(Exc0.java:4) In the error message the classname, methodname ,filename and the line number are included.

BSIT 42 JAVA Programming

189

12.5 EXCEPTION METHODS


Most Java exception handling is performed using the try, catch, throw, and finally methods. Of course, these methods can be extended if some unusual circumstance requires it. Java uses the try, catch, and throw keywords to do actual exception handling. They are conceptually similar to a switch statement; think of try like the switch statement in terms of exactly identifying the condition to be tested. catch is used to specify the action that should be taken for a particular type of exception. It is similar to the case part of a switch statement. There can be several catch statements in a row to deal with each of the exceptions that may be generated in the block specified by the try statement.

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.

190 12.5.4 Finally

Chapter 12 - Exception Handling

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.

An Example with try, catch, and finally


The following example is the standard structure for Java exception handling, incorporating try, catch, and finally: try { statement that generates an exception } catch (ExceptionType1 e) { process exception type 1 } catch (ExceptionType2 e) { process exception type 2 } finally { process all other exception types }

12.5.5 Using Try In Exception Handling


try is used to inform Java that a block of code may generate an exception and some processing of that exception will be done immediately following the try. The syntax of try is try { statement(s) } The keyword try begins the try construct and is followed by a statement or block containing the code that might generate an exception. This code could consist of several statements, one or more of which may generate an exception.

BSIT 42 JAVA Programming

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.

12.5.6 Using Catch In Exception Handling


catch is used to handle a specific exception that has been generated in a try statement. The syntax is as follows: catch (ExceptionType ExceptionObj) { statements; } The keyword catch begins the catch construct, followed by a parameter list that contains an exception type and an exception object. This in turn is followed by a statement or block containing the code used to process the exception. catch construct is a method that will be called by the Java runtime interpreter if the particular exception type specified in the parameter list is generated. The object specified in the parameter list, exceptionObj, is a variable that contains the exception object generated and is local to the catch block. Within this block it can be manipulated as needed. The object must be assigned to a variable whose scope resides outside the block to use it outside the catch block

12.5.7 Using Finally In Exception Handling


finally is used to handle any exception generated within a try statement. The catch statement discussed previously can handle only one type of exception; the finally statement can handle any type of exception. Following is the syntax: finally { statements } The keyword finally begins with the finally construct, followed by a statement or block containing the code used to process the exception.

192

Chapter 12 - Exception Handling

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.

BSIT 42 JAVA Programming

193

Example for ArrayIndexOutOfBoundException


public class array { public static void main(String[] args) { int i = 0; string names[]={ Rahul , Mohan , Madan}; While(i<4) { System.out.println(names[i]); i++; } } }

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.

Public class array { Public static void main(String[] args) {

194

Chapter 12 - Exception Handling

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.

BSIT 42 JAVA Programming

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

fter going through this chapter, you will be able to

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

Chapter 13 - Managing Input/Output

BSIT 42 JAVA Programming

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.

13.2 CONCEPT OF STREAMS


In file processing, input refers to the flow of data into a program and output means the flow of data out of a program. Input to a program may come from the keyboard, the mouse, the memory, the disk, a network, or another program. Similarly, output from a program may go to the screen, the printer, the memory, the disk, a network, or another program. This is illustrated in Fig. 13.1. Although these devices look very different at the hardware level, they share certain common characteristics such as unidirectional movement of data, treating data as a sequence of common characteristics such as unidirectional movement of data, treating data as a sequence of bytes or characters and support to the sequential access to the data. Java uses the concept of streams to represent the ordered sequence of data, a common characteristic shared by all the input/output devices as stated above. A stream presents a uniform, easy-to-use, object oriented interface between the program and the input/output devices.

198
Keyboard Mouse Input

Chapter 13 - Managing Input/Output

Output

Screen Printer

Memory
Disk

Java Program

Memory
Disk Network

Network

Fig. 13.1 Relationship of Java program with I/O devices

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

Fig. 13.2 Conceptual view of a stream

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

BSIT 42 JAVA Programming

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).

13.3 STREAM CLASSES


The java.io package contains a large number of stream classes that provide capabilities for processing all types of data. These classes may be categorized into two groups based on the data type on which they operate. 1. Byte stream classes that provide support for handling I/O operations on bytes. 2. Character stream classes that provide support for managing I/O operations on characters. These two groups may further be classified based on their purpose. Figure shows how stream classes are grouped based on their functions. Byte stream and character stream classes contain specialized classes to deal with input and output operations independently on various types of devices. We can also cross-group the streams based on the type of source or destination they read from or write to. The source (or destination) may be memory, a file or pipe.

13.4 READING CHARACTERS


To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException

200

Chapter 13 - Managing Input/Output

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

Byte Stream Classes

Character Stream

Classes

Input Stream Classes

Output Stream Classes

Reader Classes

Writer Classes

Memory

File

Pipe

Memory

File

Pipe

Fig. 13.4 Classification of Java stream classes

//use a bufferedreader to read characters from the console Import java.io.*; Class BRRead

BSIT 42 JAVA Programming

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.

13.5 READING STRINGS


To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general form is shown here: String readLine( ) throws IOException

202
As you can see, it returns a String object.

Chapter 13 - Managing Input/Output

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

BSIT 42 JAVA Programming

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.

204 13.6 WRITING CONSOLE OUTPUT

Chapter 13 - Managing Input/Output

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;

BSIT 42 JAVA Programming

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

Read Character Read Strings Write Console Output

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

You might also like