bsit 4th sem kuvempu university

218
INFORMATION TECHNOLOGY PROGRAMMES Bachelor of Science in Information Technology - B.Sc. (IT) Master of Science in Information Technology - M.Sc. (IT) In collaboration with KUVEMPU UNIVERSITY B.Sc.(IT) - 4 th Semester BSIT - 42 Java Programming Directorate of Distance Education Kuvempu University Shankaraghatta, Shimoga District, Karnataka Universal Education Trust Bangalore

Upload: warrior432

Post on 11-Apr-2015

420 views

Category:

Documents


6 download

DESCRIPTION

this is a 4th sem java programming book of kuvempu university 4th semester.....

TRANSCRIPT

Page 1: BSIT 4th sem Kuvempu University

INFORMATION TECHNOLOGY PROGRAMMESBachelor of Science in Information Technology - B.Sc. (IT)Master of Science in Information Technology - M.Sc. (IT)

Incol laboration

wi th

KUVEMPU UNIVERSITY

B.Sc.(IT) - 4th Semester

BSIT - 42 Java Programming

Directorate of Distance EducationKuvempu University

Shankaraghatta, Shimoga District, Karnataka

Universal Education TrustBangalore

Page 2: BSIT 4th sem Kuvempu University

II

Titles in this Volume :BSIT - 42 Java Programming

Prepared by UNIVERSAL EDUCATION TRUST (UET)Bangalore

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

Copyright © by UNIVERSAL EDUCATION TRUST, BangaloreAll rights reserved

No Part of this Book may be reproducedin any form or by any means without the writtenpermission from Universal Education Trust, Bangalore.

All Product names and company names mentionedherein are the property of their respective owners.

NOT FOR SALEFor personal use of Kuvempu UniversityIT - Programme Students only.

Corrections & Suggestionsfor Improvement of Study materialare invited by Universal Education Trust, Bangalore.

E-mail : [email protected]

Printed at :Pragathi Print CommunicationsBangalore - 20Ph : 080-23340100

Page 3: BSIT 4th sem Kuvempu University

III

JAVA PROGRAMMING(BSIT - 42)

: Contributing Authors :

Dr. S.N. Jagadeesha, M.E., Ph.DProfessor and Head

Department of Computer Science & EngineeringJNN College of Engineering

Shimoga

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

LecturerDepartment of Computer Science & Engineering

Jawaharlal Nehru National College of EngineeringShimoga

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

Department of Information Science & EngineeringPES School of Engineering

Bangalore

Page 4: BSIT 4th sem Kuvempu University

IV

BLANK PAGE

Page 5: BSIT 4th sem Kuvempu University

V

a

Preface

Programming languages, paradigms and practices do not survive very long. Methods and technologiesapplied yesterday become out-of-date today. This rapid rate of change makes programming anexciting task.

Java is a fine example for the above statements. In a decade or so, it has grown from a concept intoone of the most dominant computer language. Java has gone through many revisions. It has grown into atechnology. It has many new and innovative features. Each innovation in language design has been drivenby the need to solve a fundamental problem that the preceding languages could not solve. Java is noexception.

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 withinnovative concepts required by its unique environment. Java is inherited from C and C++. Java derivesits syntax from C. Its object oriented features are influenced by C++. Development of Java technologyhas its roots in the process of refinement and adaptation that has been occurring in programming languagesfor the past three decades.

Whenever a programming language is designed, trade offs like ease-of-use versus power, safetyversus efficiency and rigidity versus extensibility are often made. C++ fitted the bill. However, the WorldWide 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 onInternet. 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. Java’s magic is the byte code,which makes it platform independent. All these features make it a compulsory subject in various coursesof engineering.

This Revised study material covers all aspects of Java programming language with large number of

Page 6: BSIT 4th sem Kuvempu University

VI

illustrative examples which will help the students to enhance their skills in programming. It begins withbasics including such things as data types, control statements classes and arrays. In the latter part, wediscuss Java’s exception handling mechanism, packages, multithreading and interfaces.

We are very much thankful to the authorities of Universal Education Trust, Bangalore for providingthis opportunity to prepare the study material on Java.. Finally we thank the Principal and Management ofJ.N.N College of Engineering, Shimoga for providing the facilities.

Suggestions regarding the improvement of this material are welcome.

Dr. S.N JagadeeshaRavindra. S

B.J Sandesh

Page 7: BSIT 4th sem Kuvempu University

VII

a

Contents

Chapter 1

THE HISTORY OF JAVA 1

1.1 Introduction ..................................................................................... 11.2 What is JAVA Technology ................................................................ 2

1.2.1 Primary Goals of Java Technology........................................ 21.3 Applets & Application ....................................................................... 21.4 The history of JAVA ......................................................................... 31.5 Basic Features in JAVA.................................................................... 51.6 How JAVA differ from C & C++...................................................... 71.7 JAVA & Internet.............................................................................. 81.8 Java Development Kit(JDK).............................................................. 81.9 Java Standard Library(JSL)............................................................... 81.10 How will JAVA Technology change my life ?...................................... 91.11 Summary.......................................................................................... 10

Chapter 2

FUNDAMENTALS OF OBJECT ORIENTED PROGRAMMING 11

2.1 Introduction....................................................................................... 112.2 Programming Approaches................................................................. 122.3 What is Object-Oriented Programming............................................... 152.4 Advantages of OOP........................................................................... 182.5 Applications ..................................................................................... 192.5 Summary.......................................................................................... 19

Page 8: BSIT 4th sem Kuvempu University

VIII

Chapter 3

OVERVIEW OF JAVA LANGUAGE 21

3.1 Introduction...................................................................................... 213.2 Simple JAVA Program....................................................................... 223.3 JAVA Program Structure................................................................... 243.4 Implementing a JAVA Program.......................................................... 263.5 More of JAVA.................................................................................. 273.6 JAVA virtual machine........................................................................ 283.7 JAVA Tokens................................................................................... 293.8 Summary.......................................................................................... 31

Chapter 4

CONSTANTS, VARIABLES AND DATATYPES 32

4.1 Introduction...................................................................................... 324.2 Constants......................................................................................... 324.3 Data types........................................................................................ 354.4 Variables.......................................................................................... 384.5 Scope of Variables............................................................................ 404.6 Type Casting.................................................................................... 404.7 Summary.......................................................................................... 43

Chapter 5

OPERATORS AND EXPRESSIONS 45

5.1 Introduction...................................................................................... 455.2 Arithmetic Operators......................................................................... 46

5.2.1. Integer Arithmetic............................................................... 465.2.2. Real Arithmetic................................................................... 475.2.3 Mixed-Mode Arithmetic................................................ 485.2.4 String Concatenation.................................................... 495.2.5 Multiplication and Division in Java................................. 49

5.3 Assignment Operators...................................................................... 505.4 Relational Operators......................................................................... 515.5 Logical Operators............................................................................. 545.6 Increment and Decrement Operator................................................... 555.7 Conditional Operator.......................................................................... 57

Page 9: BSIT 4th sem Kuvempu University

IX

5.8 Bit-wise Operator............................................................................. 585.8.1 Shift and Logical Operators................................................. 585.8.2 Dot Operator...................................................................... 615.8.3 Type-Casting...................................................................... 615.8.4 Arithmetic Expressions....................................................... 615.8.5 Precedence of Arithmetic Operators.................................... 615.8.6 Operator Precedence and Associativity................................. 63

5.9 Mathematical Functions..................................................................... 645.10 Summary.......................................................................................... 68

Chapter 6

DECISION MAKINGAND BRANCHING 71

6.1 Introduction...................................................................................... 716.2 Decision Making With If Statement...................................................... 71

6.2.1 Simple IF Statement............................................................ 726.2.2 The IF…ELSE Statement.................................................... 746.2.3 Simple IF...ELSE Statements............................................... 766.2.4 The ELSE IF Ladder........................................................... 78

6.3 Switch Statement ............................................................................. 816.4 The ?: Operator in JAVA.................................................................... 856.5 Summary.......................................................................................... 86

Chapter 7

LOOPING 88

7.1 Introduction...................................................................................... 887.2 The While Loop................................................................................ 897.3 Do Statement.................................................................................... 907.4 For Statement................................................................................... 92

7.4.1. Additional Features of the for loop........................................ 967.4.2. Nested for loops.................................................................. 97

7.5 Continue and Break Statements in JAVA............................................ 1007.6 Summary.......................................................................................... 103

Chapter 8

CLASSES OBJECTS AND METHODS 105

Page 10: BSIT 4th sem Kuvempu University

X

8.1 Introduction...................................................................................... 1058.2 Classes............................................................................................. 105

8.2.1 Variables and Methods........................................................ 1068.3 Adding Variables to Class.................................................................... 1098.4 Introduction to Objects........................................................................ 1168.5 Defining Methods .............................................................................. 1228.6 Inheritance: Extending Classes.......................................................... 1278.7 Advanced class Features .................................................................. 1328.8 Summary.......................................................................................... 137

Chapter 9

ARRAYS AND STRINGS 139

9.1 Introduction...................................................................................... 1399.2 One-dimensional array....................................................................... 1399.3 Creating an Array............................................................................... 140

9.3.1. Declaration of Array............................................................ 1419.3.2 Initialization of Array............................................................ 141

9.4 Primitive and reference data types...................................................... 1469.5 Two dimensional array........................................................................ 1479.6 Strings in Java................................................................................... 151

9.6.1. Constructors....................................................................... 1529.6.2. String Methods................................................................... 154

9.7 Summary.......................................................................................... 161

Chapter 10

MULTITHREADING 163

10.1 Introduction....................................................................................... 16310.2 Thread Fundamentals......................................................................... 164

10.2.1. Advantages of Multithreading over Multitasking process........ 16510.3 The Java Thread Model..................................................................... 165

10.3.1. Thread States: Life Cycle of a Thread.................................. 16610.3.2. Context Switching............................................................... 167

10.4 Main thread....................................................................................... 16710.5 Naming the threads........................................................................... 167

10.5.1 THE getName METHOD................................................... 16810.5.2 THE setName METHOD................................................... 168

Page 11: BSIT 4th sem Kuvempu University

XI

10.6 Creating threads............................................................................... 15410.6.1 Extending the Thread Class.................................................. 16910.6.2 Implementing the Run() Method........................................... 17010.6.3 Starting New Thread........................................................... 17010.6.4 Implementing The ‘Runnable Interface’................................ 171

10.7 Synchronization................................................................................ 17310.8 Messaging........................................................................................ 17410.9 Summary.......................................................................................... 174

Chapter 11

PACKAGES & INTERFACES 175

11.1 Introduction...................................................................................... 17511.2 Creating Packages ........................................................................... 17611.3 Procedure to create our own package................................................ 17611.4 Accessing a Package........................................................................ 17711.5 Using a Package.............................................................................. 17711.6 Access Protection............................................................................. 17811.7 Adding a class to a Package.............................................................. 17911.8 Interfaces......................................................................................... 18011.9 Summary.......................................................................................... 184

Chapter 12

EXCEPTION HANDLING 185

12.1 Introduction...................................................................................... 18512.2 Exception ......................................................................................... 18612.3 Exception class hierarchy................................................................... 18712.4 Uncaught Exceptions......................................................................... 18812.5 Exception Methods............................................................................ 189

12.5.1 Throw................................................................................ 18912.5.2 Catch ................................................................................ 18912.5.3 Try..................................................................................... 18912.5.4 Finally................................................................................. 19012.5.5 Using Try In Exception Handling.......................................... 19012.5.6 Using Catch In Exception Handling...................................... 19112.5.7 Using Finally In Exception Handling...................................... 191

12.6 Summary.......................................................................................... 194

Page 12: BSIT 4th sem Kuvempu University

XII

Chapter 13

MANAGING INPUT /OUTPUT 196

13.1 Introduction....................................................................................... 19613.2 Concept of Streams........................................................................... 19713.3 Stream Classes................................................................................. 19913.4 Reading Characters........................................................................... 19913.5 Reading Strings................................................................................. 20113.6 Writing Console Output...................................................................... 20413.7 Summary.......................................................................................... 205

References....................................................................................... 206

Page 13: BSIT 4th sem Kuvempu University

Chapter 1

The Hist o r y o f JAVA

OBJECTIVES

Upon 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 thismakes 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 addressedby software engineers are maintainability, reusability, portability security, and integrity and user friendliness.

Java technology is yet another answer in this direction.

1BSIT 42 JAVA Programming

Page 14: BSIT 4th sem Kuvempu University

2

1.2 WHAT IS JAVA TECHNOLOGY?

The Java programming language is designed to meet the challenges of application development in thecontext of heterogeneous, network-wide distributed environments. Paramount among these challenges issecure delivery of applications that consume the minimum of system resources, can run on any hardwareand software platform, and can be extended dynamically.

Java Technology is a Programming language, development environment, application environment, anddeployment environment.The syntax of Java programming language is similar to C++ syntax. Java can beused 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 ofrunning 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 adeployment 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 tocreate 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 technology’s 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.

Chapter 1 - The History of JAVA

Page 15: BSIT 4th sem Kuvempu University

3

An applet is a program written in the Java programming language that can be included in an HTMLpage, much in the same way an image is included in a page. When you use a Java technology-enabledbrowser to view a page that contains an applet, the applet’s code is transferred to your system andexecuted by the browser’s 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 javaapplication 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 URL’s and doing calculations. Applets runs within a browser.

Applets have built in feature for internet such as security. For example, they are Inspected forviruses.

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 ofmetamorphosis before reaching its current status of de facto programming language for the World WideWeb. 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 projectleader of Sun’s Open Windows user environment), and several other individuals met in Aspen to discussthe ideas for the Stealth Project. The goal of the Stealth Project was to do research in the area ofapplication 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 handheld-remote-control-like device.

Gosling began with C++, but soon after he was convinced that C++ was inadequate for this particularproject. His extensions and modifications to C++ (also know as C++ ++ —), were the first step towardsthe 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 dueto a patent search, which determined that the name was copyrighted and used for another programminglanguage and renamed “Oak” as “Java “. The major milestones in the development of java technology arelisted in Table 1.1

BSIT 42 JAVA Programming

Page 16: BSIT 4th sem Kuvempu University

4 Chapter 1 - The History of JAVA

Important Years in Java history

Table 1.1 Major milestones

Year Development

1991 “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 Warner’s RFP for its interactive cable TV trial in Orlando, FL.

NCSA Mosaic 1.0, the first graphical browser for the Internet, is released

1994 “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”

Van Hoff implements Java compiler in Java. (Gosling had previously implemented it in C.)

1995 Sun formally announces Java and HotJava at SunWorld ’95 Netscape announces its intention to license Java for use in Netscape browser. Sun and Netscape announce Javascript, a scripting language based on the Java

language which is designed to be accessible to non-programmers.

1996 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

1997 Sun releases Java Development Kit 1.1

1998 Sun releases Java 2 version 1.2of Software Development Kit (SDK 1.2)

1999 Sun releases java 2 Platform standard edition(J2SE) and Enterprise edition(J2EE)

2000 Sun releases J2SE with SDK 1.3

2002 Sun releases J2SE with SDK 1.4

2004 Sun releases J2SE with JDK 5.0 (instead of JDK 1.5). Also known as J2SE 5.0

2006 Sun releases J2SE 6.0 Dolphin project begins in august 2006

2010 The current version is J2SE 6 update 22

Future Java 7 is expected to release in mid 2011. Java 8 in 2012Java 7 is expected to release in mid 2011.Java 8 in 2012

Page 17: BSIT 4th sem Kuvempu University

5

1.5 BASIC FEATURES IN JAVA

The Java programming language is a high – level language that can be characterized by all of thefollowing buzz words. The fundamental forces that necessitates the invention of Java are Portability andSecurity . Other factors also play an important role in modeling the final form of the Java language. Let’sbriefly 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-orientedprogramming use C++. Java is designed as closely to C++ as possible in order to make the system morecomprehensible. 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 toorganize a program, so that it closely models the real world in structure and in the interactions among itscomponents.

Distributed

Java was built with the Internet and Web in mind. As do most other languages, Java includes pre-builtcomponents or libraries that provide important additional capabilities beyond the language itself. However,Java’s standard libraries specifically include network-aware units that greatly facilitate writing Internetapplications.

BSIT 42 JAVA Programming

Page 18: BSIT 4th sem Kuvempu University

6

Interpreted

Java’s executable files are composed of bytecodes that are instructions and data relating to ahypothetical computer called the Java virtual machine. Each machine that runs a Java program uses asmall program, known as the Java run-time system, to execute the Java bytecodes in your program. Thisdesign 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 allowingsoftware 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 infectyour computer, or hackers who take advantage of a software glitch to invade your personal cyberspaceand make off with confidential information.

Applets, which are Java programs automatically downloaded when a Web page is displayed, aresubject to a number of limitations that are designed to reduce the chance that simply viewing someone’s

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

Java’s bytecodes are designed to be read and interpreted—in exactly the same manner—on any

computer hardware or operating system that supports a Java run-time. No translation or conversion isnecessary.

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 run-time to a new computer system.

High Performance

A typical problem with interpreted languages is that they are somewhat less efficient than compiledlanguages. 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.

Chapter 1 - The History of JAVA

Page 19: BSIT 4th sem Kuvempu University

7

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

doesn’t have to figure it out again if the same code is executed. Instead, it retrieves the memorizedsequences 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 multithreadedapplications as part of its basic library.

Dynamic

Java’s 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 powerfuland 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. Constantscan 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 C’s const keyword or the ability to pass by const reference explicitly.

Java classes are singly inherited, with some multiple-inheritance features provided throughinterfaces.

All functions must be methods. There are no functions that are not tied to classes.

The goto keyword does not exist in Java (it’s a reserved word, but currently unimplemented).You can, however, use labeled breaks and continues to break out of and continue executingcomplex switch or loop constructs.

Java does not use pointers

Java doesn’t contain the data types: struct, union, enum.

BSIT 42 JAVA Programming

Page 20: BSIT 4th sem Kuvempu University

8

1.7 JAVA & INTERNET

Internet users can use java to create applet programs and run them locally using a “java enabledbrowsers” such as hotjava. They can also use a java enabled browser to download an applet located ona computer anywhere in the internet and run it on their local computer. Internet users can also set up theirwebsites 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 traversinginformation resources on the World Wide Web. An information resource is identified by a UniformResource Identifier (URI) and may be a web page, image, video, or other piece ofcontent. 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 toaccess information provided by Web servers in private networks or files in file systems. Some browserscan 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 toretrieve 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

Chapter 1 - The History of JAVA

Page 21: BSIT 4th sem Kuvempu University

9

interface(API). These classes and methods are grouped into several functional packages. Most commonlyused packages are:

Language support packages :A collection of classes and methods required for implementingbasic 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-orientedlanguage, it’s 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 smallerthan the same program written in C++.

Write better code: The Java programming language encourages good coding practices, andautomatic garbage collection helps you avoid memory leaks. Its object orientation, itsJavaBeansTM component architecture, and its wide-ranging, easily extendible API let you reuseexisting, tested code and introduce fewer bugs.

Develop programs more quickly: The Java programming language is simpler than C++, andas such, your development time could be up to twice as fast when writing in it. Your programswill also require fewer lines of code.

Avoid platform dependencies: You can keep your program portable by avoiding the use oflibraries written in other languages.

Write once, run anywhere: Because applications written in the Java programming languageare 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 launchyour applications with a single click of the mouse. An automatic version check at startup ensures

BSIT 42 JAVA Programming

Page 22: BSIT 4th sem Kuvempu University

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 haveintroduced an overview of java history and its salient features. It has many characteristics that make itsuitable for Internet programming. Fundamental differences between Java and c++ have also beendiscussed. Various tools and environment required for implementation of java programs have also beenincluded.

EXERCISES

1. Why is Java known as platform-neutral language?

2. How is Java more secured than other languages?

3. What is multithreading? How does it improve the performance of JAVA?

4. List at least seven major differences between C and Java.

5. How is Java strongly associated with the Internet?

6. What is Hypertext Markup Language? Describe its role in the implementation of Java applets.

7. List out primary goals of Java Technology?

Chapter 1 - The History of JAVA10

Page 23: BSIT 4th sem Kuvempu University

Chapter 2

Fu n dam en t als Of Ob ject Or ien t edPr o g r am m in g

OBJECTIVES

After 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” – datastructures consisting of data fields and methods together with their interactions – to design applicationsand computer programs.

OOP is an approach to program organization and development which attempts to eliminate some ofthe pitfalls of conventional programming methods by incorporating the best of structured programmingmethods with several new concepts. It is a new way of organizing and developing and has nothing to dowith any particular language. Programming techniques may include features such as encapsulation, dataabstraction,  modularity, polymorphism, and inheritance. Many modern programming languages now supportOOP.

11BSIT 42 JAVA Programming

Page 24: BSIT 4th sem Kuvempu University

12 Chapter 2 - Fundamentals of Object Oriented

Before learning the oops concepts, we will see some of the features of programming approaches asmentioned 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 sourcecode is written in a programming language. The code may be a modification of an existing source orsomething completely new. The purpose of programming is to create a program that exhibits a certaindesired behaviour (customization). The process of writing source code often requires expertise in manydifferent 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 variousapplications. These include unstructured programming, procedural programming, modular programmingand object oriented programming.

Unstructured Programming

Usually, people start learning programming by writing small and simple programs consisting only ofone main program. Here “main program” stands for a sequence of commands or statements, whichmodify 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 (specifyingthe steps the program must take to reach the desired state),

With procedural programming you are able to combine returning sequences of statements into onesingle place. A procedure call is used to invoke the procedure. After the sequence is processed, flow ofcontrol proceeds right after the position where the call was made (Fig.2.2).

Page 25: BSIT 4th sem Kuvempu University

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 cannow be written more structured and error free. For example, if a procedure is correct, every time it isused it produces correct results. Consequently, in cases of errors you can narrow down your search tothose 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 topass data to the individual calls, the data is processed by the procedures and, once the program hasfinished, 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 iscomposed of separate, interchangeable components, called modules. Conceptually, modules representa 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

BSIT 42 JAVA Programming

Page 26: BSIT 4th sem Kuvempu University

14

elements that are provided and required by the module. The elements defined in the interface are detectableby other modules. The implementation contains the working code that corresponds to the elements declaredin the interface. A program therefore no longer consists of only one single part. It is now divided intoseveral 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 appropriatedata as parameters.

Each module can have its own data. This allows each module to manage an internal state, which ismodified by calls to procedures of this module. However, there is only one state per module and eachmodule 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 abstractionsof the problem. Rather than decomposing the problems into steps, we identify objects, which are delivereddirectly from the vocabulary of the problem domain.

we view the world (problem domain) as a set of autonomous agents that collaborate to perform somehigher level behavior. Each object in the solution embodies its own unique behavior and each one modelssome object in the real world. The object is simply a tangible entity that exhibits some well definedbehavior. Objects do things we ask them to perform what they do by sending the messages. OOP paradigmhelps us to organize the inherent complexities of software systems.

Chapter 2 - Fundamentals of Object Oriented

Page 27: BSIT 4th sem Kuvempu University

15

Definition

It is a method of implementation in which programs are organized as co-operative collection ofobjects, each of which represents an instance of some class and whose classes all members of ahierarchy 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 astelephones, cars, etc. Programmers just like to use words like encapsulation and inheritance to confusethe average person when talking about object-oriented programming. The concept is actually quite simplesince 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 whichrepresents a person, vehicle or a conceptual entity (thing in existence) like bank account, company etc.

BSIT 42 JAVA Programming

Page 28: BSIT 4th sem Kuvempu University

16

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, andmethods. 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 providemodularity and structure in an object-oriented computer program. A class should typically be recognizableto a non-programmer familiar with the problem domain, meaning that the characteristics of the classshould make sense in context. Also, the code for a class should be relatively self-contained (generallyusing 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. Eachobject of a given class contains the structure and behavior defined by the class, as if it were stamped outof a mould in the shape of a class. A class is a logical construct, an object has physical reality. When youcreate a class, you will specify the code and data that will constitute that class. Collectively, these elementsare called the members of the class. Specifically, the data defined by the class are referred to as membervariables or instance variables. The code that operates on that data is referred to as member methodsor 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 reachout and grab, or interact with, or cut down a tree you have to have a concrete instance of that tree. Ofcourse, once you have a tree class, you can create lots of different instances of that tree, and eachdifferent tree instance can have different features (short, tall, bushy, drops leaves in Autumn), while stillbehaving like and being immediately recognizable as a tree.

Chapter 2 - Fundamentals of Object Oriented

Page 29: BSIT 4th sem Kuvempu University

17

An instance of a class is another word for an actual object. The instance is the actual object createdat 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 themore general term, but both instances and objects are the concrete representation of a class. In fact, theterms instance and object are often used interchangeably in OOP language. An instance of a tree and atree object are both the same thing.

Abstraction

Abstraction is simplifying complex reality by modeling classes appropriate to the problem, and workingat 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 complexobject so as to attend to others. Solving a problem with objects requires you to build the objects tailored toyour solution. We choose to ignore its inessential details, dealing instead with the generalized and idealizedmodel of the object.

Encapsulation

The ability to provide users with a well-defined interface to a set of functions in a way, whichhides their internal workings. In object oriented programming, the technique of keeping togetherdata structures and the methods (procedures) which act on them. The easiest way to think ofencapsulation is to reference phones. There are many different types of phones, which consumers canpurchase today. All of the phones used today will communicate with each other through a standardinterface. A phone made by GE can be used to call a phone made by Panasonic for example. Althoughtheir internal implementation may be different their public interface is the same. This is the idea ofencapsulation.

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 fromanother 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 majorcode changes. Inheritance can mean just reusing code, or can mean that you have used a whole class ofobject with all its variables and functions. Why not reuse an existing class that has behaviors similar towhat you need in a new program?

BSIT 42 JAVA Programming

Page 30: BSIT 4th sem Kuvempu University

18

For example, the bike is a part of the class two wheelers, which is again a part of class vehicle asshown 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. Polymorphismallows a common data-gathering message to be sent to each class and allows each subclass object torespond to a message format in an appropriate manner to its own properties. Polymorphism encouragessomething we call ‘extendibility’. In other words, an object or a class can have it’s uses extended.

Message passing

In an object based world the only way for anything to happen is by objects communicating with eachother and acting on the results. This communication is called message passing and involves one objectsending 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 advantagesare,

Chapter 2 - Fundamentals of Object Oriented

Page 31: BSIT 4th sem Kuvempu University

19

Reusability

Elimination of redundant code and use of existing classes through inheritance. Thus provideseconomy 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 arealso 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, ArtificialIntelligence 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 hasbeen discussed. How OOP evolved as a powerful programming concept has been explained. The basicconcepts of object oriented programming namely classes, objects, encapsulation, inheritance, andpolymorphism have been introduced. Benefits and applications of OOP approach have been discussedbriefly.

EXERCISES

1. What is object-oriented programming? How is it different from the procedure-oriented programming?

2. How are data and methods organized in an object-oriented program?

BSIT 42 JAVA Programming

Page 32: BSIT 4th sem Kuvempu University

3. What are unique advantages of an object-oriented programming paradigm?

4. Distinguish between the following terms:

a) Objects and classes

b) Data abstraction and data encapsulation

c) Inheritance and polymorphism

d) Dynamic binding and message passing

5. Describe inheritance as applied to OOP.

6. List a few areas of application of OOP technology.

7. State whether the following statements are TRUE or FALSE.

a) In conventional, procedure-oriented programming, all data are shared by all functions.

b) 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) Wrapping up of data of different types into a single unit is known as encapsulation.

e) One problem with OOP is that once a class is created, it can never be changed.

f) Inheritance means the ability to reuse the data values of one object by other objects.

g) Polymorphism is extensively used in implementing inheritance.

h) Object-oriented programs are executed much faster than conventional programs.

i) Object-oriented systems can scale up better from small to large.

j) Object-oriented approach cannot be used to create databases.

Chapter 2 - Fundamentals of Object Oriented20

Page 33: BSIT 4th sem Kuvempu University

BSIT 42 JAVA Programming 21

Chapter 3

Over v iew Of JAVA Lan g u ag e

OBJECTIVES

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

Page 34: BSIT 4th sem Kuvempu University

22 Chapter 3 - Overview of JAVA Language

Stand-alone applications

Stand-alone applications are program written in JAVA to carry out certain tasks on a stand-alone localcomputer. 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 distantcomputer (Server) can be downloaded via Internet and executed on a local computer(Client) using aJava-capable browser.

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

Java Source

Java Compiler

Java Enabled Web Browser

Java Interpreter

Output Output

Applet Type Application Type

Page 35: BSIT 4th sem Kuvempu University

23BSIT 42 JAVA Programming

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, thepieces will recur in all applications. First and the foremost, Java is case sensitive. If you made anymistake in capitalization (such as typing Main instead of main), the program will not run. Now let’s lookat the source code line by line.

The keyword public is called an access modifier these modifiers control the level of access otherparts of a program have to this code. Java is a true object-oriented language and therefore, The keywordclass 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 bythe main ( ) method in determining the position from which byte code should be interpreted. A programcan contain various classes. However, only one of these needs, to contain the main ( ) method. In themain ( ) method, all the components that make up the main ( ) method are specified within a second setof braces. The entire body of the main ( ) method is contained within these braces. The main ( ) methodbody 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 aclass. The keyword static helps you do this. This is necessary because the main ( ) method is called bythe Java interpreter before any objects are created. After specifying the keyword static, you specify thevoid 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 blockof code is specified within the main ( ) method body and is contained within braces. A block of code canbe 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

Page 36: BSIT 4th sem Kuvempu University

24

statement begins with System.out. This is a constant that represents the default output mode, which in thiscase is the screen. The constant helps to read and display the data in a Java program. The output isgenerated using the built-in println( ) method. The string that is assigned to the println( ) method is displayedwhen 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 notfollowed 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 onlyone class defines a main method. Classes contain data members and methods that operate on the datamembers of the class. Methods may contain data type declarations and executable statements. To writea Java program, we first define classes and then put them together. A Java program may contain one ormore sections as shown in the Fig.3.2.

Chapter 3 - Overview of JAVA Language

Page 37: BSIT 4th sem Kuvempu University

25

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 , theauthor 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 packagename 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 ofimport 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 sectionand 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 elementsof a Java program.

Main Method Class

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

BSIT 42 JAVA Programming

Documentation Section SuggestedPackage Statement OptionalImport Statements OptionalInterface Statements OptionalClass Definitions OptionalMain Method Class{ Main Method Definition}

Essential

Page 38: BSIT 4th sem Kuvempu University

26

3.4 IMPLEMENTING A JAVA PROGRAM

Implementation of a Java application program involves a series of steps. They include creating theprogram , 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 calledfilename. 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 thecommand line Javac filename.Java. Javac compiler creates a file called filename.class containing thebyte 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. Whenexecuted, our program displays the following:

Hello World!

Chapter 3 - Overview of JAVA Language

Page 39: BSIT 4th sem Kuvempu University

27

3.5 MORE OF JAVA

Assume that we would like to compute and print the number is even or odd.

/* Even Odd Number ExampleThis 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 numbersint[] 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 anynumber 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.”);ElseSystem.out.println(numbers[i] + “ is odd number.”);

}}

}/*Output of the program would be1 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.*/

BSIT 42 JAVA Programming

Page 40: BSIT 4th sem Kuvempu University

28

Sample program with multiple classes

class Room{

float length;float breadth;

void getdata (float a, float b){

length = a;breadth = b;

}}

class RoomArea{

public static void main (String [ ] args){

float area;Room room1 = new Room (); // Creates an object room1room1. 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 variablesand one method to assign values to these variables. The class RoomArea contains the main method thatinitiates the execution.

3.6 JAVA VIRTUAL MACHINE

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

Chapter 3 - Overview of JAVA Language

Page 41: BSIT 4th sem Kuvempu University

29BSIT 42 JAVA Programming

Fig. 3.4 Process of Compilation

The virtual machine code is not machine specific. This machine specific code (known as machinecode) is generated by the Java interpreter by acting as an intermediary between the virtual machine andthe 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 ina 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

Page 42: BSIT 4th sem Kuvempu University

30 Chapter 3 - Overview of JAVA Language

Keywords

Keywords are an essential part of a language definition. They implement specific features of thelanguage. 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

Literals

Literals in Java are a sequence of characters (digits, letters, and other characters) that representconstant 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.

Abstract boolean break byte byvalue*Case cast catch char classConst* continue default do doubleElse extends false** final finallyFloat For future* generic* goto*If implements import inner* instanceofInt interface long native newNull** operator* outer* package privateProtected public rest* return shortStatic super switch synchronization thisThreadsafe* throw throws transient true**Try var* void volatile while

* Reserved for future use

Page 43: BSIT 4th sem Kuvempu University

31BSIT 42 JAVA Programming

3.8 SUMMARY

In this chapter, we have discussed a simple application program to familiarize the readers with basicjava structure and syntax. The basics of java language and steps involved in creating and executing a javaapplication program has also been presented.

EXERCISES

1. Describe the structure of a typical Java program.

2. What is the task of the main method in a Java program?

3. What is a token? List the various types of tokens supported by Java.

4. Why can’t we use a keyword as a variable name?

5. Enumerate the rules for creating identifiers in Java.

6. What are the conventions followed in Java for naming identifiers? Give examples.

7. Explain println statement in Java with an example?

8. Why main method in Java is declared as static?

9. What is Applet?

10. Explain with a simple example how to create, compile and run a program in Java?

11. Write a program in java to calculate the area of a circle.

12. Write a program in java to calculate the perimeter of a rectangle.

Page 44: BSIT 4th sem Kuvempu University

Chapter 4 - Overview of JAVA Language

Chapter 4

Co n st an t s, Var iab les An d Dat at yp es

OBJECTIVES

After 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, charactersand strings and to provide useful output known as information. The task of processing data is accomplishedby 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

Page 45: BSIT 4th sem Kuvempu University

with no decimal point using the digits 0 through 9.. They can range in magnitude from negative to positive231 - 1 (approximately two billion). Constants larger than these permissible magnitudes will produceunpredictable results. Leading plus or minus signs are permitted, as are leading zeros. Valid examples ofdecimal 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 aleading 0.

Some examples are

037 ,0 0435,0551

Real Constants

Quantities are represented by numbers containing fractional parts like 17.548. Such numbers arecalled real (or floating point) constants.

A real number may also be expressed in exponential (or scientific) notation. For example, the value215.65 may be written as 2.1565e2 in exponential notation. E2 means multiply by 102. The general formis:

The mantissa is either a real number expressed in decimal notation or an integer. The exponent is aninteger with an optional plus or minus sign. The letter e separating the mantissa and the exponent can bewritten 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 canbe 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

Mantissa e exponent

33BSIT 42 JAVA Programming

Page 46: BSIT 4th sem Kuvempu University

34 Chapter 4 - Overview of JAVA Language

“ab” “Hello!” “A line...” “”

If the string is two or more characters, it can be enclosed in single quotes instead of double quotes:

‘ab’ is the same as “ab”

If there is only one character in the string and you enclose it in single quotes, it will be taken as acharacter 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 bymultiplying 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 typeis based on 2 multiplied to a power equaling the number of bits. An 8-bit number has 28 possible values, or256.

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 tocalculate the base 10 value of binary data in Fig.4.2.

Sign Value Bit: bits:

0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 Value in each bit

7 6 5 4 3 2 1 0* Index of each bit

* Numbering of the bits starts at 0

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

values

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

Page 47: BSIT 4th sem Kuvempu University

35

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.

Fig. 4.3 Data Types in Java

Sign Value Bit: bits:

0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 Value in each bit

7 6 5 4 3 2 1 0* Index of each bit

* Numbering of the bits starts at 0

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

values

Data Types in Java

Primitive(Intrinsic)

Numeric Classes

Non-Primitive(Derived)

Non-numeric Arrays

Integer Character Floating-point InterfaceBoolean

BSIT 42 JAVA Programming

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

Page 48: BSIT 4th sem Kuvempu University

36

Integer Types

Integer types can hold whole numbers such as 123,-96,and 5639. The size of the values that can bestored 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 aresigned, meaning they can be positive or negative. The different integer types along with their range andlength are given in Table.4.1.

Table 4.1. Integer Types

Floating Point Types

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

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 explicitlystate that it is a float, not a double. Literal values for floating point types are assumed to be doublesunless you specify otherwise, using the F.

Character Type

Another data type you need to store and manipulate is single-character information. The primitivetype used for storing a single character is char. Most computer languages use the American StandardCode for Information Interchange (ASCII), an 8-bit character set that has an entry for every Englishcharacter and punctuation mark, numbers and so on. The Java programming language uses a 16-bitcharacter set called Unicode that can store all the necessary displayable characters from the vast majorityof languages used in the modern world. Your programs can therefore be written so that they will workand display the correct language for countries. Unicode contains a subset of ASCII (the first 128 characters)

Type Length Range InclusiveByte 1 Byte -128 to 127Short 2 Byte -32,768 to 32,767 Int 4 Byte -2,147,483,648 to 2,147,483,648

Long 8 Byte 9,223,372,036854,775,808 to 9,223,372,036854,775,808

Type Length Range InclusiveFloat 4 bytes Approximately ±3.40282347E+38F

Double 8 Byte Approximately ±1.79769313486231570E+308

Chapter 4 - Overview of JAVA Language

Page 49: BSIT 4th sem Kuvempu University

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 beValue of Boolean variable b1 is: trueValue of Boolean variable b2 is: falseValue 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 beValue of char variable ch1 is :aValue of char variable ch2 is :A

BSIT 42 JAVA Programming

Page 50: BSIT 4th sem Kuvempu University

38

4.4 VARIABLES

A variable is an identifier that denotes a storage location used to store a data value. Unlike constantsthat remain unchanged during the execution of a program, a variable may take different values at differenttimes during the execution of the program.

* average

* height

* total_height

* classStrength

As mentioned earlier, variable names may consist of alphabets, digits, the underscore ( _ ) and dollarcharacters, 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 totalor 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, wemust 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 bedeclared 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 thetype. Java allows any properly formed variable to have any declared data type. The declaration statementdefines the type of variable. The general form of declaration of a variable is :

type variable1, variable 2,……., variable N;

Chapter 4 - Overview of JAVA Language

Page 51: BSIT 4th sem Kuvempu University

39

Variables are separated by commas. A declaration statement must end with a semicolon. Some validdeclaration 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. Thiscan 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:

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:

Examples

int finalValue = 100;char yes = ‘X’;double total = 75.36;

VariableName = value;

type VariableName = Value;

BSIT 42 JAVA Programming

Page 52: BSIT 4th sem Kuvempu University

40

The process of giving initial values to variables is known as the initialization. The ones that are notinitialized are automatically set to zero.

The following are valid Java statements:

float x, y, z; // declares three float variablesint m = 5, n = 10; // declares and initializes two int variablesint m, n = 10; // 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 theobjects are instantiated and therefore they are associated with the objects. They take different values foreach object. On the other hand, class variables are global to a class and belong to the entire set of objectsthat class creates.

Variables declared and used inside methods are called local variables. They are called so becausethey are not available for use outside the method definition. Local variables can also be declared insideprogram blocks that are defined between an opening brace ‘{‘ and a closing brace ‘}’. These variablesare 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 theprogram 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.

Examples

Int m = 50;

Type variable1 = (type) variable2;

Chapter 4 - Overview of JAVA Language

Page 53: BSIT 4th sem Kuvempu University

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

40BSIT 42 JAVA Programming

Page 54: BSIT 4th sem Kuvempu University

42

//Convert from boolean to char.c = (char)(t?’1':’0');System.out.println (“Value of c after conversion: “ + c);c = (char) (t? 1:0);System.out.println (“Value of c after conversion in unicode: “ + c);

//Convert from boolean to long.l = (long) (t? 1:0);System.out.println(“Value of l after conversion : “ + l);

//Convert from boolean to float.f = (float) (t? 1:0);System.out.println (“Value of f after conversion: “ + f);

//Convert from boolean to double.d = (double) (t? 1:0);System.out.println (“Value of d after conversion: “ + d);

//Convert from boolean to String.g = String.valueOf (t);System.out.println (“Value of g after conversion: “ + g);g = (String) (t?”1":”0");System.out.println (“Value of g after conversion: “ + g);int sum = (int)(b + i + l + d + f);System.out.println (“Value of sum after conversion: “ + sum);

}}

Output

Values of all the variables liket = trueb = 2s = 100c =Ci =200l = 24000f =3.14d =5.3E-14g = string

Chapter 4 - Overview of JAVA Language

Page 55: BSIT 4th sem Kuvempu University

43

Value of t after conversion : 1Value of b after conversion : 1Value of s after conversion : 1Value of c after conversion : 1Value of I after conversion in Unicode: 0Value of l after conversion : 1Value of f after conversion : 1.0Value of d after conversion : 1.0Value of g after conversion : trueValue of g after conversion : 1Value of sum after conversion : 5

4.7 SUMMARY

Java constants and variables, and their representation inside the computer have been described in thischapter. Way and means of declaring and initializing java variables has also been presented. We have alsodiscussed how data type conversions is achieved in java.

EXERCISES

1. What is a Constant?

2. What is a variable?

3. List the eight basic data types used in Java. Give examples.

4. What is scope of a variable.

5. What is type casting? Why is it required in programming?

6. Which of the following are invalid constants and why.

7. Which of the following are invalid variable names and why?

0.001 5 * 1.5 RS 75.50+100 75.45E-2 “15.75”-45.6 -1.4e(+4) 0.000001234

minimum first.Name n1+n2doubles 3rd-row N$

float Sum Total Total-Marks

BSIT 42 JAVA Programming

Page 56: BSIT 4th sem Kuvempu University

8. Find errors, if any, in the following declaration statements:

int x;

float length, height;

double = p,q;

character c1;

final int total;

final pi = 3.142;

long int m;

9. Write a program to determine the sum of the following harmonic series for a given value of n:

1+1/2 + 1/3+ …………..+1/n

The value of n should be given interactively through the keyboard.

10. Write a program to convert the given temperature into Celsius using the following conversion formula

F-32C = And display the values in a tabular form.

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

Chapter 4 - Overview of JAVA Language44

Page 57: BSIT 4th sem Kuvempu University

BSIT 42 JAVA Programming 45

Chapter 5

Oper at o r s An d Exp r essio n s

OBJECTIVES

After 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

Page 58: BSIT 4th sem Kuvempu University

46 Chapter 5 - Operators And Expressions

5.2 ARITHMETIC OPERATORS

Java provides all the basic arithmetic operators. They are listed in the following table 5.1. The basicoperators in Java are:

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). Althoughthe 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 ofthese 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 iscalled an integer expression, and the operation is called integer arithmetic. Integer arithmetic alwaysyields an integer value. In the following examples, if x and y are integers, then for x=12 and y=5 we getthe following results:

x – y = 7

x + y = 17

x * y = 60

x / y = 2 (decimal part truncated)

x % y = 2 (remainder of integer division)

Operator Explanation Example+ adds two numbers x = 1 + 2- subtracts two numbers x = 7 - 4* multiplies two numbers x = 4 * 5/ divides two numbers x = 21 / 3

% Modulo operator(rest of integer division)

x = 17 % 3 //x = 2

Page 59: BSIT 4th sem Kuvempu University

47BSIT 42 JAVA Programming

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 mayassume values either in decimal or exponential form. Modulus operator can also be applied to floatingpoint data.

The following program demonstrates the arithmetic operators. It also illustrates the difference betweenfloating 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”);

Page 60: BSIT 4th sem Kuvempu University

48

double fa=1+1;

double fb=a*3;

double fc=b/4;

double fd=c-a;

double fe= -d;

System.out.println(“fa = “ +fa);

System.out.println(“fb = “ +fb);

System.out.println(“fc= “ +fc);

System.out.println(“fd = “ +fd);

System.out.println(“fe= “ +fe);

}

}

Result

Integer Arithmetic Floating point arithmetic

a=2 fa=2.0

b=6 fb=6.0

c=1 fc=1.5

d=-1 fd=-0.5

e=1 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-modearithmetic expression. If either operand is of the real type, then the other operand is converted to real andthe 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.

Chapter 5 - Operators And Expressions

Page 61: BSIT 4th sem Kuvempu University

49

5.2.4 String Concatenation

The plus sign, +, is used for numeric addition and it is also used to perform String concatenation if oneof the operands is a String (i.e. an instance of the standard Java class String). This is the only operator thatoperates 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 operandsof a + operator is a String then the other is coverted to a String and the result of the operation is a newString that contains the characters from both strings concatenated together with the characters from theleft 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 don’t have the times anddivision 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);

}

}

Here’s the result:

% javac MultiplyDivide.java

% java MultiplyDivide

i is 10

j is 2

i/j is 5

i * j is 20

BSIT 42 JAVA Programming

Page 62: BSIT 4th sem Kuvempu University

50

v op= exp;

Floats and doubles are multiplied and divided in exactly the same way. When faced with an inexactinteger 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 theusual assignment operator, ‘=’. In addition, Java has a set of ‘shorthand’ assignment operators which areused in the form

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

Chapter 5 - Operators And Expressions

Page 63: BSIT 4th sem Kuvempu University

51

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 bedone 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 expressionsis 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 belowtable 5.3.

Table 5.3 Relational operators

BSIT 42 JAVA Programming

Normal way(example)

Short way

X = X + 1 X++X = X – 1 X--X = X * 2 X*=2X = X / 3 X/=3X = X + 5 X+=5X = X - 4 X-=4

Operator Use Returns t r ue if> Op1 > op2 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

Page 64: BSIT 4th sem Kuvempu University

52

A simple relational expression contains only one relational operator and is of the following form.

Ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or combination ofthem. Below table 5.4 shows some examples of simple relational expressions and their values.

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

Chapter 5 - Operators And Expressions

ae -1 relational operator ae - 2

Expression Value15. 6 <= 20 TRUE9.5 < - 10 FALSE-20 >= 0 FALSE10 < 7 + 8 TRUEa+b == c+d TRUE

Page 65: BSIT 4th sem Kuvempu University

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:12Enter Number 2;12Both are equal

Case 2:Enter number 1:12

BSIT 42 JAVA Programming

Page 66: BSIT 4th sem Kuvempu University

54

Enter Number 2;4Both are not equal12 is greater than 4

5.5 LOGICAL OPERATORS

A relational operator compares two values and determines the relationship between them. Forexample, != returns true if the two operands are unequal. This table summarizes Java’s relational operators:

Relational operators often are used with the conditional operators to construct more complex decision-making 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 falseand 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, & alwaysevaluates both of its operands and returns true if both are true. Likewise, | is similar to || if both of itsoperands are boolean. This operator always evaluates both of its operands and returns false if they areboth false.

The following table 5.5 shows the logical operators

Table 5.5 Logical operation

Following table 5.6 gives the false and true conditions for the && and || operations when applied ontwo operands op1 and op2.

&& is logical and. && combines two boolean values and returns a boolean which is true if and only ifboth of its operands are true. For instance

Chapter 5 - Operators And Expressions

Operator Use Returns t r ue if&& Op1 && op2 op1 and op2 are both t r ue| | op1 | | op2 either op1 or op2 is t r ue! ! op op is f al se.

Op-1 op-2 op-1 && op-2 op-1 || op-2True True True TrueTrue False False TrueFalse True False TrueFalse False False False

Table 5.6: Usage of && and || operatore

Page 67: BSIT 4th sem Kuvempu University

55

boolean b;b = 3 > 2 && 5 < 7; // b is trueb = 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 eitheror both of its operands are true. For instance

boolean b;b = 3 > 2 || 5 < 7; // b is trueb = 2 > 3 || 5 < 7; // b is still trueb = 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 bis true !b is false. If b is false !b is true.

boolean b;

b = !(3 > 2); // b is falseb = !(2 > 3); // b is true

These operators allow you to test multiple conditions more easily. For instance the previous examplecan 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 inthe 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;

BSIT 42 JAVA Programming

Page 68: BSIT 4th sem Kuvempu University

56

In this case, the value of y and m would be 6. Suppose, if we rewrite the above statement as

m = 5;

y = m++;

Then, the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the operand andthen the result is assigned to the variable on left. On the other hand, a postfix operator first assigns thevalue to the variable on left and then increments the operand. Table 5.7 illustrates the use of incrementand decrement operators

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

}

}

Chapter 5 - Operators And Expressions

Operator Purpose Syntax Example

++

Pre-Increment j=++i int i=6int j=++i;i is 7 ,j is 7

Post-Increment j=i++ int i=6;int j=i++;i is 7,j is 6

--

Pre-Decrement j=--i int i=6;int j=--i;i is 5, j is 5

Post-Decrement j=i-- int i=6;int j=i--;i is 5, j is 6

Page 69: BSIT 4th sem Kuvempu University

57

Resulta = 4b = 5c = 6d = 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 = 5X = 5x + X++ = 10x = 6y = 5Y = 5y + ++Y = 11Y = 6

5.7 CONDITIONAL OPERATOR

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

BSIT 42 JAVA Programming

Page 70: BSIT 4th sem Kuvempu University

58

Where exp1, exp2 and exp3 are expressions.

The operator ?: works as follows: exp1 is evaluated first. If it is nonzero (true), then the expressionexp2 is evaluated and becomes the value of the conditional expression. If exp1 is false, exp3 is evaluatedand 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 statementas 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 shiftoperators available in the Java programming language.

Chapter 5 - Operators And Expressions

exp1 ? exp2 : exp3

Table 5.7 Shift operators in java

Operator Use Operation>> op1 >> op2 shift bits of op1 right by distance

op2<< op1 << op2 shift bits of op1 left by distance op2>>> op1 >>> op2 shift bits of op1 right by distance

op2

(unsigned)

Page 71: BSIT 4th sem Kuvempu University

59

Each shift operator shifts the bits of the left-hand operand over by the number of positions indicated bythe right-hand operand. The shift occurs in the direction indicated by the operator itself. For example, thefollowing 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 tothe right by one position—110 or 6 in decimal. Note that the bit farthest to the right falls off the end into thebit bucket.

The Java programming language also provides these four operators that perform logical functions ontheir operands:

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:

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 binaryrepresentation 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, youcan see that the two high-order bits (the two bits farthest to the left of each number) of each operand are1. Thus the resulting bit in the result is also 1. The low-order bits evaluate to 0 because either one or bothbits in the operands are 0:

1101 & 1100

———1100

BSIT 42 JAVA Programming

Operator Use Operation& op1 & op2 bitwise and| op1 | op2 bitwise or^ op1 ^ op2 bitwise xor~ ~op2 bitwise complement

op1 op2 Result0 0 00 1 01 0 01 1 1

Page 72: BSIT 4th sem Kuvempu University

60

The | operator performs the inclusive or operation and ̂ performs the exclusive or operation. Inclusiveor 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:

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.

And finally, the complement operator inverts the value of each bit of the operand: if the operand bit is1 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 youcan 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 citizenyou could check if their age was greater than or equal to 18 and their age was less than or equal to 65.

Chapter 5 - Operators And Expressions

op1 op2 Result0 0 00 1 11 0 11 1 1

op1 op2 Result0 0 00 1 11 0 11 1 0

Page 73: BSIT 4th sem Kuvempu University

61

5.8.2 Dot Operator

The dot operator(.) is used to access the instance variables and methods of class objects. Examples:

person1.age // Reference to the variable ageperson1.salary() // 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 arecompatible, the java technology performs the conversation Automatically. For example, an int value canalways be assigned to a long Variable. Where information would be lost in an assignment ,the compilerrequires that you confirm the assignment with a typecast. This can be done ,for example , by”squeezing”a long value into an int variable. Explicit casting is done like this:

Long bigvalue= 99LInt small= (int) (bigvalue);

The desired target type is placed in parentheses and used as a prefix to the expression that must bemodified.

5.8.4 Arithmetic Expressions

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

5.8.5 Precedence of Arithmetic Operators

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

BSIT 42 JAVA Programming

Algebraic Expression Java Expressiona b-c a*b-c(m+n)(x+y) (m+n)*(x+y)Ab/c a*b/c3x2+2x+1 3*x*x+2*x+1X /+cy x/y+c

Page 74: BSIT 4th sem Kuvempu University

62

High priority * / %Low priority + -

The basic evaluation procedure includes two left-to-right passes through the expressions. During thefirst 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 evaluationstatement:

x = a-b/3+c*2-1When 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 (12/3 evaluated)Step2: x = 9-4+6-1 (3*2 evaluated)

Second pass

Step3 : x = 5+6-1 (9-4 evaluated)Step4: x = 11-1 (5+6 evaluated)Step5: x = 10 (11-1 evaluated)

However, the order of evaluation can be changed by introducing parenthesis into an expression. Considerthe 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 twoor more sets of parenthesis appear one after another as shown above, the expression contained in the left-most set is evaluated first and the right-most in the last. Given below are the new steps.

First pass

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

Second pass

Step3 : 9-2*1Step4: 9-2

Third pass

Step5: 7

Chapter 5 - Operators And Expressions

Page 75: BSIT 4th sem Kuvempu University

63

5.8.6 Operator Precedence and Associativity

Each operator in Java has a precedence associated with it. This precedence is used to determine howan expression involving more than one operator is evaluated. There are distinct levels of precedence andan operator may belong to one of the levels. The operators at the higher level of precedence are evaluatedfirst. 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.8provides a complete list of operators, their precedence levels, and their rules of association.

BSIT 42 JAVA Programming

Operator Description Associativity Rank. Member selection Left to right 1() Function call[] Array element reference- Unary minus Right to left 2++ Increment-- Decrement! Logical Negation~ Ones Compliment(type) Casting* Multiplication Left to right 3/ Division% Modulus+ Addition Left to right 4- Subtraction<< Left shift Left to right 5>> Right shift>>> Right shift with zero fill< Less than Left to right 6<= Less than or equal to> Greater than>= Greater than or Equal toInstance of Type comparison== Equality Left to right 7!= Inequality& bitwise and Left to right 8^ bitwise xor Left to right 9| bitwise or Left to right 10&& Logical and Left to right 11|| Logical or Left to right 12?: Conditional operator Right to left 13= Assignment operator Right to left 14Op= Shorthand assignment

Table 5.8: List of operators & there precedence levels

Page 76: BSIT 4th sem Kuvempu University

64

5.9 MATHEMATICAL FUNCTIONS

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. Thefollowing table lists the math functions defined in the Math class. These functions should be used asfollows:

Math.function_name( )

Example

double y = Math. Sqrt(x);

Mathematical Functions

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;

Chapter 5 - Operators And Expressions

Functions ActionSin (x) Returns the sine of the angle x in radiansCos (x) Returns the cosine of the angle x in radiansTan (x) Returns the cosine of the angle x in radiansAsin (y) Returns the angle whose sine is yAcos (y) Returns the angle whose cosine is yAtan(y) Returns the angle whose tangent is yAtan2(x,y) Returns the angle whose tangent isx/ypow(x,y) Returns x raised to y (x

y)

exp(x) Returns e raised to x (ex)

log(x) Returns the natural logarithm of xsqrt(x) Returns the square root of xceil(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)f loor(x) 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)rint(x) Returns the truncated value of x.abs(x) Returns the absolute value of x.max(a,b) Returns the maximum of a and b.min(a,b) Returns the minimum of a and b.

Page 77: BSIT 4th sem Kuvempu University

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 andequal 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 thenearest 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. Everyinteger 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));

BSIT 42 JAVA Programming

Page 78: BSIT 4th sem Kuvempu University

66

// There’s a corresponding max() method that returns the larger of two numbersSystem.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 radiansdouble 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));

Chapter 5 - Operators And Expressions

Page 79: BSIT 4th sem Kuvempu University

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 there’s one Random method that returns a pseudo-random number// between 0.0 and 1.0;

System.out.println(“Here’s one random number: “ + Math.random());System.out.println(“Here’s another random number: “ + Math.random());}

}

Output

i is 7j is -9x is 72.3y is 0.34|7| is 7|-9| is 9|72.3| is 72.3|0.34| is 0.3472.3 is approximately 720.34 is approximately 0The ceiling of 7 is 7The ceiling of -9 is -9The ceiling of 72.3 is 73The ceiling of 0.34 is 1The floor of 7 is 7The floor of -9 is -9The floor of 72.3 is 72The floor of 0.34 is 0min(7,-9) is -9min(72.3,0.34) is 0.34min(7,72.3) is 7min(0.34,-9) is -9max(7,-9) is 7max(72.3,0.34) is 72.3

BSIT 42 JAVA Programming

Page 80: BSIT 4th sem Kuvempu University

68

max(7,72.3) is 72.3max(0.34,-9) is 0.34Pi is 3.14159e is 2.71828cos(0.785398) is 0.707107sin(0.785398) is 0.707107acos(0.707) is 0.785549asin(0.707) is 0.785247atan(0.707) is 0.615409exp(1.0) is 2.71828exp(10.0) is 22026.5exp(0.0) is 1log(1.0) is 0log(10.0) is 2.30259log(Math.E) is 1pow(2.0, 2.0) is 4pow(10.0, 3.5) is 3162.28pow(8, -1) is 0.125The square root of 0 is 0The square root of 1 is 1The square root of 2 is 1.41421The square root of 3 is 1.73205The square root of 4 is 2The square root of 5 is 2.23607The square root of 6 is 2.44949The square root of 7 is 2.64575The square root of 8 is 2.82843The square root of 9 is 3Here’s one random number: 0.820582Here’s another random number: 0.866157

5.10 SUMMARY

In this chapter, we have discussed all the operators in java and their usage in expressions. We havehighlighted the type conversions and order of precedence

While evaluating expressions simple programs are presented to demonstrate use of different typeexpressions operators

It should be noted that all java types are of fixed size and are machine independent.

Chapter 5 - Operators And Expressions

Page 81: BSIT 4th sem Kuvempu University

69

EXERCISES

1. Which of the following arithmetic expressions are valid?

Identify unnecessary parenthesis in the following arithmetic expressions.

a) (x-(y/5)+z) % 8) + 25b) ((x-y) * p) + qc) (m*n) + (-x/y)d) x/(3*y)

Find errors, if any, in the following assignment statements and rectify them.

e) x = y = z = 0.5, 2.0 – 5.75;f) m = ++a * 5;g) y = sqrt(100);h) p * x/y;e) s = /5;f) a = b++ -c * 2

Determine the value of each of the following logical expressions if a=5, b=10 and c=-6

a) a>b && a<cb) a<b && a>cc) a==c || b>ad) b>15 && c<0 || a>0e) (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 valueDepreciation =

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 + (at2)/2

Where u is the initial velocity (metres per second), a is the acceleration (metres per second). Write a

a) 25/3 % 2 e) –14 % 3b) +9/4 + 5 f) 15.25 + -5.0c) 7.5 % 3 g) (5/3) * 3 + 5 % 3d) 14 % 3 + 7 % 2 h) 21 % (int) 4.5

BSIT 42 JAVA Programming

Page 82: BSIT 4th sem Kuvempu University

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 5 - Operators And Expressions70

Page 83: BSIT 4th sem Kuvempu University

Chapter 6

Decision Making and BranchingOb ject ives

After 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 ascontrol 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 executionof 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

Page 84: BSIT 4th sem Kuvempu University

72

It allows the computer to evaluate the expression first and then , depending on whether the value of theexpression (relation or condition) is ‘ true ‘ (non-zero) or ‘false’ (zero), it transfers the control to aparticular statement. This point of program has two paths to follow , one for the true condition and theother for the false condition.

The if statement may be implemented in different forms depending on the complexity of the conditionsto 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 executionwill jump to statement-x, remember, when the condition is true both the statement-block and the statement-x are executed in sequence. The flowchart is depicted in Fig. 6.1

Chapter 6 - Decision Making and Branching Objectives

if (test expression){

statement block;}

Page 85: BSIT 4th sem Kuvempu University

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

}

}

BSIT 42 JAVA Programming

Page 86: BSIT 4th sem Kuvempu University

74

6.2.2 THE IF…ELSE 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 statementare executed; otherwise the false-block statement(s) executed. In either case, either true-block or false-block 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

Chapter 6 - Decision Making and Branching Objectives

Page 87: BSIT 4th sem Kuvempu University

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

}

}

BSIT 42 JAVA Programming

Page 88: BSIT 4th sem Kuvempu University

76

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 innested 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 secondtest. If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluatedand then the control is transferred to the statement-x.

Example: To find the greatest of two numberspublic 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); }

Chapter 6 - Decision Making and Branching Objectives

Page 89: BSIT 4th sem Kuvempu University

77

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 thefirst 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 notpublic class DetermineLeapYearExample

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

//year we want to checkint year = 2004;

//if year is divisible by 4, it is a leap yearif(year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))System.out.println(“Year “ + year + “ is a leap year”);

elseSystem.out.println(“Year “ + year + “ is not a leap year”);

}}

Output of the example would beYear 2004 is a leap year

else if (x == y) { System.out.println("The two numbers are equal."); } else { System.out.println(y + " is greater than " + x); } System.out.println();

}}

BSIT 42 JAVA Programming

Page 90: BSIT 4th sem Kuvempu University

78

6.2.4 The Else If Ladder

There is another way of putting ifs together when multi path decisions are involved. A multi pathdecision is a chain of ifs in which the statement associated with each else is an if. It takes the followinggeneral 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 thecontrol 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 beexecuted.

The flowchart is given in Fig. 6.5

Chapter 6 - Decision Making and Branching Objectives

Page 91: BSIT 4th sem Kuvempu University

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

BSIT 42 JAVA Programming

Page 92: BSIT 4th sem Kuvempu University

80

      grade = “Honours”;

else

if (marks >59)

      grade = “First Division”;

else

if (marks > 49)

       grade = “Second Division”;

else

if(marks > 39)

        grade = “Third division”;

else

        grade = “Fail”;

Java program

Class grade( )

{

public static void main(String[ ] args) {

int testscore = 76;

char grade;

if (testscore >= 79) {

grade = ‘Honours’;

} else if (testscore >= 59) {

grade = ‘First division’;

} else if (testscore >= 49) {

grade = ‘second division’;

} else if (testscore >= 39) {

grade = ‘Third division’;

} else {

grade = ‘Fail’;

}

System.out.println(“Grade = “ + grade);

}

}

Chapter 6 - Decision Making and Branching Objectives

Page 93: BSIT 4th sem Kuvempu University

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 thecompound if statement: 76 >= 59 and 76 >= 60. However, as the runtime system processes a compoundif 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 certaintype of multi-way branch.

A switch statement allows you to test the value of an expression and, depending on that value, to jumpto some location within the switch statement. The expression must be either integer-valued or character-valued. It cannot be a String or a real number. The positions that you can jump to are marked with “caselabels” that take the form: “case constant” This marks the position the computer jumps to when theexpression evaluates to the given constant. As the final case in a switch statement you can, optionally, usethe label “default:”, which provides a default jump point that is used when the value of the expression isnot listed in any case label.

A switch statement has the form:

BSIT 42 JAVA Programming

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

Page 94: BSIT 4th sem Kuvempu University

82

The break statements are technically optional. The effect of a break is to make the computer jump tothe end of the switch statement. If you leave out the break statement, the computer will just forge aheadafter completing one case and will execute the statements associated with the next case label. This israrely what you want, but it is legal. However, that inside a subroutine, the break statement is sometimesreplaced 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 specificallylabeled.

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 terminatethe execution of the statements.

Chapter 6 - Decision Making and Branching Objectives

Page 95: BSIT 4th sem Kuvempu University

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 bei is 0i is 1i is 2Free 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!”);

BSIT 42 JAVA Programming

Page 96: BSIT 4th sem Kuvempu University

84

}}

}

Output would bei is 0i is 1i is 2Free flowing switch example!

The switch statement evaluates its expression, in this case the value of month, and executes theappropriate case statement. Thus, the output of the program is: August. Of course, you could implementthis by using an if statement:

Deciding whether to use an if statement or a switch statement is a judgment call. You can decidewhich to use, based on readability and other factors. An if statement can be used to make decisions basedon ranges of values or conditions, whereas a switch statement can make decisions based only on a singleinteger 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 breakstatement terminates the enclosing switch statement, and the flow of control continues with the firststatement following the switch block. The break statements are necessary because without them, thecase statements fall through. That is, without an explicit break, control will flow sequentially throughsubsequent 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;

Chapter 6 - Decision Making and Branching Objectives

Page 97: BSIT 4th sem Kuvempu University

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 andon nothing else. For instance one common operation is setting the value of a variable to the maximum oftwo 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 if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator youcan 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 isreturned is dependent on the conditional test, a > b. The condition can be any expression which returns aboolean value.

BSIT 42 JAVA Programming

Page 98: BSIT 4th sem Kuvempu University

86

6.5 SUMMARY

In this chapter, we discussed the features of the following selection statements.

Available in java: If statement, switch,conditional operator.

Several applications of these statements have been presented. We also discussed how these can beused to solve problems. These concepts are useful in developing complex systems. Control execution isan important tool.

EXERCISES

1. Determine whether the following are true or false;

a) When if statements are nested, the last else gets associated with the nearest if without an else.

b) One if can have more than one else clause.

c) A switch statement can always be replaced by a series of if….else statements

d) A switch expression can be of any type.

e) A program stops its execution when a break statement is encountered.

2. In what ways does a switch statement differ from an if statement?

3. Find errors, if any, in each of the following segments;

a) if (x+y = z && y > 0)

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

Chapter 6 - Decision Making and Branching Objectives

Page 99: BSIT 4th sem Kuvempu University

87BSIT 42 JAVA Programming

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) in the range 81 to 100,

b) in the range 61 to 80,

c) in the range 41 to 60, and

d) 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:

DiscountPurchaseAmount

Mill Cloth Handloom Items

0-100 - 5.0%

101-200 5.0% 7.5%

201-300 7.5% 10.0%

Above 300 10.0% 15.0%

Page 100: BSIT 4th sem Kuvempu University

Chapter 7

LOOPING

OBJECTIVES

After going through this chapter, you will be able to write simple programs using the followingloop 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 loopis satisfied. A program loop therefore consists of two segments , first the body of the loop and other iscontrol Statement. The control statements test certain conditions and then makes the repeated executionof 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 controlvariable is tested prior to the start of each iteration whereas in post-test loops the control variable is testedat the end of each iteration (Fig. 7.1.). From an efficiency point of view, the advantage is that ,we canreduce 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).

Chapter 7 - Looping88

Page 101: BSIT 4th sem Kuvempu University

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 isthe while statement. The while statement contains a condition and a loop body. The condition is enclosedwithin parentheses. The syntax and the flow diagram are given in Fig 7.2

Fig. 7.2. Syntax and flow diagram of while loop

BSIT 42 JAVA Programming 89

Page 102: BSIT 4th sem Kuvempu University

90

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, thecondition may always remain true and the loop may never terminate. You change the values of thevariables by performing arithmetic operations on the variables.

You can write a single statement or multiple statements in the loop body. Multiple statements should beenclosed 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 thecondition evaluates to true is the loop body executed. Therefore, the while loop is also called the toptested loop. After the loop body is executed, the condition is evaluated again. The sequence of evaluatingthe condition and executing the loop body continues until the condition becomes false.

7.3 DO STATEMENT

Similar to the while statement, the do-while statement is a loop statement provided by Java. Thestatement 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 whilestatement, the loop body is executed only when the condition stated in the statement is true. In contrast, inthe do-while loop, the loop body is executed at least once, regardless of the condition evaluating to true orfalse.

After the loop body is executed once, the condition in the do-while statement is checked. If thecondition 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.

Chapter 7 - Looping

Example:class numbers{

public static void main(String args[ ]){ int n=0; int num=5; while(n<=num) { sysytem.out.printfln(n); n++; } } }

Page 103: BSIT 4th sem Kuvempu University

91

You can use the do-while loop in situations where an action must be performed at least once withoutevaluating 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 5Class numbers{

public static void main(String [ ] args){int n=0; int num=5;do

{

sysytem.out.printfln(n); n++;}

while(n<=5);}

}

BSIT 42 JAVA Programming

Page 104: BSIT 4th sem Kuvempu University

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=0int 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();

}}

7.4 FOR STATEMENTS

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

Chapter 7 - Looping

Page 105: BSIT 4th sem Kuvempu University

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 withinparentheses. The first element of the for statement is initialization expressions. The initialization expressionselement is an assignment statement. The assignment is done only once before the for statement beginsexecution. 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. Updateexpressions is the third element in the for statement. This element changes the values of the variablesused in the test condition. Update expressions are executed at the end of each iteration after the loop bodyis executed. The elements of a for statement are separated by semicolons.

Example: //the program display a number form 2 to 10class 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

BSIT 42 JAVA Programming

Page 106: BSIT 4th sem Kuvempu University

94

In the for loop(Fig. 7.4.), first variable j is initialized to 2. Next, the value of j is compared with 10. Ifthe test condition is true, the value of j is displayed on the screen. Next, the value of j is incremented byone.

After the value of j is incremented, the test condition is evaluated again. If the test condition evaluatesto true, the print function is executed again. If the test condition evaluates to false, the flow of controlcomes out of the for loop.

Example 2:

// The program displays even numbers between 2 and 10Class 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

Chapter 7 - Looping

Page 107: BSIT 4th sem Kuvempu University

95

This Java example shows how to input the number from console and check if the number is apalindrome 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 consoleBufferedReader br = new BufferedReader(new InputStreamReader(System.in));

//parse the line into intnumber = 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;

BSIT 42 JAVA Programming

Page 108: BSIT 4th sem Kuvempu University

96

//reverse the numberwhile(n > 0){temp = n % 10;n = n / 10;reversedNumber = reversedNumber * 10 + temp;

if(number == reversedNumber)System.out.println(number + “ is a palindrome number”);elseSystem.out.println(number + “ is not a palindrome number”);

}

Output is

Enter the number to check..121

Number is 121121 is a palindrome number

7.4.1. Additional Features of the for loop

The for loop has several capabilities that are not found in other loop constructs. For examplemore 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 asfor (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);

Chapter 7 - Looping

Page 109: BSIT 4th sem Kuvempu University

97

system.out.println(“j=” +j);}

}}

The test condition in the for loop may have any compound relation and the testing need not belimited 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 illustratedin Fig. 7.6.

Fig. 7.6 Nested for loops

BSIT 42 JAVA Programming

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

------------------------------------------------------------for (j=0; j<10;j++){------------------------------------------------------------}--------------------------------------------------------------

}

Page 110: BSIT 4th sem Kuvempu University

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

This Java example shows how to generate a pyramid of numbers for given number using forloop example.

import java.io.BufferedReader;import java.io.InputStreamReader;public class GeneratePyramidExample{

public static void main (String[] args) throws ExceptionBufferedReader 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++){

Chapter 7 - Looping

Page 111: BSIT 4th sem Kuvempu University

99

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

System.out.print(y + “\t”);y = y + x;

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

}

Output

Enter Number: 5Enter X: 101 23 4 56 7 8 910 11 12 13 14

Enter Number: 5Enter X: 2

02 46 8 1012 14 16 1820 22 24 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 seriesint limit = 20;long[ ] series = new long[limit];//create first 2 series elementsseries[0] = 0;series[1] = 1;//create the Fibonacci series and store it in an array

BSIT 42 JAVA Programming

Page 112: BSIT 4th sem Kuvempu University

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 200 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

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 thenext iteration of the loop statement. An example of such a situation is a password verification programwhere 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 thecontrol is returned to the start of the loop statement. This saves time because the remaining statements inthe 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 ofthe same loop. When the current iteration of a loop stops, the statements after the continue statement inthe 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 switchstatement. Use of continue statements is illustrated in the following program.

// The program displays all even numbers between 1 and 20class EvenNum20{

public static void main (string [ ] args){

int j,k;for (j =1, k= 0; j<=20; j++)

Chapter 7 - Looping

Page 113: BSIT 4th sem Kuvempu University

101BSIT 42 JAVA Programming

{k = j /2;if (k !=0)continue;elsesystem.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 do-while loops. In the case of the for statement, the continue statement causes the flow of control to moveto 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;elseSystem.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 andany remaining code in the body of the loop. When a Break statement is encountered inside the loop, theloop is terminated and program control resumes the next statement following the loop.

Page 114: BSIT 4th sem Kuvempu University

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

}}

In several instances, such as an error or incorrect input from the user, it may be necessary for the flowof 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 statementafter the loop statement or the switch statement. Exiting from a loop with a break statement is shown inFig. 7.7.

Chapter 7 - Looping

Page 115: BSIT 4th sem Kuvempu University

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

While structure

do structure

for structure

These are useful in developing concise, compact and structured programs. Break and Continuestatements are used to jump or skip out of a loop whenever the need arises.

BSIT 42 JAVA Programming

Page 116: BSIT 4th sem Kuvempu University

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. Write a program to compute the sum of the digits of a given integer number

3. 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. 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; ………. ……….}

b). m = 1;do { ………… m = m + 2;}

while (m < 10)

c). int ilfor (i=0; i<=5; i= i+2/3){ …………. ………….}

d). int m = 10;int n= 7;while ( m % n >= 0){ ………….. m = m + 1; n = n + 2; …………..}

Chapter 7 - Looping104

Page 117: BSIT 4th sem Kuvempu University

Chapter 8

Classes Ob ject s An d Met ho ds

OBJECTIVES

After 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 underlyingstructure. Anything we wish to represent in java program must be encapsulated in a class . Class definesthe state and behavior of objects . classes create objects. Objects use methods to communicate betweenthem.

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

Page 118: BSIT 4th sem Kuvempu University

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, tocreate 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 representationof an object, then an instance is its concrete representation.

Example:

You might perhaps define a motorcycle class that describes the features of all motorcycles (hascolor, make, engineon etc..). The motorcycle class serves as an abstract model for the concept of amotorcycle-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 ina class definition:

Variables

Variables are the data types that store data items that typically differentiate one object of the classfrom another. They are also referred to as data members of a class. Every class you write in Java isgenerally made up of two components: attributes and behavior. Let’s consider an object to define amotorcycle. Attributes are the individual things that differentiate one object from another and determinethe 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.

Syntax of the class declaration

class classname

{

member variable declarations;

method declarations;

}

Page 119: BSIT 4th sem Kuvempu University

107

Attributes are defined by variables, in fact, you can consider them because each instance of a classcan 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 theclass definition. Each object will have its own values for each instance variable. The name ‘instancevariable’ originates from the fact that an object is an ‘instance’ or an occurrence of a class and the valuesstored 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 avariable name, and can have an initial value specified.

Instance variables define the attributes of an object. The class defines the type of the attribute, andeach 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 betweenall 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 thatclass. 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 thevalues in other objects. A class variable must be declared using the keyword static preceding the typename.

Look at the following diagram (Fig 8.1), which illustrates the difference between the two: This showsa schematic of a class Sphere with one class variable

Fig. 8.1 Difference between the class variables and instance variables

BSIT 42 JAVA Programming

Page 120: BSIT 4th sem Kuvempu University

108

Methods

These define the operations you can perform for the class—so they determine what you can do to, orwith, objects of the class. Methods typically operate on the fields—the variables of the class. A class’sbehavior determines what instances of that class do when asked to by another class or object. Behavioris the only way that objects can have anything done to them. Our motorcycle class might well have thefollowing behavior:

Start the engine

Stop the engine

Speed up

Change gear

To define an object’s 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 thevariables 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());

}

Chapter 8 - Classes Objects And Methods

Page 121: BSIT 4th sem Kuvempu University

109

OUTPUT of the above given Java Class Example would be :

Hello Visitor

8.3 ADDING VARIABLE TO CLASS

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 variabledefined 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.ethe 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 bereturned by the method when we execute it. The method must always return a value of this type. Todefine 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

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}

BSIT 42 JAVA Programming

Page 122: BSIT 4th sem Kuvempu University

110

have to have parameters specified. A method that does not require any information to be passed to itwhen 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;

Chapter 8 - Classes Objects And Methods

Page 123: BSIT 4th sem Kuvempu University

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 variablesdouble radius; // Radius of a spheredouble xCenter; // 3D coordinatesdouble yCenter; // of the centerdouble zCenter; // of a sphere

// Static method to report the number of objects created

static int getCount ( ){

return count; // Return current object count

}

// Instance method to calculate volume doublevolume ( ){

return 4.0/3.0*PI*radius*radius*radius;}

There are two varieties of methods—instance methods and class methods. You can execute classmethods even when no objects of a class exist, whereas instance methods can only be executed inrelation 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 referredto as static methods.

BSIT 42 JAVA Programming

Page 124: BSIT 4th sem Kuvempu University

112

Since class methods can be executed when there are no objects in existence, they cannot refer toinstance variables.. In fact the Java compiler won’t let you try. If you reference an instance variable in thecode for a class method, it won’t compile—you’ll just get an error message. The method main(), whereexecution of a Java application starts, must always be declared as static, as you have seen. The reasonfor this should be apparent by now. Before an application starts execution, no objects exist, so in order tostart execution, you need a method that is executable even though there are no objects—a static methodtherefore.

Note that, although instance methods are specific to objects of a class, there is only one copy of aninstance method in memory that is shared by all objects of the class, as it would be extremely expensiveto replicate all the instance methods for each object. There is a special mechanism that ensures that, eachtime 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. Amethod 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, asfollows:

public class ClassMethod{ public static int getNumber ( )

{}

}

public class UseMethod{

// Call the method using the classnameint x = ClassMethod.getNumber ( );

...}

Returning from a Method

To return a value from a method when its execution is complete you use a return statement, forexample:

return return_value; // Return a value from a method

After executing the return statement, the program continues from the point where the method wascalled. The value, return_value, that is returned by the method, can be any expression that produces avalue of the type specified for the return value in the declaration of the method. Methods that return a

Chapter 8 - Classes Objects And Methods

Page 125: BSIT 4th sem Kuvempu University

113

value—that is methods declared with a return type other than void—must always finish by executing areturn statement that returns a value of the appropriate type. Note, though, that you can put several returnstatements within a method if the logic requires this. If a method does not return a value, you can just usethe 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 bodyof 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 thetype of each value that can be passed as an argument to the method, and the variable name that is to beused in the body of the method to refer to each value passed. The difference between a parameter andan argument is sometimes confusing because people often, incorrectly, use them interchangeably. Wewill try to differentiate them consistently, as follows:

A parameter has a name and appears in the parameter list in the definition of a method. Aparameter defines the type of value that can be passed to the method, and the name that is usedto 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 theargument is referenced by the parameter name during execution of the method.

Fig. 8.2 parameter passing and returning a value from the method

BSIT 42 JAVA Programming

Page 126: BSIT 4th sem Kuvempu University

114

Here we have the definition of a method Add( ). This can only appear within the definition of a class,but the rest of the class definition has been omitted so as not to clutter up the diagram. You can see thatthe method has two parameters, value1, and value2, both of which are of type double, that are used torefer to the arguments 3.0 and 5.0 respectively within the body of the method. Since this method has notbeen defined as static, you can only call it for an object of the class. We call Add( ) in our example for theobject, obj.

When you call the method from another method (from main( ) in this case, but it could be from someother method), the values of the arguments passed are the initial values assigned to the correspondingparameters. You can use any expression you like for an argument when you call a method, as long as thevalue it produces is of the same type as the corresponding parameter in the definition of the method. Withour method Add( ), both parameters are of type double, so both argument values must always be of typedouble.

The method Add( ) declares the variable result, which only exists within the body of the method. Thevariable is created each time you execute the method and it is destroyed when execution of the methodends. All the variables that you declare within the body of a method are local to the method, and are onlyaround while the method is being executed. Variables declared within a method are called local variablesbecause they are local to the method. Local variables are not initialized automatically. If you want yourlocal 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 classNumberFactorial{

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 beFactorial of a number is 120

This Following example shows how to swap two numberspublic class SwapElementsExample{

Chapter 8 - Classes Objects And Methods

Page 127: BSIT 4th sem Kuvempu University

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 beBefore SwappingValue of num1 is: 10Value of num2 is: 20After SwappingValue of num1 is: 20Value of num2 is: 10

Program to swap two numbers without using the third variablepublic 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 firstnum1 = num1 + num2;

BSIT 42 JAVA Programming

Page 128: BSIT 4th sem Kuvempu University

116

num2 = num1 - num2;num1 = num1 - num2;

System.out.println(“After Swapping”);System.out.println(“Value of num1 is :” + num1);System.out.println(“Value of num2 is :” +num2);

}}

Output of Swap Numbers example would beBefore SwappingValue of num1 is: 10Value of num2 is: 20After SwappingValue of num1 is: 20Value 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 suchas a car then we can describe a car by its state and its behavior. The state of the car includes the currentspeed, the type of transmission, whether it is two-wheel or four-wheel drive, whether the lights are on, thecurrent 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 stateof an object is determined by its data (variables); the behavior by its methods. Thus a software objectcombines 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-stepProcess.

1. decleare a variable of class type. This variable does not define an object instead it is a simply avariable 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 memoryfor an object and returns a reference to it. This reference is stored in the variable declared.

Chapter 8 - Classes Objects And Methods

Page 129: BSIT 4th sem Kuvempu University

117

Example:

Box mybox / / declare a reference to an object of the class

Mybox = new Box( ) //allocate a box object

The first line declares mybox as a reference to an object of type box. After the line executes, myboxcontains the value null, which indicates that it does not point to the object. The next line allocates an actualobject 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 itsclass. If any changes are made to the variables of one object, it will have no effect on variables of other.

BSIT 42 JAVA Programming

Page 130: BSIT 4th sem Kuvempu University

118

Accessing a class members

The members of the class can be accessed using the following form

Objectname.variablename;

Objectname.methodname(parameter-list);

Here objectname is the name of the object, variablename is the name of the Instance variable insidethe object that we wish to access, method name is the Method that we wish to call, and parameter list isa comma separated list of “actual values” that must match in type and number with the parameter list ofthe 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 theclass 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 = 64The volume is = 750

Constructors

The central player in object initialization is the constructor. In Java, constructors are similar to methods,

Chapter 8 - Classes Objects And Methods

Page 131: BSIT 4th sem Kuvempu University

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 specifiersto constructors, but unlike methods, constructors with public, protected, or package access are not inheritedby subclasses. (Also, instead of determining the ability to invoke a method, the access level of a constructordetermines 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:

In the following program, the Box class definition includes a constructor method that assigns the value10 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 doesnot need to assign values to the instance variables:

No return type specified

Constructor name is the same as class name

public Box( )

{... }

BSIT 42 JAVA Programming

Page 132: BSIT 4th sem Kuvempu University

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

}}ResultVolume is 1000.00

Now, suppose that you want to provide values for the length, width, and height instance variableswhen 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);}

}

Chapter 8 - Classes Objects And Methods

Page 133: BSIT 4th sem Kuvempu University

121

Note that the constructor for three parameters, like the one for zero parameters, is named forthe class in which it appears.

To tell Java to use the three-parameter constructor, blocking the involvement of the zero-parameter 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 isnot to be done with the zero-parameter constructorThe 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 definesthe this keyword. This can be used inside any method to refer to the current object. ,i.e .,this isalways a reference to the object on which the method was invoked.

Example 1:Box (double a, double b, double c)

BSIT 42 JAVA Programming

Page 134: BSIT 4th sem Kuvempu University

122

{this.width=a;this.height=b;this.depth=c;

}

Example 2:public class Class2{

String name; int age;public Class2( ){

name = “Rahul”; age = 39;}public void printName( ){

System.out.println( “The name of this object is “ + name );}

}public class Class3{

String name;int age;

public Class3 (String name, int age ){

this.name = name;this.age = age;

}

public void printName( ){

System.out.println( “The name of this object is “ + name );}

}

8.5 DEFINING METHODS

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

Chapter 8 - Classes Objects And Methods

Page 135: BSIT 4th sem Kuvempu University

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

}

Example :

Class Student{

String name;int mark;String option;

Student(String nm){

name=nm;}

public void setMark(int m)

BSIT 42 JAVA Programming

Page 136: BSIT 4th sem Kuvempu University

124

{mark = m;

}public int getMark( ){

return(mark);}

public void chooseOption(String m){

option = m;}

public String getOption( ){

return(option);}

} //Student

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 objectto 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 formore than one method. In some circumstances, you might want to write several methods in thesame class that do basically the same job with different arguments. (Compare to overriding methods.)

Chapter 8 - Classes Objects And Methods

Page 137: BSIT 4th sem Kuvempu University

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 tothe 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 overloadedmethods must differ.

2. The argument lists of the calling statement must differ enough to allow unambiguousdetermination 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 parametersint 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)

BSIT 42 JAVA Programming

Page 138: BSIT 4th sem Kuvempu University

126

{return (a+b+c);

}}

From the main method we can call the add method which is in class add. The add method isselected form the four depending on the number and type of the parameter passed to the method.

Ob.add(2,3) // calls the add method with two integer parameter

Ob.add(2,3,4) //calls the add method with three integer parameters

Ob.add(3.0,4.0) //calls the add method with two double type parameters

Ob.add(3.0,4.0,5.0) //calls the add method with three double type parameters.

Example 2:

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

}

OutputThe value is 50The value is 4200

Chapter 8 - Classes Objects And Methods

Page 139: BSIT 4th sem Kuvempu University

127

8.6 INHERITANCE: EXTENDING CLASSES

So far we have dealt with single class programs. We will declare class and then write statementsaccording to each program. The properties of each class is available to that class only. Inheritance refersto the properties of a class being available to other classes as well. The original class is called Base Classand Derived classes are classes created from the existing class (Base Class). It will have all the featuresof 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 thecode

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 ofsituation occurs when we want to add some more properties to existing class without actually modifyingit

In the following example we have a base class called book which consists of name of the book, id ofthe book and a method to display. Further we want to add variable author name to the book with existingproperties so we have created a derived class book1 in which we will add the variable author and amethod to display the author. Now this derived class will contain the properties of the base class includingits 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);}

}

BSIT 42 JAVA Programming

Page 140: BSIT 4th sem Kuvempu University

128

class book1 extends book{

String author;void showderived( ){

System.out.println(“the author name is:” +author);}

}

class simpleinhertence{

public static void main(String [] args){

book superob=new book( );book1 subobj = new book1( );superob.id=10;superob.name=”java”;system.out.println(“the contents of super object is”);superob.showsuper( );system.out.println( );subobj.id=20;

subobj.name=”c programming”;subobj.author=”Balaguruswamy”;System.out.println(“the contents of the subobj:”);subobj.showsuper( );subobj.showderived( );

}}

Result

The contents if super object is

The id and name of the book is: 10 java

The contents of the subobj:

The id and name of the book is : 20 c programming

The autor name is: Swamy

As you see, the subclass book1 includes all the members of its superclass, book. This is why subobcan access the id and name and call showsuper.

Chapter 8 - Classes Objects And Methods

Page 141: BSIT 4th sem Kuvempu University

129

Even though book is a superclass of book1 it is also a completely independent stand-alone class. Beinga 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 classthen this mechanism is known as the multilevel inheritance. The derived class is called the subclass orchild class for it’s parent class and this parent class works as the child class for it’s 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”);     }}

BSIT 42 JAVA Programming

Page 142: BSIT 4th sem Kuvempu University

130

class C extends B{   void display()

{     System.out.println(“C”);   }  public static void main(String[] args){     A a = new A();     a.get(5,6);     a.Show();     }}

Java does not support multiple Inheritance

Multiple Inheritance

The mechanism of inheriting the features of more than one base class into a single class is known asmultiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achievedby using the interface.

In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more thanone interfaces in a class.

Subclass constructors

A subclass can call constructor method defined by its superclass by use of the Following form ofsuper

The super is java keyword. As the name suggest super is used to access the members of the superclass. 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 thesub class.

The second use of the keyword super in java is to call super class constructor in the subclass. Thisfunctionality 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.

Chapter 8 - Classes Objects And Methods

Page 143: BSIT 4th sem Kuvempu University

131

To see how the super is used, consider our previous example class box. Now create a boxweight classwhich extends the box class with variable weight in it. Now define a constructor boxweight, this constructorcalls super ( ) with parameters w,h,d this causes the box constructor to be called ,which initializes width,heightand depth using these values. Boxweight no longer initializes these values itself. It only needs to initializethe 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 methodin 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);

BSIT 42 JAVA Programming

Page 144: BSIT 4th sem Kuvempu University

132

System.out.println( “The author name is “ +author);}public static void main(String args[ ] ){

Book1 x = new Book1( );x.show();

}}

Save this file as book1.java.This is our derived class. Compile and execute the derived file. You cansee the three outputs. Note that the first two print statements in the derived class is inherited from bookclass (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 baseclass called book and two derived class called book1 and book2 and if you use same methods in all thethree classes, then the last derived class method is executed although there are methods with similarnames in all the former classes. This concept in Java is called as Method Overriding. If you want todisplay the details of base class and that of derived class in the above context, then super keyword is usedin 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 associatedwith 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 Examplethis can be used as the basis for communication between instances or to keep track of the number ofinstaces that have been created

We can achieve this effect by making the variable with the keyword static .such variable is sometimescalled 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()

Chapter 8 - Classes Objects And Methods

Page 145: BSIT 4th sem Kuvempu University

133

{counter++;seraialNumber=counter;

}}

In this example, every object that is created is assigned a unique serial number, starting at 1 andcounting upwards. The variable counter is shared among all instances, so when the constructor of oneobject 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 programminglanguage does not have global as such, but a static variable is a single variable accessible form anyinstance of a class.

If static variable is not marked as private, you can access it from outside the class. To do this, you donot 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 ismarked 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;

BSIT 42 JAVA Programming

Page 146: BSIT 4th sem Kuvempu University

134

}}

We should access the methods that are static using the class name rather than an object reference, asfollows:

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 0Number 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 thesubclasses from overriding the members of the superclass, we can declare them as final using the keywordfinal 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 anyway. Similarly, the value of a final variable can never be changed. Final variables, behave like classvariables, 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 thatcannot 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 {…………………}

Chapter 8 - Classes Objects And Methods

Page 147: BSIT 4th sem Kuvempu University

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 toperform 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 processis known as initialization. Similarly, java supports a concept called finalization, which is just opposite toinitialization. We know that java run time is an automatic garbage collecting system. It automatically freesup the memory resources used by the objects. But objects may hold other non-object resources such asfile descriptors or window system fonts. The garbage collector cannot free these resources. In order tofree 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 wheneverit is about to reclaim the space for that object. The finalize method should explicitly define the tasks to beperformed.

Abstract methods and classes

An abstract class is a class that is declared abstract—it 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, andfollowed 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 tothis. That is, we can indicate that a method must always be redefined in a subclass, thus making overridingcompulsory. 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 inthe example above.

While using abstract classes, we must satisfy the following conditions:

BSIT 42 JAVA Programming

Page 148: BSIT 4th sem Kuvempu University

136

We cannot use abstract classes to instantiate objects directly. For example,

Shape s =new shape ( );

Is illegal because shape is an abstract class. The abstract methods of an abstract class must bedefined 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. Accessmodifiers define varying levels of access between class members and other objects. Access modifiersare declared immediately before the type of a member variable or the return type of a method. There arefour 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 aclass’s variables and methods. There is no actual keyword for declaring the default access modifier; it isapplied by default in the absence of any other modifier. For example, in our MotorMain program all thevariables and methods in the MotorCycle class had default access because no access modifiers werespecified. The class MotorMain could however see and use all these variables and methods because thetwo 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, bothinside and outside the class. This means that public class members have global visibility and can beaccessed 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 thatclass and subclasses (don’t worry we deal with subclasses later) of that class. This is same, as Public butit will give more protection than the public. If Protected is used then all the methods and attributes of thebase 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

Chapter 8 - Classes Objects And Methods

Page 149: BSIT 4th sem Kuvempu University

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 youtry 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 usedin 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 andapplets.

EXERCISES

1. What is class? How does it accomplish data hiding?

2. How do classes help us to organize our programs?

3. What are objects? How are they created from a class?

4. How is a method defined?

5. When do we declare a member of a class static?

6. What is a constructor? What are its special properties?

7. How do we invoke a constructor?

8. What is inheritance and how does it help us create new classes quickly?

9. Describe different forms of inheritance with examples.

10. Design a class to represent a bank account. Include the following member:

Data members

Name of the depositor

BSIT 42 JAVA Programming

Page 150: BSIT 4th sem Kuvempu University

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. Accept deposit from a customer and update the balance.

ii. Display the balance.

iii. Compute and deposit interest.

iv. Permit withdrawal and update the balance.

v. 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 8 - Classes Objects And Methods138

Page 151: BSIT 4th sem Kuvempu University

BSIT 42 JAVA Programming

Chapter 9

Ar r ays An d St r in g s

OBJECTIVES

After 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 boxholding a value. The number associated with each box is the index of the item. Each box can be accessedby, first box, second box, third box, and so on, till the nth box. The first box, or the lowest bound of an arrayis always zero, that means, the first item in an array is always at position zero of that array. Position in anarray 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 calleda single-subscripted variable or a one dimensional array.

139

Page 152: BSIT 4th sem Kuvempu University

140

One-dimensional array is a data structure which allows a collective name to be given to a group ofelements which all have the same type. An individual element of an array is identified by its own uniqueindex (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

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 areused. Creation of array involves three steps.

Declare the array

Array[0]

Array[1]

Array[2]

Array[3]

Array[4]

Chapter 9 - Arrays And Strings

Page 153: BSIT 4th sem Kuvempu University

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 thearray. 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 referencevariable. After this declaration the memory location holding the reference associated with intarray willhold 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 arrayspecifies the number of elements that are in the array and allocates memory space for these elements. Itis 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 theelements. Thus to set the size of the array intarray declared above to be 10 and allocate space for itselements would require:

Intarray = new int[10];

Or both the statement can be combined into one statement as follows

int intarray [] = new int[10];

BSIT 42 JAVA Programming

Page 154: BSIT 4th sem Kuvempu University

142

Diagrammatically this can be represented as follows:

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

The numbering of the indices of an array commence at zero. Thus an n element array will haveindices ranging from 0 to n-1.

The elements of the array will be assigned the default value associated with the data type of thearray elements.

In the example above the data type is numeric so the default value is zero and it is a ten element arrayso the subscripts run from 0 to 9.

We illustrate how storage can be allocated and initialized to specific values by example. The followingexample declares and initializes an array which holds the number of days in each of the twelve months ofthe 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 inorder so that the element with index 0 holds 31, the element with index 1 holds 28, etc. Note that thefunction new is not required when initializing an array in this way. When an array is initialized like this itssize is set to the number of values that are contained within the curly brackets. Thus the array daysInMonthhas size 12.

Chapter 9 - Arrays And Strings

Page 155: BSIT 4th sem Kuvempu University

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. Referencevariable 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. Theseelements are initialized to the default value for the type. The reference variable for A points to theallocated storage.

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

Declares A as an array variable and allocates storage of size equal to the number of values. Thisstorage 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 defaultvalues for type. A must have previously been declared as an array variable.

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

BSIT 42 JAVA Programming

Page 156: BSIT 4th sem Kuvempu University

144

Allocates storage of size equal to the number of values and initializes it to the default values for type.A must have previously been declared as an array variable.

String as an array:

A string variable is, in reality, an array. So, if we have

var myname = “Rahul”;

then myname[0] has “R”, myname[1] has a, and so on.

In a similar way, we can initialize every index position of an array. For instance:

var myname = new Array(5);

//In this way we declare an array.

myname[0 ]= “R”;myname[1] = “a”;myname[2] = “h”;myname[3] = “u”;myname[4] = “l”;

//It seems we have just filled till the index 4, but the dimension//can be any number, as long as you don’t 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

Rahul

Chapter 9 - Arrays And Strings

Page 157: BSIT 4th sem Kuvempu University

145

Accessing a size of the array

Associated with an array is a variable which holds the number of elements in the array. This variableis 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 integeranArray = new int[10]; // create an array of integers

// assign a value to each array element and printfor (int i = 0; i < anArray.length; i++){

anArray[i] = i;system.out.print (anArray[i] + “ “);

}System.out.println();

}}

Output : 0123456789

BSIT 42 JAVA Programming

Page 158: BSIT 4th sem Kuvempu University

146

This java example shows how to create a List from an array of type Object using asList method ofArrays 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,ObjectArrayConvertedToList

9.4 PRIMITIVE AND REFERENCE DATA TYPES

Data types fall into two categories namely: primitive and reference. You have already seen theprimitive types Boolean, char, int and double. A variable of primitive type contains a single value of theappropriate size and format for its type. For example a variable of type int contains an integer occupyingfour bytes.

In contrast the value stored in memory for a reference variable is a reference to the actual value or setof values represented by the variable. This reference is not the actual information itself but is a pointer towhere the information can be found. For example, a person’s address furnishes a way to find them but isnot the actual person.

When a primitive variable is declared, memory space is allocated for it, however no value is assignedto that memory space until the variable is initialized.

Chapter 9 - Arrays And Strings

Page 159: BSIT 4th sem Kuvempu University

147

Similarly when a reference variable is declared memory space sufficient to hold a reference is allocatedto it. This memory is assigned the value null to indicate that as yet there is no information associated withthis reference variable. Only when the reference variable is initialized will space be allocated for theactual information associated with the variable and the reference be updated to reference this space.

9.5 TWO–DIMENSIONALARRAY

A two-dimensional array is a sequence where the elements are themselves sequences. Each sequencerepresents one row of the matrix. The rows of the matrix may have different dimensions, thereforematrices 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 forcolumns 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

BSIT 42 JAVA Programming

Page 160: BSIT 4th sem Kuvempu University

148

Int [ ][ ] my Array;

Says that my Array can hold a reference to a 2D array of int. without any further initialization, it willstart 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 5columns, and puts the reference in myArray. All the elements of the array are initialized to zero. Thedeclaration

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

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 arrayand 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 asyou might think. It is an extension of what you already know about one dimensional arrays of objects. Thedeclaration

int[ ][ ] myArray; // 1.

declares a variable myArray which in the future may refer to an array object. Each slot of the arraymay be a reference to an int[ ] object (but so far there are no arrays.) At this point, nothing has been saidabout 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 tonull.

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

Chapter 9 - Arrays And Strings

Page 161: BSIT 4th sem Kuvempu University

149

myArray[1] = x ;

myArray[2] = y ; // 4.

Fig. 9.5. Creation of two dimensional array

BSIT 42 JAVA Programming

Page 162: BSIT 4th sem Kuvempu University

150

2D Array of int

The following program creates a 2D array of int that implements the gradeTable example. Detailsabout declaring and constructing 2D arrays will be explained later.

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

}}

Chapter 9 - Arrays And Strings

Col1

Row 0 1 2 3 40 99 42 74 83 1001 90 91 72 88 952 88 61 74 89 963 61 89 82 98 934 93 73 75 78 99

5 50 65 92 87 94

6 43 98 78 56 99

Gradetable

Page 163: BSIT 4th sem Kuvempu University

151

The declaration of gradeTable uses an initializer list as a short-cut way to create a 2D array objectand 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 holda value and works like any variable. As with one dimensional arrays, every slot in a 2D array is of thesame 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 theleft. Then,

gradeTable[ 0 ][ 1 ] // holds 42

gradeTable[ 3 ][ 4 ] // holds 93

gradeTable[ 6 ][ 2 ] // holds 78

The subscripted variables are used in assignment statements and arithmetic expressions just like anyvariable:

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 predefinedstring type. Java, while remaining with the concept of a string being an array of characters, does not dothis; instead it provides a predefined class called String. We use this in the same manner that we mightuse 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 onconstruction. Thus to assign a value to the instance name we must do this when it is created. Consider thecode given in program 1. Here we have created a 4 element array, called data of characters. We thenused this array as the argument for the String constructor to create a (constant) data item called namewhich has the value “java” which is itself a character array.

BSIT 42 JAVA Programming

Page 164: BSIT 4th sem Kuvempu University

152

Because instances of the class String are so common Java provides a short hand to achieve the aboveas 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, whichinvokes 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

Chapter 9 - Arrays And Strings

Page 165: BSIT 4th sem Kuvempu University

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 ofobjects and allows us to do some things with strings that are not possible with other objects. One simpleexample 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 haven’t used the new operator. The reason for this isthat the compiler automatically creates the necessary String objects to represent the string literals used ina 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 itis now out of the reach of our program, as there is no longer any reference variable that refers to it. Assuch it is referred to as “garbage”: memory that our program was using to store an object but which is nolonger required. Most languages that support dynamic memory allocation like this require that theprogrammer keeps track of the memory being used. Thus it is the programmer’s responsibility to ensurethat the program deallocates the memory used by an object once it is no longer required. This is anotorious source of programming errors in many programming languages, not least C++. Fortunately forus, Java has a very powerful and useful feature called automatic garbage collection. The Java run-timesystem keeps track of the references to the objects that the program is using and will automatically

BSIT 42 JAVA Programming

Page 166: BSIT 4th sem Kuvempu University

154

reclaim any memory that is no longer being used by the program (such as that being used by the “Hello”object above).

Another important fact to bear in mind with Java strings is that they are immutable. This means thatthe contents of the object cannot be changed after the object has been created. To put it another way: itis impossible to edit or modify a string object in Java. Of course, it is possible to make a String referencevariable 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.Thestring method compareTo( ) serves this purpose. It has the general form

int compareTo(String str)

Value Meaning

value less than zero the invoking string is less than strgreater than zero the invoking string is greater than strzero the two string are equal

Class equalsdemo{

public static void main(String args[ ]){

String s1=”Hello”;

Chapter 9 - Arrays And Strings

Page 167: BSIT 4th sem Kuvempu University

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 statementif (name1.compareTo(name2)==0)System.out.println(“the same”);elseSystem.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 objectpoints to, rather than the pointer itself. The == operator compares whether two objects are exactly thesame object, meaning that they reference the same spot in memory, NOT that the values of the parametersof 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 inmemory. 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 newoperator, and they definitely do not reference the same object, even though the contents of the String arethe same.

The equals() method, on the other hand, does the operation you probably intend to do, comparing thecontents of the two strings and seeing if they match. Usually you will want use the equals method.

BSIT 42 JAVA Programming

Page 168: BSIT 4th sem Kuvempu University

156

Class stringDemo{

public static void main(String args[]){

/* Compare two Strings */String firstString = “Java programming”;String secondString = “Java programming”;System.out.println((firstString == secondString)); /* returns true *//* Compare two Strings */firstString = new String(“Java programming”);secondString = new String(“Java programming”);System.out.println((firstString== secondString)); /* returns false */System.out.println((firstString.equals(secondString)); /* returns true */}

}

The results in line 11 and 13 are predictable. Line 11 returns false, because we are comparing twodifferent object instances, and they aren’t the same. The variables firstString and secondString point totwo different objects in memory. So in order to test if the strings inside the String object are the same, wemust use the equals method(line13). But what about the true result of line 5? Here we see some compileroptimazation at work. Because the secondString variable contains the same string as the firstStringvariable, the compiler already assumes both variables can point to the same space in memory. Andbecause both variables point to the same memory space, the comparison returns true. But we cannot relyon 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 thecharAt() 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 lengthmethod

int length();

Chapter 9 - Arrays And Strings

Page 169: BSIT 4th sem Kuvempu University

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, i.e.str is less than str2

System.out.println (str.charAt(0)); // H, i.e. char is position 0System.out.println (str.length() + str2.length()); // 5 + 4 = 9

}

}

Concatenation of two strings

String manipulation is something we do quite often in our applications . One of the simplest methods toconcatenate 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 methodnamed 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 outString 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 results1 = s1.concat(s2);System.out.println(“Concatenated: “ + s1);

}}

BSIT 42 JAVA Programming

Page 170: BSIT 4th sem Kuvempu University

158

Output

First String : SachinSecond String : TendulkarConcatenated : Sachin Tendulkar

Conversions

toLowerCase( ) returns a newly minted string identical to the original, but with allupper case characters cast to lower case.

toUpperCase( ) returns a newly minted string identical to the original, but with alllower 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 thesecond 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 replacementSubstring method

The subString method is used to create new instances of the class String from existing instances. Thenew 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. stringsubstring(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 toreplace 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”) );

Chapter 9 - Arrays And Strings

Page 171: BSIT 4th sem Kuvempu University

159

System.out.println( str.replaceAll(“Re”, “Ra”) );}

}

OUTPUTAeplace AegionRaplace RegionRaplace Ragion

Trim method

The trim method returns a copy of the invoking string from which any leading and trailing white spacehas 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); // HELLOSystem.out.println (str2);// javastr = 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 Examplepublic class StringToCharacterArrayExample{

public static void main(String args[]){

String strOrig = “Hello World”;char[] stringArray;

BSIT 42 JAVA Programming

Page 172: BSIT 4th sem Kuvempu University

160

stringArray = strOrig.toCharArray();for(int index=0; index < stringArray.length; index++)System.out.print(stringArray[index]);

}}

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

}

OutputFound Hello at index 0Index of Hello after 11 is 12Last occurrence of Hello is at index 12

Chapter 9 - Arrays And Strings

Page 173: BSIT 4th sem Kuvempu University

161BSIT 42 JAVA Programming

9.7 SUMMARY

In this chapter, two important java data structures namely arrays and strings were discussed we learntarrays and their usage, and , strings and their usuage. Some examples to illustrate where these structurescan be used was also highlighted.

EXERCISES

1. What is an array?

2. Why are arrays easier to use compared to a bunch of related variables?

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

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

6. Two matrices that have the same number of rows and columns can be multiplied to produce a third matrix.

Consider the following two matrices.

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.

Page 174: BSIT 4th sem Kuvempu University

7. How does String class differ from the StringBuffer class?

8. Explain about :

1. Comparision of two strings

2. Concatenation of two strings

9. Explain the methods :

1. Trim

2. Substring

3. Length

10. Write a program to split a string into multiple java string objects

11. Write a program to remove a leading thread and trailing space from string using trim method of java string class

Chapter 9 - Arrays And Strings162

Page 175: BSIT 4th sem Kuvempu University

Chapter 10

Mu lt i t h r ead in g

OBJECTIVES

After 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 worldworks. 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 performoperations concurrently. A computer can concurrently compile a program, print a file and receive e-mailover a network.

Most programming languages do not help programmers to specify concurrent activities. They generallyprovide 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 concurrencyprimitives. The programmer specifies that applications contain threads of execution. Each thread earmarksa portion of program that can be executed concurrently with other threads. This capability of Java languageis called multithreading. This facility is not available in C and C++ on which Java is based.

BSIT 42 JAVA Programming 163

Page 176: BSIT 4th sem Kuvempu University

164 Chapter 10 - Multithreading

Examples of concurrent programming:

When programs download large files of audio or video clips from WWW, one need not wait until theentire 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 memoryautomatically.

10.2 THREAD FUNDAMENTALS

In concurrent programming, there are two basic units of execution: processes and threads. In theJava 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 thatonly 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 calledtime slicing.

It’s becoming more and more common for computer systems to have multiple processors or processorswith multiple execution cores. This greatly enhances a system’s capacity for concurrent execution ofprocesses and threads — but concurrency is possible even on simple systems, without multiple processorsor execution cores.

Processes

A process has a self-contained execution environment. A process generally has a complete, private setof 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 seesas a single application may in fact be a set of cooperating processes. To facilitate communication betweenprocesses, most operating systems support Inter Process Communication (IPC) resources, such as pipesand sockets. IPC is used not just for communication between processes on the same system, but processeson different systems.

Threads

Threads are sometimes called lightweight processes. Both processes and threads provide an executionenvironment, 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 process’s resources,including memory and open files. This makes for efficient, but potentially problematic, communication.

Page 177: BSIT 4th sem Kuvempu University

165

Multithreaded execution is an essential feature of the Java platform. Every application has at least onethread — or several, if you count “system” threads that do things like memory management and signalhandling. But from the application programmer’s point of view, you start with just one thread, calledthe 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 , thereare a variety of threads executing. For example, Word may have a thread in the background automaticallychecking the spelling of what is being written, while another thread may be automatically saving changesto the document. Like Word, each application (process) can be running many threads that are performinga 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 processcommunication 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-threadcommunication 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 singlethread of control runs in an infinite loop, polling a single event queue to decide what to do next. Once thispolling mechanism returns with, say, a signal that a network file is ready to be read, then the event loopdispatches control to the appropriate event handler. Until this event handler returns nothing else canhappen. This wastes CPU time.

The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated. One threadcan pause without stopping other parts of the program. For example, the idle time created when a threadreads data from a network or waits for user input can be utilized elsewhere. When a thread blocks in aJava program, only the single thread that is blocked pauses. All other threads continue to run.

BSIT 42 JAVA Programming

Page 178: BSIT 4th sem Kuvempu University

166

10.3.1 Thread States: Life Cycle Of A Thread

Thread exists in several states. A thread just created is in the born state. When the threads startmethod 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 sleepmethod 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.Ablocked 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 uncaughtexception.Fig 10.1 depicts the state transition diagram of a thread.

Fig. 10.1 State Transition diagram of a Thread

Chapter 10 - Multithreading

Page 179: BSIT 4th sem Kuvempu University

167

10.3.2. Context Switching

A thread is assigned a priority that determines how that thread should be treated with respect toothers. Thread priorities are integers that specify the relative priority of one thread to another. Every Javathread 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 whento switch from one running thread to the next. This is called a context switch. The rules for contextswitching are simple.

A thread can voluntarily relinquish control

When this happens all other threads are examined and the highest priority thread that is inrunnable 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 calledpreemptive multitasking.

10.4 MAIN THREAD

When a java program starts, one thread begins running immediately. This is usually called the mainthread of the program, because it is the one that is executed when the program begins. The main threadis 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 fromanother and enables a parent process to query a thread for its name. A thread can be assigned a name atcreation 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 anadditional 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”.

BSIT 42 JAVA Programming

Page 180: BSIT 4th sem Kuvempu University

168

10.5.1 THE getName METHOD

You can query a thread for its name using the getName method. getName returns the name associatedwith 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 anexample 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);

}

Chapter 10 - Multithreading

Page 181: BSIT 4th sem Kuvempu University

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 interfaceRunnable. Both yield the same result. By implementing Runnable, existing classes can be converted tothreads 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 usaccess to all the thread methods directly.It includes the following steps

1. Declere the class extending the Thread class2. 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

BSIT 42 JAVA Programming

Page 182: BSIT 4th sem Kuvempu University

170

10.6.2 Implementing the Run() Method

The run() method has been inherited by the class MyThread.We have to override this mehthod inorder to implement the code to be executed by our thread.The basic implementation of run() will be asfollows

Public void run()

{- - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - -}

when we start the new thread, java calls the thread’s 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. Thethread 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 javaruntime 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”);

}

}

Chapter 10 - Multithreading

Page 183: BSIT 4th sem Kuvempu University

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 implementingthe runnable interface. We have already discussed in detail how the thread class is used for creating andrunning the threads. In this section, we shall see how to make use of the Runnable interface to implementthreads.

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 targetof the thread.

4. Call the thread’s start() method to run the thread

Following program illustartrates the implementation of the above steps. In main method , we firstcreate an instance of x and then pass this instance as the initial value of the object threadX(an object ofThread class).Whenever ,the new thread threadx starts up, its run() method calls the run() method of thetarget 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”);

BSIT 42 JAVA Programming

Page 184: BSIT 4th sem Kuvempu University

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

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

}

Chapter 10 - Multithreading

Page 185: BSIT 4th sem Kuvempu University

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 beMain thread: 0Child Thread: 0Main thread: 1Main thread: 2Child Thread: 2Child Thread: 3Main thread: 3Main thread: 4Child Thread: 4Child 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: threadinterference and memory consistency errors. The tool needed to prevent these errors is synchronization.

BSIT 42 JAVA Programming

Page 186: BSIT 4th sem Kuvempu University

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 samedata, interleave. This means that the two operations consist of multiple steps, and the sequences of stepsoverlap.

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 synchronicitywhen it is necessary. For example, if two threads are to communicate and share a data structure, there isa need to avoid conflict between them. That is, a thread must be prevented from writing data while theother 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 amonitor, 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 communicatewith each other. In Java, two or more threads can talk to each other, via calls to predefined methods thatall objects have.

10.9 SUMMARY

A thread is a single line of execution within program. Multiple threads can run concurrently in a singleprogram. 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. What is a Thread?

2. Distinguish between Multiprocessing and Multithreading?

3. Describe the life cycle of a Thread?

4. What is Synchronization? Why do we use it?

5. How a thread is created?

6. Write a program to implement the set name method of a thread class.

Chapter 10 - Multithreading174

Page 187: BSIT 4th sem Kuvempu University

Chapter 11

Packag es & In t er f aces

OBJECTIVES

After 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. Forexample, a package allows us to create a class named list, which we can store in our own packagewithout concern that it will collide with some other class named list stored elsewhere. Packages arestored in a hierarchical manner and are explicitly imported into new class definitions. Packages, a conceptsimilar to class libraries in other languages helps in achieving the reusability.

Packages are Java’s way of grouping a variety of classes and/or interfaces together. The grouping isdone 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

Page 188: BSIT 4th sem Kuvempu University

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 codeneeded for methods.

11.2 CREATING PACKAGES

Creating a package is quite easy. First declare the name of the package using the ‘package’ key wordfollowed by a package name. This statement defines a name space in which classes are stored. It isfollowed 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 listingwould be saved as a file called Firstclass.java. It is located in a directory named firstpackage. When thesource 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

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.

Package Packagename;

Page 189: BSIT 4th sem Kuvempu University

177BSIT 42 JAVA Programming

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 multiplenames 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, windowsor 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 levelpackage, package2 is the name of package inside package1 and so on. Finally, ‘class name’ is specifiedexplicitly.

Example :

import firstPackage.SecondPackage.Myclass ;Alternative Approach : import.Package.*;

In the above statement, Packagename can denote a single package or a hierarchy of packages. Thestar(*) indicates that the compiler should search this entire package hierarchy. We can access all classescontained 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 listingshows a package named package1 containing a single class class A.

Page 190: BSIT 4th sem Kuvempu University

178

Package package 1;

Public class Class A;{

Public void display A( ){

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

}

This source file should be named classA.Java. It is stored in subdirectory package1. This Java file iscompiled. Resultant is classA.class. This will be stored in the same subdirectory.

Now consider the listingimport 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 besaved as PackageTest1.Java and then compiled. The source file and the compiled file should be saved inthe 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 variablesand methods. Packages act as containers of classes and other subordinate packages. Classes act ascontainers for data and methods. The class is Java’s smallest unit of abstraction. Because of interplaybetween classes and packages, Java addresses four categories of visibility for class members.

Subclasses in the same package

Non subclasses in the same package

Chapter 11 - Packages & Interfaces

Page 191: BSIT 4th sem Kuvempu University

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 manylevels of access required. Table No.11.1 sums up the interaction.

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

{

BSIT 42 JAVA Programming

Private No modifier Protected PublicSame class Yes Yes Yes YesSame Package No Yes Yes YesSubclassSame Package No Yes Yes YesNon-SubclassDifferent Package No No Yes YesSubclassDifferent Package No No No YesNon-Subclass

Page 192: BSIT 4th sem Kuvempu University

180

//body of B

}

3. Store this as B.Java file under the directory P1.

4. Compile B.java file and creates B.class file. Place it in the directory P1.Now package P1 contains both the classes A and B.

11.8 INTERFACE

We have discussed about classes and how they can be inherited by other class in chapeter 8. Javadoes 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 methodsand properties from several distinct classes. Java provides an alternate approach called interfaces tosupport the concept of multiple inheritence.

interfaces are syntactically similar to classes but they lack instance variables, and their methods aredeclared without any body. In practice, we can define interfaces which don’t make assumptions abouthow they are implemented.once it is defined, any number of classes can implement an inferface. Also oneclass can implement any number of interfaces.

An interface only defines a method’s name, return type, and arguments. It does not include executablecode 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 keywordinstead 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 declarationsfor variables and methods.

Modifiers

The same modifiers-public and default-available to classes can be applied to an interface’s declaration.The default is nonpublic, which means accessible by any member of a given package. Most interfaces are

Chapter 11 - Packages & Interfaces

Page 193: BSIT 4th sem Kuvempu University

181

public because interfaces are the only means to share variable and method definitions between differentpackages. 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, variablesdeclared in interfaces can only function as constants. Public static final are the default modifiers. It isnot necessary to declare the modifiers explicitly, but it makes the code more self-documenting. Trying toassign other modifiers such as protected results in a compile-time error. Here are examples of variabledeclarations:

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 declaredinside an interface can only be abstract. These are the default modifiers for methods. It is not necessaryto 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 exampleinterface 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);

}

BSIT 42 JAVA Programming

Page 194: BSIT 4th sem Kuvempu University

182

Interfaces also can extend other interfaces, just as classes can extend other classes, using the extendskeyword. 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 useMyInterface will have access to not only the variables and methods declared in MyInterface, but alsothose in AnInterface.

You can also list multiple interfaces after the extends keyword. Multiple, possibly disparate, interfacescan 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 ofimplementation may lool lilke this

Chapter 11 - Packages & Interfaces

Page 195: BSIT 4th sem Kuvempu University

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 classimplements more than one interface,they are seperated by a comma. The implementation of interfacescan take various form as shown in the following example

//interface Test.javainterface 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 objectarea = rect

BSIT 42 JAVA Programming

Page 196: BSIT 4th sem Kuvempu University

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 = 200Area of circle = 314

11.9 SUMMARY

Java has several levels of hierarchy for code organization, the highest of which is the package. Packagesare java’s way of grouping a variety of classes and /or interfaces together. In this chapter, we learnt howto create a package , to add more classes to a package, to access the contents of the package, to use javapackages and also about interfaces. Interfaces provide the facility of multiple inheritence required in reallife applications.

EXERCISES

1. What is package?

2. Write a procedure to create your own package.

3. How do we design a package

4. Discuss various levels of access protection available for packages and their implications

5. Define Interface. How multiple inheritance can be implemented using interfaces?

Chapter 11 - Packages & Interfaces184

Page 197: BSIT 4th sem Kuvempu University

BSIT 42 JAVA Programming 185

Chapter 12

Excep t io n Hand l in g

OBJECTIVES

After 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 theprogram to produce unexpected results. An error may even cause the system to cause hence, it is importantto detect and manage properly all the possible error conditions in a program so that the program will runproperly during execution.

There are two types of errors , namely,compile-time error and run-time errors compile time errors areall syntax errors detected and displayed by the java compiler. Whenever the compiler displays an error, itwill not create the .class file.Hence it is necessary to fix all the errors before we can successfully compileand run the program. Most of the compile time errors are due to typing mistake. The most commomerrors are,missing semicolons, missing /mismatch of brackets in classes and methods,wrong spelling ofidentifiers and keywords, missing double quotes in strings, use of undeclared variables, incompatible typesin assignments /initialization and so on.

Page 198: BSIT 4th sem Kuvempu University

186 Chapter 12 - Exception Handling

A program may compile successfully creating the .class file. However, it may not run properly. Suchprograms produce wrong results due to wrong logic or may terminate due to errors. Most common runtime 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 rangeor value for a method,trying to illegally change the state of the thread etc., when these errors are encounteredjava 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 normalflow of the program’s instructions.An exception is a run time error. Most of the computer languages donot support exception handling. Errors must be checked and handled manually. This is cumbersome andtroublesome. Java provides the facility of exception handling and avoids the above problems. By this runtime 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. Inthis way, the exception is caught and processed. Exceptions thrown by Java relate to fundamental errorsthat 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 isimmediately followed by a zero or more ‘catch’ blocks. Each ‘catch’ block specifies the type of exceptionit can catch and contains an exception handler. After the last catch block, an optional ‘finally’ blockprovides 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 searchedfor an appropriate handler. If the type of ‘thrown’ exception matches the parameter type in one of thecatch blocks, the code for that ‘catch’ block is executed. If no exception are thrown in the try block, theexception 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 notan exception is thrown.

A ‘throws’ clause specifies the exceptions a method throws. An exceptions can be thrown from thestatements 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.

Page 199: BSIT 4th sem Kuvempu University

187BSIT 42 JAVA Programming

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 isn’t very robust. An ArrayIndexOutofBoundsexception, for example, should never be thrown if you’re properly checking to make sure your codedoesn’t extend past the end of an array. NullPointerException exceptions won’t happen if you don’t try toreference the values of a variable that doesn’t actually hold an object. If your program is causing runtimeexceptions under any circumstances whatsoever, you should be fixing those problems before you evenbegin to deal with exception management.

The final group of exceptions is the most interesting because these are the exceptions that indicate thatsomething very strange and out of control is happening. EOFExceptions, for example, happen whenyou’re reading from a file and the file ends before you expect it to. MalformedURLExceptions happenwhen a URL isn’t in the right format (perhaps your user typed it wrong). This group includes exceptionsthat 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

ObjectThrowable

ExceptionIO ExceptionArithmetic ExceptionArrays store ExceptionIllegal argument ExceptionIndex out of bound ExceptionNull pointer Exception

Runtime ExceptionFile not foundEnd of file Exception

Error

Page 200: BSIT 4th sem Kuvempu University

188

general errors, and subclasses are more specific errors. This organization will become more important toyou as you deal with exceptions in your own code.

Most of the exception classes are part of the java.lang package (including Throwable, Exception, andRuntimeException). But many of the other packages define other exceptions, and those exceptions areused throughout the class library. For example, the java.io package defines a general exception classcalled 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 suchas MalFormedURLException

12.4 UNCAUGHT EXCEPTIONS

Before you learn how to handle exceptions in your program, it is useful to see what happens when youdon’t handle them. This small program includes an expression that intentionally causes a divide-by-zeroerror.

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 exceptionobject and then throws this exception. This causes the execution of Exc0 to stop, because once anexception has been thrown, it must be caught by an exception handler and dealt with immediately. In thisexample, We haven’t supplied any exception handlers of our own, so exception caught by the defaulthandler provided by the java run time systems. Any exception that is not caught by your program will beultimately be processed by the default handler. This default handler displays the string describing theexception, 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.

Chapter 12 - Exception Handling

Page 201: BSIT 4th sem Kuvempu University

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 conceptuallysimilar to a switch statement; think of try like the switch statement in terms of exactly identifying thecondition to be tested.

catch is used to specify the action that should be taken for a particular type of exception. It is similarto the case part of a switch statement. There can be several catch statements in a row to deal with eachof 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 firstconcept you need to grasp is that of throwing an exception, Java’s name for causing an exception to begenerated. For example, say a method was written to read a file. If the method could not read the filebecause the file did not exist, this would generate an IOException. In Java terminology, it is said that themethod 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 theexception has occurred and deals with it appropriately. In Java terms, you say a thrown exception getscaught.

In the case of the IOException thrown because of the nonexistent file, the catch statement writes anerror message to the screen stating that the specified file does not exist. It then allows the user to tryentering a different filename if the first was incorrect, or it may exit. In Java terminology, the IOExceptionwas 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 ofcode that might generate (throw) an exception. The try is a way of telling the compiler that some attemptwill be made to deal with at least some of the exceptions generated by the block of code.

BSIT 42 JAVA Programming

Page 202: BSIT 4th sem Kuvempu University

190

12.5.4 Finally

The finally statement is used to specify the action to take if none of the previous catch statementsspecifically deals with the situation. It is similar to the default part of a switch statement. finally is the bignet 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 thatexception 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 codethat might generate an exception. This code could consist of several statements, one or more of whichmay generate an exception.

Chapter 12 - Exception Handling

Page 203: BSIT 4th sem Kuvempu University

191

If any one statement generates an exception, the remaining statements in the block are skipped andexecution continues with the first statement following the try construct, which must be a catch or finallystatement. This is an important point to remember. It is an easy way to determine which block of codeshould 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 isas follows:

catch (ExceptionType ExceptionObj)

{

statements;

}

The keyword catch begins the catch construct, followed by a parameter list that contains an exceptiontype and an exception object. This in turn is followed by a statement or block containing the code used toprocess the exception.

catch construct is a method that will be called by the Java runtime interpreter if the particular exceptiontype 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 blockit can be manipulated as needed. The object must be assigned to a variable whose scope resides outsidethe 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 discussedpreviously 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 thecode used to process the exception.

BSIT 42 JAVA Programming

Page 204: BSIT 4th sem Kuvempu University

192

As with the catch statement, a finally block must follow immediately after a try or other catch statementor a compilation error results. A finally statement acts like a default case in a switch statement if it followsa series of catch statements. Anything that was not explicitly matched by an earlier catch statement iscaught by the finally statement. A finally statement cannot be followed by another catch or finally statementor a compilation error will result. Because finally catches everything. Additional statements would neverbe 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 inthe program following the entire try/catch mechanism.

Chapter 12 - Exception Handling

Page 205: BSIT 4th sem Kuvempu University

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 hasexecuted 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 exceptiongenerated in the eariler version is caught and the array index is reset, allowing the program tocontinue.

Public class array{

Public static void main(String[] args){

BSIT 42 JAVA Programming

Page 206: BSIT 4th sem Kuvempu University

194

int i = 0;string names[]={ “ Rahul” ,” Mohan” ,” Madan”};While(i<4){try{

System.out.println(names[i]);}catch(ArrayIndexOutOfBoundsException e){

System.out.println(“Re-setting the index value”);i=-1;}finally{

System.out.println(“this is always printed”);}i++;

}}

}

Rahulthis is alwaysprinted Mohanthis is alwaysprinted Madanthis is alwaysprinted Re-settingindex value This isalways printed

12.6 SUMMARY

We commit both sytactic and semantic errors while writing a program sytactic errors are detectedduring compile time. Some of the run time errors can be managed using exception handling. In thischapter, we have discussed what exceptions are, how to throw system exceptions, how to catch andhandle different types of exceptions.

Chapter 12 - Exception Handling

Page 207: BSIT 4th sem Kuvempu University

195

EXERCISES

1. What is an exception?

2. How do we define a try block?

3. How do we define a catch block?

4. How many catch blocks can we use with one try block?

5. What is a finally block? When and how is it used? Give a suitable example?

6. Why does the compiler complain about interrupted exception when I try to use threads.sleep method

7. What is The Difference Between A Runtime Exception and a plain exception – why don’t runtime exceptions

have to be declared.

BSIT 42 JAVA Programming

Page 208: BSIT 4th sem Kuvempu University

Chapter 13 - Managing Input/Output

Chapter 13

Man ag in g In p u t / Ou t p u t

OBJECTIVE

After 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 aclass 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 tostandard input, which is the keyboard by default. System.err refers to the standard error stream, whichalso 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 typePrintStream. These are byte streams, even though they typically are used to read and write charactersfrom and to the console. As you will see, you can wrap these within character-based streams, if desired.

196

Page 209: BSIT 4th sem Kuvempu University

The preceding chapters have been using System.out in their examples. You can use System.err inmuch 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 streamthat is attached to the console, you wrap System.in in a BufferedReader object, to create a characterstream. BufferedReader supports a buffered input stream. Its most commonly used constructor is shownhere.

BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that is beingcreated. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, whichconverts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, usethe following constructor:

InputStreamReader(InputStream inputStream)

Because System.in refers to an object of type InputStream, it can be used for inputStream. Puttingit 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 throughSystem.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 outof a program. Input to a program may come from the keyboard, the mouse, the memory, the disk, anetwork, or another program. Similarly, output from a program may go to the screen, the printer, thememory, the disk, a network, or another program. This is illustrated in Fig. 13.1. Although these deviceslook very different at the hardware level, they share certain common characteristics such as unidirectionalmovement of data, treating data as a sequence of common characteristics such as unidirectional movementof data, treating data as a sequence of bytes or characters and support to the sequential access to thedata.

Java uses the concept of streams to represent the ordered sequence of data, a common characteristicshared by all the input/output devices as stated above. A stream presents a uniform, easy-to-use, objectoriented interface between the program and the input/output devices.

BSIT 42 JAVA Programming 197

Page 210: BSIT 4th sem Kuvempu University

198 Chapter 13 - Managing Input/Output

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). Ithas a source (of data) and a destination (for that data) as depicted in Fig. 13.2. Both the source and thedestination may be physical devices or programs or other streams in the same program.

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) hasmade streams in Java a powerful tool for file processing. We can build a complex file processing sequenceusing a series of simple stream operations. This feature can be used to filter data along the pipelining ofstreams so that we obtain data in a desired format. For example, we can use one stream to get raw datain 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 inputstream extracts (i.e. reads) data from the source (file) and sends it to the program. Similarly, an output

JavaProgram

Keyboard

Mouse

Memory

Disk

NetworkNetwork

Disk

Memory

Printer

ScreenInput Output

Source

Valve connecting the source and the stream

Stream

Destination

Page 211: BSIT 4th sem Kuvempu University

199

stream takes data from the program and sends (i.e. writes) it to destination (file). Figure illustrates the useof input and output streams. The program connects and opens an input stream on the data source and thenreads the data serially and writes data out serially. In both the cases, the program does not know thedetails 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 processingall types of data. These classes may be categorized into two groups based on the data type on which theyoperate.

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 howstream classes are grouped based on their functions. Byte stream and character stream classescontain specialized classes to deal with input and output operations independently on varioustypes of devices. We can also cross-group the streams based on the type of source or destinationthey 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 beusing is

int read( ) throws IOException

BSIT 42 JAVA Programming

Page 212: BSIT 4th sem Kuvempu University

200

Each time that read( ) is called, it reads a character from the input stream and returns it as an integervalue. It returns –1 when the end of the stream is encountered. As you can see, it can throw anIOException.

The following program demonstrates read( ) by reading characters from the console until the usertypes a “q”:

Fig. 13.4 Classification of Java stream classes

//use a bufferedreader to read characters from the console

Import java.io.*;Class BRRead

WriterClasses

JavaStream Classes

Memory

Byte StreamClasses

Character Stream

Classes

PipeFile

Output StreamClasses

PipeFile

Input StreamClasses

ReaderClasses

Memory

Chapter 13 - Managing Input/Output

Page 213: BSIT 4th sem Kuvempu University

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

C=(char) br.read();System.out.println( c);

}While (c!=’q’);

}}Here is a sample run:

Enter characters, ‘q’, to quit.123abcq

123abcq

This output may look a little different from what you expected, because System.in is line buffered, bydefault. This means that no input is actually passed to the program until you press ENTER. As you canguess, 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 theBufferedReader class. Its general form is shown here:

String readLine( ) throws IOException

BSIT 42 JAVA Programming

Page 214: BSIT 4th sem Kuvempu University

202

As you can see, it returns a String object.

The following program demonstrates BufferedReader and the readLine( ) method; the programreads 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.inBufferedReader 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 linesof text, storing each line in the array. It will read up to 100 lines or until you enter “stop”. It uses aBufferedReader to read from the console.

// A tiny editor. importjava.io.*;class TinyEdit{

public staic void main(String args[ ]) throwsIOException

Chapter 13 - Managing Input/Output

Page 215: BSIT 4th sem Kuvempu University

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.StopHere is your file:This is line one.This is line two.Java makes working with strings easy.Just create String objects.

BSIT 42 JAVA Programming

Page 216: BSIT 4th sem Kuvempu University

204

13.6 WRITING CONSOLE OUTPUT

Console output is most easily accomplished with print( ) and println( ), described earlier, which areused in most of the examples in this book. These methods are defined by the class PrintStream (whichis the type of the object referenced by System.out). Even though System.out is a byte stream, using itfor simple program output is still acceptable. However, a character-based alternative is described in thenext section.

Because PrintStream is an output stream derived from OutputStream, it also implements the low-level 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 aninteger, only the low-order eight bits are written. Here is a short example that uses write( ) to output thecharacter “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 somesituation), 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 JavaDataInputStream class.

import java.io.*;public class ReadCharFromFile{

public static void main(String[ ] args){

String strFilePath = “C://FileIO//readChar.txt”;

Chapter 13 - Managing Input/Output

Page 217: BSIT 4th sem Kuvempu University

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 SUMMARYIn 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, youwill be able to

Read Character

Read Strings

Write Console Output

EXERCISES

1. What is a file? Why do we require files to store data?

2. What is a stream? How id the concept of streams used in Java?

3. What are input and output streams? Explain them with illustrations?

4. What is a stream class? How are the stream classes classified?

BSIT 42 JAVA Programming

Page 218: BSIT 4th sem Kuvempu University

REFERENCES

1. JAVATM­ HOW TO PROGRAM, Deitel and Deital, Pearson Education Third Edition, 1999.

2. JAVATM­ 2, The Complete Reference, Patrick Naughton and Herbert Schildt, Tata Mc.Graw-Hill Third Edition,

1999.

3. JAVATM­ Programming Langauage, Sun Educational Services, Student Guides, April 2000.

4. Programming with JAVA, Jogh R Hubbard, Mc.Graw-Hill, 1999.

5. Programming with JAVA, E. Balaguruswamy.

6 Flanagan.D Java in a Nutshell,O’Reilly & Assosiates, 1996.

7 www.java.sun.com

206