object oriented programming and java...the object-oriented programming paradigm came into use owing...
TRANSCRIPT
M.Sc. [Information Technology]I - Semester
313 12
Directorate of Distance Education
OBJECT ORIENTEDPROGRAMMING AND JAVA
ALAGAPPA UNIVERSITY[Accredited with ‘A+’ Grade by NAAC (CGPA:3.64) in the Third Cycle
and Graded as Category–I University by MHRD-UGC]
(A State University Established by the Government of Tamil Nadu)
KARAIKUDI – 630 003
All rights reserved. No part of this publication which is material protected by this copyright noticemay be reproduced or transmitted or utilized or stored in any form or by any means now known orhereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recordingor by any information storage or retrieval system, without prior written permission from the AlagappaUniversity, Karaikudi, Tamil Nadu.
Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and hasbeen obtained by its Authors from sources believed to be reliable and are correct to the best of theirknowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable forany errors, omissions or damages arising out of use of this information and specifically disclaim anyimplied warranties or merchantability or fitness for any particular use.
Vikas® is the registered trademark of Vikas® Publishing House Pvt. Ltd.
VIKAS® PUBLISHING HOUSE PVT. LTD.E-28, Sector-8, Noida - 201301 (UP)Phone: 0120-4078900 Fax: 0120-4078999Regd. Office: 7361, Ravindra Mansion, Ram Nagar, New Delhi 110 055 Website: www.vikaspublishing.com Email: [email protected]
Work Order No. AU/DDE/DE1-238/Preparation and Printing of Course Materials/2018 Dated 30.08.2018 Copies - 500
Reviewer
Dr. P. PrabhuAssistant Professor in Information Technology,
Directorate of Distance Education,Alagappa University, Karaikudi
AuthorRohit Khurana, CEO, ITL Education Solutions Ltd.
"The copyright shall be vested with Alagappa University"
SYLLABI-BOOK MAPPING TABLEObject Oriented Programming and Java
BLOCK 1: Fundamentals of Object-Oriented ProgrammingUNIT-I: Basic concepts of OOP – Benefits – Applications.JavaEvolution: Features – how java differs from C and C++ - java andinternet- java support system – java environmentUNIT-II: Overview of Java Language –Introduction – Simple JavaProgram – Comments – Java Program Structure – Tokens – JavaStatements – Implementing a Java Program – JVM – Command LineArguments. Constants – Variables – Data Types – Type Casting..UNIT-III: Operators and Expressions: Arithmetic Operators – Relational,Logical, Assignment, Increment and Decrement, Conditional, Bitwise,Special Operators – Arithmetic Expressions, Evaluation of Expression– Precedence of Arithmetic Operators – Type Conversions – OperatorPrecedence and associativity – Mathematical Functions.Decision Making and Branching: If –if…..else –Nesting of if…….Else – else if– switch. Decision Making and Looping: While – do – for– jump in loops – labeled loops.
BLOCK 2: Classes, Objects And MethodsUNIT-IV: Class: Defining a class –fields –methods –creating objects –accessing class members – constructors – methods overloading –staticmembers –nesting of methods – Inheritance –overriding methods –final variables-classes –methodsUNIT-V: Arrays, Strings and Vectors :One dimensional Arrays –creating of array – Two dimensional arrays- strings –vectors –Wrapperclasses – Enumerated Types - Interfaces: Multiple InheritanceUNIT-VI: Packages: Defining interface –Extending interfaces –Implementing Interfaces - Putting Classes Together
BLOCK 3: Multithreaded ProgrammingUNIT-VII: Introduction : creating Threads –Extending the thread class–Stopping and Blocking a thread –Life cycle of a thread –using threadmethodsUNIT-VIII: Thread Exceptions –Priority –Synchronization –Implementing the ‘Runnable’ Interface
BLOCK 4: Managing Error, Exception and AppletsUNIT-IX: Exceptions: Types of errors –Exceptions –Syntax of ExceptionHandling code – 35 Multiple Catch statements –using finally statement– Throwing our own Exceptions – using exceptions for Debugging -UNIT-X: Graphics Programming: The Graphics Class – Lines andRectangles – Circles and Ellipses – Drawing Arcs – Drawing Polygons– Line Graphs – Using Control Loops in Applets – Drawing Bar Charts.UNIT-XI: Applet Programming: How applets differ from Applications– preparing to write applets – Building Applet Code – Applet life cycle– creating an Executable Applet – Designing a Web Page – Applet Tag– Adding Applet to HTML file – Running the Applet – Passingparameters to Applets – Displaying Numerical values – Getting inputfrom the user
Unit 1: Basic Concepts of OOP(Pages 1-17)
Unit 2: Overview of Java Language(Pages 18-38)
Unit 3: Operators and Expressions(Pages 39-61)
Unit 4: Classes(Pages 62-92)
Unit 5: Arrays, Strings and Vectors(Pages 93-111)
Unit 6: Packages(Pages 112-130)
Unit 7: Introduction to Thread(Pages 131-148)
Unit 8: Thread Exceptions(Pages 149-163)
Unit 9: Exceptions(Pages 164-178)
Unit 10: Graphics Programming(Pages 179-191)
Unit 11: Applet Programming(Pages 192-205)
BLOCK 5: Managing Input/Output Files in JavaUNIT-XII: Introduction – concept of streams –stream classes – bytestream classes – character StreamUNIT-XIII: I/O classes: –using stream –using the file class –Input /output Exceptions – creation of files – Reading / writing charactersUNIT-XIV: Reading writing bytes: Random access files- Interactiveinput and output –Other stream classes
Unit 12: Introduction to Streams(Pages 206-218)
Unit 13: I/O Classes(Pages 219-232)
Unit 14: Reading Writing Bytes(Pages 233-244)
BLOCK 1: FUNDAMENTALS OF OBJECT-ORIENTED PROGRAMMING
UNIT 1 BASIC CONCEPTS OF OOP 1-171.0 Introduction1.1 Objectives1.2 Concepts of OOP
1.2.1 Objects1.2.2 Classes1.2.3 Abstraction1.2.4 Encapsulation1.2.5 Inheritance1.2.6 Polymorphism1.2.7 Message Passing1.2.8 Dynamic Binding
1.3 Benefits and applications of OOP1.3.1 Applications of OOP
1.4 Java Evolution1.5 Java Features1.6 How Java Differs from C and C++
1.6.1 Java and C1.6.2 Java and C++
1.7 Java and Internet1.8 Java Support Systems1.9 Java Environment
1.9.1 JDK (Java Development Kit)1.9.2 Java Standard Library
1.10 Answers to Check Your Progress Questions1.11 Summary1.12 Key Words1.13 Self Assessment Questions and Exercises1.14 Further Readings
UNIT 2 OVERVIEW OF JAVA LANGUAGE 18-382.0 Introduction2.1 Objectives2.2 Tokens
2.2.1 Keywords2.2.2 Identifiers2.2.3 Constants2.2.4 Operators2.2.5 Punctuators
2.3 Simple Java Program2.4 Running Java Applications2.5 Structure of a Java Program
CONTENTS
2.6 JVM2.7 Command Line Arguments2.8 Data Types
2.8.1 Primitives Data types2.8.2 Non-Primitive Data Types
2.9 Variables2.10 Type Casting2.11 Answers to Check Your Progress Questions2.12 Summary2.13 Key Words2.14 Self Assessment Questions and Exercises2.15 Further Readings
UNIT 3 OPERATORS AND EXPRESSIONS 39-613.0 Introduction3.1 Objectives3.2 Operators and Operations
3.2.1 Arithmetic Operators3.2.2 Increment and Decrement Operators3.2.3 Relational Operators3.2.4 Logical Operators3.2.5 Conditional Operator3.2.6 Assignment Operators3.2.7 Other Operators3.2.8 Operators: Precedence and Associativity
3.3 Conditional Statements3.4 Iteration Statements or Loops
3.4.1 The for Loop3.4.2 The while Loop3.4.3 The do-while Loop3.4.4 Nested Loops
3.5 Jump Statements3.6 Answers to Check Your Progress Questions3.7 Summary3.8 Key Words3.9 Self Assessment Questions and Exercises
3.10 Further Readings
BLOCK 2: CLASSES, OBJECTS AND METHODS
UNIT 4 CLASSES 62-924.0 Introduction4.1 Objectives4.2 Introduction to Class
4.2.1 Defining Methods4.3 Instantiating Objects of a Class4.4 Accessing Members of a Class
4.5 Argument Passing4.5.1 Call-By-Value4.5.2 Call-By-Reference
4.6 Method Overloading4.7 Constructors
4.7.1 Parameterized Constructors4.8 Static Members4.9 Superclass and Subclass
4.9.1 Defining a Subclass4.10 Types of Inheritance
4.10.1 Single Inheritance4.10.2 Hierarchical Inheritance4.10.3 Multilevel Inheritance4.10.4 Multiple Inheritance
4.11 Access Modifier4.12 Method Overriding4.13 Using final Keyword
4.13.1 final Variables4.13.2 final Methods4.13.3 final Class
4.14 Abstract Methods and Classes4.15 Answers to Check Your Progress Questions4.16 Summary4.17 Key Words4.18 Self Assessment Questions and Exercises4.19 Further Readings
UNIT 5 ARRAYS, STRINGS AND VECTORS 93-1115.0 Introduction5.1 Objectives5.2 Arrays
5.2.1 Single-Dimensional Arrays5.2.2 Multi-Dimensional Arrays
5.3 Strings5.3.1 String Class5.3.2 StringBuffer Class
5.4 Vectors5.4.1 Wrapper Classes
5.5 Answers to Check Your Progress Questions5.6 Summary5.7 Key Words5.8 Self Assessment Questions And Exercises5.9 Further Readings
UNIT 6 PACKAGES 112-1306.0 Introduction6.1 Objectives6.2 Defining Interface6.3 Implementing Interface
6.3.1 Partial Implementations6.4 Extending Interfaces6.5 Extends and Implements Together6.6 Overview of Packages6.7 Java API Packages
6.7.1 Naming Conventions6.8 Defining Packages
6.8.1 Accessing Packages6.9 Using Packages
6.10 Adding a Class6.11 Answers to Check Your Progress Questions6.12 Summary6.13 Key Words6.14 Self Assessment Questions and Exercises6.15 Further Readings
BLOCK 3: MULTITHREADED PROGRAMMING
UNIT 7 INTRODUCTION TO THREAD 131-1487.0 Introduction7.1 Objectives7.2 Overview of Multithreading
7.2.1 Main Thread7.3 Creating a Thread
7.3.1 Extending the Thread Class7.3.2 Implementing Runnable Interface
7.4 Thread Life Cycle7.5 The Thread Control Methods
7.5.1 Using yield(), sleep() and stop() Method7.5.2 Using isAlive() and join() Method
7.6 Answers to Check Your Progress Questions7.7 Summary7.8 Key Words7.9 Self Assessment Questions and Exercises
7.10 Further Readings
UNIT 8 THREAD EXCEPTIONS 149-1638.0 Introduction8.1 Objectives8.2 Threads Priority8.3 Thread Synchronization
8.3.1 Synchronizing Methods
8.3.2 Synchronizing Statements8.3.3 Deadlock
8.4 Answers to Check Your Progress Questions8.5 Summary8.6 Key Words8.7 Self Assessment Questions and Exercises8.8 Further Readings
BLOCK 4: MANAGING ERROR, EXCEPTION AND APPLETS
UNIT 9 EXCEPTIONS 164-1789.0 Introduction9.1 Objectives9.2 Types of Errors
9.2.1 Exceptions9.3 Exception Handling
9.3.1 Syntax of Exception Handling Code (Using try and catch blocks)9.3.2 Multiple catch Statements9.3.3 Using finally Statement9.3.4 Using throw Keyword9.3.5 Using throws Keyword
9.4 Creating User-defined Exceptions9.5 Answers to Check Your Progress Questions9.6 Summary9.7 Key Words9.8 Self Assessment Questions and Exercises9.9 Further Readings
UNIT 10 GRAPHICS PROGRAMMING 179-19110.0 Introduction10.1 Objectives10.2 Working with Graphics
10.2.1 Using Graphics Class10.3 Line Graphs10.4 Control Loops in Applets10.5 Drawing Bar Charts10.6 Answers to Check Your Progress Questions10.7 Summary10.8 Key Words10.9 Self Assessment Questions and Exercises
10.10 Further Readings
UNIT 11 APPLET PROGRAMMING 192-20511.0 Introduction11.1 Objectives11.2 Applet Fundamentals
11.2.1 Difference between Console-Based Applications and Applets
11.2.2 Local and Remote Applets11.2.3 Life Cycle of an Applet
11.3 Steps to Build an Applet11.3.1 Creating an Applet Code11.3.2 Creating an Executable Applet11.3.3 Designing an HTML Document11.3.4 Executing an Applet
11.4 Passing Parameters to Applets11.5 Answers to Check Your Progress Questions11.6 Summary11.7 Key Words11.8 Self Assessment Questions and Exercises11.9 Further Readings
BLOCK 5: MANAGING INPUT/OUTPUT FILES IN JAVA
UNIT 12 INTRODUCTION TO STREAMS 206-21812.0 Introduction12.1 Objectives12.2 Streams12.3 I/O Packages
12.3.1 Byte Stream Classes12.3.2 Character Stream Classes
12.4 Answer to Check Your Progress Questions12.5 Summary12.6 Key Words12.7 Self Assessment Questions and Exercises12.8 Further Readings
UNIT 13 I/O CLASSES 219-23213.0 Introduction13.1 Objectives13.2 Reading Console Input13.3 Handling Files
13.3.1 Creation of Files: Using FileInputStream and FileOutputStream Classes13.3.2 Reading/Writing Characters: Using FileReader and
FileWriter Classes13.3.3 Using File Class13.3.4 Handling the Primitive Data Types and I/O Exceptions
13.4 Answers to Check Your Progress Questions13.5 Summary13.6 Key Words13.7 Self Assessment Questions and Exercises13.8 Further Readings
UNIT 14 READING WRITING BYTES 233-24414.0 Introduction14.1 Objectives14.2 The RandomAccessFile Class14.3 The PrintStream Class14.4 The StringTokenizer Class14.5 The StreamTokenizer Class14.6 Answer to Check Your Progress Questions14.7 Summary14.8 Key Words14.9 Self Assessment Questions and Exercises
14.10 Further Readings
INTRODUCTION
Java is considered as a set of several computer software products and SunMicrosystems specifications which when merged with Oracle Corporation providesa system to develop application software and to deploy it in a cross-platformcomputing environment. Java is used in a wide variety of computing platformsfrom embedded devices and mobile phones on the low end to enterprise serversand supercomputers on the high end. Though it is not very common on desktopcomputers, but Java applets are sometimes used for providing improved and securefunctions at the time of browsing the World Wide Web or WWW.
The word Java, alone, typically refers to the Java programming languagespecifically designed for the Java platform. The language and runtime are commonlyconsidered as a single unit. The Java platform consists of several programs, eachof which provides a portion of its overall capabilities, for example, the Java compiler,which converts Java source code into Java bytecode (an intermediate languagefor the JVM or Java Virtual Machine), is provided as part of the Java DevelopmentKit (JDK). The Java Runtime Environment (JRE), complementing the Java VirtualMachine (JVM) with a Just-In-Time (JIT) compiler, converts intermediate bytecodeinto native machine code on the fly. An extensive set of libraries are also part of theJava platform.
The success of Java depends on its write once and run anywhere conceptwhich has also given way to other similar efforts, remarkably the .NET Frameworkwhich incorporates many of the successful aspects of Java. .NET (Microsoft’simplementation) is currently only fully available on Windows platforms, whereasJava is fully available on many platforms. The Java Development Kit (JDK) is aSun product aimed at Java developers. Since the initiation of Java, it has been byfar the most widely used Java Software Development Kit (JSDK). It contains aJava compiler, a full copy of the Java Runtime Environment (JRE) and many otherimportant development tools.
Writing in the Java programming language is the primary way to producecode that will be deployed as Java bytecode. The core of the Java platform isbased on the concept of ‘virtual machine’ that executes Java bytecode programs.This bytecode remains the same irrespective of the hardware or operating systemthat the program is using. There is a JIT (Just-In-Time) compiler within the JavaVirtual Machine or JVM. The JIT compiler translates the Java bytecode into nativeprocessor instructions at run-time and caches the native code in memory duringexecution.
This book, Object Oriented Programming and Java, provides a basicunderstanding of the subject and helps the students grasp its fundamentals. EachUnit begins with an Introduction followed by an outline of the Objectives. Thedetailed content is then presented in a simple and structured format interspersedwith Check Your Progress Questions to test the student’s understanding. ASummary, a list of Key Words and a set of Self-Assessment Questions andExercises is provided at the end of each unit for effective recapitulation.
NOTES
Self-InstructionalMaterial
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 1
BLOCK - IFUNDAMENTALS OF OBJECT-ORIENTED
PROGRAMMING
UNIT 1 BASIC CONCEPTS OF OOP
Structure1.0 Introduction1.1 Objectives1.2 Concepts of OOP
1.2.1 Objects1.2.2 Classes1.2.3 Abstraction1.2.4 Encapsulation1.2.5 Inheritance1.2.6 Polymorphism1.2.7 Message Passing1.2.8 Dynamic Binding
1.3 Benefits and applications of OOP1.3.1 Applications of OOP
1.4 Java Evolution1.5 Java Features1.6 How Java Differs from C and C++
1.6.1 Java and C1.6.2 Java and C++
1.7 Java and Internet1.8 Java Support Systems1.9 Java Environment
1.9.1 JDK (Java Development Kit)1.9.2 Java Standard Library
1.10 Answers to Check Your Progress Questions1.11 Summary1.12 Key Words1.13 Self Assessment Questions and Exercises1.14 Further Readings
1.0 INTRODUCTION
The goal of programmers is to develop software that is correct and reliable andcan satisfy all the user requirements. Software development is not a static processas software needs to be modified or redesigned in accordance with the changes inuser requirements, business rules and strategies. In addition, the complexity of thesoftware also increases.
Basic Concepts of OOP
NOTES
Self-Instructional2 Material
Initially, when the computer was invented, binary language was used towrite the programs. However, as the programs grew in size, it became difficult towrite programs using binary language. Then, assembly language was invented towrite large programs. This was also not very user-friendly. With the change in userrequirements, the size and the complexity of the programs continued to grow,which led to the development of high-level languages such as BASIC andFORTRAN.
To overcome the limitations of the unstructured programming paradigm,other programming paradigms, namely, procedural and object-orientedprogramming paradigms were developed, which help programmers to developthe programs in a structured manner. In this unit, you will learn about the basics ofobject-oriented programming.
1.1 OBJECTIVES
After going through this unit, you will be able to: Understand the concept of object-oriented programming Differentiate between object, class and abstraction Explain encapsulation and the services it provides Define inheritance and its advantages Discuss the benefits and applications of OOP Understand JAVA evolution and features
1.2 CONCEPTS OF OOP
To understand the concept of object-oriented programming, it is necessary toknow the fundamental terms and concepts of this approach. These include objects,classes, data abstraction, encapsulation, inheritance, polymorphism and messagepassing.
1.2.1 Objects
Objects are small, self-contained and modular units with a well-defined boundary.An object consists of a state and behaviour. The state of an object is one of thepossible conditions that an object can exist in and is represented by its characteristicsor attributes or data. The behaviour of an object determines how an object acts orbehaves and is represented by the operations that it can perform. In OOP, theattributes of an object are represented by the variables and the operations arerepresented by the functions.
For example, an object Biscuit may consist of data product code ,product name , price and quantity in hand .These data values specify the attributes or features of the object. Similarly, consider
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 3
another object Maggi with product code , product name , price , and quantity in hand . In addition, the data in the
object can be used by the functions such as and. These functions specify the actions that can be
performed on data. Figure 1.1 shows how class and its objects are represented.
Data:
Functions:
Data: P001 Britania biscuits 20 50
Data: P002 Maggi Noodles 10 20
Class:
Objcet: MaggiObjcet: Biscuits
Fig. 1.1 Class and its Objects
Objects are what actually run in the computer and are the basic run-timeentities in object-oriented systems. They are the building blocks of object-orientedprogramming. Although, two or more objects can have same attributes, still theyare separate and independent objects with their own identity. In other words, allthe objects in a system take a separate space in the memory, independent of eachother. The main objective of breaking down complex software projects into objectsis that changes made to one part of a software should not adversely affect theother parts.
1.2.2 Classes
A class is defined as a user-defined data type which contains the entire set ofsimilar data and the functions that the objects possess. In other words, a class inOOP represents a group of similar objects. As stated earlier, in the real worldmillions of objects exist and each of them has its own identity. However, each ofthem can be categorized under different groups depending on the common propertiesthey possess and the functions they perform. For example, cars, scooters,motorbikes, buses, etc. all can be grouped under the category ‘vehicles’. Similarly,dogs, cats, horses etc. can be grouped under the category ‘animals’. Thus, vehiclesand animals can be considered as the classes.
Basic Concepts of OOP
NOTES
Self-Instructional4 Material
A class serves as a blueprint or template for its objects. That is, once a classhas been defined, any number of objects belonging to that class can be created.The objects of a class are also known as the instances or variables of that classand the process of creating objects from a class is known as instantiation. A classdoes not represent an object, rather it represents the data and functions that anobject will have.
For example, a class consists of data such as ,, and which specify the attributes or features
of the objects of the class. In addition, it consists of functions such as and that specify the actions that
can be performed on data.The data belonging to a particular class is known as its data members and
the functions of the class are known as the member functions andboth collectivelyare known as the members of the class.Note: In Java, the data members are referred as instance variables and member functions arereferred to as methods.
1.2.3 Abstraction
Abstraction is a mechanism to hide irrelevant details and represent only the essentialfeatures so that one can focus on important things at a time. It allows the managementof complex systems by concentrating on the essential features only. For example,while driving a car, a driver only knows the essential features to drive a car such ashow to use the clutch, brake, accelerator, gears, steering, etc. and is least botheredabout the internal details of the car like the motor, engine, wiring etc.
Abstraction can be of two types— and controlabstraction. Data abstraction (also known as data hiding) means hiding the detailsabout the data and control abstraction means hiding the implementation details. Inobject-oriented approach, one can abstract both data and functions. However,generally the classes in OOP are defined in such a way that the data is hidden fromthe outside world and the functions form the public interface. That is, the functionsof the class can be directly accessed by other functions outside the class and thehidden data can be accessed indirectly with the help of these functions.
Since the internal details of the class are hidden from the outside world, thedata abstraction ensures security of the data by preventing it from accidental changesor manipulations by other parts of the program.Note: Classes in the object-oriented programming are also known as Abstract Data Types(ADT) as they use the concept of abstraction.
1.2.4 Encapsulation
Encapsulation is the technique of binding or keeping the data and functions (thatoperate on them) together in a single unit called a class. Encapsulation is the wayto implement data abstraction. A well-encapsulated object acts as a ‘black box’
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 5
for other parts of the program. That is, it provides services to the external functionsor other objects that interact with it. However, these external functions or theobjects do not need to know its internal details. For example, in Figure 1.1 thedata , and and the functions
and are encapsulated in a class.
1.2.5 Inheritance
Inheritance can be defined as the process where an object of a class acquirescharacteristics from the object of another class. As stated earlier, all the objects ofa similar kind are grouped together to form a class. However, sometimes a situationarises when different objects cannot be combined together under a single group asthey share only few common characteristics. In this situation, the classes are definedin such a way that the common features are combined to form a generalized classand the specific features are combined to form a specialized class. The specializedclass is defined in such a way that in addition to the individual characteristics andfunctions, it also inherits all the properties and the functions of its generalized class.
For example, in the real world, all the vehicles cannot be automobiles—some of them are pulled vehicles also. Thus, car and scooter both are vehicles thatcome under the category of automobiles. Similarly, rickshaw and bicycle are thevehicles that come under the category of pulled vehicles. Thus, automobiles andpulled vehicles inherit the common properties of the vehicle class and also havesome other properties that are not common and differentiate them. Thus, the vehiclesclass is the generalization of automobiles and pulled vehicles class and automobilesand pulled vehicles classes are the specialized versions of the vehicles class. Whileinheriting the vehicle class, the automobiles and pulled vehicles do not modify theproperties of the vehicle class, however, can add new properties that are exclusivefor them Figure 1.2 shows the process of inheritance.
Fig. 1.2 Inheritance
In the same way, OOP allows one class to inherit the properties of anotherclass or classes. The class, which is inherited by the other classes, is known assuperclass or base class or parent class and the class, which inherits the propertiesof the base class, is called sub class or derived class or child class. The sub-classcan further be inherited to form other derived classes. For example, in Figure 1.2,
Basic Concepts of OOP
NOTES
Self-Instructional6 Material
car and scooter are the derived classes of automobiles and rickshaw and bicycleare the derived classes of pulled vehicles.
The main advantage of inheritance is reusability. The existing classes can besimply re-used in new software instead of writing a new code. Moreover, newfeatures can be added without altering or modifying the features of the existingclass.
1.2.6 Polymorphism
Polymorphism (a Greek word meanings ‘having multiple forms’) is the ability ofan entity such as a function or a message to be processed in more than one form.It can also be defined as the property of an object belonging to a same or differentclass to respond to the same message or function in a different way. For example,if a message is passed to all the vehicles then the automobileswill respond to the message appropriately but the pulledvehicles will not respond.The concept of polymorphism plays an important role in OOP as it allows anentity to be represented in various forms.
1.2.7 Message Passing
Message passing is the process of interacting between the different objects in aprogram. As discussed earlier, a program following the object-oriented paradigmcomprises of a set of objects each, with a set of data and functions. When theprogram is executed, these objects interact or communicate with each other bysending and receiving messages. The messages are exchanged by calling the memberfunctions of the classes.
Any object of a class that wants to communicate with the object of anotherclass requests the object to invoke the required member function of its class. Thisfunction call is different from the normal function call as in this case the sendingobject is sending a request for the execution of the function. However, the receivingobject may or may not accept the request depending on whether the functionforms the public interface or it is hidden from the outside world. Thus, this form ofcommunication is called message sending and is not an ordinary function call.
For example, consider two classes Product and Order. The object of theProduct class can communicate with the object of the Order class by sending arequest for placing order Figure 1.3 illustrates the process of message passing.
Fig. 1.3 Message Passing
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 7
1.2.8 Dynamic Binding
Dynamic binding is the process of linking a function call to the actual code of thefunction at run-time. That is, in dynamic binding, the actual code to be executed isnot known to the compiler until run-time. The concept of dynamic binding isimplemented with the help of inheritance and run-time polymorphism.
Consider an example in which three different classes, square, rectangle andcircle are derived from the base class . The function
of the base class is implemented in different ways in all its derivedclasses. At run-time, the desired function will be called depending on the objectbeing referenced.
1.3 BENEFITS AND APPLICATIONS OF OOP
The object-oriented programming paradigm came into use owing to its ability toovercome certain limitations of structured and unstructured programming paradigms.The new and advanced features of OOP such as encapsulation, abstraction,inheritance and polymorphism help in developing high-quality software, which hasvarious advantages. Some of the advantages of OOP are as follows.
In OOP, writing programs with the help of objects is similar to working withreal-world objects. That is, the real-world objects can be convenientlyrepresented in a program which reduces the compexity of the program andalso makes the program structure clear.
In object-oriented programs, each object is an independent and separateentity which makes modifications, locates and fixes problems in a program aneasy task. In addition, any changes made inside the class do not affect theother parts of a program. Thus, object-oriented programs are easy to writeand maintain.
In object-oriented programming, data integrity and data security is high as itfocuses on the data and its protection from manipulation by different partsof the program. As a result, object-oriented programs are less prone toerrors, and more reliable and secure.
Object-oriented programs are easy to extend as new features in a programcan be added easily by introducing some new objects without modifyingthe existing ones.
Object-oriented programming allows the reusability of codes. That is, theobjects created in one program can be reused in other programs. In addition,new classes can be created with the help of existing ones using inheritance.It leads to faster software development and high-quality programs.
Object-oriented programs are easier to adapt and scale, that is, large systemscan be created by assembling reusable subsystems.
Basic Concepts of OOP
NOTES
Self-Instructional8 Material
1.3.1 Applications of OOP
Since 1960, object-oriented paradigm has touched many major application areasof software development. Some of the application areas where OOP has beenused to develop software are as follows:
Simulation and modelling: Simulation is the technique of representing thereal-world entities with the help of a computer program. Simula-67 andSmalltalk are two object-oriented languages are designed for makingsimulations.
User-interface design: Another popular application of OOP has been inthe area of designing graphical user interfaces such as Windows. C++ ismainly used for developing user-interfaces.
Developing computer games: OOP is also used for developing computergames such as Diablo, Startcraft, Warcraft III and many more. These gamesoffer virtual reality environments in which a number of objects interact witheach other in complex ways to give the desired result.
Scripting: In recent years, OOP has also been used for developing HTML,XHTML and XML documents for the Internet. Python, Ruby and Java arethe scripting languages based on object-oriented principles which are usedfor scripting.
Object databases: These days, OOP concepts have also been introducedin database systems to develop a new database management system namedobject database. These databases store the data directly in the form ofobjects. However, they are not as popular as the traditional relationaldatabase management systems.Some other areas of applications include office automation systems, decision
support systems, Artificial Intelligence (AI) and expert systems, Neural networksand parallel programming and Computer-Aided Design (CAD) systems.
Check Your Progress
1. How can you define inheritance?2. What is simulation?
1.4 JAVA EVOLUTION
Java, initially, named ‘Oak’ was developed by the team headed by James Goslingat Sun Microsystems, USA in 1991. The first and foremost reason behind thedevelopment of Java was the need of a platform independent and portable softwareto be embedded in the consumer’s electronic devices like remote controls,microwave ovens, etc. Second reason that led to the growth of Java is the Internetand World Wide Web as these media need portable and platform independent
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 9
programs. Gosling and other team members developed web applets using thenew language that could run on all types of computers. During 1993, first webbrowser namely ‘HotJava’ was developed to locate and run applet programs.This development made Java language popular for the Internet. By the year 1996,Java became the general-purpose, object-oriented programming language whichwas used for Internet programming. Soon, Java became popular and many webbrowsers like Internet Explorer, Netscape Navigator incorporated the ability torun Java applets.
1.5 JAVA FEATURES
Java has become a popular language for Internet applications because of variousfeatures which are as follows:
Simple, Small and Familiar: Java is a simple, small and familar language.As Java inherits the syntax of C/C++ and many of the OOPs features ofC++ thus, one who is familiar with the concepts of object-oriented languagecan learn Java with least effort. Moreover Java omits the complex andunreliable code of C and C++ like operator overloading, pointers,preprocessor header files. Java provides small and convenient ways toaccomplish a given task.
Compiled and Interpreted: Unlike other languages Java uses two-stagesystem as it uses both compiler and interpreter for its program execution.First, the compiler converts the program code to bytecode which in turn isconverted to machine code on any machine using the interpreter. The machinecode so generated can be executed irrespective of the system on which it isbeing executed.
Platform-Independent and Portable: This feature makes Java languagevery special. Java programs can run on any platform, that is, they can runon different CPU and on different operating system architectures. Thebytecode produced by Java compiler can be run on any machine which hasJava runtime environment.
Object-Oriented language: Java is an object-oriented language aseverything in Java is an object. The objects and classes contain the programcode and data. The Java object model is easily extensible and classes canbe used anywhere in the program in the form of packages.
Robust and Secure: Java is a robust language because of mainly tworeasons. Firstly, it is a strictly typed language that checks the code at thecompile time. Secondly, Java does memory management in an effectiveway. In C++, the programmer has to manually deallocate the dynamicmemory used by the objects. Java automatically deallocates free memorythat is no longer referenced by the objects (with the help of garbage collector).
Basic Concepts of OOP
NOTES
Self-Instructional10 Material
Since Java is a programming language that is used for programming onInternet, security becomes an important issue. Java systems ensure that noviruses are communicated with an applet.
Distributed: Since Java is platform independent, it is suitable for developingapplications for the networks. Java can handle TCP/IP protocols and henceapplications developed in Java can access remote objects on Internet likeany object on a local system.
Multithreaded and Interactive: Java supports multithreaded programmingwhich allows us to write a program that can perform more than one tasksimultaneously. Users need not wait for the program to finish one task,before starting another. For example, users can listen to an audio clip whiledownloading the applet. This feature helps to improve the performance ofgraphical applications. Java also supports multiprocess synchronization andsmoothly running interactive system.
High Performance: As stated earlier, the Java program is converted tobytecode which is then converted to machine code using interpreter. Sincebytecode is highly optimized, it enables the JVM to execute programs atmuch faster rate.
Dynamic and Extensible: It is dynamic in nature that is Java programscan link to new class libraries, objects, methods, etc., at the run-time. Javalanguage also provides the facility to include the functions of other languageslike C and C++. They are referred to as native methods. These methodsare also linked dynamically at run-time.
1.6 HOW JAVA DIFFERS FROM C AND C++
Though Java came into existence after C and C++ language, it differs from boththe languages in a number of ways. Some of the features which are available in Cand C++ have been removed in Java. This section discusses some of the differencesbetween Java and C/C++.
1.6.1 Java and C
The main difference between Java and C is that Java is an object-oriented languageand uses the concept of classes and objects. The Java team excluded some of thefeatures of C from Java and added some new ones.
Java does not include the data types and . Java does not include the keywords and . Java does not define the type modifier keywords , ,
, , and . Since Java does not have a preproccessor, the statements ,
, and cannot be used.
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 11
Data members in Java are by default . Java does not support the concept of pointers. Execution of a Java program is little slow as the intermediate bytecode has
to be interpreted. Java adds and >>> operators and also, the labeled
and statements.
1.6.2 Java and C++
Both C++ and Java are object-oriented languages but they are very different fromeach other. Some of the features of C++ language were deliberately removed andsome new features were added to make Java a more flexible and reliable language.Some of the differences between Java and C++ are as follows:
1. Java does not support multiple inheritance directly.2. The concept of multithreading is supported by Java.3. The destructor function in Java is replaced by method.4. The keyword is not supported by Java.5. Java does not support pointers instead it uses implicit object references.6. The keyword is not supported in Java.7. Java does not support the concept of global variables.8. Java supports exception handling in different way than C++. It provides
clause for cleanup.9. The non-primitive data types are allocated memory by using the
operator.10. Java adds many features that are necessary for object-oriented programming.
1.7 JAVA AND INTERNET
In recent years, Java has become popular language for the programs that arerequired to run on different systems. Java’s new innovation named “applet” hascompletely changed the Internet programming. Applets are tiny programs that aredesigned in such a way that they can be transmitted over the Internet. They can bedownloaded on demand and executed automatically by Java compatible webbrowser. They are used to handle user input, data supplied by the server andsimple functions that executes locally on the client machine.
Applet is dynamic, self-executing program and is intelligent enough that canchange it with the user inputs. The dynamic programs when downloaded andexecuted can cause serious harms to the computer as it may contain viruses likeTrojan horse and malicious programs. These harmful programs may search thecontents on local file system of the client computer and may gather private
Basic Concepts of OOP
NOTES
Self-Instructional12 Material
information like credit card numbers, passwords, etc. Earlier viruses were scannedbefore executing the downloaded program, but Java has resolved the issue byconfining the Java programs to Java execution environment only.
1.8 JAVA SUPPORT SYSTEMS
There are various support systems available for the operation of Java and Java-enabled browsers. Below is the list of systems which are required to support Javafor delivering information across the Internet.
Web Browser: A web browser is a program that can run Java applets andallows access to the World Wide Web. The most widely used web browsersthat support the Java applets are Microsoft Internet Explorer, Apple Safari,Mozilla’s Firefox, Opera and Google’s Chrome.
Web Server: A web server is a computer program that receives requestfrom the client, processes it and sends the result to the client.
Internet Connection: There should be an Internet connection on the localcomputer.
HTML: HTML (Hypertext Markup Language) is a language which is usedto create hypertext for the Web. As HTML is static, JavaScript is used toenhance the HTML functionality by making it dynamic to develop dynamicpages.
Applet Tag: It is a tag which is used to place Java applets in HTMLdocument. An applet is a small program typically embedded within the webpage which is used to create a dynamic and interactive application. Javaapplets are portable, as they are independent of system environment andweb browser. They can be downloaded on demand and executedautomatically by Java compatible web browser.
Java Code: Java code is a program code that is written in the Javaprogramming language. Java source code files have the .java extension.The Java source code is converted into the Java bytecode by Java compiler.
Bytecode: Bytecode is a compiled Java code in the form of .class file. Thisbytecode is interpreted into the machine code. Bytecode makes Java portableand platform independent language.
Proxy Server: It is a kind of server which acts as mediator between theclient machine and the actual server. It receives any data sent from the clientand forwards it to the remote host. Similarly, it receives any response receivedfrom the remote host and forwards it to the client machine. The proxy serveris invisible to both the client and remote host, thus they are unaware aboutthe presence of proxy server which is placed between them.The proxy server can play the role of both client and server. It acts as aserver to the actual client, which requests data from the remote host. The
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 13
proxy server then processes the request like an actual server, and thenforwards the request to the remote host, acting as a client. When the remotehost sends the response of the request, the proxy server receives the responselike an actual client, and forwards that response to the original client actingas a server.
Email Server: It is an application that receives and forwards electronicmail across network. There are some mail servers which are developed inJava known as Java Email Server (JES). Java SMTP and POP3 emailserver are Java Email Server. The aim of JES is to provide a simple andefficient email server that can be setup quickly and easily.
1.9 JAVA ENVIRONMENT
In most of the programming languages, the program is converted to machine codeeither by using compiler or interpreter. The machine code so generated is machinedependent, that is, it may not run on the machine other than the one on which it isgenerated. Unlike in case of other programming languages, the Java compiler doesnot convert source code to machine code, it converts source code to a specialintermediate code known as bytecode (see Figure 1.4). The bytecode so generatedis in the form of class files that can be interpreted. The command used for compilationin Java is which converts the corresponding Java file into class file. Thebytecode is machine independent that is it can be run on any machine with the helpof Java virtual machine (JVM) which is discussed in the next topic.
Fig. 1.4 Compilation of a Java Program
1.9.1 JDK (Java Development Kit)
JDK consists of various tools that are used to develop and execute Java programs.The tools included in JDK are listed in Table 1.1.
Table 1.1 Tools in Java Development Kit
Tool Function javac Java compiler that converts source code to Java bytecode java Java interpreter that interprets class files generated by java compiler
and converts it to machine code javadoc Document generator which automatically generates documentation
form source code javah Generates C headers and a stub generator used for writing native
methods javap The class file disassembler which enables to convert bytecode files
to a program description jdb Java debugger which helps in tracking errors in the program appletviewer Used for running and debugging Java applets without a web browser
Basic Concepts of OOP
NOTES
Self-Instructional14 Material
1.9.2 Java Standard Library
The Java standard library (or Application Programming Interface) is composed ofvarious classes and methods which are grouped into several packages. Some ofthe commonly used packages include the following.
Language Support Package: It contains classes and methods which arerequired to implement the basic features of Java.
Input/Output Package: It contains classes which are required for Input/Output manipulation.
Networking Package: It contains classes that allow communicationbetween computers through Internet.
Utilities Package: It contains classes that provide utility functions such asdate and time functions.
Applet Package: It contains a set of classes for creating Java applets. AWT Package: It contains classes for implementing graphical user interface.
Check Your Progress
3. What is Java and what does it use?4. What does HTML stand for?
1.10 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. Inheritance can be defined as the process where an object of a class acquirescharacteristics from the object of another class.
2. Simulation is the technique of representing the real- world entities with thehelp of a computer program
3. Java is an object-oriented language and uses the concept of classes andobjects.
4. HTML stands for Hypertext Markup Language.
1.11 SUMMARY
Objects are small, self-contained and modular units with a well-definedboundary. An object consists of a state and behavior.
The behavior of an object determines how an object acts or behaves and isrepresented by the operations that it can perform.
Objects are what actually run in the computer and are the basic run-timeentities in object-oriented systems.
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 15
A class is defined as a user-defined data type which contains the entire setof similar data and the functions that the objects possess.
Abstraction is a mechanism to hide irrelevant details and represent only theessential features so that one can focus on important things at a time.
Encapsulation is the technique of binding or keeping the data and functions(that operate on them) together in a single unit called a class.
Inheritance can be defined as the process where an object of a class acquirescharacteristics from the object of another class.
OOP allows one class to inherit the properties of another class or classes. The main advantage of inheritance is reusability. The existing classes can be
simply re-used in new software instead of writing a new code. Polymorphism (a Greek word meanings ‘having multiple forms’) is the ability
of an entity such as a function or a message to be processed in more thanone form.
Message passing is the process of interacting between the different objectsin a program.
Any object of a class that wants to communicate with the object of anotherclass requests the object to invoke the required member function of itsclass.
Dynamic binding is the process of linking a function call to the actual codeof the function at run-time.
The object-oriented programming paradigm came into use owing to its abilityto overcome certain limitations of structured and unstructured programmingparadigms.
In OOP, writing programs with the help of objects is similar to working withreal- world objects
In object-oriented programs, each object is an independent and separateentity which makes modifications, locates and fixes problems in a programan easy task.
Object-oriented programs are easy to extend as new features in a programcan be added easily by introducing some new objects without modifyingthe existing ones.
Java is a robust language because of mainly two reasons. Firstly, it is astrictly typed language that checks the code at the compile time. Secondly,Java does memory management in an effective way.
Since Java is a programming language that is used for programming onInternet, security becomes an important issue.
The main difference between Java and C is that Java is an object-orientedlanguage and uses the concept of classes and objects.
Basic Concepts of OOP
NOTES
Self-Instructional16 Material
1.12 KEY WORDS
Web Browser: It is a program that can run Java applets and allows accessto the World Wide Web. The most widely used web browsers that supportthe Java applets are Microsoft Internet Explorer, Apple Safari, Mozilla’sFirefox, Opera and Google’s Chrome.
Web Server: It is a computer program that receives request from the client,processes it and sends the result to the client.
HTML: HTML (Hypertext Markup Language) is a language which is usedto create hypertext for the Web.As HTMLis static, JavaScript is used toenhance the HTML functionality by making it dynamic to develop dynamicpages.
Proxy Server: It is a kind of server which acts as mediator between theclient machine and the actual server. It receives any data sent from the clientand forwards it to the remote host.
Bytecode: It is a compiled Java code in the form of .class file. This bytecodeis interpreted into the machine code. Bytecode makes Java portable andplatform independent language.
1.13 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. Define objects? What does the behavior of an object determine?2. Write a short note on class and its objects.3. Write short notes on classes, abstraction, and encapsulation.4. What is message passing? Explain.5. Show a small diagrammatic representation of inheritance.
Long Answer Questions
1. Write a detailed note on Java Standard Library.2. What is Java Development Kit? What are the tools used in Java Development
Kit?3. Explain how does Java differ from C and C++?4. Discuss the concept of OOP in detail. Also write about objects, classes,
data abstraction, encapsulation, inheritance, polymorphism and messagepassing.
Basic Concepts of OOP
NOTES
Self-InstructionalMaterial 17
1.14 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Overview of Java Language
NOTES
Self-Instructional18 Material
UNIT 2 OVERVIEW OF JAVALANGUAGE
Structure2.0 Introduction2.1 Objectives2.2 Tokens
2.2.1 Keywords2.2.2 Identifiers2.2.3 Constants2.2.4 Operators2.2.5 Punctuators
2.3 Simple Java Program2.4 Running Java Applications2.5 Structure of a Java Program2.6 JVM2.7 Command Line Arguments2.8 Data Types
2.8.1 Primitives Data types2.8.2 Non-Primitive Data Types
2.9 Variables2.10 Type Casting2.11 Answers to Check Your Progress Questions2.12 Summary2.13 Key Words2.14 Self Assessment Questions and Exercises2.15 Further Readings
2.0 INTRODUCTION
Java is a third generation programming language which implements the conceptsof OOPs. It inherits most of the features of the existing languages C and C++. Inaddition, it also adds new features to make it one of the simple and easy-to-learnobject-oriented languages. One of the most important features of Java is that it isa platform independent language, that is, a program written for one system can beexecuted on any other system. This feature of Java makes it a popular languagefor developing Internet-based applications.
This unit will give you an introduction to Java language. You will also learnabout running Java applications, the structure of a program, command line arguments,data types and variables.
Overview of Java Language
NOTES
Self-InstructionalMaterial 19
2.1 OBJECTIVES
After going through this unit, you will be able to: Describe Java programming language and explain its features Run Java applications Explain the structure of a Java Program Define Command Line arguments Understand data type and variables
2.2 TOKENS
Character Set
A character set can be defined as a set of characters that either individually or incombination, represent the information. Unlike other programming languages likeC and C++, Java uses a standard known as unicode to define characters. Unicodeis a 16-bit character code set, which defines all of the characters available in allhuman languages like English, Hindi, French, German, Chinese, Japanese, etc.This makes Java a worldwide programming language. However, the characters ofmany languages can be represented by using the standard 8-bit character set (ASCIIcharacters), which includes letters, digits and punctuation marks.
Definition: Token
A token is defined as the smallest unit of a program. When a program is compiled,the compiler scans the source code and parses it into tokens to find the syntaxerrors. Java tokens are broadly classified into keywords, identifiers, constants,operators and punctuators.
2.2.1 Keywords
Keywords are the predefined words that have special significance in any language.Every keyword is reserved for a specific purpose and hence cannot be used asuser-defined names (identifiers). There are various keywords in Java, which arelisted in Table 2.1.
Table 2.1 Java Keywords
Keywords abstract const final interface short transientassert continue finally long static try boolean default for native strictfp void break do goto new super volatile byte double if package switch while case else instanceof private synchronizedcatch enum implements protected this char extends import public throw class float int return throws
Notes: The keywords and are reserved words but they are not used.
Overview of Java Language
NOTES
Self-Instructional20 Material
2.2.2 Identifiers
Identifiers are the names given to the uniquely identified various programmingelements like variables, arrays, methods, classes, objects, packages, interfaceand so on. While defining identifiers in Java, programmers must follow the ruleslisted as follows:
An identifier must be unique in a program. Alphabets, digits, underscore and dollar sign characters can be used in an
identifier. An identifier must not start with a digit. An identifier in an upper case is different from that in the lower case. An identifier must not contain other characters such as ‘*’, ‘;’ and white
space characters (tabs, space and newline).Some valid and invalid identifiers in Java are listed as follows:Pol78_ddm //validhh$gl //valid _78hhvt4 //valid902gt1 //invalid as it starts with a digitTyy;ui8 //invalid as it contains the ‘;’ characterfor //invalid as it is a Java keywordFg026 neo //invalid as it contains spaces
2.2.3 Constants
Constants, also known as literals, are the values that a program cannot alter duringits execution. For example, 391, ‘Byron,’ 51.072 and ‘p’ are all constants. Basedon the type of value (data), Java constants are broadly classified into four categories,namely, numeric constants, character constants, string constants and booleanconstants.
Numeric Constants
Numeric constants refer to the numbers consisting of a sequence of digits (with orwithout decimal point) that can be either positive or negative. By default, numericconstants are positive. Numeric constants can be further classified as integerconstants and floating-point constants which are listed in Table 2.2.
Overview of Java Language
NOTES
Self-InstructionalMaterial 21
Table 2.2 Type of Numeric ConstantsType Description Example
Integer constants Integer constants refer to integer-valued numbers. Integer constants can be represented by three different number systems namely, decimal (base 10), octal (base 8) and hexadecimal numbers (base 16). The octal constants are preceded by a 0 (zero) and hexadecimal constants are preceded by a 0x or 0X.
54, -646, 01612, 0x38A
Floating point constants
Floating-point constants refer to the real numbers, that is, the numbers with a decimal point. They are also written in the floating-point notation in which the constant is divided into a mantissa and an exponent.
64.23f, -74.32f, 537E-9f, 15e-3f
Integer constants Integer constants refer to integer-valued numbers. Integerconstants can be represented by three different number systems namely, decimal(base 10), octal (base 8) and hexadecimal numbers (base 16). The octal constantsare preceded by a 0 (zero) and hexadecimal constants are preceded by a 0x or0X.54, -646, 01612, 0x38A
Floating-point constants refer to the real numbers, that is, the numbers witha decimal point. They are also written in the floating-point notation in which theconstant is divided into a mantissa and an exponent. 64.23f, -74.32f, 537E-9f, 15e-3fNote: Use of special characters like comma ‘,’, semicolon ‘;’and question mark ‘?’ are notpermitted in numeric constants.
Character Constants
Character constants refer to a single character enclosed in single quotes (‘’). Theexamples of character constants are ‘f’, ‘M’, ‘8’, ‘&’, etc. All character constantsare internally stored as an integer value.
Character constants can represent either the printable characters or thenon-printable characters. The examples of printable character constants are ‘a’,‘5’, ‘#’, ‘;’, etc. However, there are a few character constants that cannot beincluded in a program directly through a keyboard such as backspace, new lineand so on. These character constants are known as non-printable constants andare included in a program by using the escape sequences. An escape sequencerefers to a character preceded by the backslash character (\). Some of the escapesequences used in Java are listed in Table 2.3.
Overview of Java Language
NOTES
Self-Instructional22 Material
Table 2.3 Escape Sequences
Escape sequences Character constants \b Backspace \f Form feed \n Newline (linefeed) \r Carriage return \t Tab \’ Single quote \” Double quote \\ Backslash
String ConstantsString constants refer to a sequence of any number of characters enclosed in thedouble quotes (“”). The characters can be alphabets, digits, special charactersand blank spaces. The examples of string constants are “hello java”, “2009”,“!...?”, “6+9”, “Y”, etc.Boolean ConstantsBoolean constants can represent only two values, true and false. In Java, there isno numerical representation for these values, that is, true is not equal to 1 and falseis not equal to 0.
2.2.4 Operators
Operators are the symbols that perform operations (such as addition, subtraction,multiplication etc.) on various data items to produce a result. These data items onwhich operators act are known as operands. For example, in a*b, a and b areoperands and * is an operator.
2.2.5 Punctuators
Punctuators, also known as separators, are the symbols that define the structureof a program by dividing and arranging a set of codes. The various punctuatorsdefined are braces ‘{ }’, brackets ‘[ ]’, colon ‘:’, comma ‘,’, period ‘.’, semicolon‘;’ and parentheses ‘( )’. The most commonly used punctuator is semicolon.
2.3 SIMPLE JAVA PROGRAM
Let us start learning Java with a simple Java program that prints a string on thescreen.Example 2.1: A simple Java program
Overview of Java Language
NOTES
Self-InstructionalMaterial 23
Though this program is the simplest one, it includes the basic features thatevery Java program has. Let us now look at the features one by one.
Class Definition
The first statement declares a class where c is akeyword and is the identifier that indicates the name of the class. Theopening and closing curly braces ‘ ’ enclose the definition of a class.
The Main Statement
The statement indicates the method. This method is the point where the execution of Javaprogram begins. Since, it is the startup point of any Java program, it is the mostessential part of any Java program.
This statement has keywords, namely, , and .The descriptions of these keywords are as follows.
: It is an access specifier which specifies that the method isaccessible to all other classes.
: The method is declared which specifies thatthis method belongs to the entire class. The Interpreter uses this methodbefore the creation of objects.
: The keyword specifies that the method does notreturn a value. The pair of parentheses contains the declaration of theparameters of the methods. In the above statement, the [] declares a parameter , that contains an array of objects of the classtype .
The Output Statement
The statements ; and
; are used to display information on the standard output device. is a method of the object, which is the static member of class
. These statements will display the following strings on the monitor.
The statements will be printed in separate lines as the method appends a newline character at the end of the string. However, if we use method instead of newline character is not appended at the end ofthe string. Note that like C++, every statement in Java must end with a semicolon.
Overview of Java Language
NOTES
Self-Instructional24 Material
2.4 RUNNING JAVA APPLICATIONS
A program can be created using any text editor. Nowadays, there are several texteditors available for writing programs like Notepad, Jcreator, etc. After creatingthe file, save the file with the name < > . The name of the filemust be same as that of the class name containing the method.
Once the file is created, it can be compiled to generate the bytecode usingJava compiler as given here.
If the source code is error free then the compiler creates a file containing thebytecode and the file will be named as < . In our example,the name of file will be .
Even though after compilation, the source code is converted into its equivalentbytecode, it cannot be executed. To execute this bytecode, it needs to be convertedto machine code using the interpreter. The command for converting bytecode tomachine code and run it is as follows:
After giving this command, the interpreter searches for the methodin the source code and starts executing the instructions written in this method anddisplays the corresponding output.
2.5 STRUCTURE OF A JAVA PROGRAM
The Java program structure is divided into various sections, namely documentationsection, package statement, import statements, interface statements, class definitionsand main method class (see Figure 2.1).
Documentation section
Package statement
Import statements
Interface statements
Class definitions
Main method class
Fig. 2.1 Java Program Structure
Documentation section: Comments are vital elements of a program thatare used to increase its readability and describe its functionality. They may
Overview of Java Language
NOTES
Self-InstructionalMaterial 25
also include information like program name and the author of the program,etc.
Package statement: It is the first statement in Java program that tells thecompiler that all the classes defined in the file belong to this package. Forexample, consider this statement. package employee;Here, employee is the name of the package. It is not necessary that ourclasses are part of package, so this statement is optional.
Import statements: It allows us to access a class which belongs tosome other package. For example, consider this statement. importemployee.EName;Here, employee is the name of the package and EName is the class whichyou want to access. There can be a number of import statements in aprogram.
Interface statements: An interface is the way for implementing multipleinheritance in Java. It is just like a class but it contains only methoddeclarations.
Class definitions: Class is the most important element of a program. Aprogram may consist of any number of class definitions.
Main method class: It is an essential part of a Java program as it containsthe main method which is the starting point of a program. Inside the mainmethod class, the objects of several classes can be created, accessed andmanipulated. Once all the instructions in the main method are executed, thecontrol is transferred out of the class thus terminating the entire program.
Check Your Progress
1. What is the smallest unit of a program?2. What does a numeric constant refer to?3. What sections is a Java Program divided into?
2.6 JVM
As discussed earlier, Java uses both compiler and interpreter. Source code writtenin Java is compiled to generate bytecode and then this bytecode is interpreted tomachine instructions for specific machine. The bytecode generated by the compileris not machine specific. It is generated for the virtual machine that exists only insidethe computer memory known as Java Virtual Machine (JVM). This virtualmachine is designed in such a way that it can be implemented on the top of anyexisting processor and itself acts as virtual processor chip. It hides the underlyingoperating system details from Java applications. The process of converting sourcecode to machine code is shown in Figure 2.2.
Overview of Java Language
NOTES
Self-Instructional26 Material
Source Bytecode Compile
rInterpreter
Machine Code
JVM
Fig. 2.2 Conversion of Source Code to Machine Code
JVM obtains the bytecode stream from the .class file in the form of series ofinstruction. Each instruction consists of a one-byte opcode (a valid andunderstandable command which tells the JVM what to do) and zero or moreoperands, which are required to complete the opcode.
Some of the main components of JVM are stack, registers, garbage-collection heap and method area.
Stack: JVM stacks are similar to the stacks used in C or otherconventional languages. It consists of frames, which holds the state ofJava method invocation. It holds the local variables, parameters, its returnvalue and the intermediate results. JVM stack cannot be manipulateddirectly and only pushing and popping of frames can take place. Whena method is invoked, the JVM pushes a new frame into the stack andafter the completion of execution of the method the frame is poppedand discarded by the virtual machine. The size of the JVM stack can befixed or may dynamically increase and decrease according to therequirement.
Registers: JVM uses different types of registers to control the stacks.Some of the important JVM registers are:
Optop: It points to the top of operand stack. Frame: It points to the current execution environment. Vars: It points to the local variables. Program counter: It keeps record of the next instruction in a
program to be executed. Garbage-collection heap: Heap is a free memory space used for
allocations to the variables like arrays, class instances, etc., at runtime.Whenever memory is allocated with the help of new operator, thatmemory space is allocated from the heap. Heap provides an automaticstorage management system known as garbage-collection heap.Whenever there are objects which are no longer referenced, then theruntime environment automatically reclaims the memory occupied bythe objects. Size of the heap may be fixed or may increase or decreaseaccording to the requirement.
Method area: Method area is a storage area for the compiled code.Although the method area is a part of heap, there is no specific areawhere it exists. This feature makes JVM more portable and secure.
Overview of Java Language
NOTES
Self-InstructionalMaterial 27
Size of the method area may be fixed or may increase or decreaseaccording to the requirement. Method area is used to store:
Runtime constant pool Field information Method information Code for methods and constructors Special methods that are used in class and instance initialization. Interface type initialization
The primitive data types that can be handled by the JVM are byte(8 bits),char(16 bits), short(16 bits), int(32 bits), float(32 bits), long(64 bits), double(64bits).
2.7 COMMAND LINE ARGUMENTS
Like C++, Java enables the system to pass arguments to the main() method.These arguments are passed by typing them after the program name on thecommand line. Hence, these arguments are known as command line arguments.They help in providing data to the program.
As stated earlier, the argument named as args of String type is passedto the main method. It is this argument which will receive any data passed to theprogram through command line.
Example 2.2: A program to demonstrate the use of command line arguments.
Overview of Java Language
NOTES
Self-Instructional28 Material
The command entered on the command prompt is
The output of the program isThe arguments entered are:
The number of arguments is: 4
2.8 DATA TYPES
A data type determines the type and the operations that can be performed on thedata. Java provides various data types and each data type is represented differentlywithin the computer’s memory. The type of data selected by a programmer dependson the particular application. The various data types provided by Java arecategorized into primitive data types and non-primitive data types (see Figure2.3).
Data types
Primitive data types
Non-primitive data types
Classes Arrays Interface Integer Floating-point Character Boolean
Fig. 2.3 Data Types
2.8.1 Primitives Data types
Primitive data types also known as built-in data types are the fundamental datatypes provided by a programming language. In Java, primitive data types includeinteger, floating point, character and boolean.
Integer Type
The integer data type is used to store integers like 4, 42, 5233, -32, -745. Javasupports four types of integers namely, byte, short, int and long. The default valueof these integer types is 0. There is no concept of unsigned integer in Java. Thevarious integer data types with their size and range are listed in Table 2.4.
Overview of Java Language
NOTES
Self-InstructionalMaterial 29
Table 2.4 Size and Range of Integer Data Types
Type Size(bytes) Range byte One -128 to 127 short Two -32,768 to 32,767 int Four -2,147,483,648 to 2,147,483,647
long Eight -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Note: It is recommended to use smaller data types whenever possible. This is because largerthe data type you choose, more time the program will take for the execution.
Floating Point Type
A floating point data type is used to store real numbers such as 3.28, 64.755765,-8.01, -24.53. Java supports two floating point data types, namely, float anddouble.
Float: The float type represents a single-precisionnumber. Single precisionoccupies lesser space than double precision but becomes inaccurate whenthe values are large. For example, it can be used to represent value ofmarks of the students. The default value of float data type is 0.0f.
Double: The double type specifies a double-precision number. It is thebest choice when you need to store large-valued numbers. For example, itcan be used when you want to use mathematical functions like sin(), cos(),sqrt(). The default value of double data type is 0.0d.The various floating point data types with their size and range are listed in
Table 2.5.
Table 2.5 Size and Range of Floating Point Data Types
Type Size(bytes) Range float Four 3.4e-038 to 3.4e+038 double Eight 1.7e-308 to 1.7e+308
The character data type is used to store single character enclosed in singlequotes. It is represented by using char keyword. It occupies 16-bit memory. Therange of the character data type is 0 to 65,536. The default value of char data typeis null character.Boolean TypeThe boolean data type can hold only boolean values, that is, either true or false.The keyword boolean is used to denote the boolean data type. The default valueof boolean data type is false.
2.8.2 Non-Primitive Data Types
Non-primitive data types (user-defined data types) also known as reference typesare derived from the primitive data types. In Java, these include classes, interfacesand arrays.
Overview of Java Language
NOTES
Self-Instructional30 Material
Classes
A class is defined as a user-defined data type which contains the entire set ofsimilar data and the functions that the objects possess. In other words, a class inOOP represents a group of similar objects. As stated earlier, in the real worldmillions of objects exist and each of them has its own identity. However, each ofthem can be categorized under different groups depending on the commonproperties they possess and the functions they perform. For example, cars, scooters,motorbikes, buses, etc., all can be grouped under the category vehicles. Similarly,dogs, cats, horses, etc., can be grouped under the category animals. Thus, vehiclesand animals can be considered as the classes.
A class serves as a blueprint or template for its objects. That is, once a classhas been defined, any number of objects belonging to that class can be created.The objects of a class are also known as the instances or the variables of thatclass and the process of creating objects from a class is known as instantiation.Note that a class does not represent an object, rather it represents the data andfunctions that an object will have.
For example, a class Product consists of data, such as p_code, p_name,p_price and qty_in_hand which specify the attributes or features of the objectsof the Product class. In addition, it consists of functions, such as display_product()and check_qty() that specify the actions that can be performed on data (seeFigure 2.4).
Fig. 2.4 Class and Its Objects
Note that the data belonging to a particular class is known as its datamembers and the functions of the class are known as the member functions andboth collectively are known as the members of the class.Note: In Java, the data members are referred as instance variables and member functions arereferred as methods.
Overview of Java Language
NOTES
Self-InstructionalMaterial 31
Arrays
Java uses variables of different primitive data types to store data. However, thesevariables are incapable of holding more than one value at a time. For example, asingle variable cannot be used for storing the marks of all the students in a class.For such purposes, Java provides a different kind of data type known as arrays.
Arrays are defined as a fixed size sequence of same type of data elements.These data elements can be of any primitive or non-primitive data type. The elementsof an array are stored in contiguous memory locations and each individual elementcan be accessed using one or more indices or subscripts. A subscript or an indexis a positive integer value, which indicates the position of an element in an array.Arrays are used when a programmer wants to store multiple data items of sametype into a single list and also wants to access and manipulate individual elementsof the list. Arrays can be either single-dimensional or multi-dimensional dependingupon the number of subscripts used.
Interface
An interface is just like a class. The only difference is that it contains only finalvariables and the method declarations. Hence, we can think of an interface as a‘fully abstract class’. There is no limitation to the number of interfaces that a classcan implement. An interface is defined just like a class but rather than using thekeyword class, the keyword interface is used.
2.9 VARIABLES
A variable is an identifier that represents a memory location that is used to storedata value. Data stored at a particular location can be accessed by using thevariable name. The value of a variable can be changed anytime during the programexecution. The variable name that you choose must be meaningful so as tounderstand what it represents in the program.
Declaring Variables
Variables must be declared in a program before they are used. The declaration ofa variable informs the compiler, the specific data type to which a variable isassociated and allocates sufficient memory for it.
The syntax for declaring a variable is as follows:
For example, a variable of a type int can be declared by using this statement.
Overview of Java Language
NOTES
Self-Instructional32 Material
At the time of the variable declaration, more than one variable of the samedata type can be declared in a single statement. For example, consider the followingstatement:
Initializing VariablesDeclaration of variables allocates memory for variables but it does not store anydata at the time of declaration. To store data in the variables, they need to beinitialized. For example, consider the following statements:
Here, a variable of the integer type is declared and the value 10 is assignedto it. You can combine both the statements into a single statement as follows:
Besides initializing the variable with the constant values, variables can alsobe initialized at run-time using expressions. Initialization of variables at run-time isknown as dynamic initialization.
Example 2.3: A program to demonstrate initialization of variable
The output of the program is:The value of is:1610
Receiving input through keyboardVariables can also be given values interactively through the keyboard by ng thereadLine() method.
Example 2.4: A program to demonstrate reading data from the keyboard
Overview of Java Language
NOTES
Self-InstructionalMaterial 33
The output of the program is:
Enter integer value4Enter float value6.7The integer value is 4The float value is 6.7The method readLine() of class DataInputStream is used to read string
from the keyboard which is then converted to the corresponding data type, and . To handle the error which may occur while reading data from thekeyboard, you have been provided with try and catch statements.
2.10 TYPE CASTING
While programming you might come across some situations where a value of onedata type needs to be stored into a variable of another data type. If both the datatypes are compatible and the data type of the target variable is large enough tostore the value of the source variable, Java automatically converts the source typeinto target type. This is known as automatic type conversion. For example, thevalue of data type can be assigned to a variable of long data type since longis larger than . This type of conversion in which data of smaller type is assignedto a larger type is called widening conversion.
Overview of Java Language
NOTES
Self-Instructional34 Material
However, if the target type is smaller than the source type, conversion cannotbe performed automatically. For example, the value of data type cannot beassigned to a variable of byte type. For such conversion, Java provides a mechanismknown as type casting. Type casting refers to the type conversion that is performedexplicitly.
The syntax for type casting is as follows:data_type variable1 = (data_type) variable2; where, data_type is the data type variable1 is the target variable variable2 is the source variableFor example, consider these statements:
In these statements, type casting is performed to convert data type todata type.
Following points should be kept in mind while type casting: All the integer data types can be cast to any other data type except boolean. Casting into smaller data type may lead to loss of data. Casting a floating point value to an integer type may result in truncation of
the fractional part.Example 2.5: A program to demonstrate type casting
Overview of Java Language
NOTES
Self-InstructionalMaterial 35
The output of the program is as follows:The existing variables and their values are:
Check Your Progress
4. In what form does JVM obtain the bytecode stream from the .class file?5. What does a data type determine?6. How can data stored at a particular location be accessed?7. What is called a widening conversion?
Overview of Java Language
NOTES
Self-Instructional36 Material
2.11 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. The smallest unit of a program is a token.2. Numeric constants refer to the numbers consisting of a sequence of digits
(with or without decimal point) that can be either positive or negative.3. The Java program structure is divided into various sections, namely
documentation section, package statement, import statements, interfacestatements, class definitions and main method class.
4. JVM obtains the bytecode stream from the .class file in the form of series ofinstruction.
5. A data type determines the type and the operations that can be performedon the data.
6. Data stored at a particular location can be accessed by using the variablename.
7. A conversion in which data of smaller type is assigned to a larger type iscalled widening conversion.
2.12 SUMMARY
A character set can be defined as a set of characters that either individuallyor in combination, represent the information.
When a program is compiled, the compiler scans the source code and parsesit into tokens to find the syntax errors.
Java tokens are broadly classified into keywords, identifiers, constants,operators and punctuators.
Keywords are the predefined words that have special significance in anylanguage.
Identifiers are the names given to the uniquely identified various programmingelements like variables, arrays, methods, classes, objects, packages, interfaceand so on.
Numeric constants refer to the numbers consisting of a sequence of digits(with or without decimal point) that can be either positive or negative.
Character constants refer to a single character enclosed in single quotes(‘’).
String constants refer to a sequence of any number of characters enclosedin the double quotes (“”).
Overview of Java Language
NOTES
Self-InstructionalMaterial 37
Punctuators, also known as separators, are the symbols that define thestructure of a program by dividing and arranging a set of codes.
The statement public static void main (String args[]) indicates the mainmethod. This method is the point where the execution of Java programbegins.
The Java program structure is divided into various sections, namelydocumentation section, package statement, import statements, interfacestatements, class definitions and main method class.
Source code written in Java is compiled to generate bytecode and then thisbytecode is interpreted to machine instructions for specific machine.
A data type determines the type and the operations that can be performedon the data.
Package statement: It is the first statement in Java program that tells thecompiler that all the classes defined in the file belong to this package.
JVM stacks are similar to the stacks used in C or other conventionallanguages.
2.13 KEY WORDS
Public: It is an access specifier which specifies that the main method isaccessible to all other classes.
Static: The main method is declared static which specifies that this methodbelongs to the entire class. The Interpreter uses this method before thecreation of objects.
Void: The void keyword specifies that the main method does not return avalue.
Package statement: It is the first statement in Java program that tells thecompiler that all the classes defined in the file belong to this package.
Import statements: It allows us to access a class which belongs to someother package.
Interface statements: An interface is the way for implementing multipleinheritances in Java. It is just like a class but it contains only methoddeclarations.
Class definitions: Class is the most important element of a program. Aprogram may consist of any number of class definitions.
Overview of Java Language
NOTES
Self-Instructional38 Material
2.14 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. Write a short note on tokens.2. How are numeric constants different from character constants?3. Define operators.4. Write a brief note on the structure of Java program.
Long Answer Questions
1. Write in detail about command line arguments.2. What are data types and what do they determine?3. What are variables? Write notes on declaring variables and initializing
variables.4. What do you mean by type casting? List a few things that should be kept in
mind while type casting.5. Write a program to define and demonstrate type casting.
2.15 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Operators and Expressions
NOTES
Self-InstructionalMaterial 39
UNIT 3 OPERATORS ANDEXPRESSIONS
Structure3.0 Introduction3.1 Objectives3.2 Operators and Operations
3.2.1 Arithmetic Operators3.2.2 Increment and Decrement Operators3.2.3 Relational Operators3.2.4 Logical Operators3.2.5 Conditional Operator3.2.6 Assignment Operators3.2.7 Other Operators3.2.8 Operators: Precedence and Associativity
3.3 Conditional Statements3.4 Iteration Statements or Loops
3.4.1 The for Loop3.4.2 The while Loop3.4.3 The do-while Loop3.4.4 Nested Loops
3.5 Jump Statements3.6 Answers to Check Your Progress Questions3.7 Summary3.8 Key Words3.9 Self Assessment Questions and Exercises
3.10 Further Readings
3.0 INTRODUCTION
In any programming language, writing even an elementary program requires theknowledge and clear understanding of various data types, variables, constantsand operators provided by that language. All these constitute the most basic elementsof a language, which are combined to form an instruction and a set of theseinstructions constitutes a program. In this unit, you will study about operators andoperations in Java, conditional statements, iteration statements or loops, and jumpstatements.
3.1 OBJECTIVES
After going through this unit, you will be able to: Describe operators and operations Explain conditional statements and their use
Operators and Expressions
NOTES
Self-Instructional40 Material
Discuss the functionality of jump statements Understand iteration statements and the use of loops
3.2 OPERATORS AND OPERATIONS
As stated earlier, operators are the symbols, which perform operations on variousdata items known as operands. For example, in a + b, a and b are operands and+ is an operator. Note that to perform an operation, operators and operands arecombined together forming an expression. For example, to perform an additionoperation on operands a and b, the addition (+) operator is combined with theoperands a and b forming an expression.
Depending on the function performed, the Java operators can be classifiedinto various categories. These include arithmetic operators, increment anddecrement operators, relational operators, logical operators, conditional operator,assignment operators, bitwise operators and special operators.
3.2.1 Arithmetic Operators
Arithmetic operators perform the basic arithmetic operations on operands. Theycan work on any built-in data type of Java except on boolean type.
Java provides various arithmetic operators that are, +(addition or unaryplus), -(subtraction or unary minus), *(multiplication), /(division) and %(modulus).For example, some of the expressions which involve arithmetic operators are x +y, x – y, x * y, x / y and x % y. When the unary minus operator is used with a singleoperand, the operand is multiplied by -1.Expressions formed by using arithmetic operators can be of following types:
Integer expression: The arithmetic expression where both the operandsare integers is called an integer expression. The result of the integer arithmeticis always an integer.
Real expression: The arithmetic expression where both the operands arereal is called real expression.
Mixed mode expression: The expression is mixed mode if one operandis real and the other is integer. In this case, the integer operand is convertedto real and the result is also of type real.
Note: Unlike C and C++, the modulus operator can be applied to the floating point data typealso in Java.
Example 3.1: A program to demonstrate arithmetic operators
Operators and Expressions
NOTES
Self-InstructionalMaterial 41
The output of the program is
Operators and Expressions
NOTES
Self-Instructional42 Material
3.2.2 Increment and Decrement Operators
Java provides two special unary arithmetic operators, namely the increment operator(represented by ++) and the decrement operator (represented by —). Theoperator ++ increases the value of operand by 1 and the operator — decreasesthe value of operand by 1.The increment and decrement operators can be used in two forms.
Prefix form: In this form, the increment or the decrement operator precedesits operand. The prefix increment operator is represented as ++operandand the prefix decrement operator is represented as —operand. The prefixincrement or the prefix decrement operator increments or decrements thevalue of an operand respectively before its value is used in an expression.Example 3.2: Evaluate these statements
In this example, the statement first increments the value of by 1and then assigns the incremented value to . Similarly, the decrement operatoris used to decrement the value of by 1 and then assigns the decrementedvalue to . Thus, the value of and are 11 and 10, respectively.
Postfix form: In this form, the increment or the decrement operatorsucceeds its operand. The postfix increment operator is represented asoperand++, and the postfix decrement operator is represented as operand.—The postfix increment or the decrement operator increments or decrementsthe value of an operand respectively after using it in the expression.Example 3.3: Evaluate these statements
In this example, the statement first assigns the value of to andthen increments the value of by 1. Similarly, the statement assigns thevalue of to and then decrements the value of by 1. Thus, the value of and
are 10 and 11, respectively.
3.2.3 Relational Operators
Relational operators are used for comparing two values or expressions. The variousrelational operators provided by Java are less than ‘<’, less than or equal to ‘<=’,
Operators and Expressions
NOTES
Self-InstructionalMaterial 43
greater than ‘>’, greater than or equal to ‘>=’, equal to ‘==’ and not equal to ‘!=’operator. They return values of boolean type, that is, either true or false. Forexample, consider two variables and having values 20 and 30, respectively.In this case, the expression returns true whereas the expression returnsfalse.
The operators == and != are also known as equality operators as they areused for checking the equality of operands.Note: All relational operators can work on integer, floating-point and character data types.
Example 3.4: A program to demonstrate relational operators
The output of the program is
Operators and Expressions
NOTES
Self-Instructional44 Material
3.2.4 Logical Operators
Logical operators combine expressions and then return true or false. The variouslogical operators provided by Java are listed as follows:
AND (&&) operator: It returns true only if all the expressions evaluate totrue, otherwise it returns false.
OR (||) operator: It returns true if any one or all the expressions evaluate totrue and returns false only if all the expressions evaluate to false.
Negation (!) operator: It returns true if the expression on which it isoperating is false and vice versa.For example, consider two expressions Exp1 and Exp2. Table 3.1 shows
the result after the logical operators are applied on these expressions.
Table 3.1 Truth Table
Exp1 Exp2 Exp1 && Exp2
Exp1 OR Exp2 !Exp1
true true true true false true false false true false false true false true true false false false false true
Example 3.5: A program to demonstrate logical operators
The output of the program is
Operators and Expressions
NOTES
Self-InstructionalMaterial 45
3.2.5 Conditional Operator
The conditional operator selects a value based on specified condition. Note thatthe conditional operator is a ternary operator, that is, this operator involves threeoperands.
The syntax of the conditional operator isexpression1 ? expression2: expression3If expression1 is true, then expression2 is evaluated, otherwise expression3
is evaluated.Example 3.6: Evaluate this statement
In this example, if the value of is equal to 5, then the expression returns 8,otherwise the expression returns 9.
3.2.6 Assignment Operators
Assignment operator assigns the value of an expression to a variable. Assignmentoperators are of two types, namely, the simple assignment operator and compoundassignment operators.Simple Assignment OperatorThe simple assignment operator assigns the value on its right hand side to thevariable on its left hand side. Note that the left hand side of an assignment expressionshould be a variable. It cannot be a constant or an expression. However, the righthand side of an assignment expression can be a variable, constant or an expression.
Example 3.7: Evaluate this statement
In this example, the value 8 is assigned to the variable .With the help of the assignment operator, several variables can be assigned
a common value. This is accomplished by using multiple assignments in a singlestatement. For example, in the statement =5, the value 5 is assigned to thethree variable , and .Compound Assignment OperatorsJava provides compound assignment operators (also known as Java shorthands),which is in the following form.
Operators and Expressions
NOTES
Self-Instructional46 Material
Here, is a variable, is the binary operator and is an expression.This form is equivalent to the statement ;
where you need to access only once.For example, the expression = +6 can be written as +=6. In this
expression, is incremented by 6 and then the result is assigned to . The variouscompound assignment operators used in Java are ‘+=’, ‘-=’, ‘*=’, ‘/=’ and ‘%=’.
3.2.7 Other Operators
In addition to the operators discussed, Java supports some other operators whichinclude bitwise operators and special operators.Bitwise OperatorsThe bitwise operators are used to manipulate the data values at bit level. Thisoperator can be applied to all the primitive data types such as long, int, short, charand byte. Various bitwise operators are bitwise AND (&), bitwise OR (!), bitwiseexclusive OR (^), one’s complement (~), shift left (<<), shift right (>>), shift rightwith zero fill (>>>).Special OperatorsJava provides two special operators namely, instanceof and dot operator (.).instanceof OperatorThe instanceof operator is an operator which is used to check whether the objectbelongs to a particular class or not. For example, consider this statement:novel instanceof bookThis statement returns true if the object novel belongs to the class book, otherwise,false.Dot OperatorThe instance variables and the methods of a class are accessed through objectswith the help of a dot operator. Dot operator links the name of the object with thename of the variable or method which needs to be accessed. For example, considerthe following statements:
obj.name; // accessing instance variable of the classobj.marks(); // accessing method of the class
3.2.8 Operators: Precedence and Associativity
An expression consisting of more than one operator leads to a confusion as towhich operator is to be evaluated first. For example, consider the followingexpression:
In this expression, the compiler needs to know which operator is evaluatedfirst. For this, it is important to determine the precedence and associativity ofoperators.
Operators and Expressions
NOTES
Self-InstructionalMaterial 47
Precedence: The order or priority in which various operators in anexpression are evaluated is known as precedence. Every operator in Javahas a precedence associated with it. The operators with a higher precedenceare evaluated before the operators with a lower precedence. For example,multiplication is performed before addition as the multiplication operatorhas higher precedence than the addition operator.
Associativity: The order or priority in which operators of the sameprecedence are evaluated is known as associativity. For example, the additionand subtraction operators have the same precedence. However, additionor subtraction may be performed on the expression depending upon theorder of their occurrence.The associativity of an operator can be either from left to right or from right
to left. The operators with left to right associativity are evaluated from the left handside while the operators with right to left associativity are evaluated from the righthand side.
The precedence and the associativity of Java operators are listed in Table3.2. Note that the precedence of operators decreases from top to bottom, that is,the priority is highest at the top.
Table 3.2 Precedence and Associativity of Java Operators
Operators Description Associativity .() []
Direct member selector Function call Array subscript
Left to rightLeft to right Left to right
- ++ -- ! ~
(type)
Unary minus Increment Decrement Logical negation Ones complement Casting
Right to left Right to left Right to left Right to left Right to left Right to left
* /
%
Multiplication Division Modulus
Left to right Left to right Left to right
+ -
Addition Subtraction
Left to right Left to right
<< >>
>>>
Left shift Right shift Right shift with zero fill
Left to right Left to right Left to right
<<= >
>= Instance of
Less than Less than or equal to Greater than Greater than or equal to Type comparison
Left to rightLeft to right Left to right Left to right Left to right
= = =!
Equal to Not equal to
Left to right Left to right
& Bitwise AND Left to right ^ Bitwise XOR Left to right| Bitwise OR Left to right
&& Logical AND Left to right || Logical OR Left to right ?: Conditional operator Right to left =
Op= Assignment Operator
Shorthand assignment Right to left
Operators Description Associativity
Note: The operators in the same row have same precedence.
Operators and Expressions
NOTES
Self-Instructional48 Material
3.3 CONDITIONAL STATEMENTS
Conditional statements, also known as selection statements, are used to makedecisions based on a given condition. If the condition evaluates to true, a set ofstatements is executed, otherwise another set of statements is executed.
The if StatementThe if statement selects and executes the statement(s) based on a given condition.The syntax of the if statement is as follows:
For single statement
For a set of statements
Here, if the condition evaluates to true, then a given set of statement(s) isexecuted. However, if the condition evaluates to false, then the given set ofstatements is skipped and the program control passes to the statement followingthe if statement.
The if-else Statement
The if-else statement causes one of the two possible statement(s) to executedepending upon the result of condition. The syntax of the if-else statementsis as follows:
Here, the if-else statement comprises two parts, namely, if and else.If the condition is true, the statements within if part are executed. However, ifthe condition is false, the statements within else part are executed.
Operators and Expressions
NOTES
Self-InstructionalMaterial 49
A program to demonstrate the use of if-else statement is as follows:
The output of the program is as follows:
Nested if-else Statement
A nested if-else statement contains one or more if-else statements. Inother words, if-else statement within another if-else statement is callednested if-else statement. The if-else statement can be nested in threedifferent ways, which are discussed as follows:
The if-else statement is nested within the if part.The syntax is as follows:
The if-else statement is nested within the else part.The syntax is as follows:
Operators and Expressions
NOTES
Self-Instructional50 Material
The if-else statement is nested within both the if and the elseparts.
The syntax is as follows:
nextstatement;
The if-else-if Ladder
The if-else-if ladder, also known as the if-else-if staircase, hasan if-else statement within the outermost else statement. The inner elsestatement can further have other if-else statements.
The syntax of the if-else-if ladders is as follows:
Operators and Expressions
NOTES
Self-InstructionalMaterial 51
A program to demonstrate if-else-if statement is as follows:
The output of the program is as follows:
The switch Statement
The switch statement selects a set of statements from the available sets ofstatements. The switch statement evaluates the value of an expression andcompares it with the list of integer, character, short or byte constants. It should benoted that the case constants must be compatible with the expression type. Whena match is found, all the statements associated with that constant are executed.
Operators and Expressions
NOTES
Self-Instructional52 Material
The syntax of the switch statement is as follows:
The Java keywords case and default provide the list of alternatives.Note that it is not necessary for every case label to specify a unique set ofstatements. The same set of statements can be shared by multiple case labels.
The keyword default specifies the set of statements to be executed incase no match is found. Note that there can be multiple case labels but there canbe only one default label. However, default is an optional statement.
The break statements in the switch block are optional. However, it isused in the switch block to prevent a fall through, which refers to the situationthat causes the execution of the remaining cases even after a match has beenfound. In order to prevent this, break statements are used at the end of statementsspecified by each case and default. This causes the control to immediatelybreak out of the switch block and execute the next statement.
Similar to if and if-else statements, switch statements can alsobe nested within one another. A nested switch statement contains one or moreswitch statements within its case label or default label (if any).Note: Switch statement cannot be used for testing floating-point values or string values.
A program to demonstrate the use of switch statement is as follows:
Operators and Expressions
NOTES
Self-InstructionalMaterial 53
The output of the program is as follows:
In the preceding program, since the value of x is 2 therefore the messageDay is Tuesday is displayed. In case the value of x is 8, the output Invalidoption! is displayed.
Check Your Progress
1. What types of operators does Java provides?2. What does the switch statement evaluate?3. What are conditional statements also known as?
3.4 ITERATION STATEMENTS OR LOOPS
The statements that cause a set of statements to be executed repeatedly either fora specific number of times or until some condition is satisfied are known as iterationstatements, that is, as long as the condition evaluates to true, the set of statement(s)is executed. The various iteration statements used in Java are for loop, whileloop and do-while loop.
3.4.1 The for Loop
The for loop is one of the most widely used loops in Java. The for loop is adeterministic loop, that is, the number of times the body of the loop is executed isknown in advance.The syntax of the for loop is as follows:
Operators and Expressions
NOTES
Self-Instructional54 Material
The initialize expression in for loop can initialize one or more controlvariables. A for loop can also update more than one variable in its updateexpression. Note that initialize, condition and update are optionalexpressions and are always specified in parentheses. All the three expressions areseparated by semicolons. You can also create an infinite loop by excluding all thethree expressions as follows:
A program to display a count down using for loop is as follows:
The output of the program is as follows:
for loop using comma operator
for loop allows multiple variables to control the loop using comma operator.That is, two or more variables can be used in the initialize and the updatepart of the loop. For example, consider this statement.
This statement initializes two variables, namely i and j and updates them.Note that for loop cannot have more than one condition separated by comma.
3.4.2 The while Loop
The while loop is used to perform looping operations when the number ofiterations is not known in advance, that is, unlike for loop, the while loop isnon-deterministic in nature.
Operators and Expressions
NOTES
Self-InstructionalMaterial 55
The syntax of the while loop is as follows:
The following points should be noted about the while loop: Unlike for loops where explicit initialize and update
expressions are specified, while loops do not specify any explicitinitialize and update expressions. This implies that the controlvariable must be declared and initialized before the while loop andneeds to be updated within the body of the while loop.
The while loop executes as long as condition evaluates to true.If condition evaluates to false, then the body of while loopdoes not execute.
A program to determine the sum of first n consecutive positive integers is asfollows:
Operators and Expressions
NOTES
Self-Instructional56 Material
The output of the program is as follows:
3.4.3 The Loop
As discussed earlier, in a while loop, the condition is evaluated at the beginningof the loop and if the condition evaluates to false, the body of the loop is notexecuted even once. However, if the body of the loop is to be executed at leastonce, no matter whether the initial state of the condition is true or false, thedo-while loop is used. This loop places the condition to be evaluated at theend of the loop.
The syntax of the do-while loop is as follows:
A program to calculate the sum of an arithmetic progression (AP) is asfollows:
Operators and Expressions
NOTES
Self-InstructionalMaterial 57
The output of the program is as follows:
3.4.4 Nested Loops
Nested loops are the loops present within the body of another loop. All the threeloops (for, while and do-while) can be nested.
A program to demonstrate the nested for loop is as follows:
The output of the program is as follows:
3.5 JUMP STATEMENTS
Jump statements are used to alter the flow of control unconditionally. That is, jumpstatements transfer the program control unconditionally. The jump statementsdefined in Java are break, continue and return.
The break Statement
The break statement is extensively used in loops and switch statements. Itimmediately terminates the loop or the switch statement, bypassing the remainingstatements. The control then passes to the statement that immediately follows the
Operators and Expressions
NOTES
Self-Instructional58 Material
loop or the switch statement. A break statement can be used in any of thethree Java loops. In case of nested loops, the break will exit only the singleloop, that is, the loop in which it is placed.
The continue Statement
The continue statement is used to ‘continue’ the loop with its next iteration.In other words, it skips any remaining statements in the current iteration andimmediately passes the control to the next iteration. It does not terminate the loop(as in the case of break statements) rather it only terminates the current iterationof the loop. Like a break statement, a continue statement can be used inany of the three loops.
The Statement
The return statement is used to transfer the control out of the method explicitly.It transfers the control back to the caller and terminates the method in which it ispresent. When the return statement is encountered in the main() method, ittransfers the control back to the Java run-time system and terminates the programexecution.
A program to add the factors of a number using break and continuestatements is as follows:
Operators and Expressions
NOTES
Self-InstructionalMaterial 59
The output of the program is as follows:
Check Your Progress
4. Where is the break statement used?5. State a use case of return statement.6. What is used to ‘continue’ the loop with its next iteration?
3.6 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. Java provides two special operators namely, instanceof operator and dotoperator.
2. The switch statement evaluates the value of an expression and compares itwith the list of integer, character, short or byte constants.
3. Conditional statements are also known as selection statements4. The break statement is extensively used in loops and switch statements.5. The return statement is used to transfer the control out of the method explicitly.6. The continue statement is used to ‘continue’ the loop with its next iteration.
3.7 SUMMARY
Operators are the symbols, which perform operations on various data itemsknown as operands.
Depending on the function performed, the Java operators can be classifiedinto various categories. These include arithmetic operators, increment anddecrement operators, relational operators, logical operators, conditionaloperator, assignment operators, bitwise operators and special operators.
Arithmetic operators perform the basic arithmetic operations on operands.They can work on any built-in data type of Java except on boolean type.
Assignment operators are of two types, namely, the simple assignmentoperator and compound assignment operators.
Java provides two special operators namely, instanceof operator and dotoperator.
Conditional statements, also known as selection statements, are used tomake decisions based on a given condition.
Operators and Expressions
NOTES
Self-Instructional60 Material
The switchstatement selects a set of statements from the available sets ofstatements.
The switch statement evaluates the value of an expression and compares itwith the list of integer, character, short or byte constants.
The Java keywords case and default provide the list of alternatives. Notethat it is not necessary for every case label to specify a unique set ofstatements.
Nested loops are the loops present within the body of another loop. Jump statements are used to alter the flow of control unconditionally. The break statement is extensively used in loops and switch statements. The return statement is used to transfer the control out of the method explicitly. The continue statement is used to ‘continue’ the loop with its next iteration.
3.8 KEY WORDS
Integer expression: The arithmetic expression where both the operandsare integers is called an integer expression. The result of the integer arithmeticis always an integer.
Real expression: The arithmetic expression where both the operands arereal is called real expression.
Mixed mode expression: The expression is mixed mode if one operandis real and the other is integer. In this case, the integer operand is convertedto real and the result is also of type real.
AND (&&) operator: It returns true only if all the expressions evaluate totrue, otherwise it returns false.
OR (||) operator: It returns true if any one or all the expressions evaluate totrue and returns false only if all the expressions evaluate to false.
Negation (!) operator: It returns true if the expression on which it isoperating is false and vice versa.
3.9 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. What is known as precedence?2. List a few expressions formed by using arithmetic operators.3. Which operators are used for comparing two values or expressions?
Operators and Expressions
NOTES
Self-InstructionalMaterial 61
4. Write a note on Jump statements.5. What values do assignment operators assign?
Long Answer Questions
1. Write a note on conditional statements.2. Discuss iteration statements in detail. Also write about the use and
functionality of loops.3. What do you understand by precedence and associativity of Java operators?4. Differentiate between bitwise operators and special operators.5. Define while loop. Also list a few properties of while loop.6. Write a program to determine the sum of first n consecutive positive integers.
3.10 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Classes
NOTES
Self-Instructional62 Material
BLOCK - IICLASS, OBJECTS AND METHODS
UNIT 4 CLASSES
Structure4.0 Introduction4.1 Objectives4.2 Introduction to Class
4.2.1 Defining Methods4.3 Instantiating Objects of a Class4.4 Accessing Members of a Class4.5 Argument Passing
4.5.1 Call-By-Value4.5.2 Call-By-Reference
4.6 Method Overloading4.7 Constructors
4.7.1 Parameterized Constructors4.8 Static Members4.9 Superclass and Subclass
4.9.1 Defining a Subclass4.10 Types of Inheritance
4.10.1 Single Inheritance4.10.2 Hierarchical Inheritance4.10.3 Multilevel Inheritance4.10.4 Multiple Inheritance
4.11 Access Modifier4.12 Method Overriding4.13 Using final Keyword
4.13.1 final Variables4.13.2 final Methods4.13.3 final Class
4.14 Abstract Methods and Classes4.15 Answers to Check Your Progress Questions4.16 Summary4.17 Key Words4.18 Self Assessment Questions and Exercises4.19 Further Readings
4.0 INTRODUCTION
The key objective of object oriented programming is to represent the various realworld objects as program elements. In Java, this objective is accomplished withthe help of class that binds data and the methods to manipulate that data togetherunder a single entity.
Classes
NOTES
Self-InstructionalMaterial 63
All the OOP concepts, such as data abstraction, encapsulation, inheritanceand polymorphism are implemented with the help of classes. A class serves as atemplate that provides a layout common to all of its instances known as objects.That is, a class is only a logical abstraction that specifies what data and methods itsobjects will have, whereas the objects are the physical entities through which thosedata and methods can be used in a program. Thus, objects are considered as thebuilding blocks of object oriented programming. This chapter discusses the conceptof classes and objects in detail.
Inheritance is one of the major strengths of object oriented programming. Itis the process of deriving a new class from the existing one in such a way that thenew class inherits all the members (data members and methods) of the existingclass. In other words, inheritance facilitates a class to acquire the properties andfunctionality of another class. The new class depicts the acquired properties andbehavior of the existing class as well as its own unique properties and behavior.
Inheritance allows code reusability, that is, it facilitates classes to reuse theexisting code. The new class acquires those members of the old class that arealready tested and debugged. Hence, inheritance saves time as well as increasesthe reliability. Using inheritance, we can create a general class that defines commonproperties for a set of related classes. In this chapter, you will learn about the basicconcept of inheritance.
4.1 OBJECTIVES
After going through this unit, you will be able to: Explain classes and objects that form the basis of object oriented
programming Discuss the and use of non-parameterized and parameterized methods Describe how to pass arguments to a method by value or by reference Understand the concept of method overloading Explain the purpose of constructor and its types Explain the use of static members in a class Understand the significance of inheritance Describe the basic concept of superclass and subclass Discuss various types of inheritance
4.2 INTRODUCTION TO CLASS
A class is a user-defined data type that can be used to create instances of its typecalled objects. Like any other user-defined data type, it also needs to be declared
Classes
NOTES
Self-Instructional64 Material
and defined in the program. A class definition specifies a new data type that can betreated as a built-in data type. The syntax for defining a class is:
classclass_name{
//variablesdeclaration//methodsdeclaration
}
The variables declared in the class are known as instance variables. Thevariables and methods declared within the curly braces are collectively known asmembers of the class. A class can also be empty. That is, the class definition givenbelow is also valid.
classclass_name{}
Here, since the body of the class is empty, it does not contain any variablesand methods so it cannot perform any useful action. However, this class can besuccessfully compiled and we can also create objects using it.Example 4.1: A simple class definition without any method.
classCuboid{ int length;
int width; //variablesdeclarationint height;
}
In this example, a class named Cuboid with three instance variablesof type int, namely, length, width and height is created.
4.2.1 Defining Methods
As discussed earlier, a class consists of instance variables and methods. A classwhich consists of only variables (and without methods which manipulate them)cannot perform any useful operation. Therefore, to access the instance variablesof a class and manipulate them, we must add methods in the class. The syntax fordefining a method is:
return_typemethod_name(parameter_list){
//body of the method}
where,return_type is the type of data that is returned by the method.method_name specifies the name of the method.
Classes
NOTES
Self-InstructionalMaterial 65
parameter_list consists of a series of pairs of datatype and identifiersseparated by commas.
The parameter_list can be empty and if a method does not returnany value, its return type must be void.Example 4.2: A class definition with method.
classCuboid{ int length;
int width; //variablesdeclarationint height;int volume() //methoddefinition{
return(length*width*height);}
}
Note: Methods must be declared immediately after the declaration of the instance variablesinside the body of the class.
4.3 INSTANTIATING OBJECTS OF A CLASS
Once a class is defined, it can be used to create variables of its type known asobjects. The process of creating an object of a class is known as instantiation.The relationship between an object and a class is same as that of any variable andits data type. To create an object, we need to first declare it. The syntax fordeclaring an object is:
class_nameobject_name;
where,class_name is the name of the class.object_name is the name of the object of class_name type.For example, the statement to declare an object of Cuboid type isCuboid cobj;
This statement declares a variable cobj as a reference to an object ofCuboid type. After the execution of this statement, cobj contains the Nullvalue, which indicates that it does not point to an actual object. Once the object isdeclared, we need to create it by allocating the required memory space to it. InJava, this is done with the help of the new operator. The syntax for creating anobject is:
object_name=newclass_name;
For example, the statement to create an object of Cuboid type is:cobj=newCuboid();
Classes
NOTES
Self-Instructional66 Material
This statement creates an actual object by dynamically allocating memoryspace to it and returns a reference to cobj. The above two statements can becombined into one statement as shown below:
Cuboidcobj=newCuboid ();
4.4 ACCESSING MEMBERS OF A CLASS
Each object of a class has its own set of variables. These variables should beassigned values before using them in the program. The instance variables andmethods added in the program cannot be accessed directly outside the class usingtheir names. To access the variables and methods outside the class, dot (.) operatoris used as follows:
object_name.variable_nameobject_name.method_name(parameter_list)
where,object_name is the name of the object.variable_name is the name of the instance variable that is to be
accessed.method_name is the name of the method which is to be called.parameter_list is the series of pairs of data types and their
respective identifiers.For example, the instance variable length of Cuboid class can be
accessed as follows:cobj.length;
Similarly, the method volume()of Cuboid class can be accessed asfollows:
cobj.volume();
Example 4.3: A program to demonstrate the accessing of members of a classand calling of methods.
classCuboid{ int length;
int width;int height;int volume() //methoddefinition{ return(length*width*height); }
}classClassDemo{
public staticvoid main(String args[])
Classes
NOTES
Self-InstructionalMaterial 67
{ Cuboidcobj=newCuboid(); //objectcreationcobj.length=60;cobj.width=20; //accessingvariablescobj.height=40;int vol=cobj.volume(); //callingmethod
System.out.println(“Volumeofthe cuboidis:”+vol);}
}
The output of the program isVolume of the cuboid is: 48000
In this example, the instance variables length, width and heightof the object cobj are assigned values outside the class using the dot operatorand the method volume() is also called using the dot operator. Alternatively,the instance variables can be assigned values by using a parameterized method.Example 4.4: A program to demonstrate the use of parameterized method.
classCuboid{ int length;
int width;int height;void initialize(int l, int w, int h)//parameterizedmethod{ length=l;
width=w;height=h;
}int volume(){ return(length*width*height); }
}classParameterizedMethod{
public staticvoid main(String args[]){ Cuboidc1=newCuboid(); //creatingobject
Cuboidc2=newCuboid();c1.initialize(12,10,8);
//calling initializemethodint vol1=c1.volume(); //callingvolumemethodc2.initialize(13,11,9);int vol2=c2.volume();
Classes
NOTES
Self-Instructional68 Material
System.out.println(“Volumeof the Cuboidis:”+vol1);
System.out.println(“Volumeof the Cuboidis:”+vol2);}
}
The output of the program isVolume of the Cuboid is: 960Volume of the Cuboid is: 1287
Here, the initialize() method accepts three parameter argumentsnamely, l, w and h and assigns them to the instance variables, namely, length,width and height, respectively of the appropriate object.
4.5 ARGUMENT PASSING
The argument(s) that appear in the method call statement are known as actualarguments and those which appear in the method definition are known as formalarguments. The number of actual arguments, their order and type in the methodcall must match with that of the formal arguments. There are two ways by whichan argument can be passed to the method—call-by-value and call-by-reference.
4.5.1 Call-By-Value
In call-by-value method, the values of the actual arguments are copied into theformal arguments. Putting in simple words, the method creates a copy of argumentvalues and then works with these copied values. As a result any changes made tothis set of copied values in the called method do not affect the values of the actualarguments in the calling method. In Java, when arguments of primitive type arepassed to a method, they are passed by value.Example 4.5: A program to demonstrate the call-by-value mechanism.
classFirstCall{ void vol(int i, int j, int k){ i+=3;
j+=3;k+=3;
}}classCallByValue{
public staticvoid main(String args[]){ FirstCallfc=new FirstCall();
int l=10,w=20,h=13;
Classes
NOTES
Self-InstructionalMaterial 69
System.out.println(“Length,Breadth,Heightbeforecallis:” +l+ “ “ +w+ “ ” +h);
fc.vol(l,w, h); //passingvalues as arguments
System.out.println(“Length,Breadth, Heightaftercall is:” +l+ “ “ +w+ “ ” +h);
}}
The output of the program isLength, Breadth, Height before call is :10 20 13Length, Breadth, Height after call is :10 20 13
In this program, the values of l, w and h remain same before and after thecall. This is because when the method vol() is invoked l, w and h are passedby value and their values gets copied into formal arguments i, j and k. Hence,the method vol()works with i, j and k and not with l, w and h. As a result,the values of l, w and h remain unaltered.
4.5.2 Call-By-Reference
In call-by-reference method, argument’s reference is passed as method parameter.Unlike call-by-value method, call-by-reference does not create a copy of theactual argument and the called method works with the original values. This impliesthat any changes made to the variable in the method body are reflected in thecalling method. In Java, when an object of a class is passed to a method as anargument it is passed by reference.Example 4.6: A program to demonstrate the call-by-reference mechanism.
classSecondCall{ int length,breadth, height;
//variablesdeclarationvoidvol(SecondCalls) //methoddefinition{ s.length+=3;
s.breadth+=3;s.height+=3;
}}classCallByReference{
public staticvoid main(String args[]){ SecondCallsc=newSecondCall();
sc.length=10;sc.breadth=20;sc.height=30;
Classes
NOTES
Self-Instructional70 Material
System.out.println(“ThevaluesofLength,BreadthandHeightbefore method call: “ +sc.length + “ “ +sc.breadth + “ ”+sc.height);
sc.vol(sc); //passing objectas methodargument
System.out.println(“ThevaluesofLength,BreadthandHeightafter method call: “ +sc.length + “ “ +sc.breadth + “ ”+sc.height);
}}
The output of the program isThe values of Length,Breadthand Height beforemethod call:10 20 30The values of Length, Breadth and Height after method call:13 23 33
In this program, the values of length, breadth and height ofobject sc changes after invoking the method. Because here when the methodvol() is called, the object of a class is passed as parameter. As a result changesmade to the length, breadth and height of this passed object in thevol() method are reflected in the original values.
4.6 METHOD OVERLOADING
In some cases when a similar action is to be performed on different types of data,different methods having different names are to be defined for all types of data.This makes the program very complex as the programmer must keep track of thenames of all the methods. To prevent such situations, Java allows the methods tobe overloaded.
Method overloading allows multiple methods to have same name withdifferent parameters and different definitions. The application of method overloadingis found in those programs where objects in a class are needed to perform similaroperations but using different input parameters. When a method is called, Javacompiler compares the method name, the type and number of arguments associatedwith it to determine which of the method is to be called and executed. This processis known as polymorphism.
In order to create overloaded methods in our program, we have to createdifferent method definitions in the class, all with same name but having differentparameters. The different methods are identified on the basis of the number ofparameters, the data type of the parameters or the order of the data type of theparameters passed to the method.Example 4.7: A program to demonstrate the concept of method overloading.
classShapes{ voidperimeter(int a)
Classes
NOTES
Self-InstructionalMaterial 71
//methodwith int typeparameter{ System.out.println(“The perimeter of the square is”
+(4*a));}voidperimeter(doublea)
//method withdoubletype parameter{System.out.println(“Thecircumferenceofthecircleis”+(2*a*(22/7)));}void perimeter(inta, int b)//method withtwo parameters{System.out.println(“Theperimeteroftherectangleis”
+2*(a+b));}
}classMethodOverloading{
public staticvoid main(String args[]){ Shapes s=newShapes();
s.perimeter(3.3);s.perimeter(10);s.perimeter(13,10);
}}
The output of the program isThe perimeter of the square is 40The circumference of the circle is 33.0The perimeter of the rectangle is 30
4.7 CONSTRUCTORS
A constructor is a special method which is used to initialize objects at the time oftheir creation. The name of the constructor is same as the name of the class inwhich it resides. Unlike other methods in Java, a constructor does not have anyreturn type (not even void). This is because the implicit return type of constructoris the instance of the class to which it belongs. The syntax to define a constructoris:
classclass_name{
//Variabledeclarationclass_name(parameter_list)//constructordefinition
Classes
NOTES
Self-Instructional72 Material
{//body ofthe constructor
}}
It should be noted that if you do not explicitly define any constructor, thenthe Java compiler automatically provides a default constructor that initializes allthe instance variables to 0.Example 4.8: A program to demonstrate the concept of a constructor.
classCuboid{ int length,width,height;
Cuboid()//constructordefinitionwithoutparameters
{ length=20;width=10;height=13;
}int volume(){ return(length*width*height); }
}classConstructor{
public staticvoid main(String args[]){ Cuboidc1=newCuboid();
Cuboidc2=newCuboid();int a=c1.volume();int b=c2.volume();
System.out.println(“Volumeof first cuboidis” +a);System.out.println(“Volumeofsecondcuboidis” +b);
}}
The output of the program isVolume of first cuboid is 3000Volume of second cuboid is 3000
In this example, the constructor initializes both the objects c1 and c2 ofCuboid type with the same values as a result the volume of both the cuboids issame. Clearly, a non-parameterized constructor provides same values to all theobjects of a class.
4.7.1 Parameterized Constructors
When different objects of a class need to be initialized with different values, aparameterized constructor can be defined. A parameterized constructor is a
Classes
NOTES
Self-InstructionalMaterial 73
constructor that accepts one or more parameters at the time of creation of objectsand initializes the instance variables of the objects with these parameters. It makesthe program more flexible, because using it we can assign different values to theinstance variables of the objects of a class.Example 4.9: A program to demonstrate the concept of a parameterizedconstructor.
classCuboid{ int length,width,height;
Cuboid(intl, int w,int h)//parameterizedconstructor{ length=l;
width=w;height=h;
}int volume()//method definition{ return(length*width*height); }
}classParameterizedConstructor{
public staticvoid main(String args[]){ Cuboidc1=newCuboid(10,8,9);
Cuboidc2=newCuboid(7,6,3);int a=c1.volume();int b=c2.volume();
System.out.println(“Volumeof first cuboidis” +a);
System.out.println(“Volumeofsecondcuboidis” +b);}
}
The output of the program is
Volume of first cuboid is 720Volume of second cuboid is 210
4.8 STATIC MEMBERS
So far, we have seen that members of a class can be initialized or accessed by itsobjects only. However, it is possible to define members of a class without referenceto a specific object. This is done by declaring the instance variables and methodsof a class as static. Unlike non-static members, the static members areassociated with the class as a whole, rather than with individual objects. Therefore,
Classes
NOTES
Self-Instructional74 Material
outside the class the static members of a class are called by using class namesrather than through objects. Since, the static variables and static methods containthe properties of a class and not of the individual objects, they are also known asclass variables and class methods, respectively. The syntax to declare staticvariable and static method is:
staticreturn_typevariable_name;staticreturn_typemethod_name(parameter_list);
The syntax to access static variable and static method isclass_name.variable_nameclass_name.method_name
If a class member is declared as static, only one copy of that datamember is created, regardless of the number of objects. All the objects of a classshare this single copy of the static data member.Example 4.10: A program to demonstrate the use of static members of aclass.
classStaticMembers{ static int i=10; //staticvariable
static void add(int x, int y) //staticmethod{ System.out.println(“Sumoftwonumbersis:”+(x+y));}
}classStaticExample{
public staticvoid main(String args[]){ StaticMembers.add(30,40);//callingstaticmethod
int i=StaticMembers.i;//accessingstatic//variable
System.out.println(“Valueofi is:”+i);}
}
The output of the program is
Sum of two numbersis: 70Value of i is: 10
Here, variable i and method add() are declared as static. Therefore,outside the class they are accessed using the name of the class in which they aredefined.Note: The methods declared as static can access only static data and call staticmethods.
Classes
NOTES
Self-InstructionalMaterial 75
4.9 SUPERCLASS AND SUBCLASS
The class that is inherited by other classes is called a base class or superclass orparent class. The class that inherits the properties of the superclass is called asubclass or derived class or child class. The subclass inherits all of the instancevariables and methods defined by the superclass, at the same time it also containsits own members. For example, in Figure 4.1, Animal is the superclass which isinherited by three subclasses Carnivore, Herbivore and Omnivore. Hence,Carnivore, Herbivore and Omnivore inherit all the members of the superclassAnimal.
Fig. 4.1 Superclass and Subclass
4.9.1 Defining a Subclass
Inheritance is implemented while defining the subclass. The name of the superclassis specified in the subclass definition. A subclass can be defined by using extendskeyword. The syntax to define a subclass is:
classsub_classextends super_class{
//variablesand methods declaration}
where,sub_class is the name of the subclass that inherits the superclass.super_class is the name of the superclass that is being inherited.extends is the keyword that indicates that the super_class properties
have been extended to the sub_class.
Check Your Progress
1. What is a class?2. What is instantiation?3. What should the number of actual arguments, their order and type in the
method call match with?4. Where are the values in call-by-value method copied from?5. What is a class inherited by other classes called?
Classes
NOTES
Self-Instructional76 Material
4.10 TYPES OF INHERITANCE
Inheritance allows creating a logical relationship between two or more classes. Dependingon the number of classes involved and the way the classes are inherited, inheritancemay take different forms, namely, single inheritance, hierarchical inheritance,multilevel inheritance and multiple inheritance.
4.10.1 Single Inheritance
In single inheritance, a class is derived from a single superclass. Figure 4.2shows single inheritance in which subclass is derived from thesuperclass .Person
Person
Employee
Fig. 4.2 Example of Single Inheritance
The syntax to define the subclass that implements single inheritance is
Example 4.11: A program to demonstrate single inheritance
Classes
NOTES
Self-InstructionalMaterial 77
The output of the program is
In this example, the superclass is inherited by the class. Hence, includes variables , and the
method and also defines its own datamember and method.
4.10.2 Hierarchical Inheritance
The type of inheritance in which more than one class is derived from a singlesuperclass is called hierarchical inheritance. In hierarchical inheritance, superclassincludes all the properties that are common to all of its subclasses. Figure 4.3shows hierarchical inheritance with two classes and
Classes
NOTES
Self-Instructional78 Material
deriving from a single superclass .
Person
Student Employee
Fig. 4.3 Example of Hierarchical Inheritance
The syntax to implement hierarchical inheritance involving two subclasses is
Example 4.12: A program to demonstrate hierarchical inheritance
Classes
NOTES
Self-InstructionalMaterial 79
Classes
NOTES
Self-Instructional80 Material
The output of the program is
In this example, the superclass is inherited by two classes and . The subclasses and inherit all the data members , , and the method of and also define their own data members.
4.10.3 Multilevel Inheritance
In multilevel inheritance, one class is inherited from another class, which in turnis inherited from some other class. Multilevel inheritance comprises two or morelevels. The subclass has all the properties of its direct superclass as well as itsindirect superclass. This is known as the transitivenature of multilevel inheritance.Figure 4.4 shows multilevel inheritance in which superclass is inheritedby a subclass , which is again inherited by another subclass
. Hence, is an indirect superclass to .
Person
Employee
Faculty
Superclass
Intermediate superclass
Subclass
Fig. 4.4 Example of Multilevel Inheritance
The syntax to implement multilevel inheritance is
Classes
NOTES
Self-InstructionalMaterial 81
Example 4.13: A program to demonstrate multilevel inheritance
Classes
NOTES
Self-Instructional82 Material
The output of the program is
In this example, the class is inherited by the class, which in turn is inherited by the class . This
implies that is the superclass while is theintermediate superclass. The subclass inherits the members ofboth the classes and . Hence, it includes datamembers , , and , methods.
4.10.4 Multiple Inheritance
In multiple inheritance, a class inherits properties from more than one superclassas shown in Figure 4.5. In Java, it is not possible to implement multipleinheritancedirectly. However, there is a concept known as interface through which multipleinheritance can be implemented.
Classes
NOTES
Self-InstructionalMaterial 83
Person Company
Owner
Fig. 4.5 Example of Multiple Inheritance
4.11 ACCESS MODIFIER
In the programs discussed so far, the class members are accessible everywhere inthe program and the subclass can inherit all the variables and methods of a superclassby using the keyword extends. However, there might be certain situationswhen we want to restrict the accessibility of members of a class for various reasons,security being one of the main reasons. For this, Java provides three types ofaccess modifier, namely public, private and protected. They are also known asvisibility controls.
Public: When a member of a class is declared as public, it can beaccessed everywhere in the program.
Private: A member declared as private can be accessed only within aclass.
Protected: A member declared as protected is accessible not only toall the classes and subclasses in the same package but also to subclasses inother packages.
Note that if no access modifier is specified, by default the data member of aclass is visible only within the same package. We may use the word friendly inconnection with the default access, however, friendly is not a Java keyword.
Apart from the access modifier discussed, there is another access modifiernamely privateprotected which was used with the release of Java 1.0.However, it has been dropped in Java 1.1 and further versions. If data membersare declared as private protected, they can be accessed by all thesubclasses irrespective of the package to which they belong. However, they arenot visible in other classes of the same package. Table 4.1 shows the scope of theaccess modifiers.
Classes
NOTES
Self-Instructional84 Material
Table 4.1 Access Modifiers
Example 4.14: A program to demonstrate the use of private, public anddefault access modifier.
classFirstClass{ int i; //defaultvariable
privateint j; //privatevariablepublic int k; //publicvaraibleint get_data(intl){ j=l;
return j;}
}classVisibilityTest{
public staticvoid main(String[] args){ FirstClassobj=newFirstClass();
obj.i=20; //i can be accesseddirectlyobj.k=60; //k can be accesseddirectly
//this will cause error as j cannot be accessed directly//obj.j=60;//j can be accessed through its methodint a=obj.get_data(40);
System.out.println(“The value of i,j and k are:”+obj.i+ “, ” + a +“and”+obj.k+ “respectively.”);
}}
The output of the program isThe value of i,j andk are: 20,40 and 60 respectively.
Classes
NOTES
Self-InstructionalMaterial 85
In this example, variable i is set to default access, variable j is declared asprivate and variable k is declared as public . In the classVisibilityTest, only variables i and k can be accessed directly. Thevariable j can be accessed through its method get_data().
4.12 METHOD OVERRIDING
If a subclass method has the same name, same parameter list and same return typeas a superclass method, then we say that the method in the subclass overrides themethod in the superclass. When the overridden method is called, the version ofthe method defined in the subclass will be invoked instead of the method definedin the superclass. That is, the method in the subclass will hide the method definedin the superclass.Example 4.15: A program to demonstrate method overriding.
classPerson{ String name= “John”;
int age=30;voidresult(){ System.out.println(“Thenameandtheageofthepersonare:”+name+“and“+age+”“respectively”);}
}class Employee extendsPerson{ intsalary=40000;
voidresult() //result()isoverridden{ System.out.println(“The name and the salary of theemployee are:” +name+ “and”+salary+“respectively”);}
}publicclass MethodOverriding{
public staticvoid main(String[] args){ Employee obj=newEmployee();
obj.result(); //invokesEmployee’sresult()}
}
The output of the program isThe name and the salary of the employee are: John and 40000respectively
In this example, when the method result() is invoked through an objectobj of type Employee, the method result()defined within Employee
Classes
NOTES
Self-Instructional86 Material
is executed. That is, the method result() of the subclass Employeeoverrides the method result() of the superclass Person.
4.13 USING final KEYWORD
Java provides a keyword final that can be applied to variables, methods andclasses. The meaning of the final keyword when applied to variables is differentfrom its meaning when it is applied to methods and classes.
4.13.1 final Variables
The value of a variable can be prevented from being modified by declaring avariable as final. The syntax for declaring a final variable is:
finaldata_typevariable_name=constant_value;
An attempt to alter the value of a final variable will generate a compile-time error. Note that a final variable does not occupy memory for each instance ofthe class. Hence, final variable is a constant.
4.13.2 final Methods
As stated earlier, whenever a method is defined in the subclass with the samename and same signature as in the superclass, it is by default overridden in thesubclass. However, a method can be prevented from being overridden by thesubclass by declaring the method as final. The syntax for declaring a finalmethod is:
final data_type method_name()
{
}
4.13.3 final Class
A class which cannot be further inherited or cannot have any subclass is known asfinal class. To make a class final, the class declaration is preceded by thefinal keyword. If a class is declared as final, all of its methods areautomatically declared as final. The syntax for declaring a final class is:
final classclass_name{
}
4.14 ABSTRACT METHODS AND CLASSES
As discussed earlier, a method can be prevented from being overridden in thesubclass by using the keyword. However, sometimes there might be a
Classes
NOTES
Self-InstructionalMaterial 87
situation, when the method in the superclass always needs to be redefined in thesubclass and for this overriding becomes necessary. This kind of situation canarise when the superclass is not able to provide meaningful implementation for itsmethods. In such a case, the superclass provides a generalized structure of themethod and leaves the implementation part to its subclass. To deal with suchsituation, Java allows us to specify that a method must always be overridden in thesubclass by using the keyword in the method declaration.The syntax for declaring an abstract method is
If a class has one or more abstract methods, the class must also be declaredas abstract by using the keyword .The syntax for declaring an abstract class is
The class which inherits the abstract class must provide implementation forall the methods or the class should declare itself as .HHHefwf
These are certain points that should be kept in mind while using abstractclass.
An abstract class cannot be instantiated. Abstract methods of an abstract class must always be implemented in
the subclass. Abstract methods must end with semicolon ( ) because they do not
have any functionality. There can be both defined and undefined methods in an abstract class. Constructors or static methods cannot be declared as abstract.
Example 4.16 A program to demonstrate the concept of abstract class
Classes
NOTES
Self-Instructional88 Material
The output of the program is
In this example, the is an abstract class which contains an abstractmethod and this method is implemented in the subclass .
Check Your Progress
6. What does inheritance allow?7. How can the value of a variable be prevented from being modified?8. What does the subclass inherit?
Classes
NOTES
Self-InstructionalMaterial 89
4.15 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. A class is a user-defined data type that can be used to create instances of itstype called objects.
2. The process of creating an object of a class is known as instantiation.3. The number of actual arguments, their order and type in the method call
must match with that of the formal arguments.4. In call-by-value method, the values of the actual arguments are copied into
the formal arguments.5. The class that is inherited by other classes is called a base class or superclass
or parent class.6. Inheritance allows creating a logical relationship between two or more
classes.7. The value of a variable can be prevented from being modified by declaring
a variable as final.8. The subclass inherits all of the instance variables and methods defined by
the superclass
4.16 SUMMARY
The process of creating an object of a class is known as instantiation. Therelationship between an object and a class is same as that of any variableand its data type.
Each object of a class has its own set of variables. These variables shouldbe assigned values before using them in the program.
The argument(s) that appear in the method call statement are known asactual arguments and those which appear in the method definition are knownas formal arguments.
In call-by-value method, the values of the actual arguments are copied intothe formal arguments.
In call-by-reference method, argument’s reference is passed as methodparameter.
Method overloading allows multiple methods to have same name withdifferent parameters and different definitions.
A constructor is a special method which is used to initialize objects at thetime of their creation.
Classes
NOTES
Self-Instructional90 Material
When different objects of a class need to be initialized with different values,a parameterized constructor can be defined.
A parameterized constructor is a constructor that accepts one or moreparameters at the time of creation of objects and initializes the instancevariables of the objects with these parameters.
The class that is inherited by other classes is called a base class or superclassor parent class.
The class that inherits the properties of the superclass is called a subclass orderived class or child class. The subclass inherits all of the instance variablesand methods defined by the superclass, at the same time it also contains itsown members.
Inheritance allows creating a logical relationship between two or moreclasses.
Depending on the number of classes involved and the way the classes areinherited, inheritance may take different forms, namely, single inheritance,hierarchical inheritance, multilevel inheritance and multiple inheritance.
The type of inheritance in which more than one class is derived from asingle superclass is called hierarchical inheritance.
In multilevel inheritance, one class is inherited from another class, which inturn is inherited from some other class.
If a subclass method has the same name, same parameter list and samereturn type as a superclass method, then we say that the method in thesubclass overrides the method in the superclass.
Java provides a keyword final that can be applied to variables, methodsand classes.
The meaning of the final keyword when applied to variables is differentfrom its meaning when it is applied to methods and classes.
4.17 KEY WORDS
Object: Objects are variables of class type inside which they are created. Class: A class is a user-defined data type that can be used to create
instances of its type called objects. Instantiation: The process of creating an object of a class is known as
instantiation. Dot operator: To access the variables and methods outside the class dot
(.) operator is used. Constructor: A constructor is a special method which is used to initialize
objects at the time of their creation.
Classes
NOTES
Self-InstructionalMaterial 91
Inheritance: It is the process of deriving a new class from the existing onein such a way that the new class inherits all the members (data members andmethods) of the existing class.
Superclass: It is the class that is inherited by other classes. Subclass: It is the class that inherits the properties of the superclass. Overriding: If a subclass method has the same name, same parameter list
and same return type as a superclass method, then we say that the methodin the subclass overrides the method in the superclass.
final class: A class which cannot be further inherited or cannot haveany subclass.
4.18 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions1. What is a class and how is it related to objects?2. What do you mean by instantiation?3. What is the use of dot operator?4. What are the two possible ways of passing arguments to a method?5. What is the difference between a method and a constructor?
Long Answer Questions1. Find and fix the error in the following program to display the area of the
rectangle.class Rectangle{
public static void main(String args[]){
Rectangle rect;rect.length=10;rect.width=7;
System.out.println(“Area of the rectangle rectis”+rect.area());
}}
2. What is the difference between the two methods of passing arguments to amethod? Explain with example.
Classes
NOTES
Self-Instructional92 Material
3. Define a class Student having instance variables: roll_number,marks1, marks2 and marks3 and method: calculate() tocalculate the overall percentage of marks and return the percentage of marks.
4. Can the objects of a class be initialized at run-time using constructors?Explain with an example.
5. How is a static method invoked? Explain with an example.6. Define a class Teacher having instance variables: Teacher_id,Basic, DA and HRA and method: calculate() to calculate the salary.(Hint: Salary is the sum of Basic, DA and HRA).
4.19 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 93
UNIT 5 ARRAYS, STRINGS ANDVECTORS
Structure5.0 Introduction5.1 Objectives5.2 Arrays
5.2.1 Single-Dimensional Arrays5.2.2 Multi-Dimensional Arrays
5.3 Strings5.3.1 String Class5.3.2 StringBuffer Class
5.4 Vectors5.4.1 Wrapper Classes
5.5 Answers to ‘Check Your Progress’ Questions5.6 Summary5.7 Key Words5.8 Self Assessment Questions And Exercises5.9 Further Readings
5.0 INTRODUCTION
Handling the real world data requires a mechanism that deals with a collection ofdata items. In Java, different data types like arrays, strings and vectors are offeredto handle such collections. These data types are capable of grouping the relateddata items together into a single unit. Arrays hold together few or thousands ofdata items of similar data types under a single name, strings are used to representa collection of characters, and vectors provide a way to keep the items of anydata type in any number together into a single entity.
The main objective of this unit is to make you familiar with the basic conceptsof arrays, strings and vectors.
5.1 OBJECTIVES
After going through this unit, you will be able to: Discuss one dimensional arrays Explain how arrays are created Declare, initialize and manipulate single-dimensional as well as multi-
dimensional arrays Explain the use of String and String Buffer classes Understand the significance of vectors
Arrays, Strings and Vectors
NOTES
Self-Instructional94 Material
5.2 ARRAYS
Java uses the variables of different primitive data types to store data. However,these variables are incapable of holding more than one value at a time. For example,a single variable cannot be used for storing the marks of all the students in a class.For such purposes, Java provides a different kind of data type known as arrays.
Arrays are defined as a fixed size sequence of the same type of data elements.These data elements can be of any primitive or non-primitive data type. The elementsof an array are stored in contiguous memory locations and each individual elementcan be accessed using one or more indices or subscripts. A subscript or an indexis a positive integer value, which indicates the position of an element in an array.Arrays are used when a programmer wants to store multiple data items of thesame type into a single list and also wants to access and manipulate individualelements of the list. Arrays can be either single-dimensional or multi-dimensionaldepending upon the number of subscripts used.
5.2.1 Single-Dimensional Arrays
A single-dimensional array is the simplest form of an array that requires only onesubscript to access an array element. Like an ordinary variable, an array must bedeclared before it is used in the program.
The syntax for declaring a single-dimensional array is as follows:
or
where,data_type is any data type.array_name is the name of the array.
For example, an array marks[] of type int can be declared usingeither of the following two statements:
or
After an array is declared, you need to create it by allocating space to it inmemory. Arrays are created using newoperator.
The syntax for creating an array is as follows:
where,size
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 95
For example, an array marks[] of type int and size five can be createdusing this statement.
The preceding steps of declaration and creation of an array can be combinedinto a single statement as follows:
data_type array_name=new data_type[size];
Similarly, the statement to declare and create an array marks[] of typeint and size five is as follows:
Note: All the elements created using the new operator in the array will be automaticallyinitialized to zero.
Initialization of Single-Dimensional Array
Once an array is declared and memory is allocated to it, the next step is to initializeeach array element with a valid and appropriate value. An array can be initializedat the time of its declaration.
The syntax for initializing an array at the time of its declaration is as follows:data_type array_name[]={value_1,value_2,......,value_n};
The values are assigned to the array elements in the order in which they arelisted. That is, value_1, value_2 and value_n are assigned to the first,second and nth element of the array, respectively.
If an array is declared and initialized simultaneously, then specifying its sizeis optional. For example, the statement int marks[]={51,62,43,74,55} is also valid. The size of an array marks can be obtained byusing marks.length() method.Note: If you try to store or access values outside the range of array (index with negativevalue or value greater than the length of the array), run-time error is generated.
Accessing Single-Dimensional Array Elements
Once an array is declared and initialized, the values stored in the array can beaccessed any time. Each individual array element can be accessed using the nameof the array and the subscript value. Every element in an array is associated with aunique subscript value, starting from 0 to size-1 (where, size refers to themaximum number of elements that can be stored in the array).
The syntax for accessing the values stored in a single-dimensional array isas follows:
For example, the elements of the array marks can be referred to asmarks[0], marks[1], marks[2], marks[3] and marks[4],respectively. Note that index of an array starts with 0.Note: The memory location, where the first element of an array is stored, is known as thebase address, which is generally referred to by the name of the array.
Arrays, Strings and Vectors
NOTES
Self-Instructional96 Material
Single-dimensional arrays are always allocated contiguous blocks of memory.This implies that every element in an array is always stored in a sequential mannernext to each other. The memory representation of the array marks is shown inFigure 5.1. As each element is of type int (that is, 4 bytes long), the arraymarks occupies twenty contiguous bytes in the memory, and these bytes arereserved in the memory at compile time.
marks marks[3] marks[2] marks[1] marks[0]
746251
marks[4]
2001 2005 2009 2013 2017
5543
Fig. 5.1 Memory Representation of an Array marks
Manipulation of Single-Dimensional Array Elements
An array can be manipulated with the help of various operations. These operationsinclude finding the sum, average, maximum or minimum, sorting and searching ofthe array elements.
A program to sort the array elements is as follows:
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 97
The output of the program is as follows:
5.2.2 Multi-Dimensional Arrays
Multi-dimensional arrays can be described as ‘an array of arrays’, that is, eachelement of the array is itself an array. A multi-dimensional array of dimension n isa collection of items that are accessed with the help of n subscript values.
Two-Dimensional Array
A two-dimensional array is the simplest form of a multi-dimensional array thatrequires two subscript values to access an array element. Two-dimensional arraysare useful when the data being processed are to be arranged in the form of rowsand columns (matrix form).
The syntax for declaring a two-dimensional array is as follows:
The syntax for creating a two-dimensional array is as follows:array_name[][]=new data_type[row_size][column_size];
The preceding two steps of declaration and creation can be combined intoone using a single statement as follows:
data_type array_name[][]=newdata_type[row_size][column_size];
For example, an array a[][] of type int having three rows and twocolumns can be declared and created using this statement.
Here, 3 is the row size and 2 is the column size.
Arrays, Strings and Vectors
NOTES
Self-Instructional98 Material
Initialization of Two-Dimensional Array
Like a single-dimensional array, a two-dimensional array can also be declaredand initialized at the same time. To understand how to initialize a two-dimensionalarray, consider this statement.
In this statement, an array a[][] of type int having three rows and twocolumns is declared and initialized. This type of initialization is generally used toincrease the readability.
Now, consider another statement.
In this statement, an array b[][] of type int having two rows and threecolumns is initialized.
Accessing Two-Dimensional Array Elements
Once a two-dimensional array is declared and initialized, the value stored in thearray elements can be accessed using two subscripts.
The syntax for accessing the two-dimensional array element is as follows:array_name[row][column]
The first subscript value (row) specifies the row number and the secondsubscript value (column) specifies the column number. Both the subscript valuesspecify the position of the array element within the array.
For example, the elements of array a (declared earlier) are referred to asa[0][0], a[0][1], a[1][0], a[1][1], a[2][0] and a[2][1],respectively.
Generally, two-dimensional arrays are represented with the help of a matrix.However, in actual implementation, two-dimensional arrays are always allocatedcontiguous blocks of memory. Figure 5.2 shows matrix and memory representationof two-dimensional array a.
101 51
105 67
103 76
101 51 105 67 103 76
a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[2][1]
2001 2005 2009 2013 2017 2021
first row second row third row
(a) (b)
Fig. 5.2 (a) Matrix and (b) Memory Representation of Array a[][]
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 99
Manipulation of Two-Dimensional Array Elements
A two-dimensional array can be manipulated in many ways. Some of the commonoperations that can be performed on a two-dimensional array include finding thesum of row elements, column elements and diagonal elements, finding the maximumand minimum values, etc.
A program to calculate the sum of two matrices is as follows:
Arrays, Strings and Vectors
NOTES
Self-Instructional100 Material
The output of the program is as follows:
4 4 9
Variable Size Arrays
Multi-dimensional arrays are arrays of arrays. In such multi-dimensional arrays,the size of each array can be varied. For example, consider the following statements:
where,size is the number of rows in two-dimensional array.size_1, . . . , size_n represents the number of columns in each row
of two-dimensional array.A program to demonstrate a variable size array is as follows:
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 101
The output of the program is as follows:
5.3 STRINGS
In Java, a string is an object that is created either using String orStringBuffer class. Each class has its own set of methods for creating andmanipulating strings. The difference between these two classes is that a stringcreated from the String class cannot be modified, that is, characters cannot beinserted to, replaced or removed from the string. However, the string createdusing StringBuffer class cannot only be modified but can also be expandedor contracted dynamically whenever required.
5.3.1 String Class
The String class is more commonly used for the following purposes: To display messages Search or compare the strings Extract individual characters in a string as substrings
The syntax to declare a string is as follows:
Arrays, Strings and Vectors
NOTES
Self-Instructional102 Material
The syntax for creating a string is as follows:
These two steps of declaration and creation can be combined into a singlestatement as follows:
For example, the statement to declare and create a string str1 usingString class is as follows:
The String class provides various methods for manipulating strings. Someof the most commonly used methods of String class along with their descriptionare listed in Table 5.1.
Table 5.1 String Class Methods and their Description
Methods Description str1.length() Returns the length of the string str1str1.equals(str2) Returns ‘true’ if string str1 is equal to string str2str1.compareTo(str2) Returns negative if str1<str2, positive if
str1>str2, otherwise 0 str1.concat(str2) Concatenates string str1 and string str2str1=str2.trim() Removes all the white spaces at the beginning and end
of the string str2 and assigns it to str1str1=str2.replace(‘a’,’b’) Replaces all a appearing in the string str2 with b and
assigns it to str1str1=str2.toLowerCase() Converts uppercase letters in the string str2 to
lowercase and assigns it to str1str1=str2.toUpperCase() Converts lowercase letters in the string str2 to
uppercase and assigns it to str1str1.indexOf(‘a’) Gives the position of the first occurrence of character
‘a’ in the string str1str1.indexOf(‘a’,n) Gives the position of the first occurrence of character
‘a’ that occurs after nth position in the string str1
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 103
The output of the program is as follows:
5.3.2 StringBuffer Class
As stated earlier, strings created using String class are of fixed length, whereas,strings created using StringBuffer class are of varying length.
The syntax to declare a string is as follows:
The syntax for creating a string is as follows:
These two steps of declaration and creation can be combined into a singlestatement as follows:
For example, the statement to declare and create a string str1 usingStringBuffer class is as follows:
Some of the commonly used methods of StringBuffer class alongwith their description are listed in Table 5.2.
Table 5.2 StringBuffer Class Methods and their Description
Methods Description str1.append(str2) Appends the string str2 at the end of the string str1str1.insert(n,str2) Inserts the string str2 at the position n of the string
str1str1.setCharAt(n,’x’) Sets the nth character of the string str1 to xstr1.setLength(n) Sets the length of the string str1 to n. If
n<str1.length(), str1 is truncated. If n>str1.length(), null characters are added at the end of str1
str1.reverse() Reverses the string str1str1.delete(m,n) Deletes characters of the string str1 from mth index to
(n-1)th index str1.deleteCharAt(m) Removes character of the string str1 at mth index str1.replace(m,n,”str2”)
Replaces the portion of the string str1 from mth index to (n-1)th index with the string str2
Arrays, Strings and Vectors
NOTES
Self-Instructional104 Material
A program to demonstrate the use of some of the methods ofStringBuffer class is as follows:
The output of the program is as follows:
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 105
The disadvantage of StringBuffer class is that it does not provide aset of methods for comparing strings, locating characters or substrings within astring. Thus, the String class is preferred for displaying or comparing stringswhereas the StringBuffer class is used when addition and modificationsare required.
Check Your Progress
1. What are Arrays?2. What is a multi-dimensional array of dimension?3. What is the disadvantage of StringBuffer class?
5.4 VECTORS
The Vector class contained in the java.util package defines the methodsused to store various objects into a single unit. It can be used to implement dynamicarray called vectors, which can accommodate any number and any type of objects.Consider the following statements:
Vector v2=new Vector(n); //creating vector having initialcapacity //‘n’
Here, the first statement creates a vector v1 having initial capacity 10. Thatis, when you create a vector without specifying its initial capacity, it is automaticallyset to 10. Similarly, the second statement creates a vector v2 with initial capacityn. Although, the vector v2 has been created by specifying its initial capacity, thisspecification does not pose any limitation on the size of the vector. Since, the sizeof the vector can be increased or decreased by adding or removing objects to it.
The Vector class provides a variety of methods that can be used toperform different operations on vectors. Some of which are listed in Table 5.3.
Table 5.3 Vector Methods and their Description
Methods Description vect1.addElement(object) Adds the specified object at the end of the vector list
vect1vect1.size() Returns the number of objects currently present in the
vector vect1vect1.capacity() Returns the maximum capacity of the vector vect1vect1.removeElement(object) Removes the specified object from the vector vect1vect1.elementAt(n) Returns the name of the nth object of the vector vect1vect1.removeElementAt(n) Removes the item at the nth position of the vector
vect1vect1.removeAllElements() Removes all the elements in the vector vect1vect1.firstElement() Returns the first element of the vector vect1vect1.lastElement() Returns the last element of the vector vect1vect1.trimToSize() Sets the capacity of the vector vect1 to the number
of objects it is currently holding
Arrays, Strings and Vectors
NOTES
Self-Instructional106 Material
A program to demonstrate the use of some of the methods of Vectorclass is as follows:
The output of the program is as follows:
5.4.1 Wrapper Classes
One limitation of using vectors is that we cannot store data items of primitive datatypes like int, float, char, long, double, etc. since it can store onlyobjects. Therefore, primitive data types need to be converted into objects beforestoring them in vectors. To accomplish this, Java provides wrapper classes
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 107
contained in the java.lang package. The wrapper classes are used to convertthe primitive data types into their respective class instances. For example, a floatdata type is represented as an instance of Float class.
It should be noted that Java’s primitive wrapper classes are immutable, thatis, once a value is assigned to an instance of a wrapper class it cannot be changedlater. The primitive data types and their corresponding wrapper classes are shownin the Table 5.4.
Table 5.4 Primitive Data Types and Their Corresponding Wrapper Classes
Primitive Data Type Wrapper Class boolean java.lang.Boolean byte java.lang.Byte char java.lang.Character double java.lang.Double float java.lang.Float int java.lang.Integer long java.lang.Long short java.lang.Short void java.lang.Void
Some of the methods of wrapper classes are listed in Table 5.5–5.9.
Table 5.5 Conversion of Primitive Data Types to Object Types usingConstructor Methods
Constructor Calling Action Performed Integer a=new Integer(i); coverts integer to Integer object Float b=new Float(f); coverts float to Float object Double c=new Double(d); coverts double to Double object Long d=new Long(l); coverts long to Long object
Table 5.6 Conversion of Object Numbers to Primitive Numbers usingtypeValue() Method
Method Calling Action Performed int i=a.intValue(); converts object to integer float f=b.floatValue(); converts object to float double d=c.doubleValue(); converts object to double long l=d.longValue(); converts object to long
Table 5.7 Conversion of Primitive Numbers to Strings using toString() Method
Method Calling Action Performed str=Integer.toString(i); converts Primitive integer to string str=Float.toString(f); converts Primitive float to string str=Long.toString(l); converts Primitive long to string str=Double.toString(d); converts Primitive double to string
Arrays, Strings and Vectors
NOTES
Self-Instructional108 Material
Table 5.8 Conversion of String Objects to Numeric Objects using valueOf() Method
Method Calling Action Performed IntVal=Integer.valueOf(str); converts string to Integer object FloatVal=Float.valueOf(str); converts string to Float object LongVal=Long.valueOf(str); converts string to Long object DoubleVal=Double.valueOf(str); converts string to Double object
Table 5.9 Conversion of Strings to Primitive Numbers using Parsing Methods
Method Calling Action Performed int i=Integer.parseInt(str) converts string to primitive integer long l=Long.parseLong(str) converts string to primitive long
Note: The methods defined in the wrapper classes are static.
Example 5.1: A program to demonstrate the use of wrapper classes
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 109
The output of the program is
Check Your Progress
4. What does the Vector class contained in the java.util package define?5. List a limitation of using vectors.
5.5 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. Arrays are defined as a fixed size sequence of the same type of data elements.2. A multi-dimensional array of dimension is a collection of items that are
accessed with the help of n subscript values.3. The disadvantage of String Buffer class is that it does not provide a set of
methods for comparing strings, locating characters or substrings within astring.
4. The Vector class contained in the java.util package defines the methodsused to store various objects into a single unit.
Arrays, Strings and Vectors
NOTES
Self-Instructional110 Material
5. A limitation of using vectors is that we cannot store data items of primitivedata types like int, float, char, long, double, etc. since it can store onlyobjects.
5.6 SUMMARY
Arrays are defined as a fixed size sequence of same type of data elements. The elements of an array are stored in contiguous memory locations and
each individual element can be accessed using one or more indices orsubscripts.
Arrays can be either single-dimensional or multi-dimensional depending uponthe number of subscripts used.
A single-dimensional array is the simplest form of an array that requiresonly one subscript to access an array element.
Multi-dimensional arrays can be described as an ‘array of arrays’, that is,each element of the array is itself an array.
A two-dimensional array is the simplest form of a multi-dimensional arraythat requires two subscript values to access an array element.
A string is an object that is created either using String orStringBuffer class.
The strings created using the String class are of fixed length and cannotbe modified, that is, the characters cannot be inserted to or removed fromthe string.
The strings created using the StringBuffer class are of varying lengthand cannot only be modified but also be expanded or contracted dynamicallywhenever required.
The Vector class is used to implement the dynamic array called vectorswhich can accommodate any number and any type of objects.
5.7 KEY WORDS
Array: It is as a fixed size sequence of the same type of data elements. Single-dimensional array: It is the simplest form of an array that requires
only one subscript to access an array element.
5.8 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answers Questions1. Define an array. Why are they needed?
Arrays, Strings and Vectors
NOTES
Self-InstructionalMaterial 111
2. Differentiate between single-dimensional and multi-dimensional arrays.3. Differentiate between String and StringBuffer classes.4. What are vectors? How are they different from arrays?
Long Answers Questions
1. Write a program to multiply two given matrices and print the resultant matrix.2. Consider the given string:
String str= “Java is an interesting programming language.”;(i) What will be the value of str.length()?(ii) What will be the value of str.charAt(12)?(iii) Write an expression to return letter c in the string str.
3. Write a program to create a list of names of 5 students in a class and storethem in a vector. In addition perform the following operations in the list
(i) Add a name at the end of the list.(ii) Delete a name at the third position in the list.(iii) Display the final contents of the list.
5.9 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Packages
NOTES
Self-Instructional112 Material
UNIT 6 PACKAGES
Structure6.0 Introduction6.1 Objectives6.2 Defining Interface6.3 Implementing Interface
6.3.1 Partial Implementations6.4 Extending Interfaces6.5 Extends and Implements Together6.6 Overview of Packages6.7 Java API Packages
6.7.1 Naming Conventions6.8 Defining Packages
6.8.1 Accessing Packages6.9 Using Packages
6.10 Adding a Class6.11 Answers to Check Your Progress Questions6.12 Summary6.13 Key Words6.14 Self Assessment Questions and Exercises6.15 Further Readings
6.0 INTRODUCTION
As you already know, the concept of multiple inheritance is not directly supportedby Java. This means that a subclass in Java cannot have more than one superclass.However, there are certain applications where a class needs to inherit propertiesfrom multiple classes at the same time. Java provides an approach known asinterface as a convenient alternative to implement multiple inheritance.
In this unit, you will learn about interfaces in Java. Code reusability is one ofthe important features of object oriented programming. So far we have seen that acode can be reused through inheritance. However, the reusability of code throughinheritance was restricted to only single program. A situation may arise when thecode of one program needs to be reused in some other program. This can beachieved in Java with the help of the concept known as package.
6.1 OBJECTIVES
After going through this unit, you will be able to: Explain interface and its implementation Understand how to extend interfaces
Packages
NOTES
Self-InstructionalMaterial 113
Discuss how to put classes together Differentiate between two dimensional arrays, vectors and strings Understand the concept of packages
6.2 DEFINING INTERFACE
An interface is just like a class. The only difference is that it contains only finalvariables and the method declarations. Hence, we can think of an interface as a‘fully abstract class’. There is no limitation to the number of interfaces that a classcan implement. An interface is defined just like a class but rather than using thekeyword class, the keyword interface is used.The syntax to define an interface is
interface interface_name{
}
where,interface is the Java keywordinterface_name is the name of the interfaceIf there is no access specifier included in the interface definition, then the
default access is used and the interface is visible only to the members of the samepackage. However, to make the interface accessible in any other code, it can bedeclared as public. The variables in an interface are by default static andfinal. Hence, they cannot be altered by the implementing class. The methodsare by default abstract. All the methods must be implemented by the classwhich implements the interface. For example, consider the following code segment.
Here, Area is the name of the interface. The variable pi is initialized witha constant value. Note that the method compute() does not have the bodypart and its declaration ends with semicolon.
If the interface is declared as public then, all the variables and methods areimplicitly public.
6.3 IMPLEMENTING INTERFACE
Once an interface is defined, it can be used as a superclass whose members andproperties can be inherited by other classes. One or more classes can implement
Packages
NOTES
Self-Instructional114 Material
the interface by using the keyword implements in the class definition.The syntax for implementing an interface is
For example, consider the following code segment which implements theinterface Area.
When the methods in an interface are defined in the implementing class, thepublic keyword must be used. Also, the signature of the method implementingthe interface must exactly match the signature of the method declaration in theinterface.
A class can implement more than one interface as shown below.
A class can extend another class while implementing interfaces as shownbelow.
6.3.1 Partial Implementations
If a class that implements the interface does not provide complete implementationof the methods declared in the interface, then it is necessary for the class to bedeclared as abstract. For example, consider another class Square whichimplements the interface Area.
Packages
NOTES
Self-InstructionalMaterial 115
abstract class Square implements Area
Here, the class Square is declared as abstract as it does notimplement the method compute() declared in Area. Any class that inheritsSquare must implement compute() method or the class itself must bedeclared as abstract.
6.4 EXTENDING INTERFACES
An interface can inherit another interface by using extends keyword in thesame way as a class inherits from another class. Like a class, a subinterface willinherit all the properties of the superinterface and also adds its own data members.For example consider the following code segment.
An interface can also inherit from more than one interface. To define aninterface that extends several interfaces, the names of the superinterfaces areseparated by comma (,) as shown here.
}
The methods declared in the superinterfaces cannot be implemented by thesubinterfaces. They must be implemented only by the class which implements theinterface. When a class implements an interface which is inherited from anotherinterface then the class must provide implementation for all the methods declaredin both the interfaces.
Packages
NOTES
Self-Instructional116 Material
An interface cannot extend classes. It can only extend another interface.Also, an interface cannot implement another interface.
6.5 EXTENDS AND IMPLEMENTS TOGETHER
By now you are familiar with the concept of interface. Now, you will learn how aninterface can be used to implement multiple inheritance by taking a simple example.In this example, the class Faculty extends a class Employee and implementsan interface Bonus.Example 6.1: A program to demonstrate implementation of multiple inheritancethrough interface
Packages
NOTES
Self-InstructionalMaterial 117
Packages
NOTES
Self-Instructional118 Material
The output of the program is
6.6 OVERVIEW OF PACKAGES
A package is a named collection of classes. Any number of related classes can begrouped into a single package. By grouping the classes into a package, we canachieve the following.
The classes which belong to a package of another program can be easilyreused.
Two classes in two different packages can have the same name. For example,we can create a class called Student without being concerned aboutthe collision of this name with some other class called Studentwhichbelongs to some other package.Every class belongs to a package. The classes that we have created and
used so far belong to the default package. Java packages are categorized into twotypes, namely, API packages and user-defined packages. Application ProgrammingInterface (API) packages are the standard packages available in Java which containall of the standard classes. Java also allows us to create our own package knownas user-defined packages.
Packages
NOTES
Self-InstructionalMaterial 119
Check Your Progress
1. What is the nature of variables in an interface?2. What is a package?
6.7 JAVA API PACKAGES
There is a huge list of API packages provided by Java. Some of the quite frequentlyused packages are shown in Table 6.1.
Table 6.1 Commonly Used API Packages
Package Description java.lang It includes classes that are fundamental to Java such as String,
Math, Exception, etc. java.io This package provides classes to support input and output operations. java.awt This provides a set of classes to implement graphical user interface
components such as windows, dialog boxes, menus, list, buttons, checkboxes, textfields, scrollbars, etc.
java.applet This package includes classes to create applets that can be embedded in a webpage.
java.util This package includes language utility classes such as time, date, random number, hash tables, vectors, enumeration, etc.
java.sql This package contains classes for accessing database using standard SQL.
Each Java API package is organized in a hierarchical form. For example,consider a package, say, java.lang. The java.lang package containingvarious classes is organized in hierarchical form as shown in Figure 6.1.
java
lang String
Math
………....Thread
Fig. 6.1 Hierarchical Representation of Package
Figure 6.1 shows that the package java contains the package langwhich in turn contains various classes such as Math, String, etc.
Packages
NOTES
Self-Instructional120 Material
The classes stored in a package can be accessed in two ways dependingon the following two situations:
If we need to access the class only once or when we do not need toaccess any other class of the same package.In this case, to access the class, the name of the package is followed bydot (.) operator which is followed by the name of the class. For example,the statement to access the Math class contained in lang package isas follows:
If we want to use multiple classes contained in a package or use thesame class in various places of the program.This can be achieved with the help of import statement. The syntaxto access the same class in various places is
where,import is a Java keywordpackage_name is the name of the packageclass_name is the name of the class belonging to that package
For example, consider this statement.import java.lang.Math;
In this statement, the class Math contained in the packagejava.lang is imported in the program and can now be used atvarious places in the program without using the package name.We can access multiple classes contained in a package using the statementgiven here.
For example, the statement import java.lang.* imports allthe classes contained in java.lang package.
6.7.1 Naming Conventions
There are certain Java naming conventions using which packages can be named.The names of the packages and classes or interfaces should be such that it iseasier to distinguish between the two. According to the conventions, the name ofthe packages starts with a lowercase letter whereas the name of the classes beginswith an uppercase letter. For example, consider this statement.
java.lang.Math
In this statement, the name of the package lang begins with lowercaseletter and the name of the class Math begins with uppercase letter. However, asthere are number of users working simultaneously on the internet, there may be a
Packages
NOTES
Self-InstructionalMaterial 121
chance of duplicate packages being created which may lead to run-time error.Hence, package names must be unique. To ensure uniqueness of the packagenames, the name of the package can be preceded with the internet domain name.For example, consider this statement.
In this statement, the package package_name is preceded by thedomain name dpe.aet.
6.8 DEFINING PACKAGES
To create a user-defined package, first a package must be declared using thekeyword package followed by the name of the package.
The syntax to declare a package is
where ,package is the Java keywordpackage_name is the name of the package
This statement must be the first statement in the Java source file. Once thepackage is declared, we can define any number of classes which will be the part ofthis package. For example, consider this code segment.
//body of the class
Here, ClassName is the name of the class which will belong to thepackage packagename. In Java, packages are stored in the file systemdirectories. The above code must be saved with the filenameClassName.java in a directory named packagename. When the Javacompiler compiles the source file, the ClassName.class file is created andautomatically stored in the same directory packagename. Since Java is casesensitive, the name of the directory must exactly match with the package name.
Like API packages, user-defined packages can be organized in a hierarchicalstructure. The package names forming part of this structure are separated by usingdot (.) operator. For example, consider this statement.
This package must be stored in mypackage1/mypackage2 directory.By using multileveled package statement, the packages which are related to eachother can be grouped into a single package.
Packages
NOTES
Self-Instructional122 Material
If a Java package contains multiple classes, only one of them can be declaredas public and the source file is saved with the name of public class having.javaextension. When a source file having multiple class definitions is compiled,the compiler creates separate .class file for each class.Example 6.2: A program to demonstrate the creation of a package
Save this file as SimplePackage.java under the directory calledmypackage and compile this file. Now the file can be executed using commandline as follows:
We cannot execute it using the command line java SimplePackagebecause SimplePackage is now a part of the mypackage package.
6.8.1 Accessing Packages
The user-defined packages are accessed in the same way as Java standardpackages. For example, to access a class MyClassName of a package namedmypackage1, following statements can be used.
Packages
NOTES
Self-InstructionalMaterial 123
Here, if statement 1 is used, all the members of MyClassName can bedirectly accessed without having to use the package name anywhere in the program.The asterisk (*) in statement 2 specifies that whenever the compiler has to findany class, it should search it in the package mypackage1. This allows all theclasses of this package to be accessed directly. The main advantage of this approachis that the long package names need not be used repeatedly in the program.However, the disadvantage is that it becomes difficult to identify the package towhich a particular member belongs.
6.9 USING PACKAGES
Once the required package is imported in the program, the classes belonging tothat package can be used. To understand the concept of using the package, firstlet us create a package mypackagename1.Example 6.3: A program to create mypackagename1
public void firstresult()
Save the source file as MyClassName1.java in the subdirectorymypackagename1. After compiling this file, the corresponding compiled fileMyClassName1.class will be stored in the same directory.Example 6.4: A program to demonstrate the use of packagemypackagename1
MyClassName1 obj=new MyClassName1();
The output of the program is
Now, consider another package mypackagename2.
Packages
NOTES
Self-Instructional124 Material
Example 6.5: A program to create mypackagename2
Example 6.6: A program to demonstrate importing multiple packages
The output of the program is
When multiple packages are imported, there is a chance of having morethan one package containing classes with the same name. For example, considerthe definitions of two packages packagename1 and packagename2 havingthe same class name FirstClass as shown here.Example 6.7: A program to create packagename1
Packages
NOTES
Self-InstructionalMaterial 125
Example 6.8: A program to create packagename2
Since both the packages contain the class FirstClass, the compilerwill not be able to decide which package to use thereby causing an ambiguity. Insuch case, the class name must be preceded with the name of the package whilecreating the objects of the concerned class.Example 6.9: A program to demonstrate importing multiple packages havingclasses with same name
The output of the program is
In this example, the class FirstClass in the package packagename1has the same name as the class in the package packagename2. While creating
Packages
NOTES
Self-Instructional126 Material
the objects of the classes of each package, the class name is preceded by theirrespective package names thereby causing no ambiguity.
6.10 ADDING A CLASS
A new class can be added to an already existing package. For example, considera package calledmypackage whose definition is as follows:
The package mypackage contains a public class MyClass1. Now,suppose we want to add another class MyClass2 to this package. As statedearlier, a package cannot have more than one public class. If MyClass2 is non-public, then, simply we can add its definition to the same source file as follows:
Then recompile this source file. The MyClass2.class file is createdand stored automatically in the package mypackage. Now, mypackagecontains two classes MyClass1 and MyClass2.
However, if the class MyClass2 is a public class, then we need tocreate this class in a separate source file and declare the package statement at thetop of the source file as shown here.
Compile this source file. The package mypackage will now containMyClass2.class file also. Thus, if we want to create multiple public classesin a package, it is required to create a separate source file for each class andcompile them. After compilation, the package will contain .class files of allthe source files.
Packages
NOTES
Self-InstructionalMaterial 127
Check Your Progress
3. What should be done to create a user defined package?4. How is the ClassName.class file created and where is it stored?
6.11 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. The variables in an interface are by default static and final.2. A package is a named collection of classes.3. To create a user-defined package, first a package must be declared using
the keyword package followed by the name of the package.4. When the Java compiler compiles the source file, the ClassName.class
file is created and automatically stored in the same directory packagename.
6.12 SUMMARY
Java provides an approach known as interface as a convenient alternativeto implement multiple inheritance.
An interface is just like a class. The difference between an interface and aclass is that an interface contains only final variables and the methoddeclarations.
An interface is defined just like a class but rather than using the keywordclass, the keyword interface is used. One or more classes canimplement the interface by using the keyword implements in the classdefinition.
All the methods must be implemented by the class which implements theinterface. If a class that implements the interface does not provide completeimplementation of the methods declared in the interface, then it is necessaryfor the class to be declared as abstract.
An interface can inherit another interface by using extends keyword inthe same way as a class inherits from another class.
A package is a named collection of classes. Any number of related classescan be grouped into a single package. The classes which belong to a packageof another program can be easily reused. Two classes in two differentpackages can have the same name.
Java packages are categorized into two types, namely, API packages anduser-defined packages. Application Programming Interface (API) packagesare the standard packages available in Java which contain all of the standard
Packages
NOTES
Self-Instructional128 Material
classes. Java also allows the user to create our own package known asuser-defined packages.
Some of the quite frequently used packages are java.lang, java.io,java.awt, java.applet, java.util and java.sql.
There are certain Java naming conventions using which packages can benamed. The names of the packages and classes or interfaces should besuch that it is easier to distinguish between the two. According to theconventions, the name of the packages starts with a lowercase letter whereasthe name of the classes begins with an uppercase letter.
To create a user-defined package, first a package must be declared usingthe keyword package followed by the name of the package. The packagestatement must be the first statement in the Java source file. Once thepackage is declared, we can define any number of classes which will be thepart of this package.
If a Java package contains multiple classes, only one of them can be declaredas public and the source file is saved with the name of public classhaving .javaextension. When a source file having multiple class definitionsis compiled, the compiler creates separate .class file for each class.
Both the API packages and user-defined packages can be accessed usingthe import statement. Once the required package is imported in theprogram, the classes belonging to that package can be used.
6.13 KEY WORDS
Interface: It is a reference type, similar to a class that can contain onlyconstants, method signatures and nested types.
Partial implementation: It is a situation where the interface does notprovide complete implementation of the methods declared in the interfaceand is necessary for the class to be declared as an abstract.
Package: It is a named collection of classes. API packages: They are the standard packages available in Java which
contain all the standard classes.
6.14 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. Write a short note on partial implementation.2. State the difference between an interface and an abstract class.
Packages
NOTES
Self-InstructionalMaterial 129
3. What are the advantages of using a package?4. List the steps for creating a package. How do you access a particular package
in your file?
Long Answer Questions
1. Which of the following will generate an error and why?
2. Consider the following code.
Packages
NOTES
Self-Instructional130 Material
Will the code compile successfully? Justify your answer.3. ‘Java supports the concept of multiple inheritance through interface’. Explain
in detail with an example.4. Consider a program to import a package person with all its classes. Identify
and correct the error, if any.
5. Explain the steps for creating multiple public classes in a single package.
6.15 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Introduction to Thread
NOTES
Self-InstructionalMaterial 131
BLOCK - IIIMULTITHREADED PROGRAMMING
UNIT 7 INTRODUCTION TOTHREAD
Structure7.0 Introduction7.1 Objectives7.2 Overview of Multithreading
7.2.1 Main Thread7.3 Creating a Thread
7.3.1 Extending the Thread Class7.3.2 Implementing Runnable Interface
7.4 Thread Life Cycle7.5 The Thread Control Methods
7.5.1 Using yield(), sleep() and stop() Method7.5.2 Using isAlive() and join() Method
7.6 Answers to Check Your Progress Questions7.7 Summary7.8 Key Words7.9 Self Assessment Questions and Exercises
7.10 Further Readings
7.0 INTRODUCTION
Most of the modern operating systems support multitasking which is the ability toexecute multiple programs simultaneously. Java’s multithreadingis a specializedform of multitasking. Multithreading is a programming concept in which a program(process) is divided into two or more subprograms (subprocesses), each of whichcan perform different tasks concurrently. For example, one subprogram can formattext in the text editor while another subprogram can print the same. This unit willdiscuss multithreading in Java in detail.
7.1 OBJECTIVES
After going through this unit, you will be able to: Understand what is thread and what is the concept of multithreading in Java Explain the difference between a single-threaded program and a
multithreaded program Discuss different ways of creating a thread Describe the complete life cycle of a thread
Introduction to Thread
NOTES
Self-Instructional132 Material
Explain various thread control methods Explain thread priority Discuss what is synchronization and different ways of synchronizing a thread
7.2 OVERVIEW OF MULTITHREADING
A thread is just like a program which has a single flow of control. It also has astarting point, the execution part and an end. The main programs in the precedingexamples can be called single-threaded programs. Java also allows us to usemultiple flows of control in a program and such a program is known asmultithreaded program. In a multithreaded program, each thread is a separatetiny module which runs in parallel with other threads. Running in parallel does notmean that they are running at the same time. As most of the time the threads run onthe single processor, in reality, only one thread is executed at a given time. However,the switching from one thread to another thread occurs so fast that it gives anillusion to the user that all the threads are being executed at the same time. Threadsare called lightweight processes. This is because all the threads in a main applicationprogram share the same address space in the memory.
There are several advantages of using multithreaded programs over single-threaded programs. In a traditional single-threaded environment, the CPU sitsidle most of the time, as the program has to wait for each of the task to completebefore proceeding to the next task. In multithreaded environment, since differenttasks can be assigned to different threads, the program makes maximum utilizationof the CPU, keeping the idle time of the CPU to minimum. For example, onethread can read data, another thread can process it and a third thread can write itthus improving the overall performance. Multithreading is best-suited for thoseapplications that require multiple tasks to be done simultaneously.
7.2.1 Main Thread
Java program always contains at least one thread even if we do not create one.This thread is called main thread and it is the one which immediately starts executingwhen we start a program. The main thread can be used to create and start otherchild threads and it must often be the last thread to finish execution because itperforms various other actions such as, shutdown action and releasing resourceswhich are used by the program. The main thread is created automatically but it canbe controlled through a Thread object. For this, its reference is needed whichcan be obtained by calling the method currentThread(), which is a publicstatic member of Thread class. This method returns a reference to the threadon which it is called. We can control the main thread just like any other thread,once we have a reference to it.Example 7.1: A program to control the main thread
Introduction to Thread
NOTES
Self-InstructionalMaterial 133
The output of the program is as follows:
In this example, the method currentThread() is called to obtain areference to the main thread and this reference is stored in the variable th. Here,the name of the main thread is changed by calling the method setName() andthe new thread name is redisplayed.
7.3 CREATING A THREAD
In Java, threads can be created in two ways which are as follows: By defining a class that extends the Thread class. By implementing the Runnable interface.
In both the approaches, threads are implemented in the form of objectswhich contain a method called run(). It is the most important method in theThread class. It is the entry point of a new thread and it is the place where thetask to be performed by the thread is defined. The execution of a thread startswith the call to run() method. The run() method is automatically invokedwhen we invoke another method of Thread class called start().
7.3.1 Extending the Thread Class
You can create a thread by creating a new class that extends the Thread classdefined in java.lang package and creating an instance of the class. Theextending class must override the run() method. Inside the run() method,the code that needs to be executed by the thread will be defined.
Introduction to Thread
NOTES
Self-Instructional134 Material
The code segment used to extend the Thread class and override therun() method is as follows:
Now the instance of the class ThreadName can be created and runusing the following statements:
The second statement invokes the start() method after which the threadwill be ready to run. It will start running once the Java runtime invokes its run()method.Example 7.2: A program to demonstrate creating threads by extending theThread class
Introduction to Thread
NOTES
Self-InstructionalMaterial 135
The output of the program is as follows:
Introduction to Thread
NOTES
Self-Instructional136 Material
When you start the program, the main thread immediately starts running.The main thread then starts two child threads Thread1 and Thread2, bothof which will perform different tasks. Once the main thread reaches the end of themain() method, there will be altogether three threads running concurrently ontheir own in the program, Thread1, Thread2 and the main thread. Thesethree threads will run independently whenever CPU is available to them. There isno specific order of their execution. Hence, the program may generate differentoutput every time we run it.
7.3.2 Implementing Runnable Interface
Another way of creating a thread is to create a class that implements theRunnable interface. The Runnable interface consists of a single methodrun() which is required for implementing thread. We will create a thread andpass the object of the class that implements the Runnable interface as an argumentof the Thread class’s constructor. The thread will now be activated by callingthe start() method. Implementing Runnable is much more convenientthan extending a Thread class when a program needs to inherit from a classapart from the Thread class since Java allows only a single base class.The code segment used to implement Runnable interface is as follows:
Example 7.3: A program to demonstrate creating threads by implementingRunnable interface
Introduction to Thread
NOTES
Self-InstructionalMaterial 137
The output of the program is as follows:
In this example, MyNewThread is a class which implements theRunnable interface. Inside the main() method, an instance runnableobjof MyNewThread is created which is passed as an argument to the Threadclass’s constructor. When the new thread starts, the run() method ofrunnableobj is called.
Introduction to Thread
NOTES
Self-Instructional138 Material
Check Your Progress
1. What does the Runnable interface consist of?2. What happens when a new thread starts?
7.4 THREAD LIFE CYCLE
There are various states that a Java thread can enter during its life cycle. They arenewborn, runnable, running, blocked and dead state. A thread is always in oneof these five states. The thread can transit from one state to another as shown inthe Figure 7.1.
NewbornBlocked
Dead
stop() stop()
stop()
start()
suspend() sleep()
wait()
resume()
Running
Runnable
yield()
notify()
Fig. 7.1 Life Cycle of a Thread
Newborn State (Newly created Threads)
When a thread is created, it enters a state called newborn state. It is the first statein the life cycle of a thread in which the thread is just newly born and it is not yetready to run. That is, the thread is considered not active. During this stage, we caneither schedule the thread for running by calling the start() method or kill itusing stop() method. We cannot use any other method in the newborn stateotherwise it will throw exception.
Runnable State
The thread enters the runnable state when it is ready to run and waiting for theCPU to be allocated to it. Whenever a thread is ready to run, it is placed in thequeue of threads that are waiting for the availability of the CPU. The threadscheduler picks one of the threads in the queue based on their priority. If all thethreads in the queue have equal priority, the scheduler gives time slots for executionin round robin fashion. A thread can voluntarily give up its turn and give the control
Introduction to Thread
NOTES
Self-InstructionalMaterial 139
to another thread of equal priority using a static method called yield(). It thenjoins the queue at the end and waits for its turn to come.
Running State
A thread is said to be in the running state when it gets the processor for execution,that is, when the thread scheduler picks it to be the currently executing thread. Thethread will be executed by the processor and will keep running until it gets preemptedby a thread of higher priority or it gives up the control in either of the followingconditions:
When being suspended using suspend() method: If you want tosuspend a thread for sometime but do not want to kill it, then we can use thesuspend() method. The suspended thread can be brought back to theexecution state by invoking a method called resume().
When it is made to sleep using sleep() method: The sleep()method makes the thread sleep for the specified period of time. The threadwill automatically return back to its execution state once the specified timeis elapsed.
When it is made to wait using wait() method: A thread can be madeto wait until some events occur by calling wait() method. We can makethe thread run again by using the notify() method.
Blocked State
A thread is in blocked state when the thread is either suspended, or sleeping orwaiting. The thread in this state is not considered dead, so it can re-enter therunnable state and subsequently run if the CPU is available.
Dead State
A thread is said to be in dead state if its run() method completes or it has beenkilled deliberately by invoking the stop() method at any state. Once a threadenters the dead state, it cannot re-enter any other state even if the start()method is invoked.Note: The predefined methods stop(), suspend() and resume() have been deprecatedfrom the later versions of Java. It is discussed in detail in the later section.
7.5 THE THREAD CONTROL METHODS
You have seen the usage of start() and run() method. There are variousother methods of Thread class. They are yield(), sleep(), stop(),isAlive() and join() method.
7.5.1 Using yield(), sleep() and stop() Method
The yield(), sleep() and stop() methods are responsible for controllingthe behavior of a thread and the transition of thread from one state to another.
Introduction to Thread
NOTES
Self-Instructional140 Material
The general form of sleep() method is as follows:
where, milliseconds is the number of milliseconds to suspend. Asthe sleep() method throws an exception, the call to sleep() method mustbe enclosed in a try block followed by a catch block otherwise the programwill not compile.
The general form of stop() method is as follows:
The general form of yield() method is as follows:
Example 7.4: A program to demonstrate the use of yield(), sleep() andstop() method
Introduction to Thread
NOTES
Self-InstructionalMaterial 141
Introduction to Thread
NOTES
Self-Instructional142 Material
The output of the program is as follows:
Main thread exiting
In this example, although Thread1 started first, it relinquishes its controlafter implementing the while loop only two times, as the yield() method isinvoked. Thread2 starts running and it is killed by invoking the stop() method.Thread3 while running goes to sleep for 1000 milliseconds on the invocation ofsleep() method.
Introduction to Thread
NOTES
Self-InstructionalMaterial 143
7.5.2 Using isAlive() and join() Method
As stated earlier, the main thread must often be the last thread to terminate since itperforms several other tasks. For this, you can invoke sleep() method withinmain() method as in the Example 7.4 which makes the main thread sleep forspecified period of time until all the child threads complete their execution. However,it is not considered a good approach as the main thread has no information whena child thread will finish its execution. In this case, the main thread has to sleep fora period long enough to assure the termination of child threads prior to its termination.For example, if the main thread is made to sleep for 2500 milliseconds and thechild threads altogether take 1000 milliseconds to terminate, then there will be adelay of 1500 milliseconds for the main thread to terminate. Thus, it is necessaryfor the main thread to know when the child threads have finished. There are twoways to determine whether a thread has ended. These are as follows:
First, we can call isAlive() method. The general form of isAlive()method is
This method is used to test whether a thread is still alive. It returns true ifthe thread is running, otherwise it returns false. The isAlive() methodis used occasionally.
The method which is more commonly used to wait for a thread to finish isjoin() method. The general form of join() method is
This method is used to halt the execution of current thread (calling thread)until the thread on which the method is called terminates. It ensures that thecurrent thread will wait until the called thread finishes its execution. There isanother form of join() method which takes the parameter inmilliseconds which is the maximum amount of time that a threadcan wait for the specified thread to terminate. As the join() methodthrows an exception, it must be enclosed in a try block followed by acatch block.
Example 7.5: A program to demonstrate the use of isAlive() and join()methods
Introduction to Thread
NOTES
Self-Instructional144 Material
Introduction to Thread
NOTES
Self-InstructionalMaterial 145
The output of the program is as follows:
Introduction to Thread
NOTES
Self-Instructional146 Material
Note that the join() method is called on the child threads Thread1and Thread2 to ensure that the main thread waits for these child threads tofinish.
Check Your Progress
3. What happens whenever a new thread is ready to run?4. When is a thread said to be in blocked state?
7.6 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. The Runnable interface consists of a single method run() which isrequired for implementing thread..
2. When a new thread starts, the run() method of runnableobj iscalled.
3. Whenever a thread is ready to run, it is placed in the queue of threads thatare waiting for the availability of the CPU.
4. A thread is in blocked state when the thread is either suspended, or sleepingor waiting.
7.7 SUMMARY
A thread is just like a program which has a single flow of control. It also hasa starting point, the execution part and an end.
The main programs in the preceding examples can be called single-threadedprograms.
Threads are called lightweight processes. This is because all the threads ina main application program share the same address space in the memory.
In a traditional single-threaded environment, the CPU sits idle most of thetime, as the program has to wait for each of the task to complete beforeproceeding to the next task.
Introduction to Thread
NOTES
Self-InstructionalMaterial 147
In multithreaded environment, since different tasks can be assigned todifferent threads, the program makes maximum utilization of the CPU,keeping the idle time of the CPU to minimum.
Java program always contains at least one thread even if we do not createone. This thread is called main thread and it is the one which immediatelystarts executing when we start a program.
The main thread is created automatically but it can be controlled through aThread object.
You can create a thread by creating a new class that extends the Threadclass defined in java.lang package and creating an instance of the class.
When you start the program, the main thread immediately starts running. The main thread then starts two child threads Thread1 and Thread2, both
of which will perform different tasks. Once the main thread reaches the end of the main() method, there will be
altogether three threads running concurrently on their own in the program,Thread1, Thread2 and the main thread.
Another way of creating a thread is to create a class that implements theRunnable interface.
Implementing Runnable is much more convenient than extending a Threadclass when a program needs to inherit from a class apart from the Threadclass since Java allows only a single base class.
When a thread is created, it enters a state called newborn state. It is the firststate in the life cycle of a thread in which the thread is just newly born and itis not yet ready to run.
If all the threads in the queue have equal priority, the scheduler gives timeslots for execution in round robin fashion.
A thread can voluntarily give up its turn and give the control to anotherthread of equal priority using a static method called yield().
A thread is said to be in the running state when it gets the processor forexecution, that is, when the thread scheduler picks it to be the currentlyexecuting thread.
A thread is in blocked state when the thread is either suspended, or sleepingor waiting. The thread in this state is not considered dead, so it can re-enterthe runnable state and subsequently run if the CPU is available.
7.8 KEY WORDS
Suspend() method: If you want to suspend a thread for some time butdo not want to kill it, then we can use the suspend() method.
Introduction to Thread
NOTES
Self-Instructional148 Material
Sleep() method: It method makes the thread sleep for the specifiedperiod of time.
Dead State: A thread is said to be in dead state if its run() methodcompletes or it has been killed deliberately by invoking the stop() methodat any state.
7.9 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. How are threads created?2. Write a short note on extending the thread class.3. How can you stop a thread?4. Why is multithreading best-suited for those applications that require multiple
tasks to be done simultaneously?
Long Answer Questions
1. Explain in detail how are threads created by defining class and implementingRunnable interface? Also show a diagrammatic representation of the threadlife cycle.
2. Discuss the thread control methods in detail.3. Write a program to demonstrate the use of yield(), sleep() andstop() method.
4. Write a program to demonstrate the use of isAlive() and join()methods.
5. Discuss the functionality of running state, blocked state and dead state inthread life cycle.
7.10 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Thread Exceptions
NOTES
Self-InstructionalMaterial 149
UNIT 8 THREAD EXCEPTIONS
Structure8.0 Introduction8.1 Objectives8.2 Threads Priority8.3 Thread Synchronization
8.3.1 Synchronizing Methods8.3.2 Synchronizing Statements8.3.3 Deadlock
8.4 Answers to Check Your Progress Questions8.5 Summary8.6 Key Words8.7 Self Assessment Questions and Exercises8.8 Further Readings
8.0 INTRODUCTION
A thread is like a program which has a single flow of control. It has a starting point,the execution part and an end. The main programs in the preceding examples canbe called single-threaded programs. Java also allows us to use multiple flows ofcontrol in a program and such a program is known as multithreaded program. In amultithreaded program, each thread is a separate tiny module which runs in parallelwith other threads. Running in parallel does not mean that they are running at thesame time. As most of the time the threads run on the single processor, in reality,only one thread is executed at a given time. However, the switching from onethread to another thread occurs so fast that it gives an illusion to the user that all thethreads are being executed at the same time. Threads are called lightweightprocesses. In this unit you will learn about thread exceptions.
8.1 OBJECTIVES
After going through this unit, you will be able to: Understand thread exceptions Discuss the priorities of thread Explain about thread synchronization Discuss the methods of synchronization
Thread Exceptions
NOTES
Self-Instructional150 Material
8.2 THREADS PRIORITY
The threads you have seen so far are of equal priority in which the Java schedulerselects the thread for execution on the first-come, first-serve basis. However,each thread can be assigned different priority which will decide the order in whichit is scheduled for running. Priorities are the integers which specify the relativepriority of one thread to another. When a thread is created, it inherits its priorityfrom the thread that created it. However, the priority of a thread can be changedby using the setPriority() method of the Thread class.
The syntax to set the priority of a thread is as follows:
where, n is an integer value which ranges from MIN_PRIORITY (1)and MAX_PRIORITY (10). The default priority is NORM_PRIORITY whosevalue is 5. MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITYare the constants defined in Thread class.
When there are multiple threads ready to execute, the highest priority threadis chosen and executed. Only when the high priority thread stops, yields or entersblocked state, the low priority thread starts running. However, if any higher prioritythread enters, it will preempt the currently running thread forcing it to move to therunnable state.Example 8.1: A program to demonstrate the assigning of priority to a thread
Thread Exceptions
NOTES
Self-InstructionalMaterial 151
The output of the program is as follows:
Thread Exceptions
NOTES
Self-Instructional152 Material
The first child thread Thread1 has been assigned the minimum priorityand the second child thread Thread2 has been assigned the maximum priority.So despite Thread1 being the first on which start() method is called, itsoutput is printed in the last as it has been preempted by the higher priority threadThread2.Note: The amount of CPU time a thread gets depends not only on its priority but also onother factors such as how an operating system implements multithreading.
8.3 THREAD SYNCHRONIZATION
When multiple threads need access to a single resource, there must be a way toensure that only one thread will use the resource at any given point of time otherwiseit may lead to a severe problem. For example, if one thread in a program readssalary from a file and another thread tries to update it, then the program mayproduce an undesirable output. The solution to this problem can be achieved byusing a technique known as synchronization. The objective of synchronization isto control the access to shared resources.
Synchronization uses the concept of monitor. A monitor is an object whichis used as a mutually exclusive lock. That is, it can be owned by only one thread atany given point of time. A thread is said to have entered the monitor when itacquires a lock. Any other thread which attempts to acquire the lock has to waituntil the first thread comes out of the monitor. There are two ways to implementsynchronization. These are as follows:
Synchronizing methods Synchronizing statements
8.3.1 Synchronizing Methods
You can synchronize a subset (or all) of the methods of any class by usingsynchronized keyword. When a method is declared synchronized,Java creates a monitor. To enter the monitor, you need to call a synchronizedmethod. Only one of the synchronized methods in a class object can execute atany given time. Java hands over the monitor to the thread that calls the methodfirst. As long as a thread is inside a synchronized method, other threads trying tocall it (or any other synchronized method) on the same instance have to wait. Onlywhen the currently executing thread finishes executing and exits the monitor anotherwaiting thread can enter the monitor.The syntax to declare a method as synchronized is as follows:
Thread Exceptions
NOTES
Self-InstructionalMaterial 153
To understand synchronization, let us first consider a program which is notsynchronized.Example 8.2: A program to demonstrate the need of synchronization
Thread Exceptions
NOTES
Self-Instructional154 Material
The output of the program is as follows:
The class A has a method named display() which takes a parametermsg of String type. This method will print the msg string enclosed in thefirst brackets. Note that, the sleep() method is invoked after the display()method prints the opening bracket and the string msg which causes the currentthread to halt for one second. The constructor of class MyThread takes twoarguments, a reference to an instance of class A and a string. When the firstthread starts, the object’s run() method is invoked. The run() method invokesthe display()method on the instance obj of A and passes the string str.The call to sleep() method allows execution to switch to another thread beforethe first thread could complete the method. Thus, the output of the program is notas expected and the strings are in mixed up form. This is because, the three threadscall the same method display() without anything to stop them from competingeach other to complete the method.
Now let us modify the program in Example 8.7 by preceding the definitionof display() method with synchronized keyword. This will serializeaccess to display() method by restricting its access to only one thread at atime thus producing the correct output.Example 8.3: A program to demonstrate synchronized method
Thread Exceptions
NOTES
Self-InstructionalMaterial 155
The output of the program is
Note: Once a thread is in synchronized method on an instance, no other thread can enter anyother synchronized method on the same instance. However, simultaneous execution ofsynchronized methods is possible for two different instance of the same class.
Thread Exceptions
NOTES
Self-Instructional156 Material
8.3.2 Synchronizing Statements
Another way of managing the execution of the thread is to synchronize a block ofcode or statement. This is more powerful. Synchronizing a method does not workin all cases. For example, the class we want to access is created by someone else,which does not have synchronized methods and we do not have access rights tomodify it. In this case, the access to objects of this class can be synchronized byplacing the call to the methods defined by this class inside a synchronized block.Two block of codes synchronized on the same instance cannot execute at thesame time.The general form to synchronize a block of code is as follows:
where,object is a reference to the object being synchronized.
Example 8.4: A program to demonstrate synchronized statement
Thread Exceptions
NOTES
Self-InstructionalMaterial 157
The output of the program is as folows:
By using the synchronized statement inside the run() method, access tothe object of the class A is restricted to only one thread at a time thus producingthe same correct output.
8.3.3 Deadlock
Deadlock is a situation that occurs when two or more threads are in a simultaneouswait state and each of them is waiting for the release of a resource held by one ofthe other waiting thread. For example, consider the following code segments.
Thread Exceptions
NOTES
Self-Instructional158 Material
First, Thread X starts and synchronizes on the object obj1 whichprevents other threads to call the methods of obj1. Thread X then goes tosleep by calling sleep() method and allows ThreadY to start. ThreadYstarts and synchronizes on the object obj2. This prevents method of obj2 tobe called by any other thread. Thread Y goes to sleep on the invocation ofsleep() method allowing Thread X to wake up. Thread X continuesexecution and tries to call method2() on obj2. But it cannot call the methodon obj2 until the code in Thread Y that is synchronized on obj2 finishesexecution. As Thread X cannot proceed, Thread Y gets the control andtries to call method1() on obj1 which is not possible until the code in ThreadX that is synchronized on obj1 finishes its execution. Here, neither of the threadscan continue because they are deadlocked.Example 8.5: A program to demonstrate deadlock.
Thread Exceptions
NOTES
Self-InstructionalMaterial 159
Thread Exceptions
NOTES
Self-Instructional160 Material
The output of the program is as follows:
In this example, the thread Thread1 owns the monitor on obj1 andwaits for the monitor on obj2. Similarly, the thread Thread2 owns the monitoron obj2 and waits for the monitor on obj1. Thread1 will never releaseobj1 unless it gets hold of obj2 and Thread2 will never release obj2unless it gets obj1. The program will never complete as the two threads are inthe deadlock situation. We need to press CTRL-C to end the program.
Thread Exceptions
NOTES
Self-InstructionalMaterial 161
Check Your Progress
1. What is a monitor?2. Which concept does synchronization use?3. When does a deadlock condition arises?
8.4 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. A monitor is an object which is used as a mutually exclusive lock.2. Synchronization uses the concept of monitor.3. Deadlock is a situation that occurs when two or more threads are in a
simultaneous wait state and each of them is waiting for the release of aresource held by one of the other waiting thread.
8.5 SUMMARY
Priorities are the integers which specify the relative priority of one thread toanother. When a thread is created, it inherits its priority from the thread thatcreated it.
When there are multiple threads ready to execute, the highest priority threadis chosen and executed.
Only when the high priority thread stops, yields or enters blocked state, thelow priority thread starts running.
When multiple threads need access to a single resource, there must be away to ensure that only one thread will use the resource at any given pointof time otherwise it may lead to a severe problem.
Synchronization uses the concept of monitor. A monitor is an object whichis used as a mutually exclusive lock.
Deadlock is a situation that occurs when two or more threads are in asimultaneous wait state and each of them is waiting for the release of aresource held by one of the other waiting thread.
A thread is said to have entered the monitor when it acquires a lock. You can synchronize a subset (or all) of the methods of any class by usingsynchronized keyword. When a method is declared synchronized,Java creates a monitor.
The class A has a method named display() which takes a parametermsg of String type.
Thread Exceptions
NOTES
Self-Instructional162 Material
Once a thread is in synchronized method on an instance, no other threadcan enter any other synchronized method on the same instance.
Another way of managing the execution of the thread is to synchronize ablock of code or statement.
8.6 KEY WORDS
Deadlock: It is a situation that occurs when two or more threads are in asimultaneous wait state and each of them is waiting for the release of aresource held by one of the other waiting thread.
Synchronizing Statements: It is a way of managing the execution of thethread is to synchronize a block of code or statement.
8.7 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. Write a program to demonstrate the assigning of priority to a thread class.2. What do you mean by thread priority?3. Discuss MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY.4. Write about synchronization methods and synchronization statements.
Long Answer Questions
1. If one thread in a program reads salary from a file and another thread triesto update it, then the program may produce an undesirable output. Thesolution to this problem can be achieved by using a technique known assynchronization. Discuss this in detail.
2. If the class we want to access is created by someone else, which does nothave synchronized methods and we do not have access rights to modify it.In this case, how can the access to objects of this class be synchronized?Discuss.
3. Write a program to demonstrate deadlock.4. Write a program to demonstrate synchronized statement class A?
8.8 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Thread Exceptions
NOTES
Self-InstructionalMaterial 163
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Exceptions
NOTES
Self-Instructional164 Material
BLOCK - IVMANAGING ERROR, EXCEPTION AND APPLETS
UNIT 9 EXCEPTIONS
Structure9.0 Introduction9.1 Objectives9.2 Types of Errors
9.2.1 Exceptions9.3 Exception Handling
9.3.1 Syntax of Exception Handling Code (Using try and catch blocks)9.3.2 Multiple catch Statements9.3.3 Using finally Statement9.3.4 Using throw Keyword9.3.5 Using throws Keyword
9.4 Creating User-defined Exceptions9.5 Answers to Check Your Progress Questions9.6 Summary9.7 Key Words9.8 Self Assessment Questions and Exercises9.9 Further Readings
9.0 INTRODUCTION
The main concern of programmers while developing any program is to write anerror-free code. The presence of single error in the program may result in manyundesirable situations like unintended results may be produced, an abrupt terminationof program may occur or in the extreme case the system may crash. To avoidthese unwanted occurrences, the errors in the program code must be detectedand handled in a proper manner so that the program produces the expected output.
This unit will discuss the different types of errors and exceptions that canoccur in programs. It will also discuss the exception handling mechanism of Java.
9.1 OBJECTIVES
After going through this unit, you will be able to: Define an exception or run-time error in a program Understand how an exception is handled by Java’s default exception handler Name some common exceptions found in Java
Exceptions
NOTES
Self-InstructionalMaterial 165
Explain how system generated exception are thrown and caught in Javausing try and catch blocks
Learn about the significance of finally keyword in Java Know the use of throw and throws keywords in Java Create your own exception in Java
9.2 TYPES OF ERRORS
When a program is written for the first time it usually contains errors. These errorsare mainly classified into two types; compile-time errors and run-time errors.The compile-time errors occur due to syntactical errors, like missing semicolons,missing brackets, miss spelt keywords, use of undeclared variables and so on.These errors can be detected and removed by exhaustive testing and debugging.Unlike compile-time errors, run-time errors are difficult to detect and trap. Theymay occur due to problems in arithmetic calculations like dividing by zero, tryingto access an out-of-bound array element, converting invalid string to a numberand so on. These run-time errors are usually referred to as exceptions.
9.2.1 Exceptions
The term exception is an abbreviation for the phrase ‘exceptional event’. It is anunpredicted event that occurs while the program is executing and thus disrupts thenormal flow of the program or terminates the program abnormally. The errors thatcause exception can range from simple programming errors such as opening orreading an invalid file or accessing an invalid index of an array to severe errorssuch as running out of memory.
When an error occurs within a method, Java runtime system creates anexception object. This exception object contains information about the exceptionwhich includes its type and the state of the program when the error occurred.Once an exception object is created, it is thrown and the runtime system searchesfor a method to handle the exception. It keeps on searching for a method thatcontains an appropriate exception handler. An exception handler is consideredappropriate if the type of exception handled by the handler is same as the type ofexception thrown.
Before understanding the significance of exception handling mechanism, youmust know what happens if an exceptions is not handled. The following exampleillustrates this.Example 9.1: A program to demonstrate an unhandled exception
Exceptions
NOTES
Self-Instructional166 Material
In this program, no compile-time error occurs. However, when the divisionby zero statement is executed a run-time error is generated. At this point, Javaruntime system creates an exception object and throws it. This thrown objectexpects an exception handler to handle it. Since no exception handler has beenprovided in this program, Java’s default exception handler is invoked. The defaultexception handler will display the following error message and terminate theprogram abruptly.
Types of Exceptions
Java provides several built-in classes which define all types of exceptions. Theseexception classes are arranged in a hierarchy having Throwable class on thetop (see Figure 9.1). This means that, the Throwable class is the superclassand all the exception classes inherit methods defined by it.Two immediate subclassesof the Throwable class are Exception class and Error class. Thesecan be defined as follows:
Exception class: It defines those exceptions which are thrown bymethods of standard Java class library or methods defined in users’programms. These can be trapped within the program and the programcan reasonably recover from them. This class is also used (inherited)when the users want to create their own exceptions in the application.
Error class: It defines those exceptions that do not occur frequentlyand are difficult to be recovered from. For example, a class file is missingor system runs out of memory.
Error
Throwable
Exception
Fig. 9.1 Java Exception Hierarchy
Some of the most commonly occuring exceptions that will be encounteredare listed in Table 9.1.
Exceptions
NOTES
Self-InstructionalMaterial 167
Table 9.1 Some Common Exceptions in JavaException Description
ArithmeticException thrown when arithmetic error occurs in the program such as divide-by-zero.
NullPointerException thrown when the user tries to use an object without initializing the object or in other words when an object that has not been allocated memory is used.
IOException thrown when error occurs during input/output of data.
ArrayIndexOutOfBoundsException thrown when an attempt is made to access an array element with invalid index value.
ArrayStoreException thrown when an attempt is made to store the incompatible type of data in an array.
IllegalAccessException thrown when an illegal attempt is made to access a class.
NumberFormatException thrown when an invalid conversion of a string to a numeric format takes place.
StringIndexOutOfBoundsException thrown when an attempt is made to access a string element that is beyond the index of the string.
IllegalArgumentException thrown when an illegal argument is used to invoke a method.
NegativeArraySizeException thrown when an array of negative size is created.
9.3 EXCEPTION HANDLING
Java exception handling mechanism, not only, guarantees the detection and handlingof run-time errors, but also provides a way to separate the error-handling codefrom the rest of the program. This makes the program less complex, more readableand efficient, as the normal execution path is not interrupted for checking errors.Moreover, the exception handling routine (called exception handler) is invokedautomatically whenever an error occurs.
Java exception handling is governed by the following five keywords. try catch
finally
throw throws
A set of statements that needs to be monitored for the exceptions is containedin the try block. Whenever an exception occurs within the try block, it isthrown. This passes the control to the catch block which handles the exceptionappropriately. Java runtime system automatically throws system generatedexceptions. If the user wants to throw the exception explicitly, throw keywordis used. Sometimes, a method may throw exceptions which it cannot handle; this
Exceptions
NOTES
Self-Instructional168 Material
must be specified by using throws keyword. The code which must be executedwhether an exception is thrown or not is kept within the finally block, whichis optional.
9.3.1 Syntax of Exception Handling Code (Using try and catch blocks)
The default exception handler provided by Java runtime system does not preventthe abrupt termination of the program. To prevent this, Java provides the facility toconstruct user-defined exception handlers. By constructing user-defined exceptionhandlers, the users can fix the errors on their own. This can be achieved by enclosingthe code that may throw an exception within a try block. The try block isenclosed by curly braces and preceded by the keyword try. Whenever anexception occurs within the try block, it is thrown. This passes the control to thecatch block associated with the try block.
The syntax to define try-catch block is as follows:
If the first statement of the try block causes an exception, the remainingstatements are not executed and the control passes to the catch block. Thecatch statement requires single argument which is of the same type as of exceptionthat needs to be handled. This exception type must be a subclass of Throwableclass. It is not necessary that every time the program is executed, an exceptionoccurs. If an exception is not thrown, the catch block is skipped and the controlpasses to the statement immediately following the catch block.
The try and catch blocks form a logical unit. The scope of the catchblock is limited only to those statements which are enclosed within the immediatelypreceding try block.Note: Compile-time error is generated if the try statement is not followed by any catchstatement.
Example 9.2: A program to illustrate handling of an exception using try and catch blocks
Exceptions
NOTES
Self-InstructionalMaterial 169
The output of the program is as follows:
In this example, the exception generated within the try block is caughtinside the catch block thus, preventing the abnormal termination of the programas seen in Example 9.1.
9.3.2 Multiple catch Statements
It is not necessary that the code enclosed within the try block throws a singleexception. In case, multiple exceptions are thrown within a try block, Java allowsusing multiple catch statements for handling all these exceptions.
The syntax to define multiple catch blocks is
Exceptions
NOTES
Self-Instructional170 Material
Note that there is only one try block from which the exception is thrownand depending on the type of exception thrown, the corresponding catch blockwill be executed. Whenever an exception is thrown, the catch blocks aresearched in sequential order for an appropriate match. The first catch blockwhose parameter type matches with the type of exception gets executed andother catch blocks are ignored. Once the execution of the appropriate catchblock gets over, the control passes to the statement immediately following the lastcatch block.Example 9.3: A program to demonstrate the concept of multiple catchstatements
Exceptions
NOTES
Self-InstructionalMaterial 171
The output of the program is as follows:
In this program, the divide by zero error is caught by the second catchblock containing the instance of ArithmeticException class.
It should be noted that the exception superclasses must be placed after theirsubclasses. This is because if you place catch block containing the superclassbefore its subclasses then this superclass will handle all exceptions of its type aswell as of its subclasses. As a result, subsequent catch blocks will never getexecuted and compile-time error is generated. This problem is known asunreachable code problem.
In Example 9.3, if you place the Exception class beforeArithmeticException andArrayIndexOutOfBoundsException classes, then compiling thisprogram will display the following error message:
This happens because ArrayIndexOutOfBoundsExceptionclass and ArithmeticException class are the subclasses of Exceptionclass. Thus, Exception class catches all the thrown exception relative to theseclasses and their corresponding catch blocks are never executed.
Exceptions
NOTES
Self-Instructional172 Material
Note: The try block can also be nested, that is, one try-catch block can be placed insideanother try-catch block If an exception occurs within a particular try block, then thecatch blocks associated with the try block are searched for an appropriate match.
9.3.3 Using finally Statement
It has been observed that when an exception is thrown in the program, the remainingstatements in the try block are not executed and the control directly gets transferredto the subsequent catch block. However, there are certain statements in theprogram that need to be executed whether or not exception is raised. For this,Java provides finally keyword. The code within the finally block willalways be executed whether or not the exception is thrown. If an exception israised with a matching catch block, then the finally block gets executedafter the execution of that catch block. If no matching catch block is foundthen also the finally block is executed after the execution of the try block.The finally block is optional; however, it is necessary to include either catchor finally block with try block.
Figure 9.2 shows the flowchart of working of try-catch-finallyblock.
Execute try block
Find catch block to execute
Execute catch block for Exceptiontype2
Execute catch block for Exceptiontypen
Execute catch block for Exceptiontype1
…
…
Execute finally block
[exception]
[no exception]
[exception1] [exception2] [exceptionn]
Fig. 9.2 Try-Catch-Finally Block
Example 9.4: A program to illustrate the use of finally statement
Exceptions
NOTES
Self-InstructionalMaterial 173
The output of the program is as follows:
Here, the thrown exception is caught in the catch block and an appropriateerror message is displayed. After that, the statement within the finally blockis executed.
9.3.4 Using throw Keyword
As stated earlier, Java runtime system automatically throws system-generatedexceptions. However, Java provides a mechanism to throw an exception explicitlyby using the throw keyword.
The syntax of throw statement is
where,
Exceptions
NOTES
Self-Instructional174 Material
When a throw statement is encountered in the program, the execution ofthe subsequent statements in the try block stops and corresponding catchblock is searched. The nearest try block is checked to determine if it contains acatch block to match the exception of its type. If it is found, then that catchblock is executed else subsequent try blocks are inspected. In case, if no matchingcatch block is found, then the default exception handler comes into action andstops the normal execution of the program and displays the error message on theoutput screen.
It should be noted that instances of classes other than Throwable classor its subclasses cannot be used as exception objects. The Throwable objectcan be created using a new operator or using a parameter inside catch clause.
9.3.5 Using throws Keyword
Sometimes a method may generate an exception, but cannot handle it. This meansthat, there may be a method in the program which generates, (throwing) anexceptionsj, but it does not have the appropriate exception handing mechanism.The methods which are calling such methods must be cautioned about this behaviorso that calling methods can take appropriate measures to safeguard themselvesagainst the exceptions. This is done by appending throws keyword after methodname in the method declaration statement. The throws clause includes all typesof exceptions excluding those belonging to Error or Runtime classes or theirsubclasses. All other exceptions which a method may throw must be listed afterthe throws keyword in the method declaration; otherwise compile-time error isgenerated.
The syntax of the throws clause is as follows:
}
where,exception_list includes all the exceptions that the method might
throw
Check Your Progress
1. What does Java exception handling mechanism help with?2. How can the Throwable object be created?
9.4 CREATING USER-DEFINED EXCEPTIONS
The built-in exceptions provided by the Java platform are used to handle errorsoccurring in the program. But, sometimes the programmer wants to create his
Exceptions
NOTES
Self-InstructionalMaterial 175
own application specific exceptions. User-defined exceptions can be created simplyby defining a subclass of Exception class and using the throw keyword.Example 9.5: A program to demonstrate creation of user-defined exceptions
The output of the program is as follows:
Exceptions
NOTES
Self-Instructional176 Material
This example defines a subclass of Exception calledOwnException. Thus, this class will inherit the methods defined by theThrowable class through Exception class. The CreateOwnExceptionclass defines a method divide() which throws an object oe ofOwnException type when the denominator of the fraction is zero. TheprintStackTrace() method of the Throwable class is overridden todisplay the message which contains all the information that lead to the error, suchas the name of the method which caused the error, the name of the caller of themethod which lead to the error, the line number in which that error has occurred,etc.
Check Your Progress
3. What are built-in exceptions provided by Java platform used for?4. How can user-defined exceptions be created?
9.5 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. Java exception handling mechanism, not only guarantees the detection andhandling of run-time errors, but also provides a way to separate the error-handling code from the rest of the program.
2. The Throwable object can be created using a new operator or using aparameter inside catch clause.
3. The built-in exceptions provided by the Java platform are used to handleerrors occurring in the program.
4. User-defined exceptions can be created simply by defining a subclass ofException class and using the throw keyword.
9.6 SUMMARY
The errors in a program are mainly classified into two types, namely, compile-time errors and run-time errors.
The compile-time errors mostly occur due to syntactical errors, like missingsemicolons, missing brackets, miss spelt keywords, use of undeclaredvariables and so on.
Exceptions
NOTES
Self-InstructionalMaterial 177
Run-time errors may occur due to problems in arithmetic calculations likedivide by zero, trying to access an out-of-bound array element, convertinginvalid string to a number and so on. These run-time errors are usuallyreferred to as exceptions.
The term exception is an abbreviation for the phrase ‘exceptional event’. Itis an unpredicted event that occurs while the program is executing and thusdisrupts the normal flow of the program or terminates the programabnormally.
Java exception handling mechanism not only guarantees the detection andhandling of run-time errors but also provides a way to separate the error-handling code from the rest of the program.
Java exception classes are inherited by Throwable class. Java exception handling is governed by the five keywords, namely, try,catch, finally, throw and throws.
A set of statements that needs to be monitored for the exceptions is containedin the try block.
Whenever an exception occurs within the try block, it is thrown. Thispasses the control to the catch block associated with the try block.
In case multiple exceptions are thrown within a try block, Java allowsusing multiple catch blocks for handling all these exceptions.
The code within the finally block will always be executed whether ornot the exception is thrown.
Java provides a mechanism to throw an exception explicitly by using thethrow keyword.
Sometimes a method may throw exception which it cannot handle, thismust be specified using throws keyword.
Java allows the programmer to create user-defined exceptions simply bydefining a subclass of Exception class and using the throw keyword.
9.7 KEY WORDS
Exception: It refers to an unpredicted event that occurs while the programis executing, thus disrupting the normal flow of the program or terminatingthe program abnormally.
Run time error: It refers to an error that occurs during the execution of aprogram.
Compiler: It refers to a computer program that transforms human readablesource code of another computer program into the machine readable codethat a CPU can execute.
Exceptions
NOTES
Self-Instructional178 Material
9.8 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. What is an exception? What happens when an exception is not handled inJava?
2. What is exception handling mechanism? List five keywords which rule Javaexception handling.
3. What is the role of throw keyword? Explain.4. What is the significance of throws keyword in Java?5. What is unreachable code problem in Java?
Long Answer Questions
1. Explain Java exception hierarchy. What is the difference between instancesof Exception class and Error class?
2. Describe with an example, the significance of try-catch block in exceptionhandling.
3. ‘Once the control transfers to the catch block, it does not return to the tryblock to execute the remaining code.’ Justify the statement with an example.
4. Is it compulsory to include finally block in a program in Java? Justify youranswer.
5. Give an example of creating your own exception in Java.
9.9 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Graphics Programming
NOTES
Self-InstructionalMaterial 179
UNIT 10 GRAPHICSPROGRAMMING
Structure10.0 Introduction10.1 Objectives10.2 Working with Graphics
10.2.1 Using Graphics Class10.3 Line Graphs10.4 Control Loops in Applets10.5 Drawing Bar Charts10.6 Answers to Check Your Progress Questions10.7 Summary10.8 Key Words10.9 Self Assessment Questions and Exercises
10.10 Further Readings
10.0 INTRODUCTION
The Graphics class is the abstract super class for all graphics contexts which allowan application to draw onto components that can be realized on various devicesor onto off-screen images as well. A Graphics object encapsulates all stateinformation required for the basic rendering operations that Java supports.
Graphics hold an important role in Java. This unit will explain about graphicsprogramming. The graphics class, lines and rectangles, circles and eclipses, drawingarcs, polygons, graphs, bar charts have been explained in detail.
10.1 OBJECTIVES
After going through this unit, you will be able to: Explain how to work with graphics Discuss how to draw lines and fill rectangles Understand how to draw arcs and polygons Analyze the functionality of line graphs, and control loops in applets
10.2 WORKING WITH GRAPHICS
So far, you have learned how to create and run a simple Java applet. Java alsoallows creating applet that uses various classes to draw figures of different shapes,
Graphics Programming
NOTES
Self-Instructional180 Material
add images, display text in different fonts and styles, use and create various colors,etc. Some of these classes are discussed in this section.
10.2.1 Using Graphics Class
The Graphics class provides different methods to draw and fill various shapes.
Drawing Lines
A line can be drawn using the drawLine() method of the Graphics class.This method takes four parameters which represent the coordinates of the endpoints of the line.The general form of the drawLine() method is
where,a1, b1 is the coordinate of the starting points of the linea2, b2 is the coordinate of the starting points of the lineFor example, the statement gra.drawLine(20,100,90,100)
will draw a straight line from the coordinate point (20,100) to (90,100)as shown in Figure 10.1.
Fig. 10.1 A Straight Line Having Coordinates (20,100) and (90,100)
Drawing and Filling Rectangles
A rectangle can be drawn by using the drawRect() method. This methodalso takes the four parameters.
The general form of the drawRect() method is
where,a1, b1 is the coordinate of the top left corner of the rectanglew is the width of the rectangleh is the height of the rectangleFor example, the statement gra.drawRect(20,20,50,30) will drawa rectangle starting at (20,20) with width of 50 pixels and height of 30 pixelsas shown in Figure 10.2.
Graphics Programming
NOTES
Self-InstructionalMaterial 181
30 (height)
50 (width)
(20, 20)
Fig. 10.2 A Rectangle with Width 50 pixels and Height 30 pixels
Note that the drawRect() method draws only the boundary of therectangle. To draw a solid (filled) rectangle, fillRect() method is used. Thismethod also takes four parameters similar to the drawRect() method.
To draw a solid rectangle the having same parameters as above, you canuse the statement gra.fillRect(20,20,50,30) which draws therectangle as shown in Figure 10.3.
(20, 20)
30 (height)
50 (width)
Fig. 10.3 A Filled Rectangle with Width 50 pixels and Height 30 pixels
A rounded, outlined rectangle can be drawn by using the drawRoundRect()method. This method takes the six parameters.
The general form of the drawRoundRect() method is
w(width)
h(height )
xdia, ydia (arc)
(a1, b1)
Fig. 10.4 A Rounded Rectangle
where,xdia is the diameter of the rounding arc (along X-axis)ydia is the diameter of the rounding arc (along Y-axis)
Graphics Programming
NOTES
Self-Instructional182 Material
Similarly, a rounded filled rectangle can be drawn usingdrawfillRoundRect() method. This method also takes six parameters similarto the drawRoundRect() method.Note: All the shapes are drawn relative to the Java’s coordinate system. The origin (0, 0) ofthe coordinate system is located at its upper-left corner such that the positive x values are toits right and the positive y values are to its bottom.
Drawing and Filling Ellipses and Circles
An ellipse can be drawn using the drawOval() method. The ellipse is drawnwithin an imaginary bounding rectangle. This method takes four arguments in whichthe first two represent the top left corner of the bounding rectangle and the nexttwo represent the width and height of the oval or the bounding rectangle (seeFigure 10.5).The general form of the drawOval() method is
where,a1, b1 is the coordinate of the top left corner of the bounding rectangle.w is the width of the bounding rectangle.h is the height of the bounding rectangle.
height
width
Fig. 10.5 An Ellipse
Similarly, a circle can be drawn using this method but the dimension ofwidth and height should be the same. That is, the bounding rectangle must be asquare.
Similar to rectangle methods, the drawOval() method draws theboundary of an oval and the fillOval() method draws a solid oval.
Drawing Arcs
An arc can be drawn using the drawArc() method. This method takes sixarguments in which the first four are the same as the arguments of thedrawoval() method and the next two represent the starting angle of the arcand the sweep angle around the arc, respectively.The general form of the drawArc() method is
Graphics Programming
NOTES
Self-InstructionalMaterial 183
where,a1,b1 is the coordinate of the top left corner of the bounding rectangle.w is the width of the bounding rectangle.h is the height of the bounding rectangle.strt_angle is the starting angle of the arc (in degrees).sweep_angle is the number of degrees (angular distance) around the
arc (in degrees).The arc shown in Figure 10.6 has the starting angle as 00 degrees and
sweep angle as 1350.
0o
90o
180o
270o
135o
Arc
Fig. 10.6 An Arc of 1350 Sweep Angle
You can also draw filled arcs using the fillArc() method.
Drawing Polygons
A polygon is a closed geometrical figure, which can have any number of sides. Apolygon can be drawn by using the drawPolygon() method. This methodtakes the three parameters.The general form of the drawPolygon() method is
where,a[] is the array of integers having x-coordinates.b[] is the array of integers having y-coordinates.n is the total number of coordinate points required to draw a polygon.
(a1, b1) (a2, b2)
(a3, b3)
(a4, b4)(a5, b5)
(a6, b6)
Fig. 10.7 A Polygon with Six Sides
Graphics Programming
NOTES
Self-Instructional184 Material
Example 10.1: An applet code to demonstrate the use of various methods ofGraphics class
The HTML code for GraphicsExample is
Graphics Programming
NOTES
Self-InstructionalMaterial 185
The output of the HTML code is as follows:
Check Your Progress
1. What does the graphics class provide?2. How can a line be drawn?
10.3 LINE GRAPHS
A line graph, also known as a line chart, is a type of chart used to visualize thevalue of something over time. For example, a finance department may plot thechange in the amount of cash the company has on hand over time.
The line graph consists of a horizontal x-axis and a vertical y-axis. Most linegraphs only deal with positive number values, so these axes typically intersect nearthe bottom of the y-axis and the left end of the x-axis. The point at which the axesintersect is always (0, 0). Each axis is labeled with a data type. For example, thex-axis could be days, weeks, quarters, or years, while the y-axis shows revenue indollars. Line graphs are used to track changes over short and long periods oftime.
Graphics Programming
NOTES
Self-Instructional186 Material
10.4 CONTROL LOOPS IN APPLETS
An applet is a Java program that runs in a Web browser. An applet can be a fullyfunctional Java application because it has the entire Java API at its disposal.Program to use control loops in AppletsHere, we have shown four circle one below other using “for” loop with two differentcolors. The methods used are drawOval( ), fillOval( ) and setColor( ).import java.awt.*;import java.applet.*;public class ControlLoopApplet extends Applet{ public void paint(Graphics g) {
for(int i=1;i<=4;i++) { if(i%2==0) { g.fillOval(90,i*50+10,50,50); g.setColor(Color.black); } else { g.drawOval(90,i*50+10,50,50); g.setColor(Color.red); } } }}/* <applet code=ControlLoopApplet width=300 height=300>
</applet> */
Output:
Graphics Programming
NOTES
Self-InstructionalMaterial 187
10.5 DRAWING BAR CHARTS
A bar chart is a chart that presents categorical data with rectangular bars withheights or lengths proportional to the values that they represent. The bars can beplotted both vertically and horizontally.
Drawing a Bar chart in Java
This is a Java program to draw a bar chart for the table given below which showsannual result analysis of a school from period 2001-2005. These values may beplaced in a HTML file as <param> attributes and then used in Applet for displayingbar-chart.Year 2001 2002 2003 2004 2005
Result % 80 90 100 100 98
Program:import java.applet.*;
import java.awt.*;
/*
<applet code = “BarChart.class” width=400 height=400>
<param name=”year0" value=”2001">
<param name=”year1" value=”2002">
<param name=”year2" value=”2003">
<param name=”year3" value=”2004">
<param name=”year4" value=”2005">
<param name=”result0" value=”80">
<param name=”result1" value=”90">
<param name=”result2" value=”100">
<param name=”result3" value=”100">
<param name=”result4" value=”98">
</applet>
*/
public class BarChart extends Applet
Graphics Programming
NOTES
Self-Instructional188 Material
{
int n;
String year[];
int value[];
public void init()
{
n = 5;
year = new String[n];
value = new int[n];
year[0] = getParameter(“year0”);
year[1] = getParameter(“year1”);
year[2] = getParameter(“year2”);
year[3] = getParameter(“year3”);
year[4] = getParameter(“year4”);
value[0] =Integer.parseInt(getParameter(“result0”));
value[1] =Integer.parseInt(getParameter(“result1”));
value[2] =Integer.parseInt(getParameter(“result2”));
value[3] =Integer.parseInt(getParameter(“result3”));
value[4] =Integer.parseInt(getParameter(“result4”));
}
public void paint(Graphics g)
{
Font font = new Font(“Arial”,Font.BOLD,15);
g.setFont(font);
for(int i = 0; i < n; i ++)
{
g.setColor(Color.BLUE);
g.drawString(year[i], 20, i * 50 + 30);
Graphics Programming
NOTES
Self-InstructionalMaterial 189
g.setColor(Color.RED);
g.fillRect(70, i * 50 + 10, value[i], 40);
g.drawString(String.valueOf(value[i]) + “%”,180, i * 50 + 35);
}
String msg = “Bar Chart from Year 2001 - 2005”;
g.setColor(Color.darkGray);
font = new Font(“Arial”,Font.BOLD,20);
g.setFont(font);
g.drawString(msg, 50, 300);
}
}
Output:
Check Your Progress
3. What is a line graph?4. What is a bar chart?
10.6 ANSWERS TO CHECK YOUR PROGRESSQUESTIONS
1. The Graphics class provides different methods to draw and fill variousshapes.
2. A line can be drawn using the drawLine() method of the Graphicsclass.
3. A line graph, also known as a line chart, is a type of chart used to visualizethe value of something over time.
Graphics Programming
NOTES
Self-Instructional190 Material
4. A bar chart is a chart that presents categorical data with rectangular barswith heights or lengths proportional to the values that they represent.
10.7 SUMMARY
A line can be drawn using the drawLine() method of the Graphics class. A rounded filled rectangle can be drawn using draw fill RoundRect() method. An arc can be drawn using the drawArc() method. This method takes six
arguments in which the first four are the same as the arguments of thedrawoval() method and the next two represent the starting angle of the arcand the sweep angle around the arc, respectively.
A polygon is a closed geometrical figure, which can have any number ofsides. A polygon can be drawn by using the drawPolygon() method.
A line graph, also known as a line chart, is a type of chart used to visualizethe value of something over time.
The line graph consists of a horizontal x-axis and a vertical y-axis. Most linegraphs only deal with positive number values, so these axes typically intersectnear the bottom of the y-axis and the left end of the x-axis.
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire
Java API at its disposal. A bar chart is a chart that presents categorical data with rectangular bars with
heights or lengths proportional to the values that they represent.
10.8 KEY WORDS
DrawArc() method: This method takes six arguments in which the firstfour are the same as the arguments of the drawoval() method and thenext two represent the starting angle of the arc and the sweep angle around thearc, respectively.
Bar Chart: It is a chart that presents categorical data with rectangular barswith heights or lengths proportional to the values that they represent. Thebars can be plotted both vertically and horizontally.
10.9 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. Write a short note on working with graphics?
Graphics Programming
NOTES
Self-InstructionalMaterial 191
2. Give an example of how you use graphics class.3. Write a short note on line graphs and bar charts.4. What do you mean by drawing arcs?
Long Answer Questions
1. The graphics class can be used in a variety of ways. Discuss these in detail.2. Write a detailed note on drawing and filling an eclipse and a circle.3. Write an applet code to demonstrate the use of various methods of Graphics
class.4. rite a Java program to draw a bar chart for the table given below which
shows annual profit of a firm for the years between 2014-2018. Thesevalues may be placed in a HTML file as <param> attributes and then usedin Applet for displaying bar-chart.Year 2014 2015 2016 2017 2018
Result % 80 65 87 96 45
10.10 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Applet Programming
NOTES
Self-Instructional192 Material
UNIT 11 APPLET PROGRAMMING
Structure11.0 Introduction11.1 Objectives11.2 Applet Fundamentals
11.2.1 Difference between Console-Based Applications and Applets11.2.2 Local and Remote Applets11.2.3 Life Cycle of an Applet
11.3 Steps to Build an Applet11.3.1 Creating an Applet Code11.3.2 Creating an Executable Applet11.3.3 Designing an HTML Document11.3.4 Executing an Applet
11.4 Passing Parameters to Applets11.5 Answers to Check Your Progress Questions11.6 Summary11.7 Key Words11.8 Self Assessment Questions and Exercises11.9 Further Readings
11.0 INTRODUCTION
The Java programs that you have learned about so far are console-based applicationprograms. These are full-featured, stand-alone Java programs, written, modifiedand run through Java Virtual Machine. Java defines another category of applicationprograms known as applets. Applets are small Java programs that are specificallydesigned to be used over the Web. The most significant feature of an applet is thatit transforms a static Web page into a dynamic user-interactive Web page byadding images, sounds, animations different text styles to it. In other words, anapplet helps a programmer develop a full-featured multimedia application. Thisunit will introduce you to the fundamental of applet programming.
11.1 OBJECTIVES
After going through this unit, you will be able to: Explain the classes and packages supporting the creation of an applet Differentiate between Console-based applications and applets Understand the difference between local and remote applets Describe the important methods governing the life cycle of applets Create and use applets in your application Use <PARAM> tag to pass parameters to the applets
Applet Programming
NOTES
Self-InstructionalMaterial 193
11.2 APPLET FUNDAMENTALS
An applet is a small program typically embedded within the Web page, which isused to create a dynamic and interactive application. Applets provide interactivefeatures to a Web page, which cannot be provided by HTML only. For example,applets enable capturing user inputs in the form of mouse clicks, text entry, checkboxselection, etc., and generating response to the user’s actions.
Each applet that is created must be a subclass of the Applet class,contained within the java.applet.* package. This class contains methodsthat govern the life and behavior of the applets. In addition, applets use variousmethods of the Graphics class contained inside the java.awt.* package.The Graphics class is responsible for all the operations related to display(output) of an applet. The Java applets can be executed either through anappletviewer (a tool of Java Development Kit) or any Java-compatible Webbrowser.
11.2.1 Difference between Console-Based Applications and Applets
Both applications and applets, being Java programs, share many features; however,they also differ a lot depending upon the way they are developed and executed.Some of the main differences between the two are as follows:
Console-based applications are full-featured, independent Java programs;whereas applets are small programs that cannot run independently. To runan applet, you need to insert it into a Web page.
The execution of an applet does not begin at the main() method. Unlike console-based applications that can access and use all the resources,
applets have a restricted access to the resources of the machine in whichthey are residing. For example, applets are restricted from executing codeon a local system, they are prevented from reading and writing files on alocal file system, etc.
Note: All these limitations imposed on the applets are necessary for the security of theresources of the local system.
11.2.2 Local and Remote Applets
Applets can be classified into two types, namely, local applets and remote applets.A local applet is the one which is developed, stored and executed on a localsystem. That is, to run a local applet, you do not require any Internet connection.On the contrary, a remote applet is the one which is developed by someone elseand stored on a remote computer connected to the Internet. Anyone can downloadthe remote applet on his local system and execute it, provided the system isconnected to the Internet.
Applet Programming
NOTES
Self-Instructional194 Material
11.2.3 Life Cycle of an Applet
A Java applet enters into various states during its entire life cycle, which includeborn state, running state, idle state and dead state. These states occur whendifferent methods of the Applet class are invoked by the Java runtime system.The invocation of these methods makes an applet undergo a series of state changeright from the time it is loaded till it is destroyed and frees all the resources held byit. The life cycle of an applet can be depicted as shown in Figure 11.1.
Born
Running
Idle
Dead
paint ( )
start ( )
init ( )
stop ( )
destroy ( )
Applet Begins
Applet Ends
start ( )
Fig. 11.1 Applet Lifecycle
The order of method invocation when an applet is loaded is:1. init( ): The life cycle of an applet begins when it is first loaded and theinit() method is invoked. This method is invoked only once during theentire lifetime of an applet. The body of the method includes statementsrelated to variable initialization, object creation, adding components likebuttons, textboxes, etc., setting colors of the applet, loading of images orfonts, etc. After the invocation of the init() method, the applet entersthe born state.
2. start( ): This method is automatically invoked after the init()method. Unlike init() method, start() method may be invokedmore than once. This method is called every time the Web page containingthe applet is executed and displayed on the screen. With the invocation ofthis method, the applet enters the running state.
3. paint( ): This method is invoked to display the output on the screen inthe form of text, graphics, etc. Sometimes it may happen that the window inwhich applet is running gets covered by another window, or gets minimized
Applet Programming
NOTES
Self-InstructionalMaterial 195
or resized. In all these cases, paint() method is re-invoked for theoutput to be redrawn on the screen. As depicted in the Figure 11.1 theapplet remains in the running state while paint() method is invoked.
The order of method invocation at the time of termination of an applet is:1. stop( ): This method is invoked automatically when the Web page
containing the running applet is closed or left temporarily and applet entersthe idle state. The user can also stop the running applet by invoking thestop() method explicitly.
2. destroy( ): This method is invoked to remove the applet permanentlyfrom the memory. It releases all the resources held by the applet. Likeinit() method, this method is invoked only once during the entire lifecycle of an applet. The applet becomes dead when this method is invoked.
Note: The init() and destroy() methods are called only once whereas start(),paint() and stop() methods can be called multiple times in an applet.
Check Your Progress
1. What is an Applet?2. What are the two types of Applet?3. What are the various states in the life cycle of an applet?
11.3 STEPS TO BUILD AN APPLET
To build an applet, first of all, you need to create an applet code (.java file).After successful compilation, its corresponding .class file is created. Then aWeb page also known as HTML document is to be developed. Once the HTMLdocument is created, the applet is to be inserted in it. Finally, the resultant HTMLdocument will be executed to produce the desired output. The detailed descriptionof these steps is given in this section.
11.3.1 Creating an Applet Code
The first step in building an applet is to write an applet code. The creation of anapplet code is same as creation of a Java source file.The general form of an applet code is
Applet Programming
NOTES
Self-Instructional196 Material
Here, the program begins with two import statements. The first statementimports java.applet package that contains the Applet class and the secondstatement imports java.awt package. The next statement declares the classAppletCode. Note that it is declared public as it will be accessed by the codeoutside the program. The AppletCode class contains the paint() method,which takes the object of Graphics class as a parameter. This object describesthe graphical environment in which the applet will be running.
To show the complete procedure of the creation of an applet application letus start with writing an applet code.Example 11.1: An example of an applet code
In this example, the drawString() method invoked inside thepaint() method will display the string “Hello!!! This is my firstapplet” at the location x = 20, y = 70 relative to the screen. It shouldbe noted that since the paint() method has no definition of its own it must beoverridden.Note: The Graphics class is discussed later in this chapter.
11.3.2 Creating an Executable Applet
To create an executable applet, compile the applet code. An applet code is compiledusing the command javac AppletCode.java on the command prompt.This command will generate the .class file of the applet code known asexecutable applet.
Applet Programming
NOTES
Self-InstructionalMaterial 197
11.3.3 Designing an HTML Document
As stated earlier, an applet is not an independent entity as it cannot run on its ownand it needs to be inserted into the HTML document (Web page). Therefore, thenext step is to design an HTML document that will contain the applet code. AnHTML document is a collection of text and HTML tags interpreted and executedby the Web browser or an appletviewer. Every HTML document can be broadlydivided into four major elements: HTML, HEAD, TITLE and BODY.
HTML element marks the beginning and end of the HTML document.This element indicates to the Web browser that the page loaded is an HTMLdocument.
The syntax of HTML element is
HEAD element specifies the header information about the HTML documentsuch as title, keywords, etc. The content inside the HEAD tags is notdisplayed in the Web page.The syntax of HEAD element is
TITLE element is defined within the HEAD tags of the HTML document.The title of the Web page is displayed in the title bar of the Web browser.The syntax of TITLE element is
BODY element contains the content of the Web page such as text, images,etc. It determines the appearance of the Web page on the screen. TheBODY tag is placed exactly after the HEAD tag.The syntax of BODY element is
Example 11.2: An example of an HTML document
Applet Programming
NOTES
Self-Instructional198 Material
The output of the program is
Note: An HTML document is prepared using notepad or any text editor and saved with.html extension.
An Applet tag
The <APPLET> tag specifies the applet code that is to be loaded and at thesame time tells the browser about its space requirement on the Web page.The simplest form of the <APPLET> tag is
This code tells the browser or the appletviewer to reserve the display areahaving width of 600 pixels and height of 250 pixels for the applet and load thecompiled Java applet named AppletCode.class. The three attributes,namely, CODE, WIDTH and HEIGHT must be specified while defining an applettag. Some other attributes of the <APPLET> tag are listed in Table 11.1.
Applet Programming
NOTES
Self-InstructionalMaterial 199
Table 11.1 Attributes of an Applet Tag
Attribute (optional) Description NAME=applet_name It specifies the name of the applet. In inter-applet
communication, applets refer to other applets using their names.
CODEBASE=codebase_URL It indicates the URL of the directory where the applet resides. This can be omitted in case the applet and HTML document are in the same directory.
ALT=alternate_text The text written in this attribute will be displayed if the browser is unable to run the applet.
ALIGN=alignment It determines the alignment of the applet on the Web page. The alignment can be LEFT, RIGHT, TOP, MIDDLE, BOTTOM, BASELINE, ABSMIDDLE, TEXTTOP,ABSBOTTOM.
VSPACE=pixels It specifies the amount of vertical blank space that should be left around the applet by the browser.
HSPACE=pixels It specifies the amount of horizontal blank space that should be left around the applet by the browser.
Adding an Applet tag to HTML
Once an <APPLET> tag is created, it is placed inside the <BODY> tag of theHTML document. Here, you have seen the entire HTML document with anembedded <APPLET> tag of AppletCode.java applet.
Note: The .class file and its corresponding .html file must be present in the samedirectory.
11.3.4 Executing an Applet
As you have seen earlier, an applet can be executed either through any Java-compatible Web browser or an appletviewer. An appletviewer is a tool of JavaDevelopment Kit that is specifically designed for viewing applets. Using the Webbrowser enables the user to see the entire HTML document containing the applet.
Applet Programming
NOTES
Self-Instructional200 Material
Conversely, if you run the applet using the appletviewer, you can see the output ofan applet only as it ignores the HTML tags.The command to run an applet using appletviewer is
Fig. 11.2 The Output Displayed After Running the Applet in AppletViewer
Running the same applet using a Web browser will display the output asshown in Figure 11.3
Fig. 11.3 The Output Displayed After Running the Applet on a Web Browser
Applet Programming
NOTES
Self-InstructionalMaterial 201
11.4 PASSING PARAMETERS TO APPLETS
Java allows users to pass user-defined parameters to an applet with the help of<PARAM> tags. The <PARAM> tag has a NAME attribute which defines thename of the parameter and a VALUE attribute, which specifies the value of theparameter. In the applet source code, the applet can refer to the parameter by itsNAME to find its value.The syntax of the <PARAM> tag is
For example, consider the following statements to set the text attribute of appletto This is an example of Parameter!!!
Note that the <PARAM> tags must be included between the <APPLET>and </APPLET> tags. The init() method in the applet retrieves user-definedvalues of the parameters defined in the <PARAM> tags by using thegetParameter() method. This method accepts one string argument thatholds the name of the parameter and returns a string which contains the value ofthat parameter. Since it returns String object, any data type other than Stringmust be converted into its corresponding data type before it can be used.Example 11.3: An applet code to demonstrate passing of parameters to an applet
Applet Programming
NOTES
Self-Instructional202 Material
The HTML code for ParameterExample is
The output of the HTML code is
Applet Programming
NOTES
Self-InstructionalMaterial 203
Check Your Progress4. What does an <APPLET> tag specify?5. How can we pass parameters from an HTML document to an Applet?
11.5 Answers to Check Your Progress Questions
1. An applet is a small program typically embedded within the Web pagewhich is used to create a dynamic and interactive application.
2. Applets can be classified into two types, namely, local applets and remoteapplets.
3. A Java applet enters into various states during its entire life cycle, whichinclude born state, running state, idle state and dead state.
4. The <APPLET> tag specifies the applet code that is to be loaded and atthe same time tells the browser about its space requirement on the Webpage.
5. The parameters can be passed to an applet by using <PARAM> tag in thefollowing way:<PARAM NAME=parameter_name VALUE=parameter_value>To access the parameters inside the applet, getParameter() methodis used. This method returns a string value of the parameter name.
11.6 Summary
An applet is a small program, typically embedded within the Web page,used to create a dynamic and interactive application.
Applets use various methods of the Applet class contained in thejava.applet.* package and Graphics class contained inside thejava.awt.* package.
A local applet is developed, stored and executed on a local system. A remote applet is developed by someone else, stored on a remote computer
connected to the Internet. A Java applet enters into various states during its entire life cycle, which
include born state, running state, idle state and dead state. When an applet is loaded, until it is destroyed, the methods init(),start(), paint(), stop() and destroy() are invokedautomatically.
Applet Programming
NOTES
Self-Instructional204 Material
To build an Applet, an applet code is created and compiled. Then, an HTMLdocument is developed for embedding the applet code within it using theHTML tags.
Java allows users to pass user-defined parameters to an applet withthe help of <PARAM> tags.
11.7 Key Words
Applet:A java applet was a small application that is written in the javaprogramming language, or another programming language that compiles tojava bytecode, and delivered to users in the form of java bytecode.KEYTERMS
HTML element: It indicates to the Web browser that the page loaded isan HTML document and marks the beginning and end of the HTMLdocument.
HEAD element: It specifies the header information about the HTMLdocument such as title, keywords, etc.
11.8 Self Assessment Questions and Exercises
Short Answer Questions
1. What is an applet?2. What is the difference between local and remote applets?3. Enumerate the steps involved in the applet development with the help of a
program.
Long Answer Questions
1. Differentiate between Java console-based applications and Java applets.2. Write a program to show the use of various methods which constitute the
life-cycle of an applet.3. Write a program to demonstrate the passing of parameters to an applet
using HTML document.
11.9 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Applet Programming
NOTES
Self-InstructionalMaterial 205
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Introduction to Streams
NOTES
Self-Instructional206 Material
UNIT 12 INTRODUCTION TOSTREAMS
Structure12.0 Introduction12.1 Objectives12.2 Streams12.3 I/O Packages
12.3.1 Byte Stream Classes12.3.2 Character Stream Classes
12.4 Answer to Check Your Progress Questions12.5 Summary12.6 Key Words12.7 Self Assessment Questions and Exercises12.8 Further Readings
12.0 INTRODUCTION
In this unit, you will learn about the streams and their classes. The most basic inputand output in Java is done using streams. Streams are objects that represent sourcesand destinations of data. A stream in Java is an ordered sequence of bytes ofundetermined length. You will also learn about the stream classes i.e. byte streamclasses and character stream classes and their demonstration using the programs.
12.1 OBJECTIVES
After going through this unit, you will be able to: Understand the concept of streams Explain the byte and character stream classes
12.2 STREAMS
Java manages all input and output in the form of streams. A stream refers to achannel through which data flows from the source to the destination. This data is inthe form of sequence of bytes or characters.
Java streams can be broadly categorized into two types, namely, inputstream and output stream. The streams which help to read data from varioussources, namely, keyboard, mouse, files, storage devices, etc., in order to supplyit to the program are called input streams. The streams which receive data fromthe program and direct write it to the physical devices or other programs are
Introduction to Streams
NOTES
Self-InstructionalMaterial 207
called output streams. For example, to bring the data from an input device intothe program, the program opens an input stream on the input device and reads thedata in a serial manner. Conversely, to write data from the program to an outputdevice, the program opens an output stream to the output device and writes datato it serially (see Figure 12.1).
Fig. 12.1 Java Streams
12.3 I/O PACKAGES
Java supports input/output streams through a hierarchy of classes defined in thejava.io package. On the basis of the type of data on which these classesoperate, they can be categorized into two groups: byte stream classes and characterstream classes (see Figure 12.2).
Byte Stream Classes: These classes support input and output operationson bytes (8-bit bytes). For example, while reading from or writing data to abinary file, byte stream classes are used.
Character Stream Classes: These classes perform input and outputoperations on characters (16-bit Unicode). For example, while reading fromor writing data to a text file, character stream classes are used.
Fig. 12.2 Classification of Stream Classes
Introduction to Streams
NOTES
Self-Instructional208 Material
12.3.1 Byte Stream Classes
Byte stream classes are used to perform reading and writing of 8-bit bytes. Streamsbeing unidirectional in nature can transfer bytes in one direction only, that is, eitherreading data from the source into a program or writing data from a program to thedestination. Therefore, Java further divides byte stream classes into two classes,namely, InputStream class and OutputStream class. The subclasses ofInputStream class contain methods to support input and the subclasses ofOutputStream class contain output related methods.
Java Input Stream Classes
Java’s input stream classes are used to read 8-bit bytes from the stream. TheInputStream class is the superclass for all byte-oriented input stream classes.All the methods of this class throw an IOException. Being an abstract class, theInputStream class cannot be instantiated hence, its subclasses are used. Someof these are listed in Table 12.1.
Table 12.1 Input Stream Classes
Class DescriptionBufferedInputStream Contains methods to read bytes from the buffer (memory area).ByteArrayInputStream Contains methods to read bytes from a byte array. DataInputStream Contains methods to read Java primitive data types. FileInputStream Contains methods to read bytes from a file. FilterInputStream Contains methods to read bytes from other input streams which
it uses as its basic source of data. ObjectInputStream Contains methods to read objects. PipedInputStream Contains methods to read from a piped output stream. A piped
input stream must be connected to a piped output stream. SequenceInputStream Contains methods to concatenate multiple input streams and
then read from the combined stream.
The InputStream class defines various methods to perform readingoperations on data of an input stream. Some of these methods along with theirdescription are listed in Table 12.2.
Introduction to Streams
NOTES
Self-InstructionalMaterial 209
Table 12.2 InputStream Class Methods
Method Descriptionint read() Returns the integral representation of the next available
byte of input. It returns –1 when end of file is encountered.int read(byte buffer[]) Attempts to read buffer.length bytes into the buffer
and returns the total number of bytes successfully read. Itreturns –1 when end of file is encountered.
int read(byte buffer[],int loc, int nBytes)
Attempts to read ‘nBytes’ bytes into the buffer startingat buffer[loc] and returns the total number of bytessuccessfully read. It returns –1 when end of file isencountered.
int available() Returns the number of bytes of the input available forreading.
void mark(int nBytes) Marks the current position in the input stream until‘nBytes’ bytes are read.
void reset() Resets the input pointer to the previously set mark.long skip(long nBytes) Skips ‘nBytes’ bytes of the input stream and returns the
number of actually skipped bytes.void close() Closes the input source. If an attempt is made to read even
after closing the stream then it generates IOException.
Using ByteArrayInputStream Class
The ByteArrayInputStream class opens an input stream to read bytes from abyte array. It contains an internal buffer that holds bytes that are read from thestream. It should be noted that closing the stream does not have any consequences.That is, methods of this class can be invoked even after closing the stream withoutgenerating any IOException. The ByteArrayInputStream object can becreated using one of the following constructors.
The first constructor creates a ByteArrayInputStream which uses a bytearray buffer as its input source. The second constructor creates aByteArrayInputStream which uses a subset of byte array buffer as its inputsource. The reading begins from the index specified by loc and continues untilnBytes are read.Example 12.1: A program to demonstrate the use of ByteArrayInputStreamclass.
Introduction to Streams
NOTES
Self-Instructional210 Material
The output of the program is
In this example, the getBytes() method is used to convert string intobytes. The use of available() and skip() methods is demonstrated here.Once the entire stream is read, reset() method is invoked to set the pointer atthe start of the stream.
Java Output Stream Classes
Java’s output stream classes are used to write 8-bit bytes to a stream. TheOutputStream class is the superclass for all byte-oriented output stream classes.All the methods of this class throw an IOException. Being an abstract class, theOutputStream class cannot be instantiated hence, its subclasses are used. Someof these are listed in Table 12.3.
Introduction to Streams
NOTES
Self-InstructionalMaterial 211
Table 12.3 Output Stream Classes
Class DescriptionBufferedOutputStream Contains methods to write bytes into the buffer. ByteArrayOutputStream Contains methods to write bytes into a byte array. DataOutputStream Contains methods to write Java primitive data types. FileOutputStream Contains methods to write bytes to a file. FilterOutputStream Contains methods to write to other output streams. ObjectOutputStream Contains methods to write objects. PipedOutputStream Contains methods to write to a piped input stream. PrintStream Contains methods to print Java primitive data types.
The OutputStream class defines methods to perform writing operations.These methods are discussed in Table 12.4.
Table 12.4 OutputStream Class Methods
Method Descriptionvoid write(int i) Writes a single byte to the output stream. void write(byte buffer[]) Writes an array of bytes to the output stream. void write(bytes buffer[], int loc, int nBytes)
Writes ‘nBytes’ bytes to the output stream from the buffer b starting at buffer[loc].
void flush() Flushes the output stream and writes the waiting buffered output bytes.
void close() Closes the output stream. If an attempt is made to write even after closing the stream then it generates IOException.
Using ByteArrayOutputStream Class
The ByteArrayOutputStream class, an output counterpart of theByteArrayInputStream, writes streams of bytes to the buffer. Similar toByteArrayInputStream, closing this stream has no effect. That is, methods ofthis class can be invoked even after closing the stream without generating anyIOException. The ByteArrayOutputStream object can be created using oneof the following constructors:
The first constructor creates a buffer of 32 bytes. The second constructorcreates a buffer of size equal to nBytes. The size of the buffer increases as bytesare written to it.Example 12.2: A program to demonstrate the use of ByteArrayOutputStreamclass.
Introduction to Streams
NOTES
Self-Instructional212 Material
The output of the program is
In this example, the getBytes() method is used to convert string intobytes. Once the entire stream is written, the toString() method is invoked toconvert the contents (bytes) of the buffer into a string.
12.3.2 Character Stream Classes
One of the limitations of byte stream classes is that it can handle only 8-bit bytesand cannot work directly with Unicode characters. To overcome this limitation,character stream classes have been introduced in java.io package to match thebyte stream classes. The character stream classes support 16-bit Unicodecharacters, performing operations on characters, character arrays, or strings, readingor writing buffer at a time. Character stream classes are divided into two streamclasses namely, Reader class and Writer class.
Reader Classes
Reader classes are used to read 16-bit Unicode characters from the input stream.The Reader class is the superclass for all character-oriented input stream classes.All the methods of this class throw an IOException. Being an abstract class, theReader class cannot be instantiated hence its subclasses are used. Some of theseare listed in Table 12.5.
Table 12.5 Reader Classes
Introduction to Streams
NOTES
Self-InstructionalMaterial 213
The Reader class defines various methods to perform reading operations ondata of an input stream. Some of these methods along with their description arelisted in Table 12.6.
Table 12.6 Reader Class Methods
Method Descriptionint read() Returns the integral representation of the next available
character of input. It returns -1 when end of file is encountered.
int read(char buffer[]) Attempts to read buffer.length characters into the buffer and returns the total number of characters successfully read. It returns -1 when end of file is encountered.
int read(char buffer[], int loc, int nChars)
Attempts to read ‘nChars’ characters into the bufferstarting at buffer[loc] and returns the total number of characters successfully read. It returns -1 when end of file is encountered.
void mark(int nChars) Marks the current position in the input stream until ‘nChars’ characters are read.
void reset() Resets the input pointer to the previously set mark. long skip(long nChars) Skips ‘nChars’ characters of the input stream and returns
the number of actually skipped characters. boolean ready() Returns true if the next request of the input will not have
to wait, else it returns false.void close() Closes the input source. If an attempt is made to read even
after closing the stream then it generates IOException.
Using BufferedReader Class
The BufferedReader class creates a buffered character stream between theinput device and the program. It defines the methods to read the data from thebuffer in the form of characters. The BufferedReader object can be createdusing one of the following two constructors:
The first constructor creates a buffered character stream of default buffer size.The second constructor creates a buffered character stream that uses an input bufferof size nChars.
Besides the methods provided by the Reader class, the BufferedReaderclass contains some other methods which are discussed as follows:
String readLine(): It reads a line of the input text. boolean ready(): It checks whether or not the stream is ready to be
read.
Example 12.3: A program to demonstrate the use of BufferedReader class.
Introduction to Streams
NOTES
Self-Instructional214 Material
The output of the program is
In this program, skip() method is used to skip the first character of eachword of the input string.
Writer Classes
Writer classes are used to write 16-bit Unicode characters onto an output stream.The Writer class is the superclass for all character-oriented output stream classes.All the methods of this class throw an IOException. Being an abstract class, theWriter class cannot be instantiated hence, its subclasses are used. Some of theseare listed in Table 12.7.
Introduction to Streams
NOTES
Self-InstructionalMaterial 215
Table 12.7 Writer Classes
The Writer class defines various methods to perform writing operationson output stream. These methods along with their description are listed inTable 12.8.
Table 12.8 Writer Class Methods
Using BufferedWriter Class
The BufferedWriter class, an output counterpart of the BufferedReader, isused to write characters onto the character-output stream. The BufferedWriterobject can be created using one of the following two constructors:
The first constructor creates a buffered character stream of default buffersize. The second constructor creates a buffered character stream that uses aninput buffer of size nChars. Besides the methods provided by the Writer class,the BufferedWriter class contains the newLine()method which writes a newline.Example 12.4: A program to demonstrate the use of BufferedWriter class.
Introduction to Streams
NOTES
Self-Instructional216 Material
The output of the program is
In this example, the BufferedWriter class is used to write data tocharacter-output stream (instance of StringWriter class). The getBuffer()method of the StringWriter class returns a buffer of String type.
Check Your Progress
1. What is a stream?2. What are the two types of streams?3. What is the use of byte stream class?4. What is the purpose of using writer class?
12.4 ANSWER TO CHECK YOUR PROGRESSQUESTIONS
1. A stream refers to a channel through which the data flows from the sourceto the destination in the form of a sequence of bytes or characters.
2. Input and output streams are the two types of stream.3. Byte stream classes are used to read and write 8-bit bytes. The streams
being unidirectional in nature can transfer the bytes in one direction only,that is, they can either read the data from the source into a program or writethe data from a program to the destination.
4. Writer classes are used to write 16-bit Unicode characters onto an outputstream.
Introduction to Streams
NOTES
Self-InstructionalMaterial 217
12.5 SUMMARY
Java manages all input and output in the form of streams. A stream refers toa channel through which the data flows from the source to the destination inthe form of a sequence of bytes or characters.
The streams, which help read the data from various sources, namely,keyboard, mouse, files, storage devices and so on, in order to supply it tothe program are called input streams.
The streams, which receive data from the program and write it to the physicaldevices or other programs, are called output streams.
Byte stream classes support the input and output operations on bytes (8-bitbytes).
Character stream classes perform input and output operations on characters(16-bit Unicode).
Java further divides byte stream into InputStream class andOutputStream class.
Java’s output stream classes are used to write 8-bit bytes to a stream. TheOutputStream class is the superclass for all byte-oriented output streamclasses. All the methods of this class throw an IOException.
Reader classes are used to read 16-bit Unicode characters from the inputstream. The Reader class is the superclass for all character-oriented inputstream classes.
Writer classes are used to write 16-bit Unicode characters onto an outputstream. The Writer class is the superclass for all character-oriented outputstream classes. All the methods of this class throw an IOException.
12.6 KEY WORDS
Stream: It is a channel through which the data flows from the source to thedestination in the form of a sequence of bytes or characters.
Exception: It is an error event that can happen during the execution of aprogram and disrupts its normal flow.
12.7 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. Define the term stream.
Introduction to Streams
NOTES
Self-Instructional218 Material
2. Write the syntax for creating the ByteArrayInputStream object.3. Discuss the two types of character stream class.
Long Answer Questions
1. What are the two types of I/O streams? Explain.2. Write a program to demonstrate the use of ByteArrayInputStream
class.3. Write a program to demonstrate the use of ByteArrayOutputStream
class.
12.8 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
I/O Classes
NOTES
Self-InstructionalMaterial 219
UNIT 13 I/O CLASSES
Structure13.0 Introduction13.1 Objectives13.2 Reading Console Input13.3 Handling Files
13.3.1 Creation of Files: Using FileInputStream andFileOutputStream Classes
13.3.2 Reading/Writing Characters: Using FileReader andFileWriter Classes
13.3.3 Using File Class13.3.4 Handling the Primitive Data Types and I/O Exceptions
13.4 Answers to Check Your Progress Questions13.5 Summary13.6 Key Words13.7 Self Assessment Questions and Exercises13.8 Further Readings
13.0 INTRODUCTION
A program is a set of instructions that facilitates problem solving. Every programaccepts input, processes it and transforms it into a desired output. An input isgiven to a program through standard input devices, other programs and so on.Similarly, the output from a program is sent to standard output devices, otherprograms and so on. Most of the real-life applications require a large amount ofinput and output data, which is difficult to manage using the commonly used consoleinput/output (I/O) devices like keyboard and screen. Moreover, the output obtainedusing console I/O operation is not permanent and is lost as soon as the programterminates. This necessitates the requirement of some devices such as hard disk,magnetic tape or a floppy disk to store voluminous data permanently. The data isstored in these devices in the form of files (also known as disk files). Java supportsinput and output of data through the classes included in the java.io package.This unit will take you through the various aspects of input/output handling in Java.
13.1 OBJECTIVES
After going through this unit, you will be able to: Explain the concept of files and classes that support file input and output
operations Use the File class to obtain the information about a file Discuss the significance of DataInputStream and DataOutputStream
classes
I/O Classes
NOTES
Self-Instructional220 Material
13.2 READING CONSOLE INPUT
Java 1.0 supports console input using byte streams. Since the use of byte streamsfor reading/writing console input requires using deprecated methods, this approachis not recommended. The more desired approach used for reading input for Java2 is to use character streams instead of byte streams. Java 1.1 and higher versionsof Java provide to convert byte-oriented data intocharacter-oriented data. In order to read the data from the console using characterstream, is used. refers to an object of type
; therefore, it can be used as a character-based input stream.The statement to wrap inside the
and create a character-based stream connected to theconsole through is
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
A program to demonstrate the use of class isas follows:
I/O Classes
NOTES
Self-InstructionalMaterial 221
The output of the program is as follows:
13.3 HANDLING FILES
So far you have studied how data can be read from the keyboard or written to theconsole using stream classes. Java also provides several classes including
, , ,, ,
to handle files. In this section, you will study how these classes are used.
13.3.1 Creation of Files: Using and Classes
Before reading or writing a file, it must be opened first. For this, it is required tocreate a file stream and then link this stream to the specific file. Java provides
class to read the bytes from a file. The class creates an input stream between the file and the
program and reads the bytes from the file and sends it to the program.Two commonly used constructors of the class
are as follows:1.2.
where,
A program to demonstrate the use of class toread from a file is as follows:
I/O Classes
NOTES
Self-Instructional222 Material
The output of the program is as follows:
In this example, the statement creates an input stream and causes
the file to be opened for reading. After the creation of thestream object, the method is used to read the next byte from thefile .
Similarly, the class defines the methods to writethe bytes to a file.
The two commonly used constructors of classare as follows:
1.2.
where, is the full path describing the location of the file.
I/O Classes
NOTES
Self-InstructionalMaterial 223
is the object of that describes the file.A program to demonstrate the use of class to
write to a file is as follows:
The output of the program is as follows:
In the preceding program, when the class object iscreated, a file with the specified name is automatically created by the operatingsystem. If a file with the same name already exists in the same directory, the contentsof the earlier file get overwritten with the contents of the new file.
13.3.2 Reading/Writing Characters: Using and Classes
The class is used to read the characters from the file. The functionsof the class are as follows:
To create the character stream between the file and the program To read the characters from the file and send it to the program
Similarly, to write the characters to a file, the class is used.A program to demonstrate the use of
class for reading from and writing the characters to a file is asfollows:
I/O Classes
NOTES
Self-Instructional224 Material
The output of the program is as follows:
In this program, when the class object is created, a filewith the name is automatically created by the operating system, andthe data is written to it. The object of class is used to read thecontents of the same file.
13.3.3 Using Class
The class allows you to obtain and manipulate the information about a filesuch as permissions, size, time and so on. Unlike the other classes of
I/O Classes
NOTES
Self-InstructionalMaterial 225
package, this class does not operate on the streams; it deals directly with the filesand file system. That is, it does not specify how the data is retrieved from or sentto the files. Using this class, you can also make new directories, rename as well asdelete the files.
A object can be created using any one of the following constructors:
where, is the path name of the file.
is the name of the file or subdirectory. is a object that specifies a directory.
The class defines various methods. Some of them along with theirdescription are listed in Table 13.1.
Table 13.1 Some Class Methods
Method Description boolean canExecute() Returns true if the file given by the abstract path
name can be executed boolean canRead() Returns true if the file given by the abstract path
name can be read boolean canWrite() Returns true if the file given by the abstract path
name can be written boolean createNewFile()
Creates a new empty file
boolean delete() Deletes the file or directory; directory can be deleted only if it is empty
boolean exists() Returns true if the file given by the abstract pathname exists
String getName() Returns the name of the file or directory String getParent() Returns the name of the parent directory String getPath() Returns the path of the file as a string boolean isAbsolute() Returns true if the abstract file path name is
absolute boolean isFile() Returns true if invoked on a file and false if
invoked on a directory boolean isHidden() Returns true if the file is a hidden file long lastModified() Returns the time the file was last modified long length() Returns the size of the file boolean isDirectory() Returns true if the file given by the abstract path
name is directory boolean setReadOnly() Sets the file to read only
Note: In Java, a directory is also treated as file. The only difference is that it contains a list offile names, which can be obtained using the method.
I/O Classes
NOTES
Self-Instructional226 Material
A program to demonstrate the use of some of the methods of classis as follows:
The output of this program is as follows:
File Name: Sample.txtPath: Java\Sample.txtAbsolute Path: E:\JAVA_Book\ \Java\Sample.txtParent: JavaFile was last modified at: 1264808454781File size: 31 Bytes
I/O Classes
NOTES
Self-InstructionalMaterial 227
13.3.4 Handling the Primitive Data Types and I/O Exceptions
Data streams support reading/writing of primitive data types ( , ,, , , , and ) as well as
objects. These are required when the user wants to work on data other than bytesor characters. Data streams are filtered streams, that is, they filter existing streamso that the primitive data types can be directly read from or written to the stream.Java provides class and classto read and write primitive data types, respectively.
The Class
The class performs reading of Java primitive data typesfrom the input stream. To create a data input stream, use the constructor of
class, which is defined as follows:
where, is an existing input stream which is to be filtered such as
, and so on. Some othercommonly used methods are listed in Table 13.2.
Table 13.2 Class Methods
Method Description int readInt() reads integer type values float readFloat() reads float type values char readChar() reads char type values double readDouble() reads double type values long readLong() reads long type values short readShort() reads short type values boolean readBoolean() reads boolean type values byte readByte() reads byte type values String readUTF() reads string type values
The Class
The class writes Java primitive data types onto theoutput stream. To create a data output stream, use the constructor of
class, which is defined as follows:
where, is an existing output stream which is to be filtered such as
, and so on. Some othercommonly used methods are listed in Table 13.3.
I/O Classes
NOTES
Self-Instructional228 Material
Table 13.3 Class Methods
Method Description int writeInt() writes integer type values float writeFloat() writes float type values char writeChar() writes char type values double writeDouble() writes double type values long writeLong() writes long type values short writeShort() writes short type values boolean writeBoolean() writes boolean type values byte writeByte() writes byte type values String writeUTF() writes string type values
A program to demonstrate the use of class and class for handling the primitive data types is as follows:
I/O Classes
NOTES
Self-InstructionalMaterial 229
The output of the program is as follows:
I/O Classes
NOTES
Self-Instructional230 Material
In this example, first of all a file is created. The data iswritten to this file using class. After that, an input streamis created using class for reading the content of this file.
Check Your Progress
1. What is the use of InputStreamReader?2. What are the different classes used for handling files?3. What are the functions of FileReader class?4. What are the various data types that data streams supports?
13.4 Answers to Check Your Progress Questions
1. Java provides InputStreamReader to convert byte-oriented data intocharacter-oriented data.
2. Java also provides several classes including FileInputSream,FileOutputStream, FileReader, FileWriter, File,RandomAccessFile, FileDescriptor to handle files.
3. The functions of the FileReader class are as follows: To create the character stream between the file and the program To read the characters from the file and send it to the program
4. Data streams support reading/writing of primitive data types (int, float, short,long, double, boolean, char and byte) as well as String objects.
13.5 Summary
Java provides to convert byte-oriented datainto character-oriented data. It supports reading input from the consoledevice.
The class allows the user to obtain and manipulate the informationabout a file such as permissions, size, time and so on.
Unlike other classes of package, the class class doesnot operate on the streams; it deals directly with the files and file system.
Depending on the type of data handled by the file stream, byte stream classesor character stream classes can be used.
Java provides class and class to read and write primitive data types, respectively.
I/O Classes
NOTES
Self-InstructionalMaterial 231
13.6 Key Words
• Input streams: These are the streams that help read data from varioussources, namely keyboard, mouse, files, storage devices and so on, in orderto supply it to the program.
• Output streams: These are the streams that receive data from the programand write it to the physical devices or other programs.
13.7 Self Assessment Questions and Exercises
Short Answer Questions
1. What is a file? Why is it used?2. Name the file stream classes used for reading and writing in a file.3. How would you check whether a file to be opened for writing already
exists?
Long Answer Questions
1. Java supports reading input provided by the user with the help of aconsole input device such as keyboard. Explain with the help of anexample.
2. What will happen after execution of the following code (Assume the file already exists in the current directory.)?
import java.io.*;
class example
{
public static void main(String args[])
{
try
{
FileOutputStream file = new FileOutputStream(“test.txt”);
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
I/O Classes
NOTES
Self-Instructional232 Material
3. What is the significance of the and classes? Explain with an example.
13.8 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.
Reading Writing Bytes
NOTES
Self-InstructionalMaterial 233
UNIT 14 READING WRITING BYTES
Structure14.0 Introduction14.1 Objectives14.2 The RandomAccessFile Class14.3 The PrintStream Class14.4 The StringTokenizer Class14.5 The StreamTokenizer Class14.6 Answer to Check Your Progress Questions14.7 Summary14.8 Key Words14.9 Self Assessment Questions and Exercises
14.10 Further Readings
14.0 INTRODUCTION
In this unit, you will learn about the randomaccessfiles, PrintStreamclass and other classes like StringTokennizer and StreamTokenizerclass. RandomAccessFile class allows you to move the file pointer to thearbitrary position in the file prior to read or write operation. The output is displayedto the user using Java PrintStream class. So far the two methods, print()and println(), that have been used for displaying the primitive data type, object,etc., on an output device are defined by the PrintStream class. This is a bytestream class, which is derived from the OutputStream class. TheStringTokenizer class, a part of java.util package, defines the methodsto parse an input string while the StreamTokenizer class is used to parsean input stream into ‘tokens’ determined by the delimiters, reading them one ata time.
14.1 OBJECTIVES
After going through this unit, you will be able to: Use the class Understand the concept of class Describe the significance of and
classes
Reading Writing Bytes
NOTES
Self-Instructional234 Material
14.2 THE CLASS
Using the class, you can create a file that allows you tomove the file pointer to the arbitrary position in the file prior to read or writeoperation. Once the file pointer is positioned at the desired location, the next readand write operation will take place at that location. This class is mainly used forthe files containing the records of known size. However, the records are not requiredto be of the same size; the size and position of the records can be determined.The class defines the following two constructors:
1.2.
where, is the name of the file.
is the access mode of the file. is a object that specifies the name of the file to open as
a object.The mode can take one of the following values:
: To open the file for read only mode : To open the file for read-write mode : To open the file for read-write mode and write every change
in the file’s data and metadata immediately to the storage device : To open the file for read-write mode and write every change
in the file’s data immediately to the storage deviceThe class implements the interfaces
and that defines the standard input/output methods.Therefore, the random access files can be read from or written to using the standardI/O methods. Other than implementing the standard I/O methods, it defines someother methods also. One of these methods is the method. This methodallows you to position the file pointer to any location within the file. The form ofthis method is as follows:
where,
A program to demonstrate reading and writing usingclass is as follows:
Reading Writing Bytes
NOTES
Self-InstructionalMaterial 235
The output of this program is as follows:
Reading Writing Bytes
NOTES
Self-Instructional236 Material
14.3 THE CLASS
When a program is executed, the input is read from the various sources and theoutput is sent to different destinations. Generally, keyboard and monitor screenare used as standard input and output devices, respectively. The data fed by theuser is supplied to the program using input streams, and the output of the programis supplied to the output device using output streams. This output is displayed tothe user using Java class. So far the two methods, and , that have been used for displaying the primitive data type,object, etc., on an output device are defined by the class. Thisis a byte stream class, which is derived from the class. Unlikeother output streams, the class does not throw an
even if an exceptional event occurs. class can be connected to the underlying output stream
such as , , and so on.
class defines the following types of constructor:PrintStream(OutputStream os)This constructor creates a print stream and connects it to the output stream
. In addition to and methods, the class defines some other methods, which are listed in Table 14.1.
Table 14.1 Class Methods
Method Description PrintStream append(char c)
Appends the character c to the output stream
PrintStream append(CharSequence cs)
Appends the character sequence c to the output stream
boolean checkError() Checks the error state of the stream protected void setError()
Sets the error state to true
A program to demonstrate the use of class is as follows:
Reading Writing Bytes
NOTES
Self-InstructionalMaterial 237
The output of the program is as follows:
14.4 THE CLASS
The class, a part of package, definesthe methods to parse an input string. Parsing a string requires breaking the stringinto small parts known as tokens. The breaking up of the string into tokens isdetermined by the delimiters. Delimiters are the characters that separate tokenswithin the string. There are the following two types of delimiters:
Single-character delimiters: These consist of only one character such ascomma, white space, semicolon, colon and so on. For example, the tokens of thestring will be , , ,
determined by the delimiter .
Reading Writing Bytes
NOTES
Self-Instructional238 Material
Multi-character delimiters: These consists of a sequence of charactersand each character in the sequence is considered as a delimiter. For example,“ ” is a multi-character delimiter which splits the string into tokens based onthe occurrence of comma, asterisk, colon and underscore.The class defines the following types of constructors:
The first constructor constructs a string tokenizer for the that isto be tokenized (parsed) and splits it into tokens based on the default delimiters.The default delimiters defined by Java are as follows:
Blank space Newline Carriage return Tab
The second constructor tokenizes the depending upon the specified as the second argument in the constructor.
The third constructor breaks the into tokens on the basis of. In addition, it returns the delimiter characters that separate the
tokens if the is set to . Some of the methodsdefined by the class are listed in Table 14.2.
Table 14.2 Class Methods
Method Description String nextToken() Returns the next available token in the string String nextToken(String delimiters)
Returns the next token in the string and changes the previously set delimiters to the set of characters in the string delimiters; after this method is invoked, delimitersis considered as the new delimiter set
boolean hasMoreTokens()
Checks whether or not tokens are available in the input string; returns true if tokens are present. Otherwise, returns false
int countTokens() Returns the number of tokens left in the string using the current set of delimiters
Object nextElement() Returns the same value as the nextToken() method except that it returns the next token as object
boolean hasMoreElements()
Returns the same value as the hasMoreTokens() method
Reading Writing Bytes
NOTES
Self-InstructionalMaterial 239
A program to demonstrate the use of class is as follows:
The output of the program is as follows:
14.5 THE CLASS
The class is used to parse an input stream into ‘tokens’determined by the delimiters, reading them one at a time. Unlike the
class, the class distinguishes
Reading Writing Bytes
NOTES
Self-Instructional240 Material
among numbers, identifiers, quoted strings and different comment styles. Thetokenization process involves reading each byte from the input stream, and eachbyte is considered as a character having five distinct attributes, namely, alphabets,numbers, string quote, white space and comment character. Each character isidentified to be having any of these attributes. The classdefines the following type of constructor:
StreamTokenizer(Reader input)The preceding statement constructs a stream tokenizer and tokenizes the
specified input stream .Some of the fields defined by the class are listed
in Table 14.3.
Table 14.3 Class Fields
Field Description static int TT_WORD Indicates that the word token has been read static int TT_NUMBER Indicates that the number token has been read static int TT_EOL Indicates that the end of the line has been read static int TT_EOF Indicates that the end of the file has been read int ttype Specifies the type of the token read double nval The value of number token String sval Specifies the value of a word token
Some of the methods defined by the class arelisted in Table 14.4.
Table 14.4 Class Methods
Method Description int lineno() Returns the current line number void eolIsSignificant (boolean flag)
Determines whether the ends of the line are treated as tokens
int nextToken() Returns the next token of the input stream
void whitespaceChars (int low, int high)
Specifies that all the characters within the range between low and high are white space characters
void wordChars(int low, int high)
Specifies that all the characters within the range between low and high are valid word characters
void slashSlashComments (boolean flag)
Sets whether the stream tokenizer recognizes the C++ comments
void slashStarComments (boolean flag)
Sets whether the stream tokenizer recognizes the C comments
void resetSyntax() Resets the default set of delimiters
To understand the concept of class, use the file having its contents as follows:
Reading Writing Bytes
NOTES
Self-InstructionalMaterial 241
A program that reads from the file to demonstrate theuse of class is as follows:
Reading Writing Bytes
NOTES
Self-Instructional242 Material
The output of the program is as follows:
Reading Writing Bytes
NOTES
Self-InstructionalMaterial 243
Check Your Progress
1. What is the significance of RandomAccessFile class?2. What are the two types of constructors defined by RandomAccessFile
class?3. What are the two types of delimiters?
14.6 ANSWER TO CHECK YOUR PROGRESSQUESTIONS
1. Using the RandomAccessFile class, you can create a file that allowsyou to move the file pointer to the arbitrary position in the file prior to reador write operation.
2. The RandomAccessFile class defines the following two constructors:(i) RandomAccessFile(String filename, String mode)(ii) RandomAccessFile(File fileobj, string mode)
3. Single character and multiple character delimiters are the two types ofdelimiters.
14.7 SUMMARY
Using the class, a file, that allows you to movethe file pointer to the arbitrary position in the file prior to read or writeoperation, can be created. It is mainly used for the files containing recordsof known size.
The Java class is used to display the result to the user onan output device.
The class, a part of package, definesthe methods to parse an input string.
The class distinguishes among numbers, identifiers,quoted strings and different comment styles.
Reading Writing Bytes
NOTES
Self-Instructional244 Material
14.8 KEY WORDS
Delimiters: These are the characters that separate tokens within the string. Parsing a String: It means converting that string into another class type. if
you want to parse a string into another type of data then you can use wrapperclasses to parse String class object into another class of object.
14.9 SELF ASSESSMENT QUESTIONS ANDEXERCISES
Short Answer Questions
1. For which purpose, is the class used?2. Write the syntax for the constructors defined by the RandomAccessFile
class.3. Reverse the string ‘Java Programming Language’ using the
class.
Long Answer Questions
1. Write a program to demonstrate reading and writing usingRandomAccessFile class.
2. ‘ class is used to display output to the user’. Explain.3. What is the class? How does it differ from the
class? Explain the working of.
4. Write a program to demonstrate the use of class.5. Write a program to demonstrate the use of class.
14.10 FURTHER READINGS
Arnold, Ken, James Gosling and David Holmes. 2005. The Java ProgrammingLanguage, 4th edition. Boston: Addison-Wesley.
Wigglesworth, Joe and Paula Lumby. 1999. Java Programming AdvancedTopics, Second edition. Boston: Course Technology.
Deitel, Paul and Harvey Deitel. 2011. Java: How to Program, 9th edition. NewDelhi: Prentice-Hall of India.
Harold, Elliotte Rusty. 2013. Java Network Programming, 4th edition. California:O’Reilly Media.