C19
C19
Ramesh Vasappanavara
Director
Shree Ganpati Institute of Technology
Ghaziabad, Delhi (NCR)
Anand Vasappanavara
Process Control Technologist
Shell Technologies
Bintulu, Malaysia
Gautam Vasappanavara
Lead Engineer
Samsung India Ltd
Bangalore
Chennai • Delhi • Chandigarh
Brief Contents
Preface
2 Object Modelling
4 Dynamic Modelling
10 Classes
13 IO Streaming
21 Java IO Files
22 Networking in Java
Appendix A
Appendix B
Appendix C
Contents
Preface
1.1 Introduction
1.4.1 C++
1.4.2 Java
1.4.3 C#
1.8.2 Class
1.8.3 Encapsulation
1.17 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
2 Object Modelling
2.1 Introduction
2.4.1 Class
2.4.5 Constraints
2.6 Links
2.8.1 Associations
2.11 Polymorphism
2.14 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
3.4 Overloading
3.8 Interface
3.16 Decoupling
3.18 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
4 Dynamic Modelling
4.5.1 Architecture
4.5.2 Domain
4.12 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
5.1 Introduction
5.9 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
6.1 Introduction
6.7 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
7.1 Introduction
7.5 Expressions
7.6 Operators
7.6.1 IO Operators << and >>, iostream objects cin
and cout
7.10 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
8.1 Introduction
8.6 Recursion
8.12.6 #undef
8.13 Arrays
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
9.1 Introduction
9.7 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
10 Classes
10.1 Introduction
10.12 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
11.1 Introduction
11.10 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
12 Inheritance
12.1 Introduction
12.2 Inheritance Hierarchy
12.15 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
13.1 Introduction
13.2 IO Streaming
13.3.1 Formatted IO
13.3.2 Unformatted IO
13.4 IO Manipulators
13.5 Flags
13.9 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
14.1 Introduction
14.8 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
15.1 Introduction
15.7 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
16.1 Introduction
16.14 Break
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
17.1 Introduction
17.3 Arrays
17.4 String
17.6 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
18.1 Introduction
18.4 Constructors
18.5.2 Methods
18.15 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
19.1 Introduction
19.11 Packages
19.15 Interfaces
19.16 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
20.1 Introduction
20.2.1 Errors
20.2.2 Exceptions
20.11.2 Threads
20.15 Synchronization
20.18 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
21 Java IO Files
21.1 Introduction
21.2 IO Streaming
21.10.1 Serialization
21.10.2 De-serialization
21.11 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
22 Networking in Java
22.1 Introduction
22.2.1 TCP/IP
22.7 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
23.4.2 JButton
23.4.3 JCheckBox
23.4.4 JComboBox
23.7 Applets
23.8 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
24.1 Introduction
24.5 Iterators
24.14.1 PreparedStatement
24.15 Servlets
24.15.2 HttpServletRequest
24.15.3 HttpServletResponse
24.17 Summary
Exercise Questions
Objective Questions
Short-answer Questions
Long-answer Questions
Assignment Questions
Appendix A
Appendix B
Appendix C
About the Author
Feedback
Utmost care has been taken in writing this
book to make it free of errors. However,
should you come across any error, please do
not hesitate to contact us. Your suggestions
and feedback are welcome.
How to Use This Book and Web
Resources
Object-Oriented Programming
Basics
LEARNING OBJECTIVES
Programming concepts.
Software development paradigms.
OOP paradigms and extendibility features offered by
OOP languages.
1.1 Introduction
In order to solve a problem, you need to
know the “method/procedure” or you
need to have the “know-how”. In computer
parlance, we call this an algorithm. An
algorithm or a program is a sequence of
steps to be followed, which leads to a desired
output. The sequence of steps can be called a
procedure, and, in turn, a group of
procedures can be termed as a program. For
solving a simple problem, a sequence of
steps is sufficient, but if the problem is
complex, a programming environment that
includes well-integrated and cohesive
programming elements, constructs and data
structures is required. A paradigm can be
thought of as a style of programming, which
involves elements such as functions, data
and data structures. Several programming
paradigms have been used successfully. The
structured programming paradigm with C as
implementing language, in which the
programmer breaks down the task to be
accomplished into subtasks and specifies a
step-by-step procedure or algorithm to
achieve this task, has been very successful
and popular amongst programmers, owing
largely to its reusable components in the
form of procedural calls and its ability to
manipulate memory and thus handle
hardware integration.
Low productivity of programmers, due to
factors such as changing user needs,
complexity of projects and non-availability
of extensibility and reuse features, causes
projects never to be completed on time.
Even if they are completed and
implemented, they are of little use. A
structured programming environment with
limited reuse facility afforded by procedure
call and lack of extensibility features, i.e.
inability to derive new data types from
existing ones, is not optimally suited to
handle challenges thrown by complex
projects such as fast-paced hardware and
software changes. Object-oriented
programming (OOP) promises extensive
reusability features through inheritance,
library functions in the form of standard
template library (STL), etc. C++ is one of the
most powerful OOP languages that supports
both structured as well as OOP paradigms.
1.4.1 C++
C++ was developed by Bjarne Stroustrup in
1979 at Bell Laboratories. C++ is a sequel to
the C language, with additional features.
These features include virtual functions,
function name and operator loading,
references, and free space memory along
with several features on reusability and
extendibility through inheritance, templates,
etc. Exception handling and a well-
developed standard template library are two
of the most advanced features available in
C++.
1.4.2 Java
Java was developed by James Gosling at Sun
Microsystems in 1995. It is similar to C &
C++. The main advantage of Java is that it is
hardware independent. Any code is
compiled into bytecodes. The bytecode
compiled is stored in a class file that can run
on any Java virtual machine (JVM).
JVM takes the bytecode and converts it
into an object code, which in turn is used by
a local machine to run and produce the
desired result.
Java 1.0 was released in 1995. Sun
Microsystems called it “Write Once, Run
Anywhere”. Indeed, with most of the
browsers such as IE explorer and Netscape
Navigator supporting Java 1.0, Java soon
became the industry standard. Java applets
that can run on web browsers became
popular too. In 1998, Sun Microsystems
released Java 2 with specialized
configurations to suit different types of
platforms, such as J2EE for enterprise
applications, JEME for mobile computations
and J2SE for standard editions. These have
been renamed JavaEE, JavaME and JavaSE,
respectively.
1.4.3 C#
C# was developed by Anders Hejlsberg for
Microsoft. It combines the best features of
existing OOP programming languages of
C++ and Java. It has been developed as a
powerful and versatile programming
language that is fully object oriented.
1.8.2 Class
Class: A class is a collection of objects and
can also be defined as an array of instances.
Figure 1.4 shows student class with three
instances. It can also have member
functions and member data. Here unlike
arrays, a class can have different data types
as its elements.
Figure 1.4 Student class with three instances of student object
1.8.3 Encapsulation
By now we understand that object means
attributes and functionality. Class can
contain several instances of an object.
We also understand that in object-
oriented programming, it is a data primacy
language, i.e. data is important and
functions are not important. As per memory
mapping used by C++ and other OOP
languages, data is stored in data areas such
as stack and free space, functions are stored
in code areas and there is a need to maintain
strict control over the accessing of data by
functions.
OOP languages achieve this control by
using the encapsulation feature.
Encapsulation is a binding member data
and calling function together with security
classification, so that no unauthorized
access to data takes place.
1.8.3.1 Security or Access Privileges
If we can write
Polar v3 = v2 + v1;
It means we have overloaded the +
operator.
1. C++ supports
1. Structured programming
2. Object-oriented programming
3. Both A and B
4. None of these
4. Java is
1. Hardware independent
2. Software independent
3. Language independent
4. Firmware independent
8. OOP paradigm is
1. Data primacy
2. Procedure primacy
3. Task primacy
4. Object primacy
1. i
2. i and ii
3. ii and iii
4. i, ii and iii
1. i
2. i and ii
3. i and ii
4. ii, iii and iv
Long-answer Questions
33. What are the salient features of OOP paradigms?
34. Distinguish between object-based programming and
object-oriented programming. (OOP style can be of two
types, i.e. object-based programming and object-
oriented programming. In OOP paradigms, object is
primacy.)
35. Explain inheritance and class hierarchy.
36. Distinguish between different types of inheritance.
37. Why are virtual functions useful?
38. Explain STL in C++.
1. c
2. b
3. a
4. a
5. c
6. a
7. b
8. a
9. d
10. b
11. c
12. a
13. d
14. b
15. b
16. b
17. b
18. c
2
Object Modelling
LEARNING OBJECTIVES
2.1 Introduction
Object modelling encompasses all the
elements that we studied in Chapter 1
regarding objectoriented (OO) methodology.
The principles of object modelling are
abstraction, encapsulation, modularity,
hierarchy, typing, concurrency and
persistence.
In conventional programming styles, we
conceive the problem and subdivide the
main task into subtasks and develop
functions or methods to solve these
subtasks. We call this paradigm procedure-
oriented programming style. In this
paradigm procedure is primacy and data
that is acted on is stored at a different
location in computer memory called the
code area. In object modelling, the object
embodies data and the functions that act on
the data as a single entity. To meet users’
requirements, the specifications are
prepared by experts as simple statements of
problems in English. In order to analyse
these specifications, we need to study the
vocabulary of the problem statements in
terms of objects (nouns) and classes, and
relationships between classes appearing in
the problem domain.
2.4.1 Class
A class is a description or specification for
the object, whereas the object is an instance
of the class that is created at run-time.
There can be one or several instances of the
class. In Example 2.2, we show the
representation of a student class in C++,
Java, and UML.
class Student
{ // constructors and member functions
public:
Student(){rollNo=0,name=”No
Name”;}
Student(int n, char *p)
{rollNo=n,name=p;}
int GetRollNo() const { return
rollNo;}
void SetRollNo ( int n) {
rollNo=n;}
char * GetName() const { return
name;}
void SetName( char *p) { name=p;}
private: int rollNo; char *name; //
member data & pointer to
name
};
Example 2.3: Representation of
Class Student in Java
2.6 Links
We have learnt that object modelling is not
simply a collection of isolated objects. As
shown in Figure 2.4, the system requires
that links between data belonging to
different objects need to be defined to
achieve some global functionality. There are
three distinct objects belonging to three
different classes: batch, student and
Registration. The class called batch will
have instances of students registered for all
courses for that batch, say mechanical third
semester. Here, only the student's number is
held and in order to get full details of the
student, we need to refer to another object
called Registration. This means that for
each student object, we need to maintain a
link to Registration object so that we can
refer to it for full details of the student.
Similarly, we need to maintain a link class
called batch so that we can get batch details
of the student.
We will show the implementation of link
in C++ and Java and UML as usual.
However, as a cautionary note, the examples
in C++ and Java require understanding of
the rudiments of programming skills in
these languages. Hence, first-time readers
can skip examples in C++ and Java and
concentrate only on UML; they can then
revisit these topics after acquiring the
necessary C++ or Java skills.
class StudentMaster
{ public: StudentMaster(char *p, int n)
{name=p, rollNo=n;}
char * GetName() const { return
name;}
int GetRollNo() const { return
rollNo;}
private: int rollNo; char *name; //
pointer to name}; // end of
class
class Student
{ public: Student(StudentMaster *std
){ sm=std;}
char *GetName() const { return Sm-
>GetName();}
private: StudentMaster *sm; };
void main()
{StudentMaster *sm = new StudentMaster (
“Anand”,757);
Student * S1 = new Student(sm);
cout<<s1->GetName();}
2.8.1 Associations
Associations are a type of hierarchy
that show relationships between classes
that are independent and are of equal
standing. These relationships are shown by
lines between classes; they are usually
labelled with the name of the association.
Classes in an association usually occupy
equal places within a hierarchy. For
example, in Figure 2.6, librarian and order
are independent classes.
Multiplicity: 0..* at order class means
that librarian can place an unlimited
number of orders, i.e. from 0 to unspecified
number of orders. 0…1 means 0 to 1.
Similarly, we can also state the maximum
number of books that can be borrowed by a
student as 0…4, as shown in Figure 2.8.
Figure 2.7 Association between classes. Association is named
: ordering
class Student
{ public:
……….. class declaration here………..
private:
};
class Athlet
{ public:
…….. class declaration here.: };
class Professional : public Student,
public Athlet
{ public:
…….. class declaration here.
……………..
private:
};
2.11 Polymorphism
We have understood that in inheritance
relationship subclass derives from
superclass both methods and attributes. In
inheritance, the subclass can extend and
simply use the functionality of the base class
or use its own functionality with totally
different implementations of the same
function. We have called this feature
overriding base class functions.
We have shown in Figure 2.13 a human
hierarchy. All humans have to work, so the
human class defines a function called
Work(). All Humans Work(), but a
specialized class like student, which is a
subclass of human, must work in a college
and in libraries and laboratories. Hence, you
will see that student has overridden the base
class function called Work() with its own
specialized Work() method. Also observe
that CSESTUDENT would like use (inherit)
the same Work() as that of its base class
student. Hence, he has not defined its own
version and hence base class function
Work() is available to it. On the other hand,
ECESTUDENT probably has to work in
hardware laboratories and hence has
overridden base class Students Work()
with its own implementation.
Figure 2.13 Polymorphism at work: ECE students has own
work(): CSE student works with Student Work() because
CSESTUDENT has not overridden.
2.14 Summary
Exercise Questions
Objective Questions
1. i
2. i and ii
3. i, ii and iv
4. i, ii and iv
1. i
2. i and ii
3. ii and iv
4. i, ii and iv
1. i
2. i and ii
3. ii and iv
4. i, ii and iv
1. i, iii and iv
2. i, ii and iii
3. ii and iv
4. i, ii and iv
1. i, iii and iv
2. i, ii and iii
3. ii and iv
4. i, ii and iv
1. i, iii and iv
2. i, ii and iii
3. ii and iii
4. i, ii and iv
1. i and ii
2. i, ii and iii
3. ii and iii
4. i, ii and iv
1. i and ii
2. i, ii, iii and iv
3. ii and iii
4. i, ii and iv
1. i and ii
2. i, ii, iii and iv
3. ii and iv
4. i, ii and iv
1. i and ii
2. i, ii, iii and iv
3. ii, iii and iv
4. i, ii and iv
Short-answer Questions
LEARNING OBJECTIVES
Implementation in C++
class BankAccount { … };
class SavingAccount
{private: BankAccount Account;
};
Implementation in Java
Not supported in Java. The lifetime of a
composite object depends completely on the
garbage collector.
class Human
{public:
protected: // variables declared as
protected are public to
derived classes
// protected variables
};
// Student inherited from Human,
inheritance type is public
class Student : public Human
{public:
private:
};
Implementation in C++
class BankAccount { … };
class SavingAccount : public BankAccount
{ … };
Implementation in Java
public class BankAccount { … }
public class SavingAccount extends
BankAccount { … }
3.4 Overloading
A class can declare several variations in a
function with the same name but with
different implementations. This is termed as
overloading. We show below base class
overloading its Move() method:
Move() { cout<<”move by car”):
Move(int m) { cout<<” move by Bus”); //
m =1
MoveFamily(int m , int n ) { cout<<”move
with family”); // n=number
Now if derived class Son decides to
override only on of the Move() function with
its own implementation like: Move() {
cout<<”Move by scooter”).
Then, balance two overloaded functions of
base class shown below will be truncated
and will not be available to derived class,
namely:
Move(int m) { cout<<” move by Bus”); //
m =1
MoveFamily(int m , int n ) { cout<<”move
with family”); // n=number
Implementation in C++
class Student { … };
class Athlete { … };
class Professional : public Student,
public Athlete { … };
3.8 Interface
As shown above, Java language has solved
the problem ambiguity in multiple
inheritance by simply not allowing multiple
inheritance feature at all. Instead, it solves
this problem by allowing only one
inheritance, i.e. single base class and
multiple interfaces. An interface provides
names of the functions it provides service
and a class can implement an interface
which in turn has functions implemented in
one of the derived classes of the interface.
3.16 Decoupling
In inheritance, we have reusable code.
Encapsulation means binding data and code.
When run-time polymorphism is being used,
it is best to polymorphically decouple the
encapsulation to prevent discrete code
modules from interacting with each other. In
practice, you will notice that base class
overridden function is automatically hidden
and can be called explicitly by referring to
the base class function.
3.18 Summary
1. Extensibility and reusability of OOP languages have
been realized with language features like inheritance,
virtual inheritance, standard templates, etc.
2. Containment represents a has type of relation.
Supported by C++ but not supported by Java. A class
contains an instance of another class.
3. Containment is also called composition and aggregation
in the literature.
4. Base class is called superclass in Java. Derived class is
termed as subclass. In inheritance, all non-private
members are available to descendants. That is, base
class is generalization and derived class or subclass is
specialization.
5. In inheritance, subclass functions can override base
class overloaded functions. If subclass function
overrides only one of the overloaded functions of base
class, then balance overloaded functions will be
truncated and will not be available to base class.
6. Inheritance types supported by C++ are
Single- and Multilevel inheritances
Hierarchical inheritance
Multiple and hybrid inheritance (not supported by
Java)
7. Multiple inheritance is deriving a class from more than
one base class.
8. Base class and derived class are called superclass and
subclass in Java.
9. Subclass methods can override base class functions. If
such overriding takes place of overloaded base class
functions, then balance of overloaded functions are
truncated and they are not available to subclasses.
10. If more than one subclass is derived from the same base
class, then the base class is called a virtual base class.
11. If a subclass derives from more than one base class, then
to resolve the ambiguity arising out of the multiple
inheritance relation, both the base classes must be
declared as virtual. Inheritance is called virtual
inheritance.
12. Java solves the problems of ambiguity due to multiple
inheritance type of relations by allowing only single
inheritance but several interfaces. The interfaces contain
only names of the functions and hide implementation of
these functions. Implementation of an interface is
also called realization.
13. Dynamic_cast operator, which allows the program
to safely attempt conversion of an object into an object
of a more specific object type. This feature relies on
RTTI.
14. Run-time polymorphism means that with a pointer
to base class, we can decide at run-time to call particular
derived classes overriding function. In other words, we
can bind the overriding function from several of the
derived classes with a pointer to base class.
15. Virtual Function: If function is declared as virtual
function in base class, then we can execute an overriding
function with the same name in the derived class with a
pointer to base class. Pointer to base class is provided by
virtual function.
16. Pure Virtual Function in C++: Pure virtual
functions are virtual functions with “=0” attached at the
end. No object can be created for a class with pure
virtual functions defined in it.
17. Java supports interfaces to implement the concept of
pure virtual functions of C++.
Exercise Questions
Objective Questions
1. i and ii
2. i, ii and iii
3. i, ii and iii
4. i, ii and iv
Short-answer Questions
1. False
2. True
3. b
4. c
5. a
6. a
7. b
8. b
9. a
4
Dynamic Modelling
LEARNING OBJECTIVES
4.5.1 Architecture
We have users of the system and use cases.
We have classes in the software we are
developing. Classes are a reflection of the
real-world client (users) and what they want
(use cases). Based on clients and their real-
world interactions, we define interaction
between objects and classes as links and
associations to deliver functionality. This
arrangement is termed as architecture.
We can define architecture as a depiction
of objects and their attributes together with
the operations these objects perform to meet
user specifications or needs.
4.5.2 Domain
The clients and their interactions exist in the
real world. Class is a conceptual model that
maps real-world problems to software. The
users’ world is called domain.
We will show the users domain and our
architecture as a collection of square boxes
that contain names of the objects (Fig. 4.4).
We will also show their links and
associations by drawing interconnecting
lines. As we have studied in Chapter 2, we
can also amplify by specifying role names
and multiplicities. In Example 4.2, we
consider domain and architecture of a
college.
Figure 4.4 Domain and architecture diagram for a college
Figure 4.11a Expanded state diagram for the event select item
4.12 Summary
Exercise Questions
Objective Questions
1. i and iii
2. i and ii
3. i and iii
4. i, ii and iv
1. i and iii
2. i and ii
3. i and iii
4. i, ii and iv
1. i and iii
2. i, ii and iv
3. i and iii
4. i, ii and iv
5. The UML
1. Unifies the theories of Booch, Rumbagh and Ivar Jacobson
2. Unifies development methodologies such as OOSE, OMT and
Booch
3. Unifies SASD and OOAD
4. Unifies RUP and development methodologies
1. i and iii
2. i and ii
3. i and iii
4. i, ii and iv
1. i
2. ii
3. ii and iv
4. i, ii and iii
1. i
2. ii
3. ii and iv
4. i, ii, iii and iv
1. i and ii
2. ii
3. i, iii and iv
4. i, ii, iii and iv
1. i and ii
2. ii
3. i, iii and iv
4. i, ii, iii and iv
1. i and ii
2. ii
3. i, iii and iv
4. i, ii and iii
1. i, ii and iv
2. ii
3. i, iii and iv
4. i, ii and iii
1. i, ii and iv
2. ii
3. i, ii, iii and iv
4. i, ii and iii
Short-answer Questions
1. a
2. b
3. b
4. True
5. d
6. c
7. b
8. a
9. c
10. d
11. c
12. c
13. d
14. a
15. c
16. b
5
LEARNING OBJECTIVES
Advantages
It has clearly distinguishable phases, hence amenable to
project management.
DFDs, ERDs, etc., are easy to understand graphical
tools.
Widely used in industry and mature technique.
Function/process oriented. It follows natural thinking
process.
Modular and hence flexible.
Disadvantages
Only functional requirements are met. Ignores non-
functional requirements.
User–analyst interactions cannot be automated. It is
manual and non-iterative.
Communications with user after requirement analysis is
non-existent.
Hard to decide when to stop decomposing.
Where to use structure analysis and
design
SASD is best suited for very well-known and standard
domains.
Areas where SRS is specified.
In transaction processing systems.
When good amount of development time is available.
5.5.5.6 Composition
5.5.5.7 Aggregation
CollegeIntranet GRCSITE
Grievance Class
Course DOC
GRCDET password.
TGRC AIR
Faculty Department
Event AIR
ATR
GRCSITE Student
Grievance GRCDET
AIR AIR
Event
ToInquire() ToAllocate()
ToProvide() ToCallGRC()
ToCallGRC() ToOrganize()
ToConsult() ToInitiate()
ToInform() ToDisplay()
Differences
SASD is process-oriented.
OOAD is data-oriented.
OOAD encapsulates Data and Process.
Heavy reliance of OOAD on reusable components.
In SASD, the user requirements are collected and
specifications are drawn based on requirements, and
users are then asked to sign off on the specifications.
In OOAD, the requirements and specifications are
matched repeatedly over the entire development period
and users are involved at each stage.
5.9 Summary
Exercise Questions
Objective Questions
1. Specifications are deliverables for
1. feasibility study
2. analysis phase
3. design phase
4. problem definition.
1. i
2. i and ii
3. i, ii and iii
4. ii, iii and iv
1. i
2. i and ii
3. i, ii and iii
4. ii, iii and iv
1. i and iv
2. i and iii
3. i, ii and iii
4. None
1. i
2. i and ii
3. i, ii and iv
4. ii, iii and iv
1. i
2. i and ii
3. i, ii and iv
4. i, ii, iii and iv
1. i
2. i, ii and iii
3. ii, iii and iv
4. i, ii, iii and iv
1. i
2. i, ii and iii
3. ii, iii and iv
4. i, ii, iii and iv
1. i
2. i, ii and iii
3. ii, iii and iv
4. i, ii, iii and iv
1. i and ii
2. i, ii and iii
3. iii and iv
4. i, ii, iii and iv
1. i and iv
2. i, ii and iii
3. ii, iii and iv
4. i, ii, iii and iv
1. i and iv
2. i, ii and iii
3. ii, iii and iv
4. i, ii, iii and iv
1. i, ii and iii
2. i, ii and iv
3. i, ii, iii and iv
4. ii, iii and iv
Short-answer Questions
1. b
2. d
3. d
4. c
5. b
6. a
7. c
8. d
9. c
10. d
11. b
12. c
13. a
14. b
15. c
6
LEARNING OBJECTIVES
d:\oopsc++\c++chap1> edit
HelloWorld.cpp
1. /* HelloWorld.cpp. This is our
first program to introduce you
2. to some basic io statements like
cin and cout & multi line comment*/
3. #include<iostream> //iostream, a
library file contains cin , cout
programs
4. using namespace std;
5. void main( ) // start of maim
programme
6. {
7. char name[20]; // name is a data
type of char of c++ length 20
8. cout<<”\n Please enter your name :
“; //cout is an object of iostream
9. cin>>name; // cin is an object of
iostream cout<<”\n Hello “<<name<<endl;
//\n means goto new line
10. cout<<”\n Welcome to Objective
Oriented Programming in C++”<<endl; //
endl means goto new line
11. cout<<”\n Best Wishes from
authors. Have a good day!”<<endl;
12. }// end of main
Step 2: Compile
We need to store all our compiled code in
d:\oopsc++\c++chap1. Therefore, from
the directory d:\oopsc++\c++chap1.
Compile the source file
Compile it using #gcc
HelloWorld.cpp Output using # a.out
for Linux based system
Run ----- Compile -----
Execute for Turbo C
N
o
.
8
:
6.5.2 Arrays Implementation
In this example, we will show the use of
arrays. Array is a data structure comprising
of contiguous memory location. It will store
the same data type in all locations. In
Example 6.5.1, we have taken in the radius
and immediately declared the result and
continued the process till user entered 0 to
exit. In this example, we will take all the
radii and heights of several sizes of cones
(ice cream?) together and store them in
memory location, compute corresponding
volumes of these cones and store them as
well and declare the results in the end. Array
comes to our rescue here. Array is used to
hold the same data type in contiguous
memory locations. We will define three
arrays named radius, height, and volume,
each with a dimension of 10 elements as
shown is Figure 6.5.
Figure 6.5 Arrays for radius heights and volume
Li cin>>radius[i]>>height[i] ; inputs
n values for radius and height. Data values need
e to be separated by space while entering the
N data.
o.
13
:
Li for (i=0; i<= n; i++) It is a header
n statement of for loop. Initial condition is i=0;
e Final condition for loop to terminate is i<=
N n; The loop will be executed in Steps of 1.
o.
Hence i++)
2
8:
struct Student
{
char name[20];
int rollNo;
float totalmarks;
char grade;
};
students
// Stud typecasted to Student structure
typedef struct Student
1. #include<iostream>
2. using namespace std;
3. //declare a class called Student
4. class Student
5. {
6. private:
7. int rollNo;
8. char name[30];
9. double marks[5];// set of five
subject marks
10. double tot;
11. double avg;
12.public:
13. void GetData(int n);
14. void ComputeAvg(int n);
15. void DispData(int n);
16.};
17.// Define member functions
18.void Student::GetData(int n)
19.{ cout<<“\n Enter Students Details
”<<endl;
20. cout<<“ Enter Roll No <space>
name : ”;
21. cin >>rollNo>>name;
22.cout<<“ Enter marks in ”<<n<<“
subjects separated by spaces :”;
23.for ( int i=0;i<n;i++)
24.cin>>marks[i];
25.}
26.void Student::DispData(int n)
27.{ cout<<rollNo<<“ ”<<name<<“ ”;
28.for ( int i=0;i<n;i++)
cout<<marks[i]<<“ ”;
29.cout<<“ ”<<tot<<“ ”<<avg<<endl;
30.}
31.void Student::ComputeAvg(int n)
32.{ tot=0;
33.for ( int i=0;i<n;i++)
34.tot +=marks[i];
35.avg=tot/n;
36.}
37.void main()
38.{
39.Student std[60];//std object of
class Student with maximum of 60
students
40.int n; //no of student
41.// Get the number of students in
the class
42.cout<<“ Enter number of Students in
the class : ”;
43.cin>>n;
44.// get the data for n number of
students
45.for ( int i=0;i<n;i++)
46.std[i].GetData(n);
47.// Compute Average
48.for (i=0;i<n;i++)
49.std[i].ComputeAvg(n);
50.// Print the details of the student
51.cout<<“Roll No”<<“ Name”<<“
Marks”<<“ Total”<<“ Avg”<<endl;
52.for ( i=0;i<n;i++)
53.std[i].DispData(n);
54.}
/* Output :Enter number of Students
in the class : 2
Enter Students Details
Enter Roll No <space> name : 50595
Ramesh
Enter marks in 2 subjects separated
by spaces :87 89
Enter Students Details
Enter Roll No <space> name : 60695
Gautam
Enter marks in 2 subjects separated
by spaces :99 98
oll No Name Marks Total Avg
0595 Ramesh 87 89 176 88
0695 Gautam 99 98 197 98.5
*/
1. #include<iostream>
2. #include<stdio.h> // for gets()
and puts
3. #include<string> // for finding
string length using strlen() function
4. using namespace std;
5. void main()
6. { int len;
7. char line[80]; // declare an array
of 80 characters length
8. cout<<”\nEnter any line: “;
9. gets(line); // read a line till
‘enter’(new line character is pressed )
10. len = strlen(line);
11. puts(line); // output a line
12. cout<<”\nLength of given string =
“<<len<<endl;
13. }
/*OutputEnter any line: Hello
World
Hello World
Length of given string = 11*/
1. #include<iostream>
2. #include<string>
3. using namespace std;
4. void main()
5. { int len1,len2;
6. char text[20], stg[20];
7. //char line[20];
8. cout<<”\nEnter a line of Text”;
9. cin.getline(text,20);
10. len1=strlen(text);
11. cout.write(text, len1);
12. // cout<<”\nNow input put usiing
cin>>”;
13. // cout<<”\nObserve that cin>> can
not read white spaces like space”<<endl;
14. // cin>>line;
15. // cout<<line;
16. cout<<”\noutput second string
using cin.getline()”<<endl;
17. cin.getline(stg,20);
18. len2=strlen(stg);
19.
cout.write(stg,len2).write(text,len1);
20. cout<<“\nEnd of Programme“<<endl;
21. }
/*Output: Enter a line of TextI
Love India!
I Love India!
output second string using
cin.getline()
I Love Delhi
I Love DelhiI Love India!
End of Programme*/
6.7 Summary
Exercise Questions
Objective Questions
1. i and iv
2. i, ii and iv
3. i, ii and iii
4. ii and iv
1. i and ii
2. ii, iii and iv
3. i, ii, iii and iv
4. i and iv
14. The operator >> can read white spaces like blan
TRUE/ FALSE
15. The cin.getline(string,length) can read white
space TRUE/FALSE
16. The cin.get() cannot read white
spaces TRUE/FALSE
Short-answer Questions
1. a
2. d
3. d
4. True
5. False
6. True
7. True
8. b
9. c
10. a
11. c
12. a
13. d
14. False
15. True
16. False
7
LEARNING OBJECTIVES
7.1 Introduction
In this chapter, we introduce you to rich
C++. We analyse the data types permitted by
C++ language, together with various
operators like logical operators and
arithmetic operators. In Chapter 1, you have
of course used these features, but in this
chapter we will provide you with the
underlying syntax and grammar of C++. We
have shown the workings of various types of
operators such as binary operators and
unary operators and bitwise operators with
sample programs. The precedence and
association of operators are also presented.
a) Integer Constants:
Hexadecimal constants:
A hexadecimal number must start with 0x or 0X
followed by digits 0 to 9 or alphabets a to f; both
uppercase or lowercase are allowed.
Allowed hexadecimal constants are: 0xffff, 0xa11f,
0x65000UL.
Illegal hexadecimal constants are: 0x14.55, illegal
character “.”
Note that the character constant ‘5’ is not the same as the
number 5. The last constant is a blank space. Character
constants have integer values known as ASCII values. For
example, the statement: cout<<’a’; would print number
97, the ASCII value of letter a. Since each character
constant represents an integer value, it is also possible to
perform arithmetic operations on character constants.
Special characters that cannot be printed normally,
double quote (“) apostrophe (‘), question mark (?),
backslash (\), etc. can be represented by using escape
sequences. An escape sequence always starts
with \ followed by special character stated
above. Table 7.1 provides details of escape sequences and
special effects.
Bell \a
Back space \b
Horizontal tab \t
Vertical tab \v
Form Feed \f
New line \n
Carriage return \r
Double Quote \”
Apostrophe/Single Quote \’
Backslash \\
Null \0
Octal number \On
Hexadecimal number \cHn
d) String constants:
color color1,color2;
color1=2; // means color1 will
be GREEN
f) Symbolic Constants:
7.5 Expressions
An expression can comprise any one of the
following:
1. A single character or a number.
2. A single constant or a variable.
3. A combination of variables or constants, interconnected
by operators.
4. A logical condition that is true (value 1) and false (value
0).
7.6 Operators
Line No. 7:
max=n1>n2?(n1>n3?n1:n3):(n2>n3?
n2:n3);
Firstly n1>n2 is evaluated.
If n1>n2
max=(n1>n3?n1:n3). If n1>n3
returns n1 else n3
Else
max=(n2>n3?n2:n3); If n2>n3
returns n2 else n3
1. #include<iostream>
2. using namespace std;
3. int main()
4. { int n = 149;
5. int res;
6. res = n & 0017;
7. cout<<”The resultant of Bitwise
AND operator is “<<res<<endl;;
8. res = n | 0017;
9. cout<<”The resultant of Bitwise OR
operator is “<<res<<endl;;
10. res = n && 0017; // this is
logical AND. Truth or false will be
output
11. cout<<”The resultant of Logical
AND operator is “<<res<<endl; ;
12. res = n || 0017; // this is
logical OR . Truth or false will be
output
13. cout<<”The resultant of Logical OR
operator is “<<res<<endl;;
14. res = n ^ 0017;
15. cout<<”The resultant of Exclusive
operator is “<<res<<endl;;
16. res = n <<2;
17. cout<<”The resultant of shift left
( by 2 bits) operator is “<<res<<endl;;
18. res = n >>2;
19. cout<<”The resultant of shift
right ( by 2 bits) operator is
“<<res<<endl;;
20. res = ~n;
21. cout<<”The resultant of NOT
operator is “<<res<<endl;
22. return 0;
23. }
/*Output : The resultant of
Bitwise AND operator is 5
The resultant of Bitwise OR
operator is 159
The resultant of Logical AND
operator is 1
The resultant of Logical OR
operator is 1
The resultant of Exclusive
operator is 154
The resultant of shift left (by 2
bits) operator is 596
The resultant of shift right (by 2
bits) operator is 37
The resultant of NOT operator is –
150*/
if (expression)
statement;
The syntax is
if (expression)
{
statements;
}
else
{
statements;
}
Else statement is optional. But if used
it will be associated with the nearest
if statement. In the example shown, else
is attached to innermost if.
if ( totalMarks > 60)
if ( total Marks > 70)
cout<<“passed with
distinction”<<endl;
else
cout<<“passed with first
class”<<endl;
Use of brace brackets dictate the
association rule for else statements.
Else in the following code is linked up
with first if statement:
if ( totalMarks > 60)
{ if ( total Marks > 70)
{ cout<<“passed with
distinction”<<endl;
}
1. #include<iostream>
2. #include<conio.h> // console input
/output for getch() and clrscr()
3. using namespace std;
4. const int MAX=60;
5. void main()
6. { float temp ;
7. cout<<”Enter <temperature of the
heater> :”;
8. cin>>temp;
9. while (temp<MAX)
10. cout<<”\n Temperature is
lukewarm. Switch on heater”<<endl;
11. cout<<”\nWater is hot. Switch off
the heater” <<endl;
12. } // end of main
/*Output :Enter <temperature of the
heater> :67
Water is hot. Switch off the heater
*//*
The syntax is
Do
{
block of statements
} while (expression);
1. #include<iostream>
2. #include<conio.h>// console
input/output for getch() and clrscr()
3. using namespace std;
4. void main()
5. { int n;
6. int num ,sum = 0, avg=0,count =1;
7. // input N
8. cout<<”\n Enter value of <N>:”;
9. cin>>n;
10. // control loop
11. do
12. { cout<<”\n Enter value of
“<<count<<”number”;
13. cin>>num;
14. sum+=num;
15. count++;
16. }while (count <= n ); //end of do
while. Observe semicolon
17. avg=sum/n;
18. cout<<”\n Sum of” <<n<<”numbers
=”<<sum<<endl;
19. cout<<”\n Average
of”<<n<<”numbers =”<<avg<<endl;
20.} // end of main
/*output: Enter value of <N>:3
Enter value of 1number45
Enter value of 2number76
Enter value of 3number78
Sum of 3numbers =199
Average of 3numbers =66*/
#include<iostream>
#include<conio.h>// console input
/output for getch() and clrscr()
using namespace std;
void main()
{ int n;
int num ,sum = 0, avg=0,count;
// input N
cout<<”\n Enter value of <N>:”;
cin>>n;
// control loop
for(count=1; count<=n ; count++)
{cout<<”\n Enter value of
“<<count<<”number”;
cin>>num;
sum+=num;
avg=sum/n;
cout<<”\n Sum of” <<n<<”numbers
=”<<sum<<endl;
cout<<”\n Average of”<<n<<”numbers
=”<<avg<<endl;
getch();
} // end of main
/*Output: Enter value of <N>:3
Enter value of 1number67
Enter value of 2number76
Enter value of 3number87
Sum of 3numbers =230
Average of 3numbers =76*/
#include<iostream>
#include<conio.h>// console input
/output for getch() and clrscr()
using namespace std;
void main()
{ int i , j ; // counters for outer and
inner for loop
for (i=15; i<16; i++) // outer loop
{
cout<<”\n Multiplication table for
“<< i<<” X “<<20<<endl;
for (j=15; j<20 ; j++) // inner loop
{
cout<<endl<<i<<” X “<<j<<” =
“<< i*j;
} // end of inner for loop
} // end of outer for loop
} // end of main
/*Output : Multiplication table for 15 X
20
15 X 15 = 225
15 X 16 = 240
15 X 17 = 255
15 X 18 = 270
15 X 19 = 285 */
7.9.1 Break
Break statement is used to exit from the
switch control or control loop. We can use
break statement to exit from for, while and
do-while, and switch control statements.
You have already seen the use of break
statements in Switch statement. Observe
how break is used to come out of if
statement below:
#include<iostream>
#include<conio.h>// console input
/output for getch() and clrscr()
using namespace std;
void main()
{
int count=0;
int sum,num;
for ( ;;) // for ever for loop
{ if(count == 5)
{ cout<<”\n reached upper limit of 5:
breaking the for loop”;
break;
}
else
{
cout<<”\n Enter value of “
<<count+1<< “ number :”;
cin>>num;
sum+=num;
count++;
}
} // end of for
} // end of main
/*Output
Enter value of 1 number :89
Enter value of 2 number :90
Enter value of 3 number :91
Enter value of 4 number :92
Enter value of 5 number :93
reached upper limit of 5: breaking the
for loop*/
#include<iostream>
#include<conio.h>// console input
/output for getch() and clrscr()
using namespace std;
void main()
{ int count;
for ( count=0;count<=10;count++)
{ if( (count %2)== 0) // the number is
even.
{ cout<<”\n even number: continue at
the beginning if for loop:
“<<count<<endl;
continue; //control goes to beginning
of for loop
}//end of if
else
{
cout<<”\n odd number : “<<count<<endl;
}
} // end of for
} // end of main
/*output even number: continue at the
beginning if for loop: 0
odd number : 1
even number: continue at the beginning
if for loop: 2
odd number : 3
even number: continue at the beginning
if for loop: 4
odd number : 5
even number: continue at the beginning
if for loop: 6
odd number : 7
even number: continue at the beginning
if for loop: 8
odd number : 9
even number: continue at the beginning
if for loop: 10*/
#include<iostream>
#include<conio.h>// console input
/output for getch() and clrscr()
using namespace std;
void main()
{ int num ,sum=0,count=0;
start: cout<<”\n Enter value of
<number> number :”;
cin>>num;
sum+=num;
count++;
cout<<”\n number: “<<num<<endl;
if ( count > 3)
goto stop1;
else
goto start;
stop1: cout<<”\n exiting the main
program”<<endl;
} // end of main
/*Output
Enter value of <number> number :55
number: 55
Enter value of <number> number :67
number: 67
Enter value of <number> number :54
number: 54
Enter value of <number> number :65
number: 65
exiting the main program*//*
7.10 Summary
1. A token is a smallest individual unit in a program.
2. C++ has three types of integer constants, namely,
decimal octal and hexadecimal constants.
3. Character constants must be enclosed in single quotes.
Non-printable character constants are represented by a
backslash followed by a character.
4. String constants. String constants can contain any
number of characters in sequence, but enclosed in
double quotation marks.
5. Enumeration is a user-defined data type and its
members are constants. It can be used effectively to
associate integer values to variables.
6. Intrinsic or basic data types like int, char, float, double,
etc. Intrinsic or basic data types are those that do not
contain any other data type.
7. Derived data types are: Arrays, functions, pointers,
references and constants.
8. User-defined data types are: class, structure, union and
enumeration.
9. Output operator << directs output stream to standard
output device, i.e. display. It is tied to iostream object
called cout. Similarly, input operator >> gets input from
standard input device, i.e. keyboard and tied to
iostream object called cin.
10. Unary operators: In unary operators, operators precede
a single operand. Unary operators are: –, ++, --.
sizeof.
11. sizeof operator will be useful for determining the
size allocated for a data type by the computer.
12. Arithmetic operators. The basic (also known as
intrinsic) operators are +, –, *, /, %. C++ language does
not support exponentiation.
13. Type conversion: If the variable involved in an
operation are of different types, then type conversion is
carried out before the operation.
14. Type cast: When we want to declare the result in a
particular data type, we can type cast.
15. The relational operators are: > >= < and <= . they
have lower priority than arithmetic operators. equality
operators = = and ! = have priority just below relational
operators.
16. Logical operators: These are && and ||. Evaluation
of expressions connected by logical operators are done
from left to right and evaluation stops when either truth
or falsehood is established.
17. Conditional expressions: Question mark operator. The
syntax is: z = exp1 ? expr 2 : exp3. Exp1 is
evaluated first. If it is true, z is equated to the result of
exp2. Else z is equated to exp3.
18. Comma operator: This operator is used to string
together several expressions.
19. Loop is executed once first and the condition is checked.
Use do-while loop, when we know that the loop needs to
be executed at least once.
20. For loop, as control loop is used, when we know the
exact number of times the loop needs to be executed.
21. Break. Break statement is used to exit from the switch
control or control loop. We can use break statement to
exit from for, while and do-while, and switch control
statements.
22. Continue is used when we want to stop further
processing of loop statements and start at the beginning
of the control loop.
23. Exit function. You can force a program to stop
whatever it is doing and return the control to operating
system by using exit() function.
Exercise Questions
Objective Questions
1. i and ii
2. i, ii and iii
3. ii, iii and iv
4. i, iii and iv
1. i and ii
2. i, ii and iii
3. i, ii, iii and iv
4. i, iii and iv
1. i and ii
2. i, ii and iii
3. ii, iii and iv
4. i and iv
1. i and ii
2. i, iii and iii
3. i, ii and iv
4. i and iv
1. 4
2. 5
3. 6
4. 7
1. i, ii and iii
2. i, iii and iv
3. i, ii and iv
4. i and iv
1. i and ii
2. i, iii and iv
3. i, ii and iv
4. i and iv
24. What are the data types allowed by C++? Explain with
examples.
25. What are IO operators? Explain with examples.
26. Explain type conversion and type casting of operators.
27. Explain bitwise operators with examples.
28. Explain precedence and association of operators.
29. Distinguish the switch and if else statements.
30. When do you use for statement and while statements?
State the situation when for statements are better than
while statements.
Assignment Questions
1. d
2. c
3. c
4. b
5. c
6. b
7. d
8. a
9. a
10. b
11. a
12. c
13. a
14. b
15. True
8
LEARNING OBJECTIVES
Template<class
T>
T FindMax( T a
, T b);
#include <iostream>
using namespace std;
//fn template definition
template <class T>
T FindMax (T a, T b);
void main ()
{ int i=50, j=70, k;
long int x=75000, y=98000, z;
k=FindMax<int>(i,j);
z=FindMax<long int>(x,y);
cout << «\n Larger of the two integers
: «<<i<<» & «<<j<<» : «<< k << endl;
cout << «\n Larger of the two long
integers : «<<x<<» & «<<y<<» : «<< z <<
endl;
}
//fn template definition
template <class T>
T FindMax (T a, T b)
{T max;
max = (a>b)? a : b;
return (max);
}
//Output :Larger of the two integers :
50 & 70 : 70
Larger of the two long integers: 75000 &
98000 : 98000*/
#include<iostream>
using namespace std;
// function prototype declarations
template<class T>
void Swap ( T x , T y); // to
interchange values
void main() //Calling Function
{ float x=100.00; // x & y are local
to main()
float y=1000.00;
int a=5 , b=10;
cout<<”\n Before calling Swap function
<x and y >”<< x<<”\t”<<y<<endl;
cout<<”\n Before calling Swap function
<a and b >”<< a<<”\t”<<b<<endl;
// call the function and pass
arguments x & y
Swap(x,y); //Called Function
Swap(a,b); //Called Function
cout<<”\n After return from Swap <x
and y >”<<x<<”\t”<<y<<endl;
cout<<”\n After return Swap function
<a and b >”<< a<<”\t”<<b<<endl;
}//end of main
// function definition
template<class T>
void Swap ( T x , T y)
{ float temp ; // temp is local to
Swap function
temp = x; // store x in temp
x=y; // store y in x
y=temp; // store temp in y
cout<<”\n Inside Swap <x and y
>”<<x<<”\t”<<y<<endl;
} // end of Swap//
//output :Before calling Swap function
<x and y >100 1000
Before calling Swap function <a and b
>5 10
Inside Swap <x and y >1000 100
Inside Swap <x and y >10 5
After return from Swap <x and y >100
1000
After return Swap function <a and b >5
10*/
#include<iostream>
using namespace std;
// function prototype declarations
template<class T>
void Sort( int n , T a[]); // receives
number of items & array
void main()
{ int i,n=10;// number of items
int a[] ={
67,87,56,23,100,19,789,117,6,1}; //
array with 10 elements
double b[] = {
18.0,87.9,92.1,1.0,5.0,8.7,78.99,34.0,21
.5,10.0};// array of double
cout<< “\n Given integer array”<<endl;
for (i=0;i<n;i++)
cout<<” “<<a[i];
// we are passing array a. Note that
array name is ‘a’ . Name is address.
Sort(n,a);
cout<<”\n Sorted integer array \n”;
for (i=0;i<n;i++)
cout<<” “<<a[i];
cout<< “\n Given double array”<<endl;
for (i=0;i<n;i++)
cout<<” “<<b[i];
// we are passing array b. Note that
array name is ‘b’ . Name is address.
Sort(n,b);
cout<<”\n Sorted double array \n”;
for (i=0;i<n;i++)
cout<<” “<<b[i];
}//end of main
// function definition
template<class T>
void Sort(int n , T a[])
{ for ( int i=0; i< n-1; i++) // last
value need not be sorted
{ T temp;
// find the smallest of remaining
numbers and exchange it with for ( int
j=i+1; j< n; j++)
{ if (a[j] < a[i])
{ // swap
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
//Output : Given integer array
67 87 56 23 100 19 789 117 6 1
Sorted integer array
1 6 19 23 56 67 87 100 117 789
Given double array
18 87.9 92.1 1 5 8.7 78.99 34 21.5 10
Sorted double array
1 5 8.7 10 18 21.5 34 78.99 87.9
92.1*/
Example 8.5:
callbyconstref.cpp: Passing
Constant Reference to a Function
#include<iostream>
using namespace std;
// function prototype declarations
void PrintNetPay(const float & BP ,
float & cr , float db); void main()
{ float bp=2000.00, cr = 0.60*bp, db =
.25*bp;
// we are passing variables by value ,
by reference and by constant reference
PrintNetPay(bp,cr,db);
}//end of main
// function definition
void PrintNetPay(const float &bp, float
& cr , float db)
{ float total = bp+cr-db;
//bp+=1000.00; // error . l-value
specifies const object. constant
reference .
//Hence cannot be altered. Hence
commented out
cout<<”\n Total Net Pay = “<<
total<<endl;
}
//Output :Total Net Pay = 2700 */
8.6 Recursion
Recursion is an advanced feature supported
by C++ language. Recursion means a
function calling itself. Consider the problem
of finding a factorial of a number. In the
example, we can clearly see that Fact(5) is
calling Fact(4) and so on.
Fact(5) = 5 x 4 x 3 x 2 x 1
= 5 x Fact(4)
= 5 x 4 x Fact(3)
= 5 x 4 x 3x Fact(2)
= 5 x 4 x 3x 2 x Fact(1)
= 5 x 4 x 3x 2 x 1 x Fact(0)
= 5 x 4 x 3x 2 x 1 ( Fact(0) =1)
Example 8.6: factrecur.cpp A
Program for Finding Factorial of a
Number Using Recursion
#include<iostream>
using namespace std;
// function prototype
int fact(int a);
void main()
{ int x,ans;
cout<<»enter a number:»;
cin>>x; //input from the user*/
ans=fact(x); //function call*/
cout<<»\nfactorial=»<<ans<<endl;
} //end of main*/
int fact(int a) //function definition*/
{ int ans;
if(a<=0)
return(1); // fact(0) = 1 by
definition
else
ans =a*fact(a-1); //function call
with recursion*/
return(ans); //returns the value of
fact to main*/
} //end of function fact*/
// Output: enter a number:7
factorial=5040*/
#include<iostream>
using namespace std;
// function prototype declarations
template<class T>
inline T FindArea( T r ){ return (
r*r ) ; }
// two argument surface area of the
cylinder
template<class T>
inline T FindArea( T r, T h ){ return
( r*h ) ; }
inline int FindSum( int a=10 , int
b=20 , int c=30) { return a+b+c ;}
void main() //Calling Function
{cout<<”\n Function overloading for
Different Number and Different Types of
Arguments”<<endl;
cout<<”\n calling FindArea(r) function <
r >-integer argument:”<<FindArea(10)
<<endl;
cout<<”\n calling FindArea( r , h )
function - float 2 arguments
:”<<FindArea(10.5,20.5)<<endl;
cout<<”\n calling FindArea( r , h )
function - integers 2 arguments
:”<<FindArea(10,20)<<endl;
cout<<”\n***********************”<<endl;
cout<<”\n a and b and c values set as
default values are
:”<<10<<”\t”<<20<<”\t”<<30<<endl;
cout<<”\n FindSum with no arguments
supplied “ <<FindSum()<<endl;
cout<<”\n FindSum with : a (one )
arguments supplied
“<<100<<”\t”<<FindSum(100)<<endl;
cout<<”\n FindSum with : a and b (two )
arguments
supplied”<<100<<”\t”<<200<<”\t”
<<FindSum(100,200)<<endl;
cout<<”\n FindSum with : a and b (two )
arguments
supplied”<<100<<”\t”<<200<<”\t”<<300<<”\
t”<<FindSum(100,200,300)<<endl;
}
//Output: Function over loading for
Different Number and Different Types of
Arguments
calling FindArea(r) function < r >-
integer argument:100
calling FindArea( r , h ) function -
float 2 arguments :215.25
calling FindArea( r , h ) function -
integers 2 arguments :200
a and b and c values set as default
values are :10 20 30
FindSum with no arguments supplied 60
FindSum with : a (one ) arguments
supplied 100 150
FindSum with : a and b (two ) arguments
supplied100 200 330
FindSum with : a and b (two ) arguments
supplied 100 200 300 600*/
Table 8.2 Storage classes with their location, scope and life
span
Static Variables: In several situations,
you will need accessibility of variables
declared in a function for all function; we
will declare such variables as static. For
example,
#include<iostream>
#include<conio.h>
using namespace std;
#define GETDATA cout << “Enter the
value: “ <<endl
void main()
{int x , y;
GETDATA;
cin >> x ;
GETDATA;
cin >> y;
cout << endl << «values entered are «
<<x << « « << y;
getch();
}
// Output: Enter the value: 35
Enter the value: 45
values entered are 35 45*/
Preprocessor directive like #define
GETDATA cout << «Enter the value: «
<<endl will simply substitutes all the
occurrences of GETDATA with cout <<
«Enter the value: « <<endl
#include<iostream>
#include<conio.h>
using namespace std;
#define UPPER 5000
#define BONUS1 1000
#define BONUS2 500
#define bp 1000
void main()
{ int netpay;
cout << ”The basic pay is: ” << bp ;
#if bp < UPPER
netpay=bp + BONUS1;
#else
netpay=bp+BONUS2;
#endif
cout <<endl << ”netpay = ” << netpay;
getch();
} // end of main
//Output: Enter the basic pay 1000
netpay = 2000*/
8.12.6 #undef
A macro must be undefined before it is
redefined. Consider the macro definitions.
In this module, we will also use conditional
inclusion like #ifdef
#include<iostream>
#include<conio.h>
using namespace std;
#define UPPER 100
#define LOWER 10
#define WRITEDATA cout << “answer = “ <<
ans << endl ;
void main()
{ int temp= 70,ans=10;
if (temp<UPPER && temp>LOWER)
WRITEDATA;
#ifdef UPPER
#undef UPPER
#endif
#ifdef LOWER
#undef LOWER
#endif
// now we can set new limits for UPPER
& LOWER
#define UPPER 60
#define LOWER 50
if (temp<UPPER && temp > LOWER)
WRITEDATA;
getch();
}// end of main
//Output: Answer=10(printed from the 1st
if statement, the second WRITEDATA is
not executed as the 2nd if loop returns
a false.)*/
#include<iostream>
using namespace std;
void main()
{ int i,n; //number of elements of array
x
int x[]={80,90,100,50,65,70};
n= sizeof(x)/sizeof(int);
cout<<”\n size of data type <int>:”<<
sizeof(int)<<endl;
cout<<”\n Memory space allocated to
x[6]:”<<sizeof(x)<<endl;
cout<<”\n no of elements in array x =
“<<n<<endl;
cout<<”\n array elements\taddress in
hexa “;
for (i=0;i<n; i++)
cout<<”\n”<<x[i]<<”\t\t”<<&x[i]<<endl;
cout<<”\n”;
}
//Output :size of data type <int>:4
Memory space allocated to x[6]:24
no of elements in array x = 6
array elements address in hexa
80 0012FF60
90 0012FF64
100 0012FF68
50 0012FF6
65 0012FF70
70 0012FF74*/
// #include<iostream>
using namespace std;
// function prototype declarations
void main()
{ int count=0,i;
int len; // length of the string
char c;
char x[20]; // array of characters .
string
cout<<”\n Enter a word and press
<enter> :”;
c=cin.get(); // // get a character
while ( c!=’\n’) // ‘\n’ is end of
line character, i.e. pressing
enter key
{x[count]=c;
count++;
c=cin.get();
}
// we have reached end of line. Append
‘\0’ to the string
x[count]= ‘\0’;
len = count;
// Now display the string you have just
read
cout<<”\n String inputted : “<<x;
cout<<”\n space allocated to single
char(byte) :”<<sizeof(char) <<endl;
cout<<”\n Memory space allocated to
string x[] :”<< sizeof(x) <<endl;
cout<<”\n No of characters in the string
x [] : “<<len<<endl;
// now reverse the string
cout<<”\n string X reversed : “;
for ( i=len-1;i>=0;i--)
cout<<x[i];
}//Output :Enter a word and press
<enter> :HELLO
String inputted : HELLO
space allocated to single char(byte) :1
Memory space allocated to string x[] :20
No of characters in the string x [] : 5
string X reversed : OLLEH */
#include<iostream>
using namespace std;
// functional prototype declarations
void Transpose( int A[10][10], int n
);// n is the order of square matrix
void ReadMatrix( int A[10][10], int n );
void PrintMatrix( int A[10][10], int n
);
void main()
{ int n,A[10][10];
cout<<”Enter the order of square
matrix <n>”;
cin>>n;
ReadMatrix(A,n);
cout<<”The elements of the Matrix
are:”<<endl;
PrintMatrix(A,n);
cout<<”The elements of the Transpose
Matrix are:\n”<<endl;
Transpose(A,n); //function call. A is
name of matrix. Name is address is
} //end of main
void Transpose(int A[10][10],int n)
//function definition*/
{ for(int i=0;i<n;i++) //loop1. i=1
because you don’t have to touch
x[0][0]
{ int t;
for(int j=0;j<i;j++) //loop2
{t=A[i][j];
A[i][j]=A[j][i]; //swapping
A[j][i]=t;
} //end of loop2
}
PrintMatrix(A,n); // output the matrix
} //end of function transpose
void ReadMatrix( int A[10][10], int n)
{cout<<”Enter the elements :”<<endl;
for(int i=0;i<n;i++)
{for(int j=0;j<n;j++)
cin>>A[i][j]; //input elements*/
}
}//end of ReadMatrix
void PrintMatrix( int A[10][10], int n)
{for(int i=0;i<n;i++)
{ for(int j=0;j<n;j++)
{ cout<<”\t”<<A[i][j]; }
cout<<”\n”<<endl;
}
}//end of ReadMatrix
//output : Enter the order of square
matrix <n>2
Enter the elements
1 2 3 4
The elements of the Matrix are:
1 2
3 4
The elements of the Transpose Matrix
are:
1 3
2 4 */
#include<iostream>
using namespace std;
// Fn Prototypes
void Concat ( char x[],char y[]);
void main()
{ char x[20],y[20]; // x & y are two
strings
cout<<»enter any 2 strings\n»;
cin>>x>>y; //input 2 strings from the
user*/
Concat(x,y); //function call*/
}//end of main*/
void Concat(char a[],char b[])
//function definition*/
{ for(int i=0;a[i]!=’\0’;i++) // check
for ‘\0’ occurrence
cout<<a[i];
cout<<» «;
for(i=0;b[i]!=’\0’;i++)
cout<<b[i];
} //end of function concat*/
// output :enter any 2 strings HELLO
BROTHER : HELLO BROTHER*/
8.14 Summary
Exercise Questions
Objective Questions
Short-answer Questions
1. a
2. c
3. True
4. False
5. b
6. a
7. b
8. b
9. False
10. c
11. a
12. b
13. a
14. c
15. b
16. b
17. d
18. b
19. c
9
LEARNING OBJECTIVES
9.1 Introduction
In our experience of teaching C++, we found
that learners are pretty confused about
pointers and references and related memory
management. This is mainly because they
would have probably picked up the “what”
of pointers and references and not the
“why” of pointers and references. In this
chapter, we would like to bring out special
characteristics of pointers and references
like
Pointers are just like any other variables.
Pointers have an address like a variable.
Pointers point to a variable or a structure like array or
an object.
If you want a value of the object pointed by pointer just
dereference the pointer.
Operator new allocates memory for the pointer and
delete frees the memory.
The best part of pointers is that they can be reassigned.
References are another name for the object.
References always refer to the object.
References cannot be reassigned.
int age=50;
int age2=18;
//we want pointer ptr to point to age;
ptr = & age; // you have assigned ptr
to age. & is called address operator
cout<< age; // displays 50
cout<<*ptr; // displays 50 . *ptr which
is value stored location, i.e. 50
//Once created you can reassign
pointers
ptr=& age2;
cout<<*ptr; // displays 18 . *ptr which
is value stored location, i.e. 18
#include<iostream>
using namespace std;
void main()
{ int age1=50;
int age2=18;
//create a pointer
int * ptr=0;
// assign it to age1
ptr = & age1; // & is address of
operator
cout<<”\n age1 “<< age1<<endl; //
displays 50
cout<<”\n age1 with *ptr “<<
*ptr<<endl; // displays 50 .*ptr is
value.
cout<<”\n address using (&age1) and
ptr : “<<&age1<<”\t”<<ptr<<endl;
// ptr is address of age1, so is
&age1. Hence both must be same
// now we will reassign the same
pointer to age2
ptr = & age2;
cout<<”\n your age (*ptr) : “<<”\t”<<
*ptr; // displays 18 .*ptr is value
stored location
cout<<”\n address of (&age2) and ptr :
“<<& age2<<”\t”<<ptr<<endl;
// ptr is address of age2 so is &age2.
Hence both must be same.
cout<<”\n address of(&ptr) :”<<”\t”<<
& ptr<<endl; // prints out address of
variable
// ptr. We are not interested in this
address. It is just another address.
}//end of main
/*Output:
age1 50
age1 with *ptr 50
address using (&age1) and ptr : 0012FF7C
0012FF7C
your age (*ptr) : 18
address of (&age2) and ptr : 0012FF78
0012FF78
address of(&ptr) : 0012FF74
#include <iostream>
using namespace std;
// declaration of function prototypes
void Swap( int a , int b); // call by
value
void PtrSwap ( int *a , int * b); //
Call by Ref. a & b are pointers by def
void main()
{ int x=5;
int y=10;
// call by value
Swap( x,y);
cout<<"\nafter call by value :"<<endl;
cout<<"x value after swap:"<<x<<endl;
cout<<"y value after swap:"<<y<<endl;
// call by reference using pointers.
Note that we have to send pointers
//i.e. addresses of x & y . Hence we
will pass &x , and & y.
PtrSwap(&x,&y);
cout<<"\nafter call by ref using
pointers :"<<endl;
cout<<"x value after Ptrswap:"
<<x<<endl;
cout<<"y value after Ptrswap:"
<<y<<endl;
}//end of main
// Function definitions
void Swap ( int a, int b)
{ int temp ; // two local variables
temp=a;
a=b;
b=temp;
cout<<"\ninside Swap using pointers
:"<<endl;
cout<<"x value inside Swap:"
<<a<<endl;
cout<<"y value inside Swap:"
<<b<<endl;
}
void PtrSwap ( int *a, int *b)
{ // a & b are pointers . Hence we
need a pointer called temp
int temp;
temp=*a;
*a=*b;
*b=temp;
cout<<"\ninside PtrSwap using
pointers :"<<endl;
cout<<"x value inside Ptrswap:"
<<*a<<endl;
cout<<"y value inside Ptrswap:"
<<*b<<endl;
}
/*Output :inside Swap using pointers :
x value inside Swap:10
y value inside Swap:5
after call by value :
x value after swap:5
y value after swap:10
inside PtrSwap using pointers :
x value inside Ptrswap:10
y value inside Ptrswap:5
after call by ref using pointers :
x value after Ptrswap:10
y value after Ptrswap:5 */
#include<iostream>
sing namespace std;
// function prototypes
template<class T>
T FindMax( T x[] , int n);
template<class T>
void SortArray( T *a , int n);
void main()
{ int n;
int max; // n=no of values in an array
int *x; // x is a pointer to an array
cout<<"how many elements in your array
:";
cin>>n;
// allocate dynamic memory space using
new operator
x=new int[n]; // allocates 12
contiguous location to pointer x
// read in the array
for (int i=0;i<n;i++)
{ cout<<"value for "
<<i+1<<"element:";
cin>>x[i];
}
cout<<("\n The entered array is….\n");
for (i=0;i<n;i++)
cout<<" "<<* (x+i); // same as writing
x[i]
// call Findmax function
max=FindMax(x,n);//x is a pointer to
array
cout<<"\n maximum value of given
array="<<max<<endl;
// call SortArray function
SortArray(x,n);
cout<<("\n The entered array is….\n");
for (i=0;i<n;i++)
cout<<" "<<x[i]; // same as writing *
(x+i)
// now that our work with array is over
let us delete the memory allocated
delete [] x; // memory allocated with
new operator stands released
}//end of main
// Fn definition
template<class T>
T FindMax(T x[], int n)
{ T max;
int i;
max=T(); // *x is the value of 1
element
for(i=1;i<n;i++)
{ if (max<*(x+i))
max=*(x+i);
}
return max;
} // end of FindMax
template<class T>
void SortArray( T *a ,int n)
{ int i,j; // i for outer loop j for
inner loop and temp for swapping
T temp=T();
for ( i=0; i< n-1; i++) // last value
need not be sorted
{
// find the smallest of
remaining numbers and exchange it with
for ( j=i+1; j< n; j++)
{ if (*(a+j) < *(a+i))
{ // swap
temp=*(a+i);
*(a+i)=*(a+j);
*(a+j)=temp;
}
}
}
}
/*output : how many elements in your
array :6
value for 1element:32
value for 2element:43
value for 3element:34
value for 4element:65
value for 5element:67
value for 6element:12
The entered array is….
32 43 34 65 67 12
maximum value of given array=67
The sorted array is….
12 32 34 43 65 67
#include<iostream>
using namespace std;
// functional prototype declarations
void ReadMatrix( int **A,int m , int n);
void PrintMatrix( int **A , int m , int
n);
void main()
{ int m,n;
int **A=0; // A is a pointer to
pointer
cout<<”Enter the order of matrix <m,n>
:”;
cin>>m>>n;
/* Now allocate dyn memory. First
allocate to rows
Then allocate to columns. We will use
try and catch blocks.
Try will allocate dyn memory. If it
fails due to non-availability of memory
then it will throw the exception object.
Catch block will catch the exception
thrown by try block and take
remedial measures. */
try
{ A=new int * [m]; // dynamic memory
for row allocation
for (int i=0;i<m;i++)
A[i]=new int[n]; // dynamic memory
for columns
}
catch (bad_alloc)
{ cout<<”\n bad
allocation”<<endl;
exit(1);
}
ReadMatrix(A,m,n);
printf(“The elements of the Matrix
are:\n”);
PrintMatrix(A,m,n);
} /*end of main*/
void ReadMatrix( int **A, int m,int n)
{ int i,j;
cout<<”Enter the elements :”;
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
cin>>A[i][j]; /*input
elements*/
}
}//end of ReadMatrix
void PrintMatrix( int **A, int m,int n)
{ int i,j;
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
cout<<” “<<A[i][j];
cout<<endl;
}
}
/*output: Enter the order of matrix
<m,n> :2 2
Enter the elements :1 2 3 4
The elements of the Matrix are:
1 2
3 4*/
#include<iostream>
using namespace std;
void main()
{ // array of pointers with 5 elements
char *ptr[5]=
{“welcome”,”to”,”self_learning”,”C++A”,”
Books”};
char *x; // x is a pointer of type char
x=ptr[0]; // x now points to ptr, i.e.
starting pointer in an array of pointers
for ( int i = 0 ; i< 5; i++)
cout<<”\n”<< *(ptr+i)<<endl;
// following cout statements will teach
you more about array of pointers
cout<<”\n”<< *ptr[3]; // you can expect
value of starting element in CDS i.e. C
}
/*Output:
welcome
to
self_learning
C++
Books*/
Declaration:
int x;
float salary;
void *ptr ; // pointer to void data type
declaration
Definition:
ptr = & x ; // assign pointer to type
integer
Usage:
Type casting the void pointer is mandatory
cout<<*(int*)ptr;
Reassignment:
ptr=&sal;
cout<< * (float*)ptr; // typecasting of
ptr to float
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
void main()
{ int x=100;
float sal=2000.00;
void * ptr;// ptr is a pointer to
data type void
// assign void pointer to int
ptr=&x;
cout<<”\nptr type casted to integer
:”<< *(int*)ptr; // typecasting of ptr
to int
// assign void pointer to float
ptr=&sal;
cout<<”\nptr type casted to float
:”<<*(float*)ptr; // typecasting of ptr
to float
}//end of program
/*Output : ptr type casted to integer
:100
ptr type casted to float :2000*/
// pointer to int
int val = 25;
// int variable
int *ptr = & val ; // ptr
is a normal pointer
cout<<++(*ptr); // output 26
cout<<++ptr; // ptr is incremented
// constant pointer to int
int const * cptr = & val; // cptr is
constant pointer to int
cout<<++(*cptr); // Allowed . output
26
cout<<++cptr; // Not allowed . cptr
cannot be incremented
// pointer to constant float PI
const float PI=3.14159;
// float variable PI declared as
constant
const float * cfptr = &PI; //
cfptr is pointer to const data type
float
cout<<++(*cfptr); // Not Allowed as
*cfptr is constant
cout<<++cfptr; // Allowed .
Increments cfptr
// constant pointer to constant float PI
const float * const cfptc = & PI ; //
cfptr is const pointer to const data
cout<<++(*cfptr); // Not
Allowed as *cfptr is constant
cout<<++cfptr; // Not
Allowed . cfptr is constant.
#include<iostream>
using namespace std;
void FindTriangle(float &a , float & b
);
void FindRect(float &a , float & b );
void (*funptr) ( float & , float & ); //
ptr to function
void main()
{ float x= 25.0 , y=50.0;
int choice;
cout<<"\n Enter your choice .. < 0 to
quit : 1 for Triangle : 2 for Rectangle
>";
cin>>choice;
while ( choice !=0)
{ switch (choice)
case 0 : cout<<"\n exiting the
programme…."<<endl;
exit(0);
case 1 : funptr = FindTriangle;
break;
case 2 : funptr=FindRect; break;
}// end of switch
funptr(x,y);
cout<<"\n Enter your choice .. < 0 to
quit : 1 for Triangle : 2 for Rectangle
>";
cin>>choice;
}//end of while
}//end of main
//Fn definitions
void FindTriangle( float &a , float &b)
{cout<<"\n Area of the Triangle = "<<
0.5*a*b << endl;}
void FindRect( float &a , float &b)
{cout<<"\n Area of the Rectangle = "<<
a*b << endl;}
/*Output : Enter your choice .. < 0 to
quit : 1 for Triangle : 2 for Rectangle
>1
Area of the Triangle = 625
Enter your choice .. < 0 to quit : 1 for
Triangle : 2 for Rectangle >2
Area of the Rectangle = 1250
Enter your choice .. < 0 to quit : 1 for
Triangle : 2 for Rectangle >0*/
#include<iostream>
using namespace std;
void main()
{ int age1=50;
int age2=18;
//create a reference to age1 i.e. an
alias by name rage to age1
int & rage=age1; //rage is an alias or
another name to age1
cout<<”\n age1 “<< age1<<”\t”<<”&age1
“<< &age1<<endl; // displays address of
age1
cout<<”\n age1 with rage”<<
rage<<”\t”<<”&rage “<< &rage<<endl;
cout<<”\n both rage and age1 must have
same addresses..”<<endl;
/* you cannot reassign references like
you did for pointers. If you do, the
original assigned data will be lost*
rage = age2;
cout<<”\n wehave forcibly reassigned a
reference to “;
cout<<”\n another variable. Rage is an
alias of age1.”;
cout<<”\n Therefore age1 will now have
value of age2.”<<endl;
cout<<”\n age1 “<< age1<<”\t”<<”&age1
“<< &age1<<endl;
cout<<”\n age2 “<< age2<<”\t”<<”&age2
“<< &age2<<endl;
cout<<”\n rage assigned to age2 but
value it hold is age1 :”<<rage<<endl;
}//end of main
/*Output : age1 50 &age1 0012FF7C
age1 with rage50 &rage 0012FF7C
both rage and age1 must have same
addresses..
we have forcibly reassigned a reference
to
another variable. Rage is an alias of
age1.
Therefore age1 will now have value of
age2.
age1 18 &age1 0012FF7C
age2 18 &age2 0012FF78
rage assigned to age2 but value it holds
is age1 :18*/
#include<iostream>
using namespace std;
// declaration of function prototypes
void RefSwap ( int &a , int & b); //
Call by Ref. a & b are pointers by def.
void main()
{ int x=5, y=10;
// call by reference using reference.
Note that we have to send reference
//In prototype we have promised to
send references like &a and &b
//i.e. addresses of x & y . Hence we
will pass x and y.
RefSwap(x,y);
cout<<”\nafter call by ref using
References :”<<endl;
cout<<”x value after
RefSwap:”<<x<<endl;
cout<<”y value after
RefSwap:”<<y<<endl;
}//end of main
// Function definitions
void RefSwap ( int &a, int &b)
{ // a & b are references . Hence we
need ordinary variable temp
int temp; temp=a; a=b; b=temp;
cout<<”\ninside RefSwap using
reference :”<<endl;
cout<<”x value inside
RefSwap:”<<a<<endl;
cout<<”y value inside
RefSwap:”<<b<<endl;
}
/*Output:
inside RefSwap using reference :
x value inside RefSwap:10
y value inside RefSwap:5
after call by ref using References :
x value after RefSwap:10
y value after RefSwap:5 */
Example 9.14: RefSwap.cpp. A
Program to Swap Values by Using
References Concepts
22. What are pointers? List out reasons for using pointers.
23. Explain the process of assessing a variable through its
pointer. Give an example.
24. How to use pointers as arguments in a function? Explain
through an example.
25. Explain the process of declaring and initializing
pointers. Give an example.
26. Distinguish pointer * operator (indirection operator)
and address operator(&) with examples.
27. Explain passing by reference using pointers and using
reference.
28. Which usage is better: pointers or reference? Why?
29. Distinguish & operator and reference in C++ language.
30. Differentiate array of pointers and pointer to an array.
31. Explain heap memory space or free storage space.
32. Explain dynamic memory operators new and delete.
33. How do you declare an array on heap memory? Explain
with examples.
34. How do you allocate dynamic memory for a two-
dimensional array using pointer to pointer concept.
35. Explain how a void pointer could be useful.
36. Explain pointer to a function with examples.
37. Distinguish dangling pointer and memory leak with
examples.
38. Explain different ways to use & operator.
39. Distinguish reference operator and dereference
operator.
40. Explain pointer to pointer declaration in case of two-
dimensional array.
Long-answer Questions
1. d
2. b
3. d
4. b
5. True
6. True
7. False
8. True
9. a
10. d
11. True
12. True
13. False
14. True
15. False
16. a
17. d
18. False
19. True
20. True
21. False
10
Classes
LEARNING OBJECTIVES
10.1 Introduction
We use class in C++ to define our own data
type. A class is a derived data type like an
array. The difference is that in an array you
have single data type, while in a class data
type you can have different data types. These
different data types can be intrinsic data
types such as int, float, etc. or derived or
user-defined data types or functions
or operators.
Object contains data types and functions
and/or operators defined by class. So we can
call object as an instance of a class. In
other words, object is a variable of data
type class. We can define an object as an
independent entity that holds its own data
and member functions. We can say that
object tells us the data it holds and allowable
operations on the object. A class therefore
allows us to encapsulate member
functions and member data into
single entity called object.
Object-oriented programming involves
writing programs that use classes. We create
objects of different classes to solve the
problem at hand and make objects
communicate with each other through the
member functions. In this chapter, we will
learn how to solve problems by using classes
and objects. We will also cover topics such
as data hiding and abstraction and access
privileges enjoyed by members of the class.
This chapter introduces the concepts of
constructor and destructor. Variations in
member functions such as friend functions
and inline functions are discussed. Classes
within a class, called container classes, are
introduced. Different methods to use
dynamic memory with objects using
pointers and references are highlighted with
their merits and demerits. This operator and
static member functions and their relevance
and usage are explained.
#include<iostream>
using namespace std;
//declare a class called Student
class Student
{ public:
// overloaded constructors
Student(){rollNo=0,name=”No Name”;}
Student(int n, char *p)
{rollNo=n,name=p;}
Student( const Student & src) //
copy constructor
{
rollNo=src.GetRollNo();name=src.GetName(
);
cout<<” Copy
Constructor….”<<endl;}
~Student(){}; // Default destructor
// public access functions
int GetRollNo() const { return
rollNo;}
void SetRollNo ( int n) {
rollNo=n;}
char * GetName() const { return
name;}
void SetName( char *p) { name=p;}
private:
int rollNo;
char *name; // pointer to name
};
void main()
{ Student std; // object created
cout<<” \n Students rollNo set by
Default constructor : “
<<std.GetRollNo()<<endl;
cout<<”\n Students name set by
Default constructor : “
<<std.GetName()<<endl;
//set roll no to 6060 and name to
gautam.
//We have to use public accessory
function to update private data
// Why ? Because we are not inside
member function
std.SetRollNo(6060);
std.SetName(“Gautam”);
cout<<”\n Students rollNo set by
SetRollNo :”
<<std.GetRollNo()<<endl;
cout<<”\n Students name set by
SetName :”
<<std.GetName()<<endl;
// Now let us make use of overloaded
constructor
Student std2(7070,”Ramesh”);
cout<<” \n Students rollNo set by
(int n, char *p) overloaded
constructor : “
<<std2.GetRollNo()<<endl;
cout<<”\n Students name set by (int
n, char *p) overloaded : “
<<std2.GetName()<<endl;
// Now let us use copy constructor
and copy std2 onto std3
Student std3(std2); // std is copied
on to new object called std3
cout<<” \n Students(std3 rollNo) :
“<<std3.GetRollNo()<<endl;
cout<<”\n Students (std3 name) :
“<<std3.GetName()<<endl;
}
/*Output : Students rollNo set by
Default constructor : 0
Students name set by Default constructor
: No Name
Students rollNo set by SetRollNo :6060
Students name set by SetName :Gautam
Student(std2.rollNo) set by (int n, char
*p) overloaded constructor : 7070
Student(std2.name) name set by (int n,
char *p) overloaded : Ramesh
Copy Constructors
Students(std3 rollNo) : 7070
Students (std3 name) : Ramesh*/
// constructor
~Polar(){} // Default Destructor
friend void DisplayPolar(Polar v);
// to display in polar forms
friend Polar Multiply(Polar v1,
Polar v2);
// all member data is declared as
private
private:
double r; // magnitude
double t; // angle theeta
};
void DisplayPolar(Polar v) // For a
friend we do not use scope resolution
operator
{ // We can directly use r and t because
DisplayPolar() is a friend function
cout<<”Magnitude”<<v.r<<” Angle
=”<<v.t<<endl;
}
Polar Multiply(Polar v1, Polar v2)
{ Polar v3;
v3.r = v1.r * v2.r; // multiply
the magnitudes
v3.t = v1.t+v2.t; // add the
angles
return v3;
}
void main()
{Polar v1(5.0,53.0),v2(6.0,28.0),v3; //
v1,v2,v3 is the object of Polar class
// multiply Polar Vectors v1 & v2 and
store it in v3
v3=Multiply(v1,v2);
cout<<“\nThe Given Vectors in Polar
form form ….\n“<<endl;
cout<<“\nPolar form vector v1 :“;
DisplayPolar(v1);
cout<<“\nPolar form vector 2 v2 :“;
DisplayPolar(v2);
cout<<“\nv3=v1*v2 in Polar Form :“;
DisplayPolar(v3);
}// end of main
/*Output :The Given Vectors in Polar
form form ….
Polar form vector v1 :Magnitude5 Angle
=53
Polar form vector 2 v2 :Magnitude6 Angle
=28
v3=v1*v2 in Polar Form :Magnitude30
Angle =81*/
#include <iostream>
using namespace std;
class Date
{public:
Date ( int d=0, int m=0,int y=0)
:dd(d),mm(m),yy(y) { } // constructor
void SetDate( int d, int m, int y){
dd=d,mm=m,yy=y;}
int GetDD() const { return dd;};
int GetMM() const { return mm;};
int GetYY() const { return yy;};
private:
int dd;
int mm;
int yy;
};
class Student
{ public:
Student();
~Student(){}; // Default destructor
int GetRollNo() const { return
rollNo;}
void SetRollNo ( int n) { rollNo=n;}
Date GetDOB() const { return
dateDOB;}
Date GetDOJ() const { return
dateDOJ;}
void SetDOB( Date dtb) {
dateDOB=dtb;}
void SetDOJ( Date dtj) {
dateDOJ=dtj;}
private:
int rollNo;
Date dateDOB;
Date dateDOJ;
};
Student::Student()
{ dateDOB.SetDate(14,11,54);
dateDOJ.SetDate(25,11,77);
rollNo=5050;
}
void main()
{ Student std; // object created
cout<<” \n Students rollNo set by
Default constructor : “<<std.
GetRollNo()<<endl;
cout<<”\n date of Birth :”;
cout<<std.GetDOB().GetDD()
<<”/”<<std.GetDOB().GetMM()
<<”/”<<std.GetDOB().GetYY()<<endl;
cout<<”\n date of Joining :”;
cout<<std.GetDOJ().GetDD()
<<”/”<<std.GetDOJ().GetMM()
<<”/”<<std.GetDOJ().GetYY()<<endl;
}
/*Output : Students rollNo set by
Default constructor : 5050
date of Birth :14/11/54
date of Joining : 25/11/77*/
void main()
{ Student std; // object created
Student *ptr = new Student;//
object on free store created
cout<<” \n Students rollNo set by
Default constructor : “
<<ptr->GetRollNo()<<endl;
cout<<”\n Students name set by
Default constructor : “
<<ptr->GetName()<<endl; // access
member data from heap
//set roll no to 50
ptr->SetRollNo(6060);
ptr->SetName(“Gautam”);
cout<<”\n Students rollNo set by
SetRollNo :”
<<ptr->GetRollNo()<<endl;
cout<<”\n Students name set by
Default constructor :”
<<ptr->GetName()<<endl;
//now delete the memory from heap
delete ptr; // we need to delete
and free dynamic memory
}
/*output :Students rollNo set by Default
constructor : 50595
Students name set by Default constructor
: Anand
Students rollNo set by SetRollNo :6060
Students name set by Default constructor
:Gautam*/
#include<iostream>
using namespace std;
//declare a class called Student
class Student
{ public:
Student(){rollNo=50595,grade=’A’;}
~Student(){}; // Default destructor
int GetRollNo() const { return
rollNo;}
void SetRollNo ( int n) {
rollNo=n;}
char GetGrade() const { return
grade;}
void SetGrade( char p) { grade=p;}
private:
int rollNo;
char grade;
};
void main()
{ // ptr is normal pointer on heap
Student *ptr = new Student;
// conststudent is a pointer to
constant Student
const Student *conststudent = new
Student
//constptr is constant pointer to
Student
Student * const constptr = new
Student;
const Student * const cptr = new
Student;
cout<<”explore the possibilities
with normal heap pointer *ptr”<<endl;
cout<<” \n Students rollNo set by
Default constructor : “
<<ptr->GetRollNo()<<endl;
cout<<”\n Students Grade set by
Default constructor : “
<<ptr->GetGrade()<<endl;
//set roll no to 50 and Garde to B
ptr->SetRollNo(6060);
ptr->SetGrade(‘B’);
cout<<“\n Students rollNo set by
SetRollNo() function :“
<<ptr->GetRollNo()<<endl;
cout<<“\n Students name set by
setgrade() function:“
<<ptr->GetGrade()<<endl;
cout<<“\nexplore the possibilities
with pointer *conststudentto“<<endl;
cout<<“ constant object
Student“<<endl;
cout << ”\n Display Grade
…“<<conststudent ->GetGrade()<<endl;
//conststudent->SetGrade(‘C’);
//NOT OK.
/*const pointer calling non-const
fn . This is error. conststudent is a
pointer to constant Student, whereas
SetGrade is a non-constant function and
can change value. Hence we cannot use.
You will observe error C2662: ‘SetGrade’
: cannot convert ‘this‘ pointer from
‘const class Student‘ to ‘class Student
&‘ Hence it
shown in comments */
// constant pointer to constant
data object
cout<<“\nexplore the possibilities
with const pointer *cptr to“<<endl;
cout<<“ constant object
Student“<<endl;
cout<<“\ncptr->
GetGrade()..“<<cptr->GetGrade()
<<endl;//ok
//cout<<“\ncptr-
>SetGrade(‘C‘)..“<<cptr->SetGrade(‘C‘)
<<endl;//not ok
//now delete the memory from heap
delete ptr;
delete cptr;
delete conststudent;
}
/*Output :explore the possibilities
with normal heap pointer *ptr
Students rollNo set by Default
constructor : 50595
Students Grade set by Default
constructor : A
Students rollNo set by SetRollNo()
function :6060
Students name set by setgrade()
function:B
explore the possibilities with pointer
*conststudentto
constant object Student
Display Grade …A
explore the possibilities with const
pointer *cptr to
constant object Student
cptr-> GetGrade()..A/*
<<*(std2->GetGrade())<<endl;
//pass by ref ptr
#include<iostream>
using namespace std;
//declare a class called Student
class Student
{ public:
Student();
Student(int n, float t, char c);
Student(Student &);
~Student(){cout<<”\n This is
destructor..\n”;
delete rollNo;delete grade;delete
total;} // Default destructor
int *GetRollNo() const { return
rollNo;}
void SetRollNo ( int n) {
*rollNo=n;}
char *GetGrade() const { return
grade;}
void SetGrade( char p) { *grade=p;}
float * GetTotal() const { return
total;}
void SetTotal( float t) { *total=t;}
private:
int *rollNo;
float *total;
char *grade;
};
Student::Student()
{ cout<<"\nThis is default
constructor…\n";
rollNo= new int;
grade= new char(‘D’); //
default Grade
total=new float;
}
Student::Student(int n, float t,
char c)
{ cout<<"\n This is
Student(int,float,char) constructor…\n";
rollNo= new int(n);
grade= new char(c);
total=new float(t);
}
Student::Student(Student &src) //
src means source
{ cout<<"This is copy
constructor..\n";
rollNo=new int(*
(src.rollNo));
grade=new char(*(src.grade));
total=new float(*
(src.total));
}
// Three non-member functions
Student FindGrade( Student std); //call
by value
Student * FindGrPtr(Student *std); //
call by ref using pointers
Student & FindGrRef (Student &std); //
call by reference using reference
void main()
{ cout<<"\n create an ordinary object
called std for Student class..\n";
Student std; // an object made.
Therefore constructor will be called
Student *std2=new Student(); // std2 is
created on heap.
std.SetRollNo(50);
std.SetTotal(99.0);
cout<<”\n RollNO:”<<*(std.GetRollNo())
<<”\t”
<<”Total:”<<*(std.GetTotal())<<endl;
// now call a function FindGrade(Student
std)
// See how copy constructors are
involved one for forward copy and one
for return
// see also how value set by local
variable(grade =A) is reflected in the
main
// because you are returning the object
by value using statement return std
// you should also see two destructors
FindGrade(std);
cout<<”\n Students Grade set by
FindGrade() :”
<<*(std.GetGrade())<<endl;
// now call a functon FindGrPtr( Student
*std)
// See how copy constructors and
destructors are not involved at all
// see also how value set by local
variable(grade) is reflected in the main
std2=FindGrPtr(std2); // pass by
reference pointer method
cout<<”\n Students Grade set by
FindGrPtr() : “
<<*(std2->GetGrade())<<endl;
//pass by ref ptr
// now call a function FindGrref(Student
& std)
// See how copy constructors and
destructors are not involved at all
// see also how value set by local
variable(grade) is reflected in the main
FindGrRef(std); // pass by
reference reference method
cout<<”\n Students Grade set by
FindGrRef() :”
<<*(std.GetGrade())<<endl; //
pass by reference - reference */
}// end of main
// Define functions
Student FindGrade( Student std)
{ cout<<”\n FindGrade( Student std)
function …\n”;
cout<<” \n Students Grade set by
FindGrade() : \n”;
std.SetGrade(‘A’);
cout<<”\n inside FindGrade..:”<<*
(std.GetGrade())<<endl;
return std;
}
Student * FindGrPtr(Student *std)
{ std->SetGrade(‘B’);
cout<<”\n Inside FindGrPtr() :
“<<*(std->GetGrade())<<endl;
return std;
}
Student & FindGrRef ( Student &std)
{ std.SetGrade(‘C’);
cout<<”\n Inside FindGrRef() : “<<*
(std.GetGrade())<<endl;
return std;
}
/*Output :This is copy constructor..
FindGrade( Student std) function …
Students Grade set by FindGrade() :
inside FindGrade..:A
This is copy constructor..
This is destructor..
This is destructor..
Students Grade set by FindGrade() :D
Inside FindGrPtr() : B
Students Grade set by FindGrPtr() : B
Inside FindGrRef() : C
Students Grade set by FindGrRef() :C
This is destructor..*/
10.9 Constant Pointers and Constant
References
Recall that in the above example function
Student * FindGrPtr(Student
*std); receives the object by reference
using pointers. It also amends the Grade.
What if we want the function to receive the
object by reference because of efficiency and
yet should not be able to change the values.
Clearly the solution is to pass a constant
pointer to Student and thus FindGrPtr ()
not amend the object. This is because of the
stipulation that a constant pointer can only
call a constant function and constant
function by definition cannot alter the
values.
const Student * const FindGrPtr(const
Student * const std);
const Student & FindGrRef (const Student
&std);
//constptrref.cpp
#include<iostream>
using namespace std;
//declare a class called Student
class Student
{ public:
Student();
Student(int n, float t, char c);
Student(Student &);
~Student(){cout<<”\n This is
destructor..\n”;
delete rollNo;delete grade;delete
total;} // Default destructor
int *GetRollNo() const { return
rollNo;}
void SetRollNo ( int n) { *rollNo=n;}
char *GetGrade() const { return
grade;}
void SetGrade( char p) { *grade=p;}
float * GetTotal() const { return
total;}
void SetTotal( float t) { *total=t;}
private:
int *rollNo;
float *total;
char *grade;
};
Student::Student()
{ cout<<"\nThis is default
constructor…\n";
rollNo= new int;
grade= new char(‘D’); // default
Grade
total=new float;
}
Student::Student(int n, float t, char c)
{ cout<<"\n This is
Student(int,float,char) constructor…\n";
rollNo= new int(n);
grade= new char(c);
total=new float(t);
}
Student::Student(Student &src) // src
means source
{
cout<<"This is copy constructor..\n";
rollNo=new int(*(src.rollNo));
grade=new char(*(src.grade));
total=new float(*(src.total));
}
const Student * const FindGrPtr(const
Student * const std);
const Student & FindGrRef (const
Student &std);
void main()
{ cout<<"\n create an ordinary objet
called std for Student class..\n";
Student std; // an object made .
Constructor will be called
std.SetRollNo(50);
std.SetTotal(99.0);
cout<<"\n RollNO :"<<*std.GetRollNo()
<<"\t"<<"Total :"
<<*std.GetTotal()
<<"Grade : "<<*std.GetGrade()
<<endl;
// now call const Student * const
FindGrPtr(const Student * const std);
FindGrPtr(& std); // pass by
reference pointer method
cout<<"\n Students Grade after
return from FindGrPtr() : "
<<*std.GetGrade()<<endl;
// now call a function : const
Student & FindGrRef (const Student
&std);
FindGrRef(std); // pass by
reference reference method
cout<<"\n Students Grade after
returning from FindGrRef() :"
<<*std.GetGrade()<<endl;
}// end of main
const Student * const FindGrPtr(const
Student * const std)
{ //std->SetGrade(‘B’); // clearly
error constant pointer to constant obj
cout<<"\n Inside FindGrPtr() : "
<<*std->GetGrade()<<endl;
return std;
}
const Student & FindGrRef ( const
Student & std)
{ //std.SetGrade(‘C’); // clearly error
. student is a constant obj
cout<<"\n Inside FindGrRef() : "
<<*std.GetGrade()<<endl;
return std;
}
/*Output :create an ordinary objet
called std for Student class..
This is default constructor…
RollNO :50 Total :99Grade : D
Inside FindGrPtr() : D
Students Grade after return from
FindGrPtr() : D
Inside FindGrRef() : D
Students Grade after returning from
FindGrRef() :D
This is destructor..*/
Note that in cout statements in main()
and functions std.GetGrade() return a
pointer of character type as per our function
prototype declaration. Hence we have used
dereference operator * : *std.GetGrade()
or *std->GetGrade();
#include<iostream>
using namespace std;
//declare a class called Student
class Student
{ public:
Student(){count++;}
~Student(){count--;} // Default
destructor
static int count; // static data
member declared as public
};
int Student::count=0; // mandatory to
declare in global section
void main()
{
{ Student a,b; // two objects have been
created
Student ramesh, suresh;
cout<<”ramesh.count”<<ramesh.count<<”\t”
<<”suresh.count”
<<suresh.count<<endl;
cout<<”The above result shows that
static variable is available to ramesh &
suresh”;
}
cout<<”\nafter brace brackets
:”<<endl;
cout<<”a.count=”<<a.count<<endl;
Student w,x,y,z;
cout<<”\nafter creation of w x y z
:”<<endl;
cout<<”a.count”<<a.count<<”\t”<<”b.count
”<<b.count<<endl;
}
/*Output :ramesh.count4 suresh.count4
The above result shows that static
variable is available to ramesh & suresh
after brace brackets :
a.count=2
after creation of w x y z :
a.count6 b.count6*/
What happens if you declare the static
data as private? Quite simple. By now you
must have understood that the only way to
access a private data is through a public
accessory function. Code is reproduced for
static data type that is declared as private.
#include<iostream>
using namespace std;
//declare a class called Student
class Student
{public:
Student(){count++;}
~Student(){count--;} // Default
destructor
int GetCount() const { return
count;}// public function to access
static private data
private:
static int count; // static data
member declared as private
};
int Student::count=0; // mandatory
to declare in global section
void main()
{ Student a,b;
{ Student ramesh, suresh;
cout<<”ramesh.count”<<ramesh.GetCount()
<<”\t”<<”suresh.count”
<<suresh.GetCount()<<endl;
cout<<”The above result shows
that static variable is available to
ramesh & suresh”;
}
cout<<”\nafter brace brackets
:”<<endl;
cout<<”a.count=”<<a.GetCount()
<<endl; // because static private
declaration
Student w,x,y,z;
cout<<”\nafter creation of w x y z
:”<<endl;
cout<<”Student.count”<<x.GetCount()
<<”\t”<<”y.count”<<y.GetCount()<<endl;
}
/*Output :ramesh.count4 suresh.count4
The above result shows that static
variable is available to ramesh & suresh
after brace brackets :
a.count=2
after creation of w x y z :
Student.count :6 y.count : 6*/
10.11 Static Member Functions
The data members declared as static is
available for all instances of the class. That is
why we could use x.GetCount() and
y.GetCount() in the above program.
Therefore, it really does not matter which
object calls the function that displays static
data.
To make it independent of object we need
to define the member function as static.
static int GetCount() { return count;}//
public function to access static private
cout<<Student::GetCount() // you can
call static function without object
// by using
class name and scope resolution operator
#include<iostream>
using namespace std;
//declare a class called Student
class Student
{ public:
Student(){count++;}
~Student(){count--;} // Default
destructor
static int GetCount() { return
count;}// public function to access
static private data
private:
static int count; // static data
member declared as public
};
int Student::count=0; // mandatory
to declare in global section
void main()
{ Student a,b;
{ Student ramesh, suresh;
cout<<”Student.count”<<Student::GetCount
()<<endl;
}
cout<<”\nafter brace brackets :”<<endl;
cout<<”Student.count=”<<Student::GetCoun
t()<<endl;
Student w,x,y,z;
cout<<”\nafter creation of w x y z
:”<<endl;
cout<<”Student count
:”<<Student::GetCount()<<endl;
}
/*Output : Student.count4
after brace brackets :
Student.count=2
after creation of w x y z :
Student count :6
*/
10.12 Summary
Exercise Questions
Objective Questions
Short-answer Questions
1. a
2. a
3. d
4. c
5. True
6. False
7. False
8. True
9. b
10. b
11. c
12. b
13. b
14. c
15. b
16. True
17. a
18. b
11
LEARNING OBJECTIVES
11.1 Introduction
Many of you would have come across a pop-
up while using the Internet or operating
system, wherein the pop message says “OS
or Browser has experienced a serious
problem and needs to be closed down. Error
reporting is in process”. Indeed, error has
occurred. Despite elaborate testing prior to
delivery, errors cannot be prevented but
they can be minimized. In this chapter, we
will study of mechanism of C++ to handle
errors and exceptions.
An important feature of any modern OOPs
language is overloading. Overloading means
making a function or operator perform more
than one task, depending on the arguments
supplied, at run-time. Function overloading
is one such example. C++ has overloaded
the operators too. Intrinsic operators have
been overloaded thus enhancing the
efficiency of language.
1. try
2. { A=new int * [m];
3. for (int i=0;i<m;i++)
4. A[i]=new int[n];
5. }catch (bad_alloc) { cout<<”\n bad
allocation”<<endl;exit(1);}
try
{
// allocation code here
}
catch (bad allocation object){ }
catch ( File IO exception object) { }
try
{ // allocation code here
try{// inner try block code here}
catch ( File IO exception object)
{ }
}
catch (bad allocation object){ }
catch ( File IO exception object) { }
N
o
.
1
5
:
1. #include<iostream>
2. #include<string>
3. using namespace std;
4. const int max_size=3;
5. class Stack
6. { public:
7. Stack(); //default constructor
8. ~Stack(); //destructor
9. Stack& operator=(const Stack&);
//Assignment operator overloading
10. int size() const; //returns number
of elements in stack
11. int empty() const; //returns 1 if
stack is empty
12. int & top(); //returns top of stack
13. void pop(); //pops top of stack
14. void push(const int &); //pushes
element on top of stack
15. // exception classes
16. class stackfullerror {};
17. class stackemptyerror {};
18. private:
19. int* stack_array; //dynamic array
20. int tos; //top of stack pointer
21. int stack_size; //size of dynamic
array
22. };
23. //default constructor
24. Stack :: Stack()
25. { stack_array = new int[max_size];
26. stack_size = max_size;
27. tos = -1;
28. }
29. //destructor
30. Stack:: ~Stack() {delete []
stack_array;}
31. Stack& Stack :: operator=(const
Stack& S) // Assignment Operator
32. { stack_array = new
int[S.stack_size];
33. tos = S.tos;
34. stack_size = S.stack_size;
35. for(int i =0 ; i<S.size(); i++)
36. stack_array[i] = S.stack_array[i];
37. return * this; // for chaining
purpose
38. }
39. int Stack :: size() const {return
tos+1;}
40. int Stack :: empty() const
41. { if(tos == -1)
42. return 1;
43. else return 0;
44. }
45. void Stack:: push(const int & val)
46. {if( tos<stack_size-1 )
47. { tos++;
48. stack_array[tos] = val;
49. }
50. else
51. throw stackfullerror();
52. }
53. void Stack :: pop()
54. { if(tos >= 0)
55. tos--;
56. else
57. throw stackemptyerror();
58. }
59. int& Stack :: top()
{return(stack_array[tos]);}
60. void main()
61. { Stack s;
62. //check for stack full exception
63. try
64. {s.push(10);s.push(20); s.push(30);
65. }catch(Stack::stackfullerror)
66. { cout<<”\nstack full exception.
Cannot be pursued on to stack:”<<endl;
67. cout<<”\nExiting the catch block of
stackfull exception ..”<<endl;
68. }
69. //overloaded assignment operator
70. cout<<”\n Result of = operator on
stack objects s & t ..”<<endl;
71. Stack t;
72. t=s; // assignment Operator
73. cout<<”\n Elements of Stack s
“<<endl;
74. while(!s.empty())
75. { cout<<s.top()<<endl;s.pop();}
76. cout<<”\n Elements of Stack t after
= operator”<<endl;
77. while(!t.empty())
78. { cout<<t.top()<<endl; t.pop();}
79. }//end of main
/* Output: Result of = operator on stack
objects s & t ..
Elements of Stack s : 30 20 10
Elements of Stack t after = operator 30
20 10*/
Line Declare a class for Stack class.
No. 5:
For multiplication:
Convert both into polar form.
Multiply magnitude of polar1 &
polar2 to get resultant magnitude.
Add angles of polar1 & polar2 to get
resultant theta.
Declare resultant magnitude and resultant
theta as a result of multiplication.
1. #include<iostream>
2. #include<cmath>
3. using namespace std;
4. class Polar
5. {// public accessory functions
6. public:
7. Polar(){r=0.0;t=0.0;a=0.0;b=0.0;}
8. Polar(double x, double y)
{a=x;b=y;r=0.0;t=0.0;}
9. double GetA() const{return a;}
10. double GetB() const {return b;}
11. double GetR() const{return r;}
12. double GetT() const {return t;}
13. void ConvertToPolar(); // to
convert to polar form
14. void ConvertToCartesian(); // to
convert to Cartesian form
15. friend void DisplayPolar(const
Polar &v); // to display in cartesian
forms
16. friend void DisplayCartesian(const
Polar &v);
17. Polar operator+(const Polar &v1);
18. Polar operator*(const Polar &v1);
19. private:
20. double r; //mag
21. double t; //theeta
22. double a; // real
23. double b; // imaginary
24. };
25. void Polar::ConvertToPolar()
26. { double x=0.0;
r=sqrt(a*a + b*b);
x=atan(b/a);
t= (7.0/22.0)*180.0*x; // PI radians
equals 180 degrees
27. }
28. void Polar::ConvertToCartesian()
29. { double x=0.0;
x=atan(b/a);
a=r*cos(x);
b=r*sin(x);
30. }
31. Polar Polar::operator+ (const Polar
&v)
32. { Polar v3(a+v.GetA(),b+v.GetB());
return v3;}
33. Polar Polar::operator* (const
Polar &v)
34. { Polar v3;
35. float x=0.0;
36. v3.r=r*v.GetR();
37. v3.t=t+v.GetT();
38. x = t*(7.0/22.0)*180;
39. v3.a=r*cos(x);
40. v3.b=r*sin(x);
41. return v3;
42. }
43. void DisplayCartesian(const Polar &
v)
44. { cout<< «\n Vector in cartesian :
real = «<<v.a<<» imaginary
=»<<v.b<<endl; }
45. void DisplayPolar(const Polar & v)
46. { cout<< “\n Vector in polar form
etc: magnitude = “<<v.r<<” Angle
=”<<v.t<<endl;
47. }
48. void main()
49. { Polar v1(3.0,4.0),v2(3.0,4.0),v3
,v4;
50. cout<<»\n Given Vector V1 :»;
51. DisplayCartesian(v1);
52. cout<<»\n Given Vector V2 :»;
53. DisplayCartesian(v2);
54. v3=v1+v2;
55. cout<<”\n after v1 + v2 :operator
overloading ..”<<endl;
56. DisplayCartesian(v3);
57. v1.ConvertToPolar();
58. v2.ConvertToPolar();
59. DisplayPolar(v1);
60. DisplayPolar(v2);
61. v4=v1*v2;
62. cout<<»\n after v1 * v2 :operator
overloading ..»<<endl;
63. DisplayPolar(v4);
64. }
1. #include<iostream>
2. #include<cmath> // for maths related
functions like sqrt,cos, tan, tan- etc
3. using namespace std;
4. // Declaration of class called Polar
5. class Polar
6. { public: Polar():r(0.0),t(0.0){} //
Default constructor
7. Polar( double f , double
g):r(f),t(g){} // constructor
8. ~Polar(){} // Default Destructor
9. Polar operator*(const Polar &v1);
10. void Display(ostream & src) const
11. { src<<”Magnitude =
“<<r<<”\t”<<”Angle theeta =”<<t<<endl;}
12. double GetR() const{return r;}
13. double GetT() const {return t;}
14. private:double r; t ; // magnitude
& angle theeta
15. };
16. ostream & operator<<(ostream &src,
const Polar v){ v.Display(src); return
src;}
17. Polar Polar::operator* (const Polar
&v)
18. { Polar v3;
19. float x=0.0;
20. v3.r=r*v.GetR();
21. v3.t=t+v.GetT();
22. return v3;
23. }
24. void main()
25. { Polar
v1(5.0,53.0),v2(6.0,28.0),v3; //
v1,v2,v3 is the object of Polar class
26. cout<<“\nThe Given Vectors in
Polar form form ….\n“<<endl;
27. cout<<“\nPolar form vector v1
:“<<v1<<endl;
28. cout<<“\nPolar form vector 2 v2
:“<<v2<<endl;
29. // multiply Polar Vectors v1 & v2
and store it in v3 using overloaded
operator
30. v3=v1*v2;
31. cout<<“\nv3=v1*v2 in Polar Form
:“;
32. cout<<v3;
33. }// end of main
34. /*Output: The Given Vectors in Polar
form form ….
35. Polar form vector v1 :Magnitude = 5
Angle theeta =53
36. Polar form vector 2 v2 :Magnitude =
6 Angle theeta =28
37. v3=v1*v2 in Polar Form :Magnitude =
30 Angle theeta =81*/
1. #include<iostream>
2. #include<cmath> // for maths related
functions like sqrt,cos , tan , tan- etc
3. using namespace std;
4. class Height {
5. public:
6. Height(float h);
7. Height & operator ++ (); //pre fix
8. Height & operator ++ (int); // post
fix
9. ~Height(); // Destructor
10. Height(Height const& m); // Copy
constructor
11. Height& operator= (Height const& m);
// Assignment operator
12. float GetHeight() const { return
yourHeight;}
13. private:float yourHeight;
14. };
15. inline Height::Height(float
h):yourHeight (h){}
16. inline Height::~Height() {} //
Destructor
17. Height & Height::operator++ (){
++yourHeight;return * this;}
18. Height & Height::operator ++ (int)
{yourHeight++;return * this;}
19. void main()
20. { Height
Ramesh(179.0),Gautam(172.0),Anand(171);
// three objects created
21. cout<<”\n Given Height…”<<endl;
22. cout <<Ramesh.GetHeight()<<” :
“<<Anand.GetHeight()<<” :
“<<Gautam.GetHeight()<<endl;
23. ++Ramesh;++Anand;++Gautam;
24. cout<<”\n Height after prefix ++
overloading…”<<endl;
25. cout <<Ramesh.GetHeight()<<” :
“<<Anand.GetHeight()<<” :
“<<Gautam.GetHeight()<<endl;
26. Ramesh++;Anand++;Gautam++;
27. cout<<”\n Height after postfix ++
overloading…”<<endl;
28. cout <<Ramesh.GetHeight()<<” :
“<<Anand.GetHeight()<<” :
“<<Gautam.GetHeight()<<endl;
29. }
/*Output: Given Height…179 : 171 :
172
Height after prefix ++ overloading…
180 : 172 : 173
Height after postfix ++ overloading…
181 : 173 : 174*/
1. #include <iostream>
2. #include <cstdlib> // for using
malloc() & free operators
3. #include <new> // including new fro
c standard library
4. using namespace std;
5. class Stundent
6. {public:
7. Stundent() {rollNo = marks = 0;}
//default constructor
8. Stundent(int a, int b) {rollNo =
a;marks = b;}
9. void Display()
10. {cout <<”Roll No :”<<rollNo << “
Marks : “<<marks << endl;}
11. int GetrollNo()const { return
rollNo;}
12. int Getmarks()const { return marks;}
13. void * operator new(size_t size);
14. void operator delete(void *std);
15. private :
16. int rollNo, marks;
17. };
18. // overloaded new operator
19. void *Stundent::operator new(size_t
size)
20. { void *std;
21. cout << “In overloaded new.\n”;
22. std = malloc(size); // we are
using malloc because we are overloading
new
23. if(!std)
24. {bad_alloc e; throw e;}
25. return std;
26. }
27. // delete operator overloaded
28. void Stundent::operator delete(void
*std)
29. { cout << “In Side overloaded
delete.\n”; free(std);}
30. void main()
31. { Stundent *std;
32. try {
33. std = new Stundent (50595, 89);
34. }catch (bad_alloc e) {cout <<
“Allocation error for obj1.\n”;exit(1);}
35. std->Display();
36. delete std; // free an object
37. }
/*Output: In overloaded new.
Roll No :50595 Marks : 89
In Side overloaded delete.*/
1. #include<iostream>
2. #include<cstring>
3. using namespace std;
4. class OwnString
5. { public:
6. OwnString(); //default
constructor
7. OwnString(const char *s){stg=s;};
// constructor with argument
8. operator const char *() {return
stg;} // conversion operator to convert
to ctype string
9. private:
10. const char *stg;
11. int size;
12. };
13. void main()
14. { OwnString stg(“Example of
conversion Operator”);
15. int n = strcmp(stg,”Example”);
16. cout<<”Strings are NOT same :
“<<n<<endl;
17. n=strcmp(stg,”Example of
conversion Operator”);
18. cout<<”Strings are same :
“<<n<<endl;
19. }
/*Output
Strings are NOT same : 1 : Strings are
same : 0*/
Li is overloaded constructor
ne
No
. 7:
Exercise Questions
Objective Questions
1. i and ii
2. ii and iii
3. iii
4. i and iv
1. i and ii
2. ii and iii
3. ii, iii and iv
4. i and iv
1. i, ii and iv
2. ii and iii
3. iii and iv
4. i and iv
1. i, ii and iv
2. ii and iii
3. iii and iv
4. i and iv
1. i, ii and iv
2. ii, iii and iv
3. iii and iv
4. i and iv
1. i, ii and iv
2. ii, iii and iv
3. ii and iv
4. i and iv
1. i
2. ii
3. iii
4. iii and iv
1. ii and iv
2. ii and iii
3. i and iii
4. iii and iv
Short-answer Questions
13. Distinguish errors, exceptions.
14. Differentiate synchronous and asynchronous exceptions.
15. What are logical errors?
16. What are bugs? How can they be minimized?
17. Differentiate roles of try and catch blocks.
18. What is the role of exception object?
19. What is operator overloading?
20. Why does OOPS language support operator
overloading?
21. Which of the operators cannot be overloaded? And why?
Long-answer Questions
1. c
2. b
3. a
4. d
5. b
6. a
7. b
8. a
9. False
10. True
11. d
12. a
12
Inheritance
LEARNING OBJECTIVES
12.1 Introduction
The concept of inheritance is not new to us.
We inherit property, goodwill and name
from our parents. Similarly, our descendants
will derive these qualities from us.
Reusability of code is one of the strong
promises that are made by C++ and
inheritance is the tool selected by C++ to
fulfill this promise. In this chapter, we take
you through inheritance and its properties
and rules. We will dwelve into the
terminology of inheritance and the types of
inheritances. We will introduce the reader to
overloading and overriding concepts and
introduce the various types of inheritances
through examples. We will also cover the
virtual functions and ADTs in detail. Each
concept you will learn through an example.
class Human
{ public:
protected: // variables declared as
protected are public to
derived classes
// protected variables
};
// Student inherited from Human ,
inheritance type is public
class Student : public Human
{ public:
private:
};
Note that members declared as private are
not available to derived class. If you make
these member data as public then security is
compromised. So what is the way out?
Declare the member data as protected.
Protected variables mean that these
variables are public to derived classes and
private to other classes.
If a public member function has the
object, i.e. object has invoked the member
function, then that function can access all
the public member functions and public
member data. Public functions of a class
can access all the private member data and
member functions of its own class and
protected member data and member
functions of their base classes.
1. #include<iostream>
2. using namespace std;
3. enum CAT { BTECH,MBA,MCA,MSC}; //
Category of student
4. enum BAT { ATHLETE,SPORTS}; // Batch
of Athlete or sports person
5. class Human
6. { public:
7. Human():idNo(0),name(“Noname”) //Base
constructor
8. {cout<<”\n default Human
constructor..”<<endl;}
9. Human(int n , char
*p):idNo(n),name(p) // Base overloaded
constructor
10. {cout<<”\nHuman
constructor..”<<endl;}
11. ~Human(){cout<<”\nHuman
destructor..”<<endl;} // base destructor
12. // Public functions
13. int GetReg()const{return idNo;}
14. void SetId(int n) { idNo=n;}
15. char * GetName() const { return
name;}
16. void SetName( char *p) { name=p;}
17. void Learn()const{ cout<<”\n Human
beings strive to learn …”<<endl;}
18. void Work()const { cout<<”\n Human
work ….”<<endl;}
19. protected:
20. int idNo;
21. char *name;
22. };
23. class Student : public Human
24. { public:
25. Student():Human(),stcat(BTECH)
{cout<<”\nStudent constructor..
”<<endl;}
26. Student(int n , char *p
):Human(n,p),stcat(BTECH)
27. {cout<<”\n Student(int n, char *p)
constructor..”<< endl;}
28. ~Student(){}; // Default destructor
29. CAT GetCAT() const { return stcat;}
30. void SetCAT ( CAT c) { stcat=c;}
31. //students do differently functions
32. //void Learn(){ cout<<\n Students
learn professional subjects…” endl;}
33. //void Work(){ cout<<\n Students
work at college laboratories…” endl;}
34. void Play() { cout<<”\n Students
play at college and at home… ”<<endl;}
35. void UseNet(){ cout<<”\n Students
use internet for learning..”<<endl;}
36. private:
37. CAT stcat; // students category
38. };
39. void main()
40. { Student std(50,”Thunder”);
41. std.Learn();
std.Work();std.UseNet();
42. cout<<”\n Students name is
:”<<std.GetName()<<endl;
43. cout<<”\n Explicit call to base
class work………..”<<endl;
44. std.Human::Work(); // explicit call
to base class work
45. }
46. /*Output : Human constructor..
47. Student(int n, char *p)
constructor..
48. Human beings strive to learn …
49. Human work ….
50. Students use internet for
advancement…
51. Students name is :Thunder
52. Explicit call to base class
work………..
53. Human work ….
54. Human destructor..*/
Li std.Learn();
n std.Work();std.UseNet(); are invoked by
e object std. As we have commented out
N statement 32 & 33 , learn() and Work() of
o. base class Human are invoked as shown in line
46 & 47.
41
:
1. #include<iostream>
2. using namespace std;
3. class Human
4. {public:
5. void Learn()const{ cout<<”\n Human
beings strive to learn …”<<endl;}
6. void Learn(int f)const{ cout<<”\n
Humans learn at good speed… ”<<endl;}
7. void Learn(int f, int g) const{
cout<<”\n Humans learn at good speed.&
well”<<endl;}
8. void Work()const { cout<<”\n Human
work ….”<<endl;}
9. };
10. class Student:public Human
11. { public:
12. /* students do differently
functions. So it overrides base class
Learn() function. But base class has
Learn() as over loaded function.
Therefore balance two overloaded
functions are lost to Student.*/
13. void Learn(){ cout<<”\n Students
strive to learn professional
subjects…”<<endl;}
14. };
15. void main()
16. { Human hum; // object of base class
17. Student std; // object of derived
class
18. cout<<”\n Object of base class can
call all varieties of overloaded
function..”<<endl;
19. hum.Learn();
20. hum.Learn(2); // Learn with double
speed
21. hum.Learn(2,2); // Learn with good
speed and well
22. cout<<”\n Objectof Student….”<<endl;
23. cout<<”\n Student over rides Learn()
of base class”<<endl;
24. std.Learn(); //std over ride one of
the base class function Learn()
25. cout<<”\n Two other base class over
loaded functions Learn(int),
Learn(int,int) are lost”<<endl;
26. //std.Learn(2); //lost
27. cout<<”\nstd can still call an
overloaded base class function by
explicit call”<<endl;
28. std.Human::Learn(2);
}
/*Output : Object of base class can call
all varieties of overloaded function..
Human beings strive to learn : Humans
learn at good speed
Humans learn at good speed & well
Objectof Student. : Student overrides
Learn() of base class
Students strive to learn professional
subjects
Two other base class overloaded
functions Learn(int), Learn (int,int)
are lost
std can still call an overloaded base
class function by explicit call
Humans learn at good speed */
1. #include<iostream>
2. using namespace std;
3. enum CAT { BTECH,MBA,MCA,MSC}; //
Category of student
4. enum BAT { ATHLETE,SPORTS};
5. enum DIV { DISTINCTION,FIRST,SECOND
,NATIONAL, STATE, COLLEGE};
6. // Division obtained by Students
7. enum OKAY{FALSE,TRUE}; // eligible
for selection or not
8. class Humans
9. {public:
10. Humans(int n):idNo(n)
11. {cout<<"\n default Humans
constructor.."<<endl;} //Base
constructor
12. virtual ~Humans(){cout<<"\nHumans
destructor.."<<endl;} //
base destructor
13. // Public functions
14. virtual int GetId()const{return
idNo;}
15. virtual void SetId(int n) { idNo=n;}
16. protected:
17. int idNo;
18. };
19. class Student:virtual public Humans
20. { public:
21. Student(CAT cat , DIV d , int num);
22. virtual ~Student(){}; // Default
destructor
23. // students do differently functions
24. virtual void Learn()const{ cout<<”\n
Students learn relevant courses\n”;}
25. virtual void Work()const{ cout<<”\n
Students worked Industry programs\n”;}
26. virtual CAT GetCAT() const { return
stcat;}
27. virtual void SetCAT(CAT c) {
stcat=c;}
28. virtual DIV GetDIV() const { return
division;}
29. virtual void SetDIV ( DIV d) {
division = d;}
30. protected:
31. CAT stcat; // students category
32. DIV division; // division
Distinction/first class etc
obtained
33. };
34. Student::Student(CAT cat , DIV d ,
int idnum):
35. Humans(idnum),stcat(cat),
division(d)
36. { cout<<”\n Students
constructor..”<<endl;}
37. class Athlet:virtual public Humans
38. { public:
39. Athlet(CAT cat , DIV d , OKAY ok ,
int idnum);
40. virtual ~Athlet(){}; // Default
destructor
41. virtual void AtLearn()const{
cout<<”\n Athlets learn subjects &
sports\n;}
42. virtual void AtWork()const{
cout<<”\n Athlets worked at lab and
GYM\n”;}
43. virtual void Play() const{ cout<<”\n
Athlets can play games and events\n”;}
44. virtual CAT GetCAT() const { return
stcat;}
45. virtual void SetCAT(CAT c) {
stcat=c;}
46. virtual DIV GetDIV() const { return
division;}
47. virtual void SetDIV ( DIV d) {
division = d;}
48. virtual OKAY GetOKAY() const {
return qualified;}
49. virtual void SetOKAY ( OKAY q) {
qualified = q;}
50. private:
51. CAT stcat;
52. DIV division; //
national/state/district/college
53. OKAY qualified;
54. };
55. Athlet::Athlet(CAT cat , DIV d ,
OKAY ok, int idnum):
56.
Humans(idnum),stcat(cat),division(d),qua
lified(ok)
57. {cout<<”\n Athlet
constructor..”<<endl;}
58. class Professional : public Student
, public Athlet
59. { public:
60. Professional(CAT cat , DIV d, OKAY q
,int idnum , int n); ~Professional()
{cout<<”\n Professionals
destructor..”<<endl;}
61. // n is no of companies giving
weightage to all round development
62. virtual GetNum() const { return
num;}
63. //num : these are companies willing
to give weightage to sports
64. virtual DIV GetDIV() const { return
Student::division;}
65. void AtLearn() const { Learn();} //
Learn subjects like students
66. void AtWork() const { Work();} //
Work in Laboratories like Students
67. private:
68. int num ; //Number of companies who
are willing to give weightage to sports
69. };
70. Professional::Professional(CAT cat ,
DIV d, OKAY q ,int idnum, int n):
71.
Student(cat,d,num),Athlet(cat,d,q,idnum)
,Humans(idnum),num(n)
72. { cout<<”\n Professionals
constructor..”<<endl;}
73. void main()
74. {Professional *ptr = new
Professional(BTECH,FIRST,TRUE,50595,100)
;
75. int rollNo = ptr->GetId();
76. ptr->Learn();
77. //Though we call AtLearn() of Athlet
, it will call learn() of Student.
78. //We want student to be sound in
Knowledge.
79. ptr->AtLearn();
80. ptr->Play(); // play like an athlete
81. cout<<"\n No of companies allocating
weightage to all round personality :"
<<ptr->GetNum()<<endl;
82. cout<<"\n Division obtained by the
professional :"<<ptr->GetDIV()<<endl;
83. cout<<"\n The selected Professional
is : "<<rollNo<<endl;
84. delete ptr;
85. }
/*Output : default Humans constructor..
Students constructor.. : Athlet
constructor..: Professionals
constructor..
Students learnt Industry relevant
courses: Students learnt Industry
relevant courses
Athletes can play games and participate
in events
No. of companies allocating weightage to
all round personality: 100
Division obtained by the professional: 1
Companies tion The selected Professional
is: 50595
Professionals destructor..
Humans destructor*/
L Professional::Professional(CAT cat,
i DIV d, OKAY q, int idnum, int n)
n Student(cat,d,num),
e Athlet(cat,d,q,idnum),
N
Humans(idnum), num(n) are for constructor
o
for Professional. Observe that Student, Athlet
.
and Human constructors are called in turn to
7
create an object called Professional
0
&
7
1
:
1. #include<iostream>
2. using namespace std;
3. const double PI=3.14159;
4. class Shape
5. { public:
6. Shape(){};
7. ~Shape(){}
8. virtual double ComputeArea()
9. {cout<<”\n Shape has no definite Area
“<<endl;return 0.0;}
10. virtual double ComputePerimeter()
11. {cout<<”\n Shape has no definite
Area “<<endl; return 0.0;}
12. virtual void DrawShape() {}};
13. class Circle: public Shape
14. {public: Circle(double r):radius(r)
{};
15. ~Circle(){}; // Default destructor
16. // Circles do functions differently
17. double ComputeArea()
18. {cout<<"\n Circle implementation of
ComputeArea "<<endl;
19. return PI*radius*radius; }
20. virtual double ComputePerimeter()
21. {cout<<"\n Circle implementation of
ComputePerimeter <<endl;
22. return 2*PI*radius; }
23. virtual void DrawShape() {cout<<"\n
Circle Draw code here" <<endl;}
24. private:double radius;
25. };
26. class Square: public Shape
27. {public: Square(double r):side(r){};
28. ~Square(){}; // Default destructor
29. // Squares do functions differently
30. double ComputeArea()
31. {cout<<"\n Square implementation of
ComputeArea "<<endl;
32. return side*side; }
33. virtual double ComputePerimeter()
34. {cout<<"\n Square implementation of
ComputePerimeter "<<endl;
35. return 4*side; }
36. virtual void DrawShape() {cout<<"\n
Square Draw code here"<<endl;}
37. private:double side;
38. };
39. void main()
40. { int choice;
41. Shape *ptr; // pointer to base
class
42. while(choice!=3)
43. { cout<<"\n 1 : Circle 2 : Square
3: Exit .. :";
44. cin>>choice;
45. switch(choice)
46. { case 1 : ptr = new
Circle(2.0); break;
47. case 2 : ptr= new Square(5.0);
break;
48. case 3 : exit(0);
49. default: cout<<"\n wrong
choice. Try Again.."<<endl; continue;
50. }
51. // Function Polymorphism and
Dynamic Binding at work
52. ptr->ComputeArea(); // call to
derived class function
53. ptr->ComputePerimeter();ptr-
>DrawShape();
54. }//end of while
55. }//end of main
/*Output 1 : Circle 2 : Square 3: Exit
.. :1
Circle implementation of ComputeArea
Circle implementation of
ComputePerimeter
Cirle Draw code here
1 : Circle 2 : Square 3: Exit .. :2
Square implementation of ComputeArea
Square implementation of
ComputePerimeter
Square Draw code here
1 : Circle 2 : Square 3: Exit .. :3
*//*output :1 : Circle 2 : Square 3:
Exit .. :1
Circle implementation of ComputeArea
Circle implementation of
ComputePerimeter
Cirle Draw code here
1 : Circle 2 : Square 3: Exit .. :2
Square implementation of ComputeArea
Square implementation of
ComputePerimeter
Square Draw code here
1 : Circle 2 : Square 3: Exit .. :4
wrong choice. Try Again..
1 : Circle 2 : Square 3: Exit .. :3 */
1. #include<iostream>
2. using namespace std;
3. const double PI=3.14159;
4. class Shape
5. {public: Shape(){};
6. ~Shape(){}
7. virtual double ComputeArea()=0;
//pure virtual function
8. virtual double ComputePerimeter()
=0;
9. virtual void DrawShape()=0;
10. };
11. // We will implement DrawShape (),
though it is a pure virtual Function
12. // to include common functionality
of all the derived functions
13. void Shape::DrawShape()
14. {cout<<”\n Completion of DrawShape()
mechanism from derived class…”<<endl; }
15. class Circle: public Shape
16. {public: Circle(double r):radius(r)
{};
17. ~Circle(){}; // Default
destructor
18. // Circles do functions
differently
19. double ComputeArea()
20. {cout<<"\n Circle implementation
of ComputeArea "<<endl;
21. return PI*radius*radius;}
22. double ComputePerimeter()
23. {cout<<"\n Circle implementation
of ComputePerimeter "<<endl;
24. return 2*PI*radius;}
25. void DrawShape()
26. {cout<<"\n Circle Draw code here"
<<endl;
27. Shape::DrawShape();} // call to
base class to finish common
functionality
28. private: double radius;
29. };
30. class Square: public Shape
31. {public: Square(double r):side(r){};
32. ~Square(){}; // Default
destructor
33. // Square implements functions
differently
34. double ComputeArea()
35. {cout<<"\n Square implementation
of ComputeArea "<<endl;
36. return side*side;}
37. double ComputePerimeter()
38. {cout<<"\n Square implementation
of ComputePerimeter "<<endl;
39. return 4*side;}
40. void DrawShape()
41. {cout<<"\n Square Draw code here"
<<endl;
42. Shape::DrawShape(); } // call to
base class to finish common
functionality
43. private:double side;
44. };
45. void main()
46. {int choice;
47. Shape *ptr; // pointer to base class
48. while(choice!=3)
49. {cout<<"\n 1 : Circle 2 : Square 3:
Exit .. :";
50. cin>>choice;
51. switch(choice)
52. { case 1 : ptr = new Circle(2.0);
break;
53. case 2 : ptr= new Square(5.0);
break;
54. case 3 : exit(0);
55. default: cout<<"\n wrong choice.
Try Again.."<<endl; continue;
56. }
57. ptr->ComputeArea(); ptr-
>ComputePerimeter(); ptr->DrawShape();
58. }//end of while
59. }
/*Output 1 : Circle 2 : Square 3: Exit
.. :1
Circle implementation of ComputeArea
Circle implementation of
ComputePerimeter
Cirle Draw code here
Completion of DrawShape() mechanism from
derived class…
1 : Circle 2 : Square 3: Exit .. :2
Square implementation of ComputeArea
Square implementation of
ComputePerimeter
Square Draw code here
Completion of DrawShape() mechanism from
derived class…
1 : Circle 2 : Square 3: Exit .. :3
12.15 Summary
Exercise Questions
Objective Questions
1. i
2. i and ii
3. ii and iii
4. i, ii and iii
1. i only
2. ii only
3. i and ii
4. i and iii
8. In C++ pointer to base class can be assigned to derived
class. TRUE/FALSE
9. For run-time polymorphism and dynamic binding to
work the following are required: Pointer to base class
1. Inheritance relation
2. Function to be declared as virtual
3. Function to be overridden in derived class
1. i and ii
2. i, ii and iii
3. i, ii, iii and iv
4. NOT i, ii, iii and iv
1. Inheritance
2. Virtual base class
3. Multiple inheritance
4. All of a, b, c
1. i
2. ii
3. iii
4. i and ii
1. Hierarchical inheritance
2. Virtual base class
3. Multiple inheritance
4. a, b and c
1. c
2. c
3. d
4. True
5. False
6. False
7. d
8. True
9. c
10. c
11. b
12. c
13. a
14. False
15. False
16. d
17. d
18. a
19. c
20. True
21. False
22. True
13
IO Streaming
LEARNING OBJECTIVES
13.1 Introduction
What crosses your mind when you think of
streams? Probably streams of water, we call
them springs, flowing from the top of a hill
to plains. In C++, we call streams or IO
streams.
This chapter will introduce to you
unformatted and formatted input and
output streams. It deals extensively with
stream manipulators that are used to format
and control stream data. The chapter also
concentrates on file handling in C++
through <fstream> header file. The
concepts covered are sequential file handling
and random/direct access techniques. The
techniques to handle formatted data and
raw data are discussed. We will wrap up the
chapter with object read and write
operations onto a file.
13.2 IO Streaming
In C++, IO streams are flow of bytes from
one input device to memory and vice versa.
A stream is like a pipe. It can carry anything
in the pipe, be it kerosene, milk, water, etc. –
refer to Figure 13.1 shown below.
Figure 13.1 Streams – A concept
13.3.1 Formatted IO
In order to perform I/O operations, a stream
is attached to an I/O device. Typical I/O
devices include consoles, keyboards, files
and electronic devices like sensors. The
inserters represented by the “<<” symbol
work as translators which translate in
memory representation of data types such as
integers, floats and user-defined data types
into data types which can be understood by
the I/O devices. The extractor represented
by the “>>” symbol translates data sent by
I/O devices to in memory representation
formats such as integers and floats. Typical
I/O devices like consoles and keyboards
send and receive data in ASCI format.
Let us see with an example how extractors
and inserters work. Consider the following
piece of code int n; cin >> n; Now
using the keyboard, assume the user has
entered numbers 6, 7 and 8 followed by the
enter key. Following this operation, the
buffer associated with the input stream
would look like Figure 13.3.
13.3.2 Unformatted IO
Unformatted I/O is also called low-level I/O.
It offers the highest efficiency and
throughput amongst all the other I/O
mechanisms. Unlike formatted I/O, here
input has no automatic whitespace, Tab,
carriage return detection and processing,
and also data is not formatted – the
programmer has to interpret the data.
Input:
get():
Reads a character from stream including delimiters like
white spaces, EOF markers and returns it.
Usage cin.get()
get(char& ch):
Reads a character from stream and stores it in ch
Usage cin.get()
Output:
put(char ch):
Function writes the character ch to the stream.
Usage: cout.put(ch);
Miscellaneous:
putback(char c)
Places the character c obtained by get() back in to the
stream.
peek()
Returns the next character from the stream without
removing it
1. #include<iostream>
2. #include<cstring>
3. using namespace std;
4. void main()
5. {char ch, str[10];
6. cout<<”\n Enter any string : Showing
character input thru cin.get() :”;
7. while((ch = cin.get()) != ‘\n’) //
using get() function
8. cout << ch;
9. cout<<”\n Enter a string<Less Than 9
or less characters : cin.read>: “;
//using read fn
10. cin.read(str, sizeof(str));
11. str[9] = ‘\0’;
12. cout << endl << str;
13. }
/*Output: Enter any string: Showing
character input through cin.get() :Hello
World
Hello World
Enter a string<Less Than 9 or less
characters : cin.read>: hello USA*
Line No 7 Shown cin.get() . Line No 10
shows cin.read() . Note that read() also
works with cin object.
Example 13.2: unformatio2.cpp
Program to Show Unformatted
Output Functions
1. hello USA*/
2. #include<iostream>
3. #include<conio.h>
4. #include<string.h>
5. using namespace std;
6. void main()
7. { int i;
8. char str[] = “I enjoy programming in
C++” ;
9. for(i = 0 ; str[i] != ‘\0’; i++)
cout.put(str[i]); //using write function
10. cout<<endl; cout.write(str,
strlen(str)); getch();
11. }
/*Output I enjoy programming in C++ I
enjoy programming in C++*/
Line No 9 shows usage of cout.write().
Note that write works with cout also.
#include<iostream>
#include<conio.h>
using namespace std;
void main()
{int value;
cout << “Enter Value: “;cin >> value;
cout <<endl <<”goodbit: “<<
cin.good();cout <<endl <<”eofbit : “<<
cin.eof();
cout <<endl <<”failbit: “<<
cin.fail();cout <<endl <<”badbit : “<<
cin.bad();
cout <<endl <<"Enter Value(enter
characters to see effect on flags):
";cin >> value;
cout <<endl <<"goodbit: "<<
cin.good();cout <<endl <<"eofbit : "<<
cin.eof();
cout <<endl <<”failbit: “<<
cin.fail();cout <<endl <<”badbit : “<<
cin.bad();
getch();
}
/* Output : Enter Value: 47 goodbit:
1eofbit : 0failbit: 0badbit : 0
Enter Value(enter characters to see
effect on flags): ghj :
goodbit: 0eofbit : 0failbit: 1badbit :
0*/
#include<iostream>
using namespace std;
void main()
{double price; char title[30]; char
author[30];
char * tell = “ Enter the title of the
Book, Author and price :”; cout<<tell;
cin>>title>>author>>price;
cout<<”\nTile of the book
:”<<title<<endl;
cout<<”\nAuthor of the book
:”<<author<<endl;
cout<<”\nPrice of the book
:”<<price<<endl;
}
/*Output :Enter the title of the Book,
Author and price :C++ ramesh 250.00
Tile of the book :C++ : Author of the
book :ramesh : Price of the book :250*/
13.4 IO Manipulators
Manipulators alter the status of streams. For
using this feature we need to include the
statement: #include<iomanip> in global
section. For example, if we use a
manipulator setprecision(2), all the
floating point variable output will be two
digits after decimal point. A few of the
important IO manipulator are:
cout<<dec<<intvar;decimal / hexa / octal
representation from integers
cout<<hex; cout <<oct;
cout<<setiosflags(ios::dec) Sets the
formatting bits as decimal
cout<<resetiosflags(ios::hex) Resets
already set flags as per format
specified
cout<<setbase(int n) :Sets bas to n
cout<<setw(int n) :specifies width for
output formatting
cout<<setfill(“*”); :fills the unfilled
space set with setw() with fill
character
1. #include<iostream>
2. #include<iomanip>
3. using namespace std;
4. void main()
5. {double price; char title[30]; char
author[30]; int copies;
6. char * tell1 = “ Enter the title of
the Book :”;
7. char *tell2 = “ Enter the Author of
the Book :”;
8. char *tell3 = “ Enter the price of
the Book :”;
9. char *tell4 = “ Enter No of copies
of the Book :”;
10. cout<<tell1<<flush;
11. cin>>ws>>title; cout<<tell2<<flush;
cin>>author; cout<<tell3 <<flush;
12. cin>>price; cout<<tell4<<flush;
cin>>dec>>copies;
13. cout<<setiosflags(ios::left)
<<”\nTitle of the book :”<<title <<endl;
14. cout<<”\nAuthor of the book
:”<<author<<endl;
15. cout<<resetiosflags(ios::right)
<<”\nPrice of the book :”<<setw(10)
<<price<<endl;
16. cout<<”\n Number of copies
:”<<setw(10)<<copies<<endl;
17. }
/*Output: Enter the title of the Book
:C++ : Enter the Author of the Book
:Ramesh
Enter the price of the Book :250 :Enter
No of copies of the Book : 10000
Title of the book :C++ :Author of the
book :Ramesh : Price of the book :250
Number of copies :10000 */
13.5 Flags
The arguments that can be passed to
setiosflag and resetiosflags manipulators are
shown below:
ios::skipws skip white spaces in input
stream
ios::scientif
ic
ios::hex,ios:
:oct
#include<fstream>
#include<iostream>
using namespace std;
void main(int argc , char **argv)
{if ( argc<3)
{cout<<”\n correct usage of
command line argument is : copyfile
inputfile
outputfile..”<<endl; exit(0); }
// open inputfile and connect it
to input stream inputstream
ifstream inputstream(argv[1]);
if(!inputstream)
{ cout<<”\n cannot open the input
file ..”<<argv[1]<<endl; exit(1); }
//open the output file and connect
it to outputstream
of stream outputstream(argv[2]);
if(!outputstream)
{ cout<<”\n cannot open the output
file ..”<<argv[2]<<endl; exit(1); }
// now read from input file and
copy to output file
char ch;
while ( (inputstream.get(ch)) &&
outputstream ) outputstream.put(ch);
}
#include<fstream>
#include<iostream>
using namespace std;
void main()
{ char filename[30];
char text[80]; // for user input
cout <<”\n Enter source file name..:
“;
cin>>filename;
//Now lets open the file once again
for append mode
ofstream outfile(filename,ios::app);
if(!outfile)
{ cout<<”\n cannot open the input
file for appending..”<<filename <<endl;
exit(1); }
cout<<”\n Enter text for inputting
to file …”<<endl; cin.ignore(1,’\n’);
cin.getline(text,80);
outfile<<text<<”\n”;outfile.close();
cout<<”\n completed writing to
output file”<<endl;
// now lets read the file, we have
just outputted our text for confirmation
cout<<filename<<endl;
ifstream infile(filename);
if(!infile)
{cout<<”\n cannot open the input
file ..”<<filename<<endl; exit(1);}
char ch;
while ( infile.get(ch)) // now read
from input file and copy to output file
cout<<ch;
cout<<”\n display process
completed..”<<endl;
infile.close();
}
/*Output:
Enter source file name..: io4.cpp :
Enter text for inputting to file …
Hi we are trying out appending through
io5.cpp : completed writing to output
file
Hi we are trying out appending through
io5.cpp : display process completed..*/
Note that C++ supports all form of input
and output statements of C language. You
can freely use them in C++. We have used
the following statements in the program
char text[30]; // buffer for user
input
cin.getline(text,30); // getline
takes in to buffer text maximum of 30
characters
// But new line character \n is
ignored and not taken in
cin.ignor(1,’\n’); // ignores 1
character shown as second argument
inoutfile.open(filename,ios::in|ios::out
);
do{cout<<"\n MENU ";
cout<<"\n 1.Add a record\n 2.Display
nth record\n 3.Exit\n";
cout<<" Enter choice of operation:
";cin>>ch;
switch(ch)
{case 1: if (sz>=max)
{ cout<<"\n out of bounds.."
<<endl; exit(1); }
std[sz].GetData();
inoutfile.write((char*)&std[sz],sizeof(s
td[sz]));
sz++; // keep the count
inoutfile.close();
break;
case 2: inoutfile.seekg(0); // go to
beginning
cout<<"\nEnter the position of the
record to be displayed : ";
cin>>p;
if(p>max)
{cout<<"\nPosition out of
bounds";break; }
pos = (p-1) * sizeof(std) ;
inoutfile.seekg(pos);
inoutfile.read((char*)&std[p-
1],sizeof(std[p-1]));
cout<<"\nDetails of record "
<<p<<endl;
std[p-1].DisplayData();
inoutfile.close();
break;
case 3: exit(1);
}//end of switch
}while( ch>=1 && ch<4);
}//end of main
/*Output: Enter filename…Student.dat :
MENU
1.Add a record 2.Display nth record
3.Exit
Enter choice of operation: 1 Enter name:
Ramesh Enter id No: 100
Enter <Maths, Science and English> Marks
:90 90 90
MENU Enter choice of operation: 2 enter
the position of the record to be
displayed: 2
details of record 2: Name: Gautam Total:
294.00 : Average: 98.00 */
13.9 Summary
1. IO streaming is flow of data from one device to another
device. For example, from input device like console to
memory or from memory to output device like console.
2. Input from keyboard and output to console are called
standard input and output device.
3. There are operators like inserters and extractors (<< and
>>) provided to work with IO stream objects like cin,
cout, cerr to convert into ASCII to intrinsic data for
storage and convert back to ASCII for outputting to
standard IO devices.
4. The extractor represented by the “>>” symbol translates
data sent by I/O devices in memory representation
formats such as integers and floats.
5. iostream library object cin coupled with the extractor
operator >> provides the user translation services and
also the processing of special characters such as Carriage
Return(CR), Space, Tabs and End of File(EOF).
6. IO streaming functions make use of buffers to cater to
different speeds of IO devices and computer systems.
Various flags are set by IO streaming function to inform
to the user the status IO streaming.
7. High-level disk IO also called standard IO/stream IO:
Buffer management is done by the compiler/operating
system.
8. Low-level disk IO also called system IO: Buffer
management is to be taken care by the programmer.
9. console IO: All the input and output functions control
the way input has to be fed and the way output looks on
standard output devices, i.e. screen.
10. Console IO is further classified ad formatted IO and
unformatted IO.
11. Unformatted I/O is also called low-level I/O. It offers
the highest efficiency and throughput amongst all the
other I/O mechanisms. Unlike formatted I/O, here input
has no automatic whitespace, Tab, carriage return
detection and processing, and also data is not formatted
– the programmer has to interpret the data.
12. I/O library in C++ provides a mechanism to test
whether a particular I/O operation has succeeded or
failed. Each stream object maintains a set of flags which
indicates the state of the stream after an I/O operation.
13. C++ supports istream for input and ostream for output.
IO stream library includes four types of predefined
streams. cin,cout,cerr,clog
14. IO manipulators alter the status of streams. For using
this feature we need to include the statement:
#include<iomanip> in global section.
15. Flags are the arguments that can be passed to setiosflag
and resetiosflags manipulators.
16. File is a collection of records. Records are a collection of
fields. Fields are the smallest units of data. Fields can be
basic data types or user-defined or derived data.
17. Sequential File All records are stored sequentially as
they are entered.
18. Random Access File: In this mode of access, a record is
accessed using an index maintained for this purpose.
19. Direct Access File: In this mode, the records are stored
based on their relative position with respect to first
record.
20. Files can be further classified as text files or binary
files. Normally, in a text file, data is stored using ASCII
character code. In binary files, data is stored just like it
is stored in memory. Hence, binary mode saves memory.
21. The classes required in connection with file handling in
C++ are all kept in fstream header. Therefore, insert a
statement : #include<fstream>
22. In C++, logical NOT has been overloaded to check the
stream file creation. if(!infile) {cerr<<”\n
Sorry cannot open the file
infile..”<<endl; exit(1); }. In C++, a flag
called ios::binary will specify the mode.
23. Stream operating modes are used to control the stream
files opening modes. Include these mode switches while
creating the object through constructors.
24. Seekg() alters the get position, i.e. the position from
where we can read from a file.
25. Seekp() alters the position from where we can write.
26. tellg() and tellp() functions on the other hand
tell us about the position of read and write during our
next read and write operation.
Exercise Questions
Objective Questions
1. i
2. i and ii
3. i, ii and iii
4. d) ii, iii and iv
1. i and iii
2. i and ii
3. i, ii and iii
4. ii, iii and iv
1. i and iii
2. i and ii
3. ii and iii
4. ii, iii and iv
1. i
2. i, iii and iv
3. i, ii and iii
4. ii, iii and iv
1. i
2. i, iii and iv
3. i , ii and iii
4. i, ii and iv
1. i
2. i and ii
3. iv
4. ii and iii
1. ii and iii
2. i, ii and iii
3. i and iv
4. i, iii and iv
31. Write a program to merge two files into a third file. Each
file holds a specified number of strings.
32. Write a program to print telephone directory. Use a class
called Telephone to hold the data and member functions
for telephone directory to create the directory and the
file.
33. Write a program to sort the file that holds a specified
number of strings.
1. d
2. a
3. c
4. b
5. d
6. b
7. b
8. b
9. d
10. True
11. d
12. False
14
LEARNING OBJECTIVES
14.1 Introduction
Generic programming means writing
programs that will work for any type of data,
i.e. make the programs independent of the
type of data. With generic programs, there
will be no need to develop type-specific
programs for each data type. Templates in
C++ are implementation tools provided to
write generic programs. For example, a data
structure such as stack can be used for
storing different types of data such as
integers, floats, characters and strings of
messages. Using template facility provided
by the C++ language, a generic program can
be written and stored in a directory and can
be used by all programmers for different
data types.
Example 14.2:
stacktemplate1b.cpp
Implementation of Stack Data
Structure Using Templates
#include<iostream>
#include<iomanip>
using namespace std;
const int max=10; // declares maximum
of array size
class Student
{public:
Student(int roll); // constructor
with roll no input
Student():rollNo(0){} //default
constructor
~Student() {}; // default
destructor
int Display() const {return
rollNo;}
friend ostream &
operator<<(ostream &src, Student &S)
{src<<S.Display();return src; }
private: int rollNo;
};
Student::Student(int roll):rollNo(roll)
{}
template <class T>
class Stack
{ public: Stack(); //default constructor
Stack(const Stack&); //Copy constructor
~Stack(){ delete [] stack_array;}
//destructor
Stack& operator=(const
Stack&);//Assignment operator
int Size() const;
int empty() const; //returns 1 if
stack is empty
T& top(); //returns top of stack
void pop(); //pops top of stack
void push(const T&); //pushes
template<class T>
friend ostream &
operator<<(ostream & out1,Stack<T>&S);
private:
T *stack_array; // Stack of data
integers,double,students
int tos; //top of stack
int stack_size; // Stack size
};
template<class T>
ostream & operator<<(ostream &
out1,Stack<T>&S)
{out1<<”\n \t”<<”content”<<endl;
for ( int j=0 ; j<max; j++)
out1<<S.top()<<" : "; }
template <class T> //default constructor
Stack<T> :: Stack()
{stack_array = new T[max]; stack_size =
max; tos = -1;}
//copy constructor
template <class T> //copy constructor
Stack<T> :: Stack(const Stack& S):
stack_array(new T[S.size]),
tos(S.tos),stack_size(S.stack_size)
{for(int i =0 ; i<stack_size; i++)
stack_array[i] = S.stack_array[i]; }
template <class T>
Stack<T>& Stack<T> :: operator=(const
Stack& S)
{ stack_array = new T[S.stack_size];
tos = S.tos;
stack_size =S.stack_size;
for(int i =0 ; i<size; i++)
stack_array[i] = S.stack_array[i];
}
template <class T>
int Stack<T> :: Size() const { return
tos+1;}
template <class T>
int Stack<T> :: empty() const
{if(tos == -1) return 1;
else return 0; }
template <class T>
void Stack<T> :: push(const T& val)
{if( tos<stack_size-1 )
{ tos++;stack_array[tos] = val; }
}
template <class T>
void Stack<T> :: pop()
{if(tos >= 0) tos--; }
template <class T>
T& Stack<T> :: top()
{return (stack_array[tos--]); }
void main()
{Stack<int> I; //Stack of integers
Stack<float> F; //Stack of floats
Stack<Student> stdStack;
for ( int i=0;i<max;i++)
{ I.push(i+10); F.push(i+20);
stdStack.push(i+10000); }
cout<<"\n The contents of the int
stack"<<endl;
cout<<" "<<I;cout<<endl;
cout<<"\n The contents of the float
stack"<<endl;
cout<<" "<<F; cout<<endl;
cout<<"\n The RollNos of the Student
from stack"<<endl;
cout<<" "<<stdStack; cout<<endl;
cout<<"\n endof program"<<endl;
}
/*Output :The contents of the int stack
Content 19 : 18 : 17 : 16 : 15 : 14 :
13 : 12 : 11 : 10 :
The contents of the float stack
Content 29 : 28 : 27 : 26 : 25 : 24 :
23 : 22 : 21 : 20 :
The RollNos of the Student from stack
content10009 : 10008 : 10007 : 10006
: 10005 : 10004 : 10003 : 10002 : 10001
: 10000*/
Example 14.3:
stacktemplate2b.cpp A Non-
template Friend Function
FindSum() That Will Work Only on
Integer Arrays
#include<iostream>
using namespace std;
const int max=10; // declares maximum
of array size
template <class T>
class Stack
{ public: Stack(); //default
constructor
Stack(const Stack&); //Copy
constructor
~Stack(){ delete [] stack_array;}
//destructor
Stack& operator=(const
Stack&);//Assignment operator
int Size() const;
int empty() const; //returns 1 if
stack is empty
T& top(); //returns top of stack
void pop(); //pops top of stack
void push(const T&); //pushes
template<class T>
friend ostream & operator<<(ostream &
out1,Stack<T>&S);
int FindSum( Stack<int> I ) // I is
array of integers
private: T *stack_array; // Stack
of data integers, double, students
int tos;
int stack_size; // Stack size
};
template<class T>
ostream & operator<<(ostream &
out1,Stack<T>&S)
{out1<<”\n \t”<<”content”<<endl;
for ( int j=0 ; j<max; j++)
out1<<S.top()<<" : ";}
//definition of friend FindSum().Gets
access to private data
int FindSum( Stack<int> I ) // I is
array of integers
{ int sum=0;
for ( int j=0 ; j<max; j++)
sum+=I.top();
return sum;
}
template <class T> //default
constructor
Stack<T> :: Stack()
{stack_array = new T[max]; _size =
max; = -1; }
template <class T> //copy constructor
Stack<T> :: Stack(const Stack& S):
stack_array(new T[S.stack_size]),
tos(S.tos),stack_size(S.stack_size)
{ int i;
for(i =0 ; i<stack_size; i++)
stack_array[i] =
S.stack_array[i];
}
template <class T>
Stack<T>& Stack<T> :: operator=(const
Stack& S)
{ stack_array = new T[S.stack_size];
tos = S.tos;
stack_size =S.stack_size;
for(int i =0 ; i<size; i++)
stack_array[i] = S.stack_array[i];
}
template <class T>
int Stack<T> :: Size() const { return
tos+1;}
template <class T>
int Stack<T> :: empty() const
{if(tos == -1) return 1;
else return 0;
}
template <class T>
void Stack<T> :: push(const T& val)
{if( tos<stack_size-1 )
{ tos++;stack_array[tos] = val; }
}
template <class T>
void Stack<T> :: pop()
{if(tos >= 0) tos--; }
template <class T>
T& Stack<T> :: top()
{ return (stack_array[tos--]); }
void main()
{ Stack<int> I; //Stack of integers
//populate int stack
for ( int i=0;i<max;i++)
{I.push(i+10);}
cout<<"\n Use friend function int
FindSum(Stack<int>)"
<<"\n to calculate the sum
of int Stack"<<endl;
int sum = FindSum(I);
cout<<"\n Sum of integer Stack:
" << sum<<endl;
cout<<"\n endof program"<<endl;
}
/* Output Use friend function int
FindSum(Stack<int>)
to calculate the sum of int Stack :
Sum of integer Stack: 145 */
out1<<”\n\t”<<j<<”\t\t”<<S[j];
}
tos(S.tos),stack_size(S.stack_size)
{ int i;
for(i =0 ; i<stack_size; i++)
stack_array[i] = S.stack_array[i];
}
template <class T>
Stack<T>& Stack<T> :: operator=(const
Stack& S)
{ stack_array = new T[S.stack_size];
tos = S.tos;
stack_size =S.stack_size;
for(int i =0 ; i<size; i++)
stack_array[i] = S.stack_array[i];
}
template <class T>
int Stack<T> :: Size() const
{return tos+1;}
template <class T>
int Stack<T> :: empty() const
{if(tos == -1) return 1;
else return 0;
}
template <class T>
void Stack<T> :: push(const T& val)
{if( tos<stack_size-1 )
{ tos++;stack_array[tos] = val; }
}
template <class T>
void Stack<T> :: pop()
{if(tos >= 0) tos--; }
template <class T>
T& Stack<T> :: top()
{ return (stack_array[tos--]); }
void main()
{Stack<int> I1; //stack of integers
Stack<float> F1; //stack of floats
// fill the data in to all three
stacks
for ( int i=0;i<max;i++)
{ I1.push(i+10);
F1.push(i+20.0);
}
cout<<"\n output using friend <<
operator"<<endl;
cout<<"\n The contents of the stack
of int type"<<endl; cout<<I1;
cout <<"\n The contents of the stack
of float type"<<endl; cout<<F1;
//tos() function decrements tos for
each display till tos=-1
//To Go to top of stack Call SetTos()
function for reusing Stack
F1.SetTos(); I1.SetTos();
cout<<"\nUse friend function T
FindSum(Stack<T>)"
<<"\nto calculate the sum of T
type stack"<<endl;
cout<<"\n Sum of integer stack :
";FindSum(I1);
cout<<"\n Sum of float stack : ";
FindSum(F1);
}
/*Output: out put using friend <<
operator
The contents of the stack of int type
Content 19 : 18 : 17 : 16 : 15 :
The contents of the stack of float
type
Content 29 : 28 : 27 : 26 : 25 :
Use friend function T
FindSum(Stack<T>)
to calculate the sum of T type stack
Sum of integer stack : 145 Sum of
float stack : 245 */
14.6 Templates and Static Member
Functions and Member Data
While handling static member data and
member functions, all the rule that apply to
static declarations with respect to ordinary
classes also apply for template classes and
member functions. Static declaration in
template allows each instant of template to
have its own static data. For example, if we
declare a static member data to stack like
numberOfStacks in our array class, then
each instantiation of Student array and
integer array will have its own
numberOfStacks to keep track of how
many student arrays or integer arrays have
been created.
tos(S.tos),stack_size(S.stack_size)
{ int i;
for(i =0 ; i<stack_size; i++)
stack_array[i] =
S.stack_array[i];
numOfStacks++;
}
template <class T>
Stack<T>& Stack<T> :: operator=(const
Stack& S)
{ stack_array = new T[S.stack_size];
tos = S.tos;
stack_size =S.stack_size;
for(int i =0 ; i<size; i++)
stack_array[i] = S.stack_array[i];
}
template <class T>
int Stack<T> :: Size() const { return
tos+1;}
template <class T>
int Stack<T> :: empty() const
{if(tos == -1) return 1;
else return 0;
}
template <class T>
void Stack<T> :: push(const T& val)
{if( tos<stack_size-1 )
{ tos++;stack_array[tos] = val; }
}
template <class T>
void Stack<T> :: pop()
{if(tos >= 0) tos--; }
template <class T>
T& Stack<T> :: top()
{ return (stack_array[tos--]); }
void main()
{ Stack<int> I1; //stack of integers
Stack<float> F1; //stack of floats
Stack<Student> stdStack; // stack
of Students
// fill the data in to all three
stacks
for ( int i=0;i<max;i++)
{I1.push(i+10); F1.push(i+20.0);
stdStack.push(i+10000);
}
// declare & fill the data in
Second set of Stacks
Stack<int> I2; //Stack of integers
Stack<float> F2; //Stack of floats
Stack<Student> stdStack2; // Stack
of students
// fill the data in to all three
stacks for second set
for ( i=0;i<I2.Size();i++)
{ I2.push(i+10); F2.push(i+20.0);
stdStack2.push(i+10000);
}
cout<<"\n Display static data
using full class specification.."<<endl;
cout<<"\n integers Stacks"<<"\t"
<<Stack<int>::GetNumberOf Stacks()
<<endl;
cout<<" float Stacks"<<"\t"<<"\t"
<<Stack<float>::GetNumberOf Stacks()
<<endl;
cout<<" Student Stacks"<<"\t"
<<Stack<Student>::GetNumberOf Stacks()
<<endl;
cout<<"\n Display static data
using object say I2 , F2 , stdStack2.."
<<endl;
cout<<"\n integers Stacks"<<"\t"
<<I2.GetNumberOfStacks()<<endl;
cout<<" float Stacks"<<"\t"<<"\t"
<<F2.GetNumberOfStacks() <<endl;
cout<<" Student Stacks"<<"\t"
<<stdStack2.GetNumberOfStacks() <<endl;
}
/*Output Display static data using
full class specification.
integers Stacks 2
float Stacks 2
Student Stacks 2
Display static data using object say
I2 , F2 , stdStack2..
integers Stacks 2
float Stacks 2
Student Stacks 2*/
class Stack
{public: ………………….
// Exception classes
class stackfullerror {};
class stackemptyerror {}
};
catch(Stack<string>::stackfullerror)
{ cout<<”\nstack full exception .
Cannot be pushed on to stack:”<<endl;
cout<<”\nExiting the catch block of
stackfull exception ..”<<endl;
}
Ex 3 at the end of the chapter gives
complete solution.
14.8 Summary
Exercise Questions
Objective Questions
1. ii
2. i and ii
3. i, ii and iii
4. i and iv
1. b
2. c
3. c
4. b
5. b
6. d
7. True
8. False
9. c
10. a
11. True
12. False
15
Object-Oriented Programming
with Java
LEARNING OBJECTIVES
Object-oriented programming is a
methodology in which we create cooperating
objects that communicate with each other
and accomplish the desired task. Java is a
pure object-oriented language. You cannot
write a Java program without a class. In fact
program resides in a class. Java program
uses objects and classes. So when we refer to
object called Student we refer to both
attributes(state) and behaviour. Attributes
are also called state of an object.
Path:
% /usr/local/jdk1.6.0/bin/>javac
HelloWorld.java
To find out if the path is properly
set, execute:
% java -version
/usr/local/Oopsjava/examples/TestDriver:
Current working directory by default
classpath search directory. Setting the
CLASSPATH variable or using the -classpath
command-line option overrides that default,
hence we have included the current
directory “.” in the search path.
You can also get the same result by
executing the following command:
In csh % setenv CLASSPATH
classpath1:classpath2…
In sh enter; CLASSPATH =
path1:path2:… export CLASSPATH
To clear classpath already set from
the previous commands
In csh: unsetenv CLASSPATH
In sh : unset CLASSPATH
To check if classpath is set
correctly on Linux, execute the
following:
% echo $CLASSPATH
If CLASSPATH is not set you will get
a
CLASSPATH: Undefined variable
error
Changing Startup Settings:
If the class path is set at system
startup then we should:
For shells csh , tcsh look for
setenv command in .cshrc file
(~/.cshrc): and enter
% setenv CLASSPATH
classpath1:classpath2…
For shells sh , ksh look into
.profile export command(~/.
profile):
CLASSPATH= classpath1:classpath2:
export classpath
C:\OopsJava\examples\src>javadoc
com.oops.chap1
cd
C:\Oopsjava\examples\src\com\oo
ps\chap1> edit HelloWorld.java
Step 2: Compile: We need to store all our
compiled code in
C:\Oopsjava\examples\bin\com\oop
s\chap1. Therefore from the directory
C:\Oopsjava\examples\src\com\oop
s\chap1. Compile the source file and
redirect the class file into
C:\Oopsjava\examples\bin\com\oop
s\chap1. For redirecting you have to use –
d option and provide the complete path to
bin directory as shown below:
C:\OopsJava\examples\src\com\oo
ps\chap1>javac -d
c:\Oopsjava\examples\bin
HelloWorld.java
1. // A program HelloWorld.java to
print a line
2. package com.oops.chap1;
3. public class HelloWorld
4. {
5. public static void main(String[]
args)
6. {
7. System.out.println(“Welcome to
Object Oriented Programming in Java “);
8. }
9. }
Welcome to Object-oriented
Programming in C++ and Java
L package: As a developer, you would like to keep
i all your work together, so that you can reuse
n them in future if needed. We would like to keep
e all our work as a “package”. Suppose you are
N working in a company called “oops.com”,
o then it is customary to create package as
. “com.oops”. Now we are writing programs for
2 Chapter 1. Hence we will name our package as
: “com.oops.chap1”. More details about
package later in Chapter 19 (refer to Figure
15.8). Path variable will link up to
c:\Oopajava\example\src. It is your
package statement which will link to
com.oops.chap1.
C:\OopsJava\examples\src\com\oo
ps\chap1\ edit HelloWorld.java
C:\OopsJava\examples\src\com\oo
ps\chap1>javac -d
c:\Oopsjava\examples\bin
HelloWorld.java
C:\OopsJava\examples\bin>java
com/oops/chap1/HelloWorld
//HelloWorldDialog.java
//We will use Dialog box offered
in swing components
1. package com.oops.chap1;
2. import javax.swing.JOptionPane;
3. public class HelloWorldDialog {
4. public static void main(String[]
args) {
5. String input =
JOptionPane.showInputDialog(“Enter your
name?”);
6. // create the message
7. String message =
8. String.format(“Welcome %s to
Object oriented programming in
9. Java”,input);
10. // display the message
11.
JOptionPane.showMessageDialog(null,
message);
}
}
C:\Oopsjava\examples\src\com\oo
ps\chap1\ edit
HelloWorldDialog.java
C:\OopsJava\examples\src\com\oo
ps\chap1>javac -d
c:\Oopsjava\examples\bin
HelloWorldDialog.java
C:\OopsJava\examples\bin>java
com/oops/chap1/HelloWorldDialog
a
Dialog Boxes
Caution/Note: We are providing detailed
compile and run instructions only in
Chapter 1. We expect you to practice these
commands well. In the succeeding chapters,
we provide example programs only. Now
that you have practiced two programs and
learnt the edit, compile and load and run in
command screen, we will introduce you to
Java programming using “eclipse” JDE.
1. package com.oops.chap1;
2. import javax.swing.*;// for
JOptionPane
3. public class Calculator
4. {
5. public static void main(String[]
args)
6. {
7. String number1,number2,choice; // two
numbers from the user from console
8. int num1,num2,result,ch; // we need
these data to do internal calculations
Output
Lin Number1,number2, and choice have been
e defined as variables of string class of Java. All
No inputs we will get as String class in Java.
. 7:
1. package com.oops.chap1;
2. import javax.swing.*;
3. public class Calculator2 {
4. public static void main(String[]
args) {
5. int num1 = Integer.parseInt(args[0]);
6. int num2 = Integer.parseInt(args[1]);
7. int ch = Integer.parseInt(args[2]);
8. int result;
9. if (ch==1)
10. result=num1+num2;
11. else
12. //subtract
13. result=num1-num2;
14. //display result
15.
JOptionPane.showMessageDialog(null,”The
result is “+result,
”Answer”,JOptionPane.PLAIN_MESSAGE);
16. // return i.e exit programme
17. System.exit(0);
18. }
19. } // end Calculator prog
C:\OopsJava\examples\src\com\oo
ps\chap1>javac -d
c:\Oopsjava\examples\bin
Calculator2.java
Now go to bin directory and type the
command to execute Java program giving
full package path with arguments: 10 10 1
C:\OopsJava\examples\bin>java
com/oops/chap1/Calculator2 10
10
15.7 Summary
1. Java is a networking language. The Internet is a
collection of cooperating networks. A network is a
collection of cooperating computers.
2. WWW (World Wide Web or simply web) is a way of
accessing information from the network. We use
HTTP/FTP for retrieval of information from the web.
Email (through Simple Mail Protocol, SMP) is another
important and widely used method to exchange
information on the web.
3. Java is platform independent, i.e. it is independent of
underlying hardware and operating systems that are
controlling the hardware resources.
4. Java was originally named as “OAK” by its inventors
James Gosling and Patrik Naughton.
5. Extending/Deriving new classes from existing classes,
containment through inner classes, Extending through
Inheritance mechanism.
6. Single, multi level , and hierarchical inheritance are
allowed by Java . Java does not support multiple
inheritance.
7. A class with abstract method is called abstract class with
keyword abstract. An abstract class need not necessarily
have abstract methods.
8. Interface is declared with keyword interface instead of
usual keyword class. Interface can only contain abstract
methods. However, using keyword abstract for these
methods is optional.
9. A class can extend to only one class but can
implement several interfaces.
10. Generic programming is a facility provided by Java to
achieve reusability of code. Generics can be applied to
classes and methods. Generic programming is very
useful to abstract over types.
11. Java supports single line, multiline, and Java API
documentation comments.
12. Byte code is an instruction set of 1 byte (8 bits). Byte
codes are compact numeric codes and references
(normally numeric addresses).
13. JVM is not portable but byte code is fully portable. JVM
is specific to hardware and Operating System.
14. Package is a collection of all class files.
15. Path command is used to link all resources situated in
any directory.
16. Classpath is used to inform the Java runtime
environment where to find class files.
17. Javadoc is a compiler used to generate API documents
for a package.
18. Java.io.* is an import statement used to import all
files related to io. Similarly java.lang.* is a package
imported to include Java features. This is default
package Java imports automatically by default.
19. Keyword public means that methods inside a public
class can be called outside the class hierarchy.
20. Keyword static means that the class can be invoked
directly without using an instance of the class to invoke
the method “main”.
21. Java extended package called Javax houses several
graphical libraries which would greatly enhance the
graphics components.
Exercise Questions
Objective Questions
8. Inheritance is
1. Has-type of relation
2. Is-type relation
3. As-is-type relation
4. None of the above
1. i
2. ii
3. i, iii and iv
4. ii, iii and iv
Short-answer Questions
1. a
2. a
3. b
4. a
5. b
6. c
7. c
8. b
9. c
10. c
11. b
16
LEARNING OBJECTIVES
Bell \a
Back space \b
Horizontal tab \t
Vertical tab \v
Form feed \f
New line \n
Carriage return \r
Double Quote \”
Apostrophe/Single quote \’
Backslash \\
Null \0
Octal number \On
Hexadecimal number \cHn
//FindMaxDemo.java
1. package com.oops.chap16;
2. import java.io.*;
3. class FindMax{
4. public int Max3Numbers(int a ,int b,
int c){
5. int max=a;
6. if ( max<b) max = b;
7. else if ( max<c) max=c;
8. return max;}
9. }//end of Findmax
10. public class FindMaxDemo{
11. public static void main(String[]
args) {
12. // create an object of FindMax
13. FindMax obj=new FindMax();
14. int num1=0;int num2=0;int num3=0;int
max=0;
15. try{
16. BufferedReader input = new
BufferedReader (new InputStreamReader
(System.in));
17. System.out.println(“Enter value for
number num1:”);
18. num1 =
Integer.parseInt(input.readLine());
19. System.out.println(“Enter value for
number num1:”);
20. num2 =
Integer.parseInt(input.readLine());
21. System.out.println(“Enter value for
number num1:”);
22. num3 =
Integer.parseInt(input.readLine());
23. }catch(Exception e){}
24. //get data for 3 numbers. Call
GetNumbers() ofFindmax
25. max=obj.Max3Numbers(num1,num2,num3);
26. System.out.println(“Maximum of three
numbers:” + num1+” : “+num2 +” : “+ num3
+ “ = “+max);
27. }
28. }// end of class FindMaxDemo
Output: Enter value for number num1: 45
Enter value for number num1: 67
Enter value for number num1: 12
Maximum of three numbers:45 : 67 : 12 =
67
L num1 =
i Integer.parseInt(input.readLine());
n This is how we will read data from keyboard.
e
N
o
.
1
8
:
//QuadraticDemo.java
1. package com.oops.chap16;
2. import java.io.*;
3. class Quadratic{
4. public void FindRoots(int a ,int b,
int c){
5. int d;
6. float root1,root2;
7. System.out.println(“The Equation is
“);
8. System.out.println( a + “X^2” + “+” +
b+ “*”+ “X”+”+”+c);
9. d = ((b*b)-(4*a*c));
10. if (d<0)
11. { System.out.println( “No real
solution since d<0”);
12. System.out.println( “roots are
imaginary\n”);
13. double sqrd= (double)Math.sqrt(-
d/(2*a));
14. double real = (double)(-b)/(double)
(2*a);
15. System.out.println( “root1 : “+ real
+ “+ i “+ (float)(sqrd));
16. System.out.println( “root1 : “+ real
+ “- i “+ (float)(sqrd));
17. }
18. if(d==0)
19. { System.out.println( “roots are
real\n”);
20. System.out.println( “root1&2 are
equal “+ (float)-b/(2*a));
21. }
22. else
23. if ( d>0)
24. { double sqrd = Math.sqrt(d);
25. System.out.println( “root1 : “+
(float)(-b + sqrd)/(2*a));
26. System.out.println( “root2 : “+
(float)(-b - sqrd)/(2*a));
27. }
28. }//end of FindRoots
29. }//end of Quadratic
30. public class QuadraticDemo{
31. public static void main(String[]
args) {
32. // create an object of Quadratic
33. Quadratic obj=new Quadratic();
34. int num1=0 ;int num2=0; int num3=0;
35. try{
36. BufferedReader input =
newBufferedReader (new InputStreamReader
(System.in));
37. System.out.println(“Enter Non-zero
Integer value for number num1:”);
38. num1 =
Integer.parseInt(input.readLine());
39. System.out.println(“Enter Non-Zero
Integer value for numbernum1:”);
40. num2 =
Integer.parseInt(input.readLine());
41. System.out.println(“Enter Non-Zero
Integer value for number num1:”);
42. num3 =
Integer.parseInt(input.readLine());
43. }catch(Exception e){}
44. // Call FindRoots of Quadratic
45. obj.FindRoots(num1,num2,num3);
46. System.out.println(“End of Programme
…”);
47. }
48. }// end of class QuadratciDemo
Output: Enter Non-Zero Integer value for
number num1:3
Enter Non-Zero Integer value for
numbernum1:2
Enter Non-Zero Integer value for number
num1:-5
The Equation is :3X^2+2X+-5
root1 : 1.0
root2 : -1.6666666
End of Programme …
Enter Non-Zero Integer value for number
num1:2
Enter Non-Zero Integer value for
numbernum1:3
Enter Non-Zero Integer value for number
num1:4
The Equation is 2X^2+3X+4
No real solution since d<0
roots are imaginary
root1 : -0.75+ i 2.236068
root1 : -0.75- i 2.236068
End of Programme …
//LogicalDemo.java
1. package com.oops.chap16;
2. import java.io.*;
3. class Logical{
4. public boolean Eligibility(int marks,
int att){
5. boolean yesno=true;
6. if ( (marks>50)&& (att>=75) )
yesno=true;
7. else yesno=false;
8. return yesno;
9. }//end of FindReverse
10. }//end of Reverse class
11. public class LogicalDemo{
12. public static void main(String[]
args) {
13. //create an object of Logical
14. Logical obj=new Logical();
15. int marks=0;int attendance=0;String
name=””;boolean yesno;
16. try{
17. BufferedReader input = new
BufferedReader (new InputStreamReader
(System.in));
18. System.out.println(“Enter Name of
Student”);
19. name=input.readLine();
20. System.out.println(“Enter marks “);
21. marks =
Integer.parseInt(input.readLine());
22. System.out.println(“Enter Attendance
“);
23. attendance =
Integer.parseInt(input.readLine());
24. }catch(Exception e){}
25. //Call Eligibility() of class
Logical
26.
yesno=obj.Eligibility(marks,attendance);
27. System.out.println(“Name :” + name
);
28. System.out.println(“Marks :
Attendance : “ + marks + “ : “+
attendance);
29. System.out.println(“eligibility:” +
yesno );
30. if( yesno==true)
31. System.out.println(“ Collect Admit
Card”);
32. else System.out.println(“Sorry.
falling short of academic or Attendance
Standard”);
33. }
34. }// end of class LogicalDemo
Output:
Enter Name of Student Suresh Enter marks
65 Enter Attendance 66
Name: Suresh Marks : Attendance : 65 :
66 eligibility:false
Sorry. falling short of academic or
Attendance Standard
2 run: Enter Name of Student Gautam
Enter marks 98 Enter Attendance89
Name: Gautam Marks : Attendance : 98 :
89eligibility:true
Collect Admit Card
Note that the last four bits are 0101 and are
unaffected, i.e. they are just reproduced in
the result, whereas the left four bits are all
0s, i.e. they are masked.
1. package com.oops.chap16;
2. public class Ternary {
3. public static void main(String[]
args) {
4. byte a=56, b=101, c=45, max;
5. // find the maximum of a & b
6. max=(a>b)?a:b;
7. System.out.println(“maximum of a &
b =” + max);
8. max=( ( a>( max=(b>c)?b:c))?a :max
);
9. System.out.println(“maximum of a &
b & c =” + max);
10. }
11. }
maximum of a & b =101
maximum of a & b & c =101
Left
to
right
11
Left
to
right
12
?: conditional operator Righ
t to
= Assignment operator left
13
Righ
t to
left
14
= += -= *= /= %= ^= != <<= >>= Righ
t to
left
, Left
to
right
}
else // associated with outer if
{ …else block………}
1. package com.oops.chap16;
2. public class IfLoop {
3. public static void main(String[]
args) {
4. //Declare two arrays to hole marks
and attendance of 5 students
5. int[] idNo = new int[]{ 50595,
50596,50597,50598,50599};
6. float[] marks = new float[]
{96.0F,65.8F,71.0F,46.0F,33.0F};
7. float[] att = new float[]
{78.0F,66.0F,71.0F,75.0F,45.0F};
8. boolean [] yesno = new boolean[5];
9. for ( int i=0;
i<5;i++)yesno[i]=false; //initial value
for yesno
10. // To be eligible attendance >=60.0
and marks>=50.0
11. for (int i=0; i<5;i++)
12. if ((marks[i]>=50.0)&&
(att[i]>=60.0)) yesno[i]=true;
13. System.out.println(“List of eligible
candidates”);
14. for (int i=0; i<5; i++)
15. if( yesno[i]== true)
16. System.out.println(“ IdNo : “ +
idNo[i] + “ marks :” + marks[i] +”
attendance “ + att[i]);
17. }
18. }//end of IfLoop class
1. package com.oops.chap16;
2. public class SumDigits {
3. public static void main(String[]
args) {
4. int num = 989989,rem,sum=0, count
=0,temp;
5. temp=num; // store it in temp
6. while ( num>0)
7. {rem=num%10; // finds remainder
8. num=num/10;
9. count++;//increments counter
10. sum+=rem; //adds remainder to sum
Figure 16.5 Control flow for while and for loops
Example 16.14:
SumDigitsDoWhile.java a Program
to find sum of digits and also no of
digits using do while
1. package com.oops.chap16;
2. public class SumDigitsDoWhile {
3. public static void main(String[]
args) {
4. int num = 989989,rem,sum=0, count
=0,temp;
5. temp=num; // store it in temp
6. do
7. {rem=num%10; // finds remainder
8. num=num/10;
9. count++;//increments counter
10. sum+=rem; //adds remainder to sum
11. }while( num>0);
12. System.out.println(“Given Number” +
temp);
13. System.out.println(“No of digits=” +
count);
14. System.out.println(“Sum of digits=”
+sum);
15. }
16. }//end of class
Output: Given Number989989 No of
digits=6 Sum of digits=52
The syntax is
for ( int i=0;i<n;i++)
{for (int j=0;j<n;j++)
{statement}
}
package com.oops.chap16;
public class Fibonaaci{
public static void main(String[] args) {
int [] FibArray = new int [20];
int numOfTerms = 20; //number of terms
in the series
FibArray[0]=0; FibArray[1]=1; // first
two number of the series
for (int i =2 ; i< numOfTerms; i++)
{ FibArray[i]=FibArray[i-1]+FibArray[i-
2];}
System.out.println(“ The fibonaacii
series for 20 terms …”);
for (int i =0; i< numOfTerms; i++){
System.out.print(FibArray[i] + “ “);}
}
}//end of class
Output: The fibonaacii series for 20
terms …
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
610 987 1597 2584 4181
16.14 Break
Break statement is used to exit from the
switch control or control loop. We can use
break statement to exit from for, while and
do while, and switch control statements. You
have already seen use of break statement in
Switch statement. When used within a
nested block, a break statement can be used
to go to the end of the block in which the
break is used. There is another use in break
statement. For example: break label2;
takes you to the end of the block labeled as
label2.
Example 16.16: BreakUses.java: A
Program that Demonstrates Break
Statement
1. package com.oops.chap16;
2. import java.io.*;
3. public class BreakUses {
4. public static void main(String[]
args) throws IOException {
5. int count=0; int sum=0,num;
6. // write a forever for loop for
demonstration of
7. // break for going out of control
loop
8. BufferedReader input = new
BufferedReader (new InputStreamReader
(System.in));
9. for(;;){
10. if ( count ==5)
11. { System.out.println(“upper limit of
5 reached”);
12. break;}
13. else{
14. System.out.println(“enter value of
“+(count+1)+ “number”);
15. num =
Integer.parseInt(input.readLine());
16. sum+=num; count++;}
17. }// end of for
18. // Second use of break with label
19. label1:{System.out.println(“Entered
label1 “);
20. label2:{System.out.println(“Entered
label2 “);
21. label3:{System.out.println(“Entered
label3 “);
22. System.out.println(“Inside a label3
Using break label2 Statement”);
23. break label2;
24. }//end of label3
25. }//end of label2
26. System.out.println(“reached end of
label2 “);
27. }//end of label1*/
28. } //end of main()
29. }//end of class
Output: enter value of 01number10
enter value of 11number20
enter value of 21number30
enter value of 31number40
enter value of 41number50
upper limit of 5 reached
Entered label1
Entered label2
Entered label3
Inside a label3 Using break label2
Statement
reached end of label2
Lin uses for evr for loop. It can be only stopped
e by Line No 10 which tests for count == 5
No.
9:
1. package com.oops.chap16;
2. import java.io.*;
3. public class Continue {
4. public static void main(String[]
args){
5. int count=0;
6. for(count = 0;count<=10;count++){
7. if ( count%2==0)
{System.out.println(“The number “+count+
“ is even “);
8. continue;} //control goes to begining
of for loop
9. System.out.println(“The number
“+count+ “ is odd”);
10. }//end of for
11. }// end of main
12. }//end of class
Output:
The number 0 is even The number 1 is odd
The number 2 is even
The number 3 is odd The number 4 is even
The number 5 is odd
The number 6 is even The number 7 is odd
The number 8 is even
The number 9 is odd The number 10 is
even
16.16 Summary
1. Java supports integral, character and Boolean constants.
Literal constants are those that do not change their
value during the running of the program.
2. Integral constants are Integer constants, Octal constants
and Hexa constants.
3. Floating point or real constants are expressed in decimal
or exponent form.
4. Character constants are character and String constants.
5. Boolean literals are expressed as true or false.
6. Constants declared as final cannot change their value
during running of the program.
7. Integer data types are byte (1 byte), short (2
bytes), int (4 bytes), long (8 bytes).
8. Float data types are float (4 bytes) and double (8
bytes).
9. The scope of the variable is local. This means that a
variable declared in a function is accessible only within
the function.
10. The basic (also known as intrinsic) operators are +
addition − subtraction * multiplication /
division % modulus (remainder after
division).
11. Type Conversion: If the variables involved in an
operation are of different types, then Java carries out
type conversion automatically before the operation. The
process of conversion to a larger data type from a
smaller data type is called widening and conversion
from larger to smaller data type is called narrowing.
12. Type Cast: Suppose we want to declare the result in a
particular data type, we can type cast the variable :
(data type) variable.
13. Unary Operators: In unary operators, the operator
precedes a single operand. The minus operator is both a
unary and a binary operator.
14. ++ , -- operators are called increment and decrement
operators.
15. Assignment Operator operator is =. This is also
called equality operator.
16. The relational operators are : > >= < and <=. Two
more operators, known as equality operators = =
and ! =, have priority just below relational operators.
17. Logical Operators: These are && and || and NOT
operator (!). Evaluation of expressions connected by
logical operators are done from left to right and
evaluation stops when either truth or falsehood is
established.
18. Bit-wise operators available in Java language are Seven.
They are & Bit wise AND, | Bitwise OR, ^
Bit wise Exclusive OR, << Left Shift, >>
Right Shift, >>> Bitwise zero Fill Shift
Operator, ~ Tilde operator . one's
complement Operator.
19. instanceof operator to test if the object belongs to a
particular class or not.
20. new operator It is used to allocate resources when we
create objects for classes.
21. Syntax of if statement: if (expression) statement.
22. There will be several occasions when a programmer has
to execute a set of instructions repeatedly till a condition
is met. In these situations, we need control loops. The
switch statement is similar to if-else-if ladder.
23. The syntax of while loop is : While(expression){
statement1;statement2;}.
24. Do-while loop :The syntax is Do{ block of
statements} while (expression).
25. For loop syntax is: for ( exp1 ; exp2 ; exp3),
where exp1 is initialization block, exp2 is condition test
block, exp3 is alter initial value assigned to exp1.
26. Break statement is used to exit from the switch control
or control loop.
27. Continue is used when we want to stop further
processing of loop statements and start at the beginning
of the control loop.
Exercise Questions
Objective Questions
1. i
2. i and ii
3. i, ii and iii
4. iii
1. iv
2. i and ii
3. i, ii and iii
4. iii
1. ii and iii
2. i and ii
3. i, ii and iii
4. iii and iv
1. ii and iv
2. i and ii
3. i, ii and iii
4. iii and iv
20. What are the literal constants and data types provided
by Java? Explain with suitable examples.
21. Distinguish type casting and type conversion with
examples.
22. Explain the usage of bit-wise operators of Java.
23. What is operator precedence and Associativity? Discuss
with examples.
24. Explain the difference between if–else–if and switch
statements. Which is better and why?
25. Explain variations in for loop statements in Java with
examples.
26. Which one of these are better for control loop: for, while,
do while?
27. Distinguish continue and break statement.
Assignment Questions
1. c
2. c
3. d
4. a
5. d
6. a
7. False
17
LEARNING OBJECTIVES
Example
17.2: EmployeeCredits.java: To
Obtain Multiple Inputs in a Single
Line Using StringTokenizer.
1. package com.oops.chap17;
2. import java.util.*; // For using
StringTokenizer()
3. import java.io.*;
4. import javax.swing.JOptionPane;
// Swing components
5. public class EmployeeCredits {
6. public static void main(String[]
args) throws IOException{
7. String name,idNo,crdts,debts;//
variables or reading input date
8. double credits,debits,netPay; //
variables for internal computations
9. BufferedReader input = new
BufferedReader (new InputStreamReader
(System.in));
10. System.out.println(ʺEnter Emp
name, idNo,credits,debits separated by
commaʺ);
11. String stg = input.readLine(); //
multiple data separated by comma
12. StringTokenizer stkn = new
StringTokenizer(stg,","); // object of
StringTokenizer
13. name = stkn.nextToken(); // break
into tokens
14. idNo = stkn.nextToken();
idNo.trim(); // trim is to remove
leading trailing spaces
15. crdts = stkn.nextToken();
crdts.trim();
16. debts =
stkn.nextToken();debts.trim();
17. // convert to double
18. credits =
Double.parseDouble(crdts);
19. debits =
Double.parseDouble(debts);
20. netPay = credits-debits;
21.
JOptionPane.showMessageDialog(null,"Name
"+ name +
22. "\tId Number :" + idNo
+"\nCredits :" +
23. credits+"\t Debits " + debits
+"\t Net Pay :"+ netPay,"Employee Pay
Bill",JOptionPane.PLAIN_MESSAGE);
24. }
25. }
L idNo = stkn.nextToken();
i idNo.trim(); shows how to break a
n continuous string into token by using
e nextToken(). Further idNo.trim()
N
removes leading and trailing spaces if any.
o
.
1
4
:
1. package com.oops.chap17;
2. import java.util.*; // for Scanner
class
3. import java.io.*;
4. import javax.swing.JOptionPane;
5. public class ScannerInput {
6. public static void main(String[]
args) throws IOException{
7. String name;// variables or
reading input date
8. int idNo;
9. double credits,debits,netPay;
10. System.out.println(ʺEnter Emp
name, idNo,credits,debits separated by
spacesʺ);
11. Scanner scn = new
Scanner(System.in);
12. name = scn.next();
13. idNo = scn.nextInt();
14. credits = scn.nextDouble();
15. debits = scn.nextDouble();
16. netPay = credits-debits;
17.
JOptionPane.showMessageDialog(null,ʺName
ʺ+ name +
18. ʺ\tId Number :ʺ + idNo +ʺ
\nCredits :ʺ +
19. credits+ʺ \t Debits ʺ + debits +ʺ
\t Net Pay :ʺ +
20. netPay,ʺ Employee Pay Billʺ
,JOptionPane.PLAIN_MESSAGE);
21. }
22. }
1. package com.oops.chap17;
2. import java.util.*;
3. import java.io.*;
4. import javax.swing.JOptionPane;
5. public class PrintfJava {
6. public static void main(String[]
args){
7. String name;// variables or
reading input date
8. int idNo;
9. double credits,debits,netPay;
10. System.out.println(ʺEnter Emp
name, idNo,credits,debits separated by
spacesʺ);
11. Scanner scn = new
Scanner(System.in);
12. name=scn.next();
13. idNo=scn.nextInt();
14. credits =scn.nextDouble();
15. debits=scn.nextDouble();
16. netPay=credits-debits;
17. System.out.println(ʺEmployee
pay Bill…..ʺ);
18. System.out.printf(ʺString =
name : %s idNo : %dʺ ,name,idNo );
19. System.out.printf(ʺString =
Credits:%8.2f debits: %8.2f NetPay
%8.2fʺ ,credits,debits,netPay );
20. }
21. }
22. Output: Enter Emp name,
idNo,credits,debits separated by spaces
23. ʺRameshʺ 50595 20000.00 2000.00
24. Empleoyee pay Bill…..
25. String = name : ʺRameshʺ idNo :
50595String = Credits :20000.00 debits :
2000.00 NetPay 17000.00
L stg=String.format(ʺname : %s idNo :
i %dʺ ,name,idNo ); shows the formatting the
n argument for name and idNo.Line No. 17
e similarly show the formatting for credits and
N debits and netPay using %8.2f
o
.
1
7
:
17.3 Arrays
In day-to-day life, there are several
occasions wherein we have to store data of
the same type in contiguous locations For
example, consider a situation where you
would like to store the marks obtained by a
student in six different subjects. Java
provides us with a feature called Arrays
which can be used to accomplish the above
task.
An array is defined as a collection of
elements where each element is of the same
type. The elements of the array can either be
elementary data types like int, float,
char or they can be complex data types like
structures and objects. An array is a data
structure that defines a contiguous memory
location for a single data type. It can be a
group of students’ marks or it can be a group
of employees’ salaries. For example, float
marks[5]; represents an array with 5
marks. The particular value of an array can
be accessed by referring to cell number
called index of an array. For example,
marks[5] refers to marks at index 5.
Generally, the indexes are numbered for 0 to
n-1, where n is the number of elements in
the array. Marks obtained by a student in six
different subjects are shown in an array
named marks in Figure 17.2. Elements of
the array are referenced by array name
followed by subscript. We have shown an
array named marks; six subject marks
scored by the student can be represented by
marks[0]=80.0 and marks[5]=70.0 etc.
1. package com.oops.chap17;
2. public class ArrayLengthTest {
3. public static void main(String[]
args) {
4. int[] arr = new int[]
{10,20,30,40,50,60,70};
5. System.out.println(ʺ Given
Array…………ʺ);
6. for(int i = 0; i < arr.length ;
i++ )
7. { System.out.print(arr[i] + ʺ, ʺ
);}
8. System.out.println(ʺ\nGiven Array
Length :ʺ +arr.length);
9. }
10. }
Output: Given Array…………
10, 20, 30, 40, 50, 60, 70,
Given Array Length :7
Line shows the usage of arr.length. Here
No. arr.length returns the length of array
6: arr.
MethodName(arrayname),
1. package com.oops.chap17;
2. class IntSort1{
3. public void Sort(int myArray[],
int len){
4. int temp;
5. for(int i=0; i <len-1; i++){
6. for ( int j=i+1; j<len; j++){
7. if(myArray[i]<myArray[j]){ //swap
8. temp=myArray[i];
myArray[i]=myArray[j]; myArray[j]=temp;
}//end of if
9. }// end of inner for loop
10. }// end of outer for loop
11. }//end of method Sort
12. }//end of class IntSort
13. class IntSortDemo {
14. public static void
main(String[] args) {
15. IntSort1 obj = new
IntSort1();//make an object
16. int[] myArray = new int[]
{10,13,17,20};
17. int len = myArray.length;
18. System.out.println(ʺ Given
Array ……ʺ);
19. for(int i=0;i<len;i++)
20. System.out.print( ʺ ʺ +
myArray[i]);
21. obj.Sort(myArray, len);
22. System.out.println(ʺ \nSorted
Array ……ʺ);
23. for(int i=0;i<len;i++)
24. System.out.print( ʺ ʺ +
myArray[i]);
25. }
26. }
Output : Given Array …… 10 13 17 20
Sorted Array …… 20 17 13 10
N
o
.
1
5
:
Example
17.8: ArrayCopyDemo1.java : To
Copy an Array and Return the Array
to Calling Method
package com.oops.chap17;
class ArrayCopy1{
public int[]Copy( int[] myArray) {
int [] arr = new int[myArray.length];
for(int i=0; i <myArray.length; i++)
arr[i]=myArray[i];
return arr;
}//end of method Copy
}//end of class ArrayCopy
class ArrayCopyDemo1 {
public static void main(String[] args) {
ArrayCopy obj = new ArrayCopy();//make
an object
int[] myArray = new int[]
{10,15,20,30,35};
int[] copyArray = new
int[myArray.length];
System.out.println(ʺ Given Array ……ʺ);
for(int i=0;i<myArray.length;i++)
System.out.print( ʺ ʺ + myArray[i]);
copyArray=obj.Copy(myArray);
System.out.println(ʺ \nCopied Array ……ʺ);
for(int i=0;i<copyArray.length;i++)
System.out.print( ʺ ʺ + copyArray[i]);
}
}
Output : Given Array …… 10,15,20,30,35
Copied Array ……ʺ) 10,15,20,30,35
// Matrix transpose
1. package com.oops.chap19;
2. import java.io.*;
3. class Matrix{
4. void ReadMat(int A[][],int rows,
int cols){
5. //input matrix related data using
scanner
6. Scanner scn=new
Scanner(System.in);
7. for ( int i=0;i<rows;i++)
8. for ( int j=0;j<cols;j++)
9. { System.out.print(ʺEnter[ʺ+i+ʺ ]ʺ
+ʺ [ʺ+j+ʺ ] element :ʺ);
10. A[i][j]=scn.nextInt();}
11. }//end of ReadMat
12. void DisplayMatrix(int A[]
[],int rows, int cols){
13. for ( int i=0;i<rows;i++)
14. {for ( int j=0;j<cols;j++)
15. { System.out.print( A[i][j] +ʺ
ʺ);}
16. System.out.print( ʺ\nʺ);
17. }
18. }
19. void TranspMat(int A[][],int
rows, int cols){
20. for (int i=0;i<cols;i++)
21. {for (int j=0;j<rows;j++)
22. { System.out.print( A[j][i] +ʺ
ʺ);}
23. System.out.print( ʺ\nʺ);
24. }
25. }//end of TranspMat
26. }//end of Matrix
27. class MatTranspose{
28. public static void
main(String[] args)
29. { Scanner scn = new
Scanner(System.in);
30. System.out.print(ʺEnter no of
rows & columns:ʺ);
31. int rows= scn.nextInt();
32. int cols= scn.nextInt();
33. int A[][]= new int[rows][cols];
//two-dimensional matrix
34. Matrix mat = new Matrix();
//create an object
35. mat.ReadMat(A,rows,cols);
36. System.out.println(ʺGiven
Matrixʺ);
37. mat.DisplayMatrix(A,rows,cols);
38. System.out.println(ʺTransposed
Matrixʺ);
39. mat.TranspMat(A, rows, cols);
40. }
41. }//end of MatTranspose
Output : Enter no of rows & columns:3
3
Enter[0][0] element :1 Enter[0][1]
element :2 Enter[0][2] element :3
Enter[1][0] element :4 Enter[1][1]
element :5 Enter[1][2] element :6
Enter[2][0] element :7 Enter[2][1]
element :8 Enter[2][2] element :9
Given Matrix
1 2 3
4 5 6
7 8 9
Transposed Matrix
1 4 7
2 5 8
3 6 9
Example
17.10: ArraysClassDemo.java: To
Show Usage of Arrays Class Static
Methods
1. package com.oops.chap17;
2. import java.io.*;
3. import java.util.Arrays;
4. public class ArraysClassDemo {
5. public static void main(String []
args)
6. throws
IOException,ArrayIndexOutOfBoundsExcepti
on{
7. int[]myArray = new int[12];
8. // fill the array with zeros as
initial values
9. Arrays.fill(myArray, 0);
10. System.out.print(ʺ\nArray with
initial values\nʺ);
11. DisplayArray(myArray);
12. System.out.print(ʺ\nnow
allocate values to arrayʺ);
13. //populata the array in aloop
14. for ( int i=0;i<=
(myArray.length)/2;i++)
15. myArray[i]=(4*i);
16. for ( int i=myArray.length-
1;i>myArray.length/2;i--)
17. myArray[i]=i;
18. System.out.print(ʺ\nArray after
allocating values\nʺ);
19. DisplayArray(myArray);
20. System.out.print(ʺ\nSorting the
array….ʺ);
21. Arrays.sort(myArray);
22. System.out.print(ʺ\nArray after
sorting values\nʺ);
23. DisplayArray(myArray);
24. System.out.print(ʺ\nBinary
Search the array….ʺ);
25. int pos =
Arrays.binarySearch(myArray,4);
26. System.out.print(ʺ\n index = ʺ +
(pos+1));
27. }//end of main
28. static void DisplayArray(int
myArray[]){
29. for ( int
i=0;i<myArray.length;i++)
30. System.out.print(myArray[i]+ʺ
ʺ);
31. // System.out.println(ʺ\nʺ);
32. }// end of DisplayArray
33. }// end of ArraysClassDemo}//
end of ArraysClassDemo
Output:
Array with initial values
0 0 0 0 0 0 0 0 0 0 0 0
now allocate values to array
Array after allocating values
0 4 8 12 16 20 24 7 8 9 10 11
Sorting the array….
Array after sorting values
0 4 7 8 8 9 10 11 12 16 20 24
Binary Search the array….
Pos = 2
Lin throws
e IOException,ArrayIndexOutOfBounds
No Exception.
. 6:
stg2=stg1.trim(
);
Example
17.11: StringMethodsDemo.java: To
Show Usage of String Class Methods
1. package com.oops.chap17;
2. public class StringSort {
3. public static void main(String[]
args) {
4. //create array of Strings
5. String [] cityNames= new String[]
{ʺMADRASʺ ,ʺ BANGALOREʺ ,ʺ GHAZIABADʺ ,ʺ
BINTULUʺ ,ʺ VIZAGʺ ,ʺ RAIPURʺ };
6. // Get the size
7. int len = cityNames.length;
8. System.out.println(ʺ\nCity Names
………ʺ);
9. for ( int i=0;i<len-1;i++)
10. System.out.print(cityNames[i]+ʺ
ʺ);
11. String temp;
12. for ( int i=0;i<len-1;i++){
13. for ( int j=i+1;j<len;j++){
14. if(
cityNames[j].compareTo(cityNames[i])<0)
15. { // swap city names
16. temp=cityNames[i];
cityNames[i]=cityNames[j];
17. cityNames[j]=temp;
18. }
19. }//inerfor loop
20. }//outer for loop
21. System.out.println(ʺ\nCity
Names Sorted alphabeticallyʺ);
22. for ( int i=0;i<len-1;i++)
23. System.out.print(cityNames[i]+ʺ
ʺ);
24. }//end of main
25. }// end of class StringSort
Output: City Names ………
MADRAS BANGALORE GHAZIABAD BINTULU
VIZAG
City Names Sorted alphabetically
BANGALORE BINTULU GHAZIABAD MADRAS
RAIPUR
L if(cityNames[j].compareTo(cityNames[
i i])<0)uses compareTo() method. This
n method compares cityNames[j]&
e cityNames[i]) and returns <0 or 0
N
or >0 i.e negative, zero, and
o
positive depending on of
.
1 cityNames[i]) is alphabetically
4 appears before cityNames[j]
:
stg.setLen
gth(n);
Example
17.12: StringBufferDemo.java: To
Show Usage of StringBuffer Class
Methods
1. package com.oops.chap17;
2. import java.util.*;
3. public class StringBufferDemo {
4. public static void main(String[]
args) {
5. //create object of StringBuffer
6. StringBuffer stg = new
StringBuffer(ʺC++ & Javaʺ);
7. System.out.println(ʺ\nGiven String
: ʺ + stg);
8. int len = stg.length();
9. System.out.println(ʺPrinting Given
String character by characterʺ);
10. for (int i=0;i<len;i++)
11.
System.out.print(stg.charAt(i)+ʺ ʺ);
12. System.out.println(ʺ\nInserting
a string :OOPS in: at the beginning ʺ);
13. String stg2=ʺ OOPS in ʺ;
14. stg.insert(0,stg2);
15. System.out.println(ʺString
after insertingʺ);
16. System.out.println(stg);
17. System.out.println(ʺModifying
few elements of Stringʺ);
18. stg.setCharAt(0,’o’);
19. stg.setCharAt(1,’o’);
20. stg.setCharAt(2,’p’);
21. stg.setCharAt(3,'s’);
22. System.out.println(ʺString
after modificationsʺ);
23. System.out.println(stg);
24. System.out.println(ʺAppending
Stringʺ);
25. stg.append(ʺ Languagesʺ);
26. System.out.println(ʺString
after appendingʺ);
27. System.out.println(stg);
28. }//end of main
29. }//end of class
StringBufferDemo
Output: Given String : C++ & Java
Printing Given String character by
character
C + + & J a v a
Inserting a string :OOPS in: at the
begining
String after inserting
OOPS inC++ & Java
Modifying few elements of String
String after modifications
oops inC++ & Java
Appending String
String after appending
oops inC++ & Java Languages
Set<T> HashSet<T>
LinkedHashSet<T>
List<T> Stack<T>
LinkedList<T>
ArrayList<T>
Vector<T>
Queue<T> LinkedList<T>
Map<k,s> HashMap<k,s>
Hashtabel<k,s>
boolean
removeAllElement
s()
1. package com.oops.chap17;
2. import java.util.*;
3. public class VectorDemo {
4. public static void main(String[]
args) {
5. // create an object of vector
class to store integers
6. Vector<Integer> vec = new
Vector<Integer>();
7. // define an integer array
8. int [] x = new int []{
10,20,30,40,50,60,70};
9. /* store the integers into vec.
But integers are converted to objects
automatically by a feature autoboxing*/
10. for ( int i=0;i<x.length; i++)
11. vec.add(x[i]);
12.
System.out.println(ʺ\nDisplaying Vector
using vec.get()ʺ);
13. for ( int i=0;i<vec.size();
i++)
14. System.out.print(vec.get(i)+ʺ
ʺ);
15. System.out.println(ʺDisplaying
using ListIteratorʺ);
16. ListIterator itr =
vec.listIterator();
17. System.out.println(ʺUsing
ListIterator move forwardʺ);
18. while (
itr.hasNext())System.out.print(itr.next(
)+ʺ ʺ);
19. System.out.println(ʺUsing
ListIterator move reverseʺ);
20. while ( itr.hasPrevious())
21.
System.out.print(itr.previous()+ʺ ʺ);
22. }// end of main
23. }// end of vectorDemo
Output: Displaying Vector elements
using vec.get()
10 20 30 40 50 60 70 Displaying
Vector elements using ListIterator
Using ListIterator move forward
10 20 30 40 50 60 70
Using ListIterator move reverse
70 60 50 40 30 20 10
Li Vector<Integer> vec = new
ne Vector<Integer>();creates an object
No called vec of Vector<Integer>
. 6:
17.6 Summary
Exercise Questions
Objective Questions
1. i and iii
2. ii and iii
3. ii and iv
4. iii and iv
1. ii and iv
2. i and iii
3. iii and iv
4. i and ii
1. True
2. c
3. d
4. c
5. False
6. False
7. True
8. False
9. False
10. True
18
LEARNING OBJECTIVES
18.1 Introduction
Java is a pure object-oriented language and
hence all programming is enclosed in
classes. Object-oriented programming
involves writing programs that use classes.
We create objects of different classes to solve
the problem at hand and make objects
communicate with each other through the
member functions.
In this chapter, we will learn how to solve
problems by using classes and objects. We
will also cover topics such as data hiding,
abstraction, access privileges enjoyed by
members of the class, and concepts of
constructor and destructor. Variations in
methods such as methods definition,
recursion and factory methods are also
discussed. Classes within a class, called
inner classes, are introduced. This operator
and static member functions and their
relevance and usage are explained. Java's
garbage collector and finalizer methods are
also discussed.
Encapsulation. An object-oriented
programming like Java is a data primacy
language i.e. data is important and functions
are not important. As per memory mapping,
data is stored in data area, such as stack and
free space, and functions are stored in code
area and there is a need to maintain strict
control over the accessing of data by
functions. Java achieves this control by
using the encapsulation feature.
Encapsulation is binding member data and
calling function together with security
classification, so that no unauthorized
access to data takes place. Java depends
heavily on access specifiers to maintain data
integrity. The security access specifiers are
public, private, protected and default
specifier package.
1. package com.oops.chap19;
2. import java.io.*;
3. //import java.math.*;
4. class Polar2{
5. // all member data is declared as
private
6. private double r; // magnitude
7. private double t; // angle theeta
8. private double a; // real
9. private double b; // imaginary
10. public void Setr( double rd){
r=rd;}
11. public void Sett( double td){
t=td;}
12. public void Seta( double ad){
a=ad;}
13. public void Setb( double bd){
b=bd;}
14. //constructors
15. //Default Constructor
16. Polar2() {
17. System.out.println(“Polar2
Default constructor….”);
18.
Setr(0.0);Sett(0.0);Seta(0.0);Setb(0.0);
}
19. //parameterized constructor
20. Polar2(double ad, double bd){
21.
System.out.println(“parameterized(a & b)
constructor.”);
22.
Setr(0.0);Sett(0.0);Seta(ad);Setb(bd);}
23. Polar2(double ad, double bd ,
double rd, double td){
24.
System.out.println(“parameterized(
a,b,r,t) constructor.”)
25.
Setr(rd);Sett(td);Seta(ad);Setb(bd);}
26. // public accessory functions
27. public void ConvertToPolar()
{double x=0.0;
28. r=(a*a + b*b)*0.5;
x=Math.atan(b/a);//x in radians
29. t=Math.toDegrees(x);
30. } // to convert to polar form
31. public void DisplayPolar(){
32. System.out.println(“Inside
DisplayPolar .”);
33. /*directly use r and t because
accessed inside method */
34.
System.out.println(«magnitude<r>:» +r +
«Angle<t>» + t);}
35. }// end of class Polar1
36. class Polar2Demo {
37. public static void
main(String[] args) {
38. // create an object of class
Polar1-Default constructor
39. Polar2 pol2 = new Polar2();
40. pol2.DisplayPolar();
41. Polar2 pol2a = new
Polar2(3.0,4.0); // 3 + J4
42. pol2a.ConvertToPolar();
43. pol2a.DisplayPolar();
44. Polar2 pol2b = new
Polar2(3.0,4.0,12.5,53.13); //3+J4 & r,Φ
45. pol2b.DisplayPolar();
}
}// end of Polar2Demo
Output Inside Polar2 Default
constructor………….
Inside DisplayPolar .
magnitude <r> :0.0Angle<t>0.0
Inside Polar2 parameterized(a & b)
constructor………….
Inside Polar2 parameterized( a,b,r,t)
constructor………….
Inside DisplayPolar.
magnitude <r> :12.5Angle<t>53.13
Inside DisplayPolar .
magnitude <r>
:12.5Angle<t>53.13010235415598
18.5.2 Methods
Once the object to a class is created, we can
access the member functions and public
member data of a class using the dot (.)
operator.
In Java, class member functions are called
Methods. A method is nothing but a code
written to achieve a result. The syntax is:
1. package com.oops.chap19;
2. import java.io.*;
3. class Student3{
4. // member data or attributes
5. private String name=””; // name of
the student
6. private int rollNo;
7. private double totalMarks;
8. private String grade=””;
9. //public metods
10. public void GetData() {
11. try{
12. BufferedReader input = new
BufferedReader (new
InputStreamReader(System.in));
13. System.out.println(“Enter
Students name :”);
14. name = input.readLine();
15. System.out.println(“Enter
Students roll number :”);
16. rollNo=
Integer.parseInt(input.readLine());
17. System.out.println(“Enter total
marks :”);
18. totalMarks=
Double.parseDouble(input.readLine());
19. }catch ( Exception e){}
20. }//endof GetData()
21. public void DisplayData() {
22. System.out.println(“Students
Details are………”);
23. System.out.println(“Roll
Number:” + rollNo);
24. System.out.println(“Name:” +
name);
25. System.out.println(“Total
Marks:” + totalMarks);
26. System.out.println(“Grade:” +
ComputeGrade(totalMarks));
27. }
28. public String
ComputeGrade(double totalMarks) {
29. String grade=””;
30. if( totalMarks >=80.0)
grade=”A”;
31. else if (totalMarks>= 60.0)
grade=”B”;
32. else if (totalMarks>= 50.0)
grade=”C”;
33. else grade=”D”;
34. return grade;
35. }
36. }// end of Student3
37. class Student3Demo {
38. public static void main(String[]
args) {
39. // create an object of class
Student3
40. Student3 Gautam = new
Student3();
41. Gautam.GetData();
42. Gautam.DisplayData();
43. }
44. }// end of Student3Demo
Output: Students Details are………
Roll Number:50595
Name:Ramesh
Total Marks:98.0
Grade:A
1. package com.oops.chap19;
2. import java.io.*;
3. class Polar1{
4. // all member data is declared as
private
5. private double r; // magnitude
6. private double t; // angle theeta
7. private double a; // real
8. private double b; // imaginary
9. // public accessory functions
10. public void GetData(){
11. try{
12. BufferedReader input = new
BufferedReader (new
InputStreamReader(System.in));
13. System.out.println(“Enter
Cartesian <real number a>:”);
14. a =
Double.parseDouble(input.readLine());
15. System.out.println(“Enter
Imaginary <b> :”);
16. b=
Double.parseDouble(input.readLine());
17. System.out.println(“Enter
magnitude <r> :”);
18. r=t=0.0; // in side a member
method.r & t can be accessed d
19. }catch( Exception e){}
20. }
21. public void ConvertToPolar(){
22. double x=0.0;
23. r=Math.sqrt(a*a + b*b);
24. x=Math.atan(b/a); // x is in
radians, b/a in radians
25. t= (7.0/22.0)*180.0*x; // PI
radians equals 180 degrees
26. t=Math.toDegrees(x); //conver
to degrees
27. } // to convert to polar form
28. public void DisplayPolar(){
29. System.out.println(“Inside the
classes member function .”);
30. /*We can directly use r and t
because it is inside the
31. member function of the class
thus equal to public*/
32.
System.out.println(«magnitude<r>:» + r +
«Angle<t>» + t);
33. } // to display in polar and
cartesian forms
34. }// end of class Polar1
35. class Polar1Demo {
36. public static void
main(String[] args) {
37. // create an object of class
Polar1
38. Polar1 pol1 = new Polar1();
39. pol1.GetData();
40. pol1.ConvertToPolar();
41. pol1.DisplayPolar();
42. }
43. }// end of Polar1Demo
Output: Enter Cartesian form Vector
Details <real number a>: 3
Enter Imaginary <b> : 4
Enter magnitude <r> :
Inside the classes member function .
magnitude <r>
:12.5Angle<t>53.13010235415598
Line declare the attributes as private and type
Nos. double.
5 to
8:
System.out.println("magnitude<r>:" + r +
"Angle<t>" + t);
Example
18.5: PassByValDemo.java –
Passing Arguments by Call by Value
//PassByValDemo.java
1. package com.oops.chap19;
2. import java.io.*;
3. class CallByVal{
4. public void SwapData(int x, int y)
{
5. System.out.println(“Inside
SwapDataBefore Swap………”);
6. System.out.println(“x:” + x +
“y:”+y);
7. int temp=x;x=y;y=temp;
8. System.out.println(“Inside
SwapData, After Swap”);
9. System.out.println(“x:” + x +
“y:”+y); }
10. }// end of class callBy Val
11. class PassByValDemo {
12. public static void main(String[]
args) {
13. int x=10;int y=100;
14. CallByVal val = new CallByVal();
15. val.SwapData(x,y);
16. System.out.println(“Inside main
:return from SwapData, “);
17. System.out.println(“x:” + x +
“y:”+y);}
18. }
Output: Inside SwapDataBefore Swap………
x:10y:100
Inside SwapData, After Swap ……….
x:100y:10
Inside main on return from SwapData,
x:10y:100
//StdGradedemo.java
1. package com.oops.chap19;
2. import java.io.*;
3. class StdGrade{
4. // member data or attributes
5. String name=””; // name of the
student
6. int rollNo;
7. double totalMarks;
8. String grade=””;
9. public void DisplayData() {
10. System.out.println(“Students
Details are………”);
11. System.out.println(“Roll
Number:” + rollNo);
12. System.out.println(“Name:” +
name);
13. System.out.println(“Total
Marks:” + totalMarks);
14. System.out.println(”Grade:“ +
grade);
15. }
16. public StdGrade
ComputeGrade(StdGrade std) {
17. String grade=””;
18. if( totalMarks >=80.0)
std.grade=”A”;
19. else if (totalMarks>= 60.0)
grade=”B”;
20. else if (totalMarks>= 50.0)
grade=”C”;
21. else grade=”D”;
22. return std;
23. }
24. }
25. class StdGradeDemo {
26. public static void
main(String[] args) {
27. // create an object of class
Student3
28. StdGrade std1 = new StdGrade();
29. std1.name=”Gautam”;
30. std1.rollNo=6274;
31. std1.totalMarks=98.78;
32. //compute grade by passing
object and receiving back object
33. std1= std1.ComputeGrade(std1);
34. std1.DisplayData();
35. }
36. }// end of StudentDemo
Output: Students Details are………
Roll Number:6274 Name:Gautam Total
Marks:98.78 Grade:A
//PassObjConst.java
1. package com.oops.chap19;
2. import java.io.*;
3. class Polar4{
4. private double a; // real
5. private double b; // imaginary
6. public void Setab(double ad,
double bd){a=ad;b=bd;}
7. //parameterized constructor
8. Polar4(double a, double b)
{Setab(a,b);}
9. // public accessory functions
10. Polar4(Polar4 pol){ a=
pol.a;b=pol.b;}//pass object
11. public void DisplayPolar(){
12. System.out.println(“Inside
DisplayPolar .”);
13. System.out.println(“Real <a> :”
+ a + “Imag <b>” + b);
14. } // to display in cartesian
form
15. }//end of class
16. class PassObjConst {
17. public static void main(String[]
args) {
18. Polar4 pol4 = new
Polar4(3.0,4.0); // 3 + J4
19. System.out.println(“Given Vector
in Cartesian form .”);
20. pol4.DisplayPolar();
21. Polar4 pol4a = new Polar4(pol4);
// we have passed pol4 object to make a
clone of pol4
22. System.out.println(“Cloned
Vector pol4a Cartesian form .”);
23. pol4a.DisplayPolar();
24. }
25. }// end of PassObjConst
Output: Polar4 parameterized(a & b)
constructor………….
Given Vector in Cartesian form .
Inside DisplayPolar .
Real <a> :3.0Imag <b>4.0
Cloned Vector pol4 in Cartesian form
.
Inside DisplayPolar .
Real <a> :3.0Imag <b>4.0
L Polar4(Polar4 pol){ a=
i pol.a;b=pol.b;} and statement 21
n Polar4 pol4a = new Polar4(pol4);
e shows passing of the object to a constructor.
N Pol4a ia clone of pol4
o
.
1
0
:
//FindDemo.java
1. package com.oops.chap19;
2. import java.io.*;
3. class OverLoadedFind{ // over
loaded Find for square, rect, cube
4. public double Find( double
side){ return side*side;}
5. public double Find( double l ,
double b ){ return l*b;}
6. public double Find(double l,
double b, double h){return l*b*h;}
7. }
8. class FindDemo {
9. public static void
main(String[] args) {
10. OverLoadedFind ovrfind = new
OverLoadedFind();
11. System.out.println(“ Area of a
square: “ + ovrfind.Find(10.0));
12. System.out.println(“Area of a
rect”+ ovrfind.Find(10.0,20.0));
13. System.out.println(“ Vol
ofCube:”+ovrfind.Find(10.0,20.0,30. 0));
14. }
15. }// end of FindDemo.java
Output: Area of a square: 100.0
Area of a rectangle: 200.0 Vol of a
Cube: 6000.0
1. package com.oops.chap19;
2. import java.io.*;
3. class Polar3{
4. private double r; // magnitude
5. private double t; // angle theeta
6. private double a; // real
7. private double b; // imaginary
8. public void Setr(double r)
{this.r=r;}
9. public void Sett(double t)
{this.t=t;}
10. public void Seta(double a)
{this.a=a;}
11. public void Setb(double b)
{this.b=b;}
12. //constructors Default
Constructor
13. Polar3() {
14. System.out.println(“Polar3
Default const..”);
15.
Setr(0.0);Sett(0.0);Seta(0.0);Setb(0.0);
}
16. Polar3(double a, double b){
17.
System.out.println(“parameterized(a & b)
const…”);
18.
Setr(0.0);Sett(0.0);Seta(a);Setb(b);}
19. // public accessory functions
20. public void ConvertToPolar()
{double x=0.0;
21. r=(a*a + b*b)*0.5;
x=Math.atan(b/a);//x in radians
22. t=Math.toDegrees(x);
23. } // to convert to polar form
24. public void DisplayPolar(){
25. System.out.println(“Inside
DisplayPolar .”);
26. System.out.println(“mag<r> :”+
this.r +”Angle<t>”+ this.t);
27. } // to display in polar and
cartesian forms
28. }// end of class Polar1
29. class PolarThis1Demo {
30. public static void
main(String[] args) {
31. Polar3 pol3a = new
Polar3(3.0,4.0); // 3 + J4
32. pol3a.ConvertToPolar();
33. pol3a.DisplayPolar();
34. }
35. }// end of Polar2Demo
Output: Inside Polar3 parameterized(a
& b) constructor………..
Inside DisplayPolar.
magnitude <r> :12.5Angle<t>53.13
//EmpStatic.java
1. package com.oops.chap19;
2. class EmpStatic{
3. static int countEmp;
4. static int mcount;
5. static int fcount;
6. static boolean mf;
7. static double totalSal;
8. // static block initilization
9. static
10. {System.out.println( “block
initializes all static:”);
11.
countEmp=0;mcount=0;fcount=0;mf=true;tot
alSal=0.0; }
12. static void Counts(boolean mf,
double s)
13. {if (mf==true) ++mcount;
14. else ++fcount;
15. totalSal+=s;
16. ++countEmp;}
17. static void Display()
18. {System.out.println(“Total
Sal:”+EmpStatic.totalSal);
19. System.out.println(“Total emp
:”+ EmpStatic.countEmp);
20. System.out.println(“Male
employess :”+ EmpStatic.mcount);
21. System.out.println(“Female
employess :”+EmpStatic.fcount);}
22. public static void
main(String[] args) {
23. EmpStatic.Counts(true,
10000.00);
24. EmpStatic.Counts(false,
12000.00);
25. EmpStatic.Display();}
26. }// end of EmpStatic class
Output: block initializes all static
variable :
Total Sal:22000.0
Totall No of employess:2
No of male employess:1
No of female employess :1
//EmpStatic2.java
1. package com.oops.chap19;
2. class StaticOutClass{
3. static int countEmp;
4. static int mcount;
5. static int fcount;
6. static boolean mf;
7. static double totalSal;
8. // static block initilization
9. static
10. {System.out.println( “block
initializes static vars :”);
11.
countEmp=0;mcount=0;fcount=0;mf=true;tot
alSal=0.0;}
12. static void Counts(boolean mf,
double s)
13. { if (mf==true) ++mcount;
14. else ++fcount;
15. totalSal+=s;
16. ++countEmp;}
17. static void Display(){
18. System.out.println(“total
Sal:”+StaticOutClass.totalSal);
19. System.out.println(“Total empl:”+
StaticOutClass.countEmp);
20. System.out.println(“male emp:”+
StaticOutClass.mcount);
21. System.out.println(“female
emp:”+StaticOutClass.fcount);}
22. }
23. class EmpStatic2{
24. public static void main(String[]
args) {
25. StaticOutClass.Counts(true,
10000.00);
26. StaticOutClass.Counts(false,
12000.00);
27. StaticOutClass.Display();
28. // enter more
29. StaticOutClass.Counts(true,
20000.00);
30. System.out.println( “Display
static vars outside class”);
31. System.out.println(“total
Sal:”+StaticOutClass.totalSal);
32. System.out.println(“Total empl:”+
StaticOutClass.countEmp);
33. System.out.println(“male emp:”+
StaticOutClass.mcount);
34. System.out.println(“female
emp:”+StaticOutClass.fcount);
35. }
36. }// end of EmpStatic2 class
Output: block initializes all static
variable :
total employess salary :22000.0
Total No of employess :2
No of male employess :1
No of female employess :1
Display static variable directly
outside class
total employess salary :42000.0
Total No of employess :3
No of male employess :2
No of female employess :1
//StdNested.java
1. package com.oops.chap19;
2. import java.io.*;
3. class StdNested{
4. // member data or attributes
5. String name=”Ramesh”; // name of
the student
6. int rollNo=50595;
7. double totalMarks=98.5;
8. String grade=”A”;
9. void UseInner() {
10. DateInner dateinner=new
DateInner();
11. dateinner.DataDisplay();}
12. //Now define inner class
DateInner
13. class DateInner{
14. int dd=15;int mm=10;int yy=10;
15. void DataDisplay(){
16. System.out.println(“Students
Detail : outer class are………”);
17. System.out.println(“Roll
Number:” + rollNo);
18. System.out.println(“Name:” +
name);
19. System.out.println(“Total
Marks:” + totalMarks);
20. System.out.println(”Grade:“ +
grade);
21. System.out.println(“DOJ from
inner class ………”);
22. System.out.println(“DOJ
:”+dd+”/”+mm+”/”+yy);
23. } //end of DataDisplay()
24. }// End of class Dateinner
25. }//end of class StdNested
26. class StdNestedDemo {
27. public static void
main(String[] args) {
28. StdNested stdouter = new
StdNested();
29. stdouter.UseInner(); }
30. }// end of StdNestedDemo
Output: Students Details from outer
class are………
Roll Number:50595
Name:Ramesh
Total Marks:98.5
Grade:A
DOJ from inner class ………
DOJ :15/10/10
18.15 Summary
1. i, ii and iv
2. i and ii
3. i and iii
4. i and iv
1. i, ii and iii
2. i, ii, iii and iv
3. i and iv
4. i, ii and iv
1. i, ii and iii
2. i, ii, iii and iv
3. i and ii
4. i, ii and iv
1. ii and iv
2. i, ii, iii and iv
3. i and ii
4. i, ii and iv
1. i, ii and iv
2. i, ii, iii and iv
3. ii and iv
4. i, ii and iv
1. i, ii and iv
2. i, ii, iii and iv
3. ii, iii and iv
4. i and iv
Short-answer Questions
1. c
2. True
3. d
4. c
5. a
6. d
7. c
8. a
9. c
10. c
19
LEARNING OBJECTIVES
19.1 Introduction
This chapter introduces you to one of the
most powerful features of any objective-
oriented language, i.e. inheritance.
Inheritance is a tool offered by Java to create
another class from an existing class. We call
this creation as extending a class. In the
literature, the class that is a starting point or
source of extension is called base class. Java
calls this a superclass. The class that is
extended is called derived class. In Java,
derived class is called subclass. A subclass
can inherit all the members, both methods
and attributes, and also can implement its
own methods. Further, a subclass can
override superclass methods. We also
introduce you to concepts of abstract class
and interfaces which are part of Java's
concepts for extending from existing classes.
//Student1Demo.java
1. package com.oops.chap19;
2. import com.oops.chap19.Person;
3. class Student1 extends Person {
4. // member data or attributes
5. private double totalMarks;
6. private String grade;
7. //access and mutator methods
8. double GetMarks(){ return
totalMarks;}
9. void SetMarks(double mks ){
totalMarks=mks;}
10. String GetGrade(){ return
grade;}
11. void SetGrade(String gd){
grade=gd;}
12. //public method
13. public Student1
ComputeGrade(Student1 std) {
14. if( totalMarks >=80.0)
std.grade=”A”;
15. else if (totalMarks>= 60.0)
grade=”B”;
16. else if (totalMarks>= 50.0)
grade=”C”;
17. else grade=”D”;
18. return std;
19. }
20. }//end of class Student
21. // Driver class
22. class Student1Demo{
23. public static void
main(String[] args){
24. // create an object of Student
25. Student1 std = new Student1();
26. std.SetMarks(97.8);
27. std.SetName(“Ramesh”); // we
have called super method
28. std.SetIdNo(50595);
29. std=std.ComputeGrade(std);
30. std.DisplayData();
31. System.out.println(“Details of
Subclass Student: “);
32. System.out.println(“Total
Marks:” + std.GetMarks());
33. System.out.println(”Grade:“ +
std.GetGrade());}
34. }//end of class Student1Demo
Output: Basic Details are………
Id Number:50595
Name:Ramesh
Details from Sub class Student:
Total Marks:97.8
Grade:A
1. package com.oops.chap19;
2. class Person2 {
3. // member data or attributes
4. protected String name; //protected
5. protected int idNo;
6. private double salary;
7. //access and mutator methods
8. int GetIdNo(){ return idNo;}
9. void SetIdNo(int id){ idNo=id;}
10. String GetName(){ return name;}
11. void SetName(String nm){
name=nm;}
12. double GetSal(){ return
salary;}
13. void SetSal(double sl){
salary=sl;}
14. public void DisplayData() {
15. System.out.println(“Person
Details are………”);
16. System.out.println(“Id Number:”
+ idNo);
17. System.out.println(“Name:” +
name);
18. }
19. public void DisplaySal(){
20. System.out.println(“Salary:” +
salary);}
21. }//end of class Person
Compile it as Person2.java
//Student2Demo.java
1. package com.oops.chap19;
2. import com.oops.chap19.Person2;
3. class Student2 extends Person2 {
4. // member data or attributes
5. private double totalMarks;
6. private String grade;
7. //access and mutator methods
8. double GetMarks(){ return
totalMarks;}
9. void SetMarks(double mks ){
totalMarks=mks;}
10. String GetGrade(){ return grade;}
11. void SetGrade(String gd){
grade=gd;}
12. //public method
13. public Student2
ComputeGrade(Student2 std) {
14. if( totalMarks >=80.0)
std.grade=”A”;
15. else if (totalMarks>= 60.0)
grade=”B”;
16. else if (totalMarks>= 50.0)
grade=”C”;
17. else grade=”D”;
18. return std;
19. }
20. }//end of class Student
21. // Driver class
22. class Student2Demo{
23. public static void
main(String[] args){
24. // create an object of Student
25. Student2 std = new Student2();
26. std.SetMarks(97.8);
27. std.SetName(“Ramesh”); // we
have called super method
28. std.SetIdNo(50595);
29. //std.salary=19000.00;// error.
salary is private in person2
30. std.SetSal(30000.00);//ok as we
are using Set method
31. std=std.ComputeGrade(std);
32. std.DisplayData();
33. System.out.println(“Details
from Sub class Student: “);
34. System.out.println(“Total
Marks:” + std.GetMarks());
35. System.out.println(”Grade:“ +
std.GetGrade());
36. //System.out.println(”Salary“+
std.salary);//Error. salary not visible
37. System.out.println(“Salary : “+
std.GetSal());}
38. }//end of class Student2Demo
Output: Person Details are………
Id Number:50595
Name:Ramesh
Details from Sub class Student:
Total Marks:97.8
Grade:A
Salary : 30000.0
L //std.salary=19000.00;// error Since
i salary is private and is not visible outside the
n class> However, Line No 30
e std.SetSal(30000.00);//ok as we are
N using Set method. The same concept holds good
o for Line No 37as well.
.
2
9
:
1. package com.oops.chap19;
2. class Person2b {
3. // member data or attributes
4. protected String name; //protected
5. protected int idNo;
6. //Over loaded constructors
7. Person2b()
8. {System.out.println(“Super Default
Const called “);
9. name=”NoName”;idNo=0;}
10. Person2b(String nm, int id)
11.
{System.out.println(“Super(name,idNO)
called”);
12. name=nm;idNo=id;}
13. Person2b(Person2b per)
14.
{System.out.println(“Super(object) Const
called “);
15. name=per.name;idNo=per.idNo;}
16. //access and mutator methods
17. public void DisplayData() {
18. System.out.println(“Person
Details are………”);
19. System.out.println(“Id Number:”
+ idNo);
20. System.out.println(“Name:” +
name);
21. }
22. }//end of class Person
Example 19.3b:
Student2bDemo.java To Show
Calling of Super Constructors
1. package com.oops.chap19;
2. import com.oops.chap19.Person2b;
3. class Student2b extends Person2b {
4. // member data or attributes
5. private double totalMarks;
6. private String grade;
7. //create object of Student2b by
calling super constructor
8. Student2b(Student2b std2b){
9. super(std2b);
10. totalMarks=std2b.totalMarks;
11. grade=std2b.grade;
12. }
13. //constructor with all
parameters given
14. Student2b(String nm, int rn,
double tm, String gd){
15. super(nm,rn);
16. totalMarks=tm;
17. grade=gd;
18. }
19. //access and mutator methods
20. double GetMarks(){ return
totalMarks;}
21. void SetMarks(double mks ){
totalMarks=mks;}
22. String GetGrade(){ return
grade;}
23. void SetGrade(String gd){
grade=gd;}
24. //public method
25. public Student2b
ComputeGrade(Student2b std) {
26. if( totalMarks >=80.0)
std.grade=”A”;
27. else if (totalMarks>= 60.0)
grade=”B”;
28. else if (totalMarks>= 50.0)
grade=”C”;
29. else grade=”D”;
30. return std;
31. }
32. public void
DisplayData(Student2b std) {
33. super.DisplayData();
34. System.out.println(“Total
Marks:” + std.GetMarks());
35. System.out.println(”Grade:“ +
std.GetGrade());
36. }//end of class Student
37. }
38. // Driver class
39. class Student2bDemo{
40. public static void
main(String[] args){
41. // create an object of Student
42. Student2b std1 = new
Student2b(“Ramesh”,50595,97.8,”X”);
43. std1.ComputeGrade(std1);
44. std1.DisplayData(std1);
45. System.out.println(“Total
Marks:” + std1.GetMarks());
46. System.out.println(”Grade:“ +
std1.GetGrade());
47. }
48. }//end of class Student2bDemo
1. package com.oops.chap19;
2. public class Person3 {
3. public void Learn(){
System.out.println(“Persons Learn “);}
4. public void Work()
{System.out.println(“Persons work at
work spots”);}
5. }//end of class Person3
Compile it as Person3.java
Line No. declare two public methods called
3 & 4: Learn() and Work()
Example
19.4: Athlete2bDemo.java
1. package com.oops.chap19;
2. import com.oops.chap19.Student2b;
3. class Athlete2b extends Student2b
{
4. // member data or attributes
5. private String sport;
6. private String level; // S/N/I for
state and N for national
7. //create object of Athlete2b by
calling super constructor
8. Athlete2b (Athlete2b ath2b){
9. super(ath2b);
10. sport=ath2b.sport;
11. level=ath2b.level;
12. }
13. //constructor with all
parameters given
14. Athlete2b (String nm, int rn,
double tm, String gd, String sp,String
lv){
15. super(nm,rn,tm,gd);
16. sport=sp;
17. level=lv;
18. }
19. //access and mutator methods
20. public String GetSport(){
return sport;}
21. public String GetLevel(){return
level;}
22. //public method
23. public void
DisplayData(Athlete2b ath2b) {
24. super.DisplayData(ath2b);
25. System.out.println(“Details
from Athlete2b are :”);
26. System.out.println(“Sport:” +
ath2b.GetSport());
27. System.out.println(“Level:” +
ath2b.GetLevel());
28. }//end of class Student
29. }
30. // Driver class
31. class Athlete2bDemo{
32. public static void
main(String[] args){
33. // create an object of Athlet
34. Athlete2b ath1 = new Athlete2b
(“Ramesh”,50595,97.8,”X”,”FootBall”,”S”)
;
35. ath1.ComputeGrade(ath1);
36. ath1.DisplayData(ath1);
37. }
38. }//end of class Athlete2bDemo
Output: Super(name,idNO) called
Person Details are…… Id Number:50595
Name:Ramesh
Details from Student2b are : Total
Marks:97.8 Grade:A
Details from Athlete2b are :
Sport:FootBall Level:S
//RunTimePoly.java a programme to
shown run time ploy morphism
1. package com.oops.chap19;
2. class Shape{
3. void FindArea(){
4. System.out.println(“Inside Shape.
No definite Area”);}
5. }// end of Shape
6. class Circle extends Shape{
7. void FindArea(){
8. System.out.println(“Inside Circle.
Area=PI*r*r”);}
9. }// end of Circle
10. class Triangle extends Shape{
11. void FindArea(){
12. System.out.println(“Inside
Triangle. Area=0.5*base*alt”);}
13. } // end of class Triangle
14. class RunTimePoly {
15. public static void
main(String[] args) {
16. // create object to classes
17. Shape shp = new
Shape();//object of Shape
18. Circle circ = new
Circle();//object of Circle
19. Triangle trg = new
Triangle();//object of Triangle
20. System.out.println(“A ref to
super can refer to sub class over ridden
Methods”);
21. System.out.println(“Therefore
create a ref to super”);
22. Shape refsuper; // reference to
super class Shape
23. System.out.println(“A refrence
to super “);
24. refsuper=shp; // refsuper
refers to Shape object
25. refsuper.FindArea();
26. System.out.println(“A refrence
to Circle “);
27. refsuper=circ; // refsuper
refers to Circle object
28. refsuper.FindArea();
29. System.out.println(“A refrence
to Triangle “);
30. refsuper=trg; // refsuper
refers to Triangle object
31. refsuper.FindArea();}
32. }// end of runtime poly
Output: A refrence to super can refer
to sub class over ridden Methods
Therefore create a referecne to super
A refrence to super
Inside Shape. No definite Area
A refrence to Circle
Inside Circle. Area=PI*r*r
A refrence to Triangle
Inside Triangle. Area=0.5*base*alt
class Person {
final void Update() { //update code
here. Final Methods. Cannot be
inherited}
} // end of person
class Student extends Person {
void update() { // Error cannot be
inherited}
} // end of student
1. package com.oops.chap19;
2. class Person4 implements
Cloneable{
3. String name;
4. Person4(String nm){name=nm;}
5. public String Getname() {return
name;}
6. public void DisplayData() {
7. System.out.println(“Person Details
are………”);
8. System.out.println(“overriden
toString() Method:” + toString());
9. System.out.println(“Obj Details
from static method hashcode()”);
10. System.out.println(“Object Hash
Code :” + hashCode());}
11. public String toString()
12. {String stg;
13. stg = “Name :” + Getname();
14. return stg;}
15. public void
CompareObjects(Person4 per2){
16. System.out.println(“ using
equals(obj) static method”);
17. if (this.equals(per2))
18. System.out.println(“Per1& Per2
are same.”);
19. else System.out.println(“Per1 &
Per2 are NOT same.”);}
20. public Object CloneObj()throws
CloneNotSupportedException
21. {return super.clone();}
22. }//end of class Person
23. public class ObjectDemo {
24. public static void
main(String[] args) throws
CloneNotSupportedException
25. {
26. //Two different objects. Their
references are NOT same
27. // But Content same
28. System.out.println(“Two objects
per1&2 with same content”);
29. Person4 per1 = new
Person4(“Salman”);
30. Person4 per2 = new
Person4(“Salman”);
31. per1.CompareObjects(per2);
32. System.out.println(“Displaying
per1 data”);
33. per1.DisplayData();
34. System.out.println(“Clone per1
object to per3”);
35. Person4 per3 =
(Person4)per1.CloneObj();
36. System.out.println(“Displaying
per3 data”);
37. per3.DisplayData();
38. }
39. }
Output: Creating two objects per1 and
per2 with same content using equals(obj)
static method
Per1 & Per2 are NOT same.
Displaying per1 data
Person Details are………
Using overriden toString()
Method:Name :Salman
Object Details from static method
hashcode() of Object class are………
Hash Code of Object:1671711
Clone per1 object to per3
Displaying per3 data
Person Details are………
Using overriden toString()
Method:Name :Salman
Object Details from static method
hashcode() of Object class are………
Hash Code of Object:11394033
C:\OopsJava\examples\bin>java
com/oops/chap19/Date1
N
o
.
1
:
N
o
.
2
:
N
o
.
6
:
N
o
s
.
1
5
–
2
6
:
1. package com.oops.chap19;
//import com.oops.chap19.Date1;
Need not be imported because same
package
2. public class Date1tester{
3. public static void main(String[]
args) {
4. // intialize the Date1 object
5. Date1 date = new Date1(19,11,10);
6. System.out.println(“date
in<dd:mm:yy>format”+ date.toString());
7. System.out.println();
8. System.out.println(“date
in<dd:mm:yy>format”+ date.toString());
9. System.out.println(“date
in<dd:mmm:yy>format”+ date.toDDMMMYY
String());
10. }
11. }//end of Date1tester class
Output : The Given Date is …….
date in<dd:mm:yy>format19:11:10
date in<dd:mmm:yy>format19:NOV:10
19.15 Interfaces
In Section 19.8, we have shown you the
power of dynamic polymorphism offered by
java. It provided a facility wherein a
reference to super can refer to any one of the
subclass overridden methods based on the
type of object. We have further dealt with
abstract classes that contain abstract
methods. Abstract methods will have only
the head terminated by a semicolon, but no
body showing the implementation. We have
also learnt that an abstract class cannot be
instantiated since it has abstract methods.
However, a reference to abstract class can be
created that can then be made to refer to
objects of subclasses.
Java permits only single inheritance and
multilevel inheritance. A subclass can have
only one super. Then how will java solve the
problems wherein more than one super is
required? The solution is a powerful tool
provided by Java called interface. A class in
Java can extend only to one super, but it can
implement several Interfaces.
Refer to Figure 19.4. It shows a situation
wherein super, called interface rather than a
class, has abstract methods. Subclasses
called Circle and Triangle implement all
abstract methods. Also note that the dotted
arrow pointing to interface rather than a
solid arrow. This is notation as per
modelling language UML.
Figure 19.4 Interface in Java
1. package com.oops.chap19;
2. public interface Shape {
3. final static double PI = 3.141519;
4. // abstract methods. Only Head no
body.
5. //Using key word abstract is
optional
6. double ComputeArea(double x);
7. double ComputePerimeter(double x);
8. void DrawShape();
}// end of interface shape
1. package com.oops.chap19;
2. // Circle
3. class Circle2 implements Shape
4. {public double ComputeArea(double
radius){
5. double area=0; area =
PI*radius*radius;
6. return area;
7. }
8. public double
ComputePerimeter(double radius){
9. double perim=0;perim =
2*PI*radius;return perim;}
10. public void DrawShape(){
11. System.out.println(“Draw Circle
Shape here!”);}
12. }// end of class Circle1
13. class Square implements Shape
14. {public double
ComputeArea(double side){
15. double area=0; area =
side*side;return area;}
16. public double
ComputePerimeter(double side){
17. double perim=0;perim =
4*side;return perim;}
18. public void DrawShape(){
19. System.out.println(“Draw Square
Shape here!”); }
20. }// end of class Square
21. class ShapeTest{
22. public static void
main(String[] args){
23. //Create a reference to
Interface Shape
24. Shape shp;
25. //Create objects of sub classes
26. Circle2 circ = new Circle2();
27. Square sqr = new Square();
28. // make ref to refer to Circle
29. shp=circ;
30. System.out.println(“Area of
Circle”+ shp.ComputeArea(10.0));
31. System.out.println(“Perim of
Circle”+ shp.ComputePerimeter (10.0));
32. shp.DrawShape();
33. System.out.println(); //blank
line
34. shp=sqr;
35. System.out.println(“Area of
Square”+ shp.ComputeArea(10.0));
36. System.out.println(“Perim of
Square”+ shp.ComputePerimeter (10.0));
37. shp.DrawShape();
38. }
39. }
Exercise Questions
Objective Questions
1. i and iv
2. i, ii and iii
3. ii and iii
4. iii and iv
1. i, iii and iv
2. i, ii and iii
3. i, ii, iii and iv
4. i, ii and iv
1. i, iii and iv
2. ii and iii
3. i, ii, iii and iv
4. i, ii and iv
1. i, iii and iv
2. ii and iii
3. i, ii, iii and iv
4. i, iii and iv
1. c
2. a
3. c
4. d
5. a
6. b
7. d
8. a
9. b
10. a
11. d
12. True
20
LEARNING OBJECTIVES
20.1 Introduction
Many of you would have come across a pop-
up while you are using the Internet or
operating system, wherein the pop message
would say “OS or Browser has experienced a
serious problem and needs to be closed
down. Error reporting is in process”. Indeed,
an error has occurred. Despite elaborate
testing prior to delivery, errors cannot be
prevented, but they can be minimized. In
this chapter, we will study the mechanism of
Java to handle errors and exceptions.
An important and innovative feature of
Java programming is multithreaded
programming. Just as Operating System
manages several processes concurrently and
schedules the next process CPU should
handle, Java provides multithreaded
programming wherein we can create several
concurrent threads and manage thread
scheduling at programmer's level. The
advantage is that more than one thread
process can be running at the same time
albeit with different priorities.
20.2.2 Exceptions
Exceptions, on the other hand, are unusual
conditions that occur at run time and can
lead to errors that can crash a program. The
exceptions can be classified as:
20.2.2.1 Synchronous
1. package com.oops.chap20;
2. import java.util.*;
3. class MatrixAlloc {
4. void ReadMat(int A[][],int rows,
int cols){
5. //input matrix related data using
scanner
6. Scanner scn=new
Scanner(System.in);
7. for ( int i=0;i<rows;i++)
8. for ( int j=0;j<cols;j++)
9. A[i][j]=scn.nextInt();
10. }
11. void DisplayMatrix(int A[][],int
rows, int cols){
12. for ( int i=0;i<rows;i++)
13. {for ( int j=0;j<cols;j++)
14. { System.out.print( A[i][j] +”
“);}
15. System.out.print( “\n”);}
16. }//end of DisplayMatrix
17. void AddMat(int A[][],int B[]
[],int rows, int cols){
18. for ( int i=0;i<rows;i++)
19. {for ( int j=0;j<cols;j++)
20. System.out.print( (A[i][j]+B[i]
[j]) +” “);
21. System.out.print( “\n”);}
22. }//end of TranspMat
23. }//end of MatrixAlloc
24. class TwoDMatrix{
25. public static void main(String[]
args)
26. {try{
27. Scanner scn = new
Scanner(System.in);
28. MatrixAlloc obj=new
MatrixAlloc();
29. System.out.print(“Enter no of
rows & columns:”);
30. int rows= scn.nextInt();
31. int cols= scn.nextInt();
32. int A[][]= new int[rows][cols];
33. int B[][]= new int[rows][cols];
34. MatrixAlloc mat = new
MatrixAlloc();
35. System.out.println(“Enter Data
for Matrix A”);
36. obj.ReadMat( A ,rows,cols);
37. System.out.println(“Enter Data
for Matrix B”);
38. obj.ReadMat( B ,rows,cols);
39. System.out.println(“Addition of
two Matrices”);
40. mat.AddMat(A,B,rows, cols);
41. } catch( Exception e){};
42. }
43. } //end of MatTranspose
OUTPUT : Enter no of rows & columns:2
2
Enter Data for Matrix A 10 20 30 40
Enter Data for Matrix B 10 20 30 40
Addition of two Matrices
20 40
60 80
N
o
.
4
1
:
try
{ // allocation code here
public void DisplayNumbers() throws
NumberFormatException{
//display code here that uses number
formatting }
public int FindMaxArray( int a[] ,
int n) throws ArrayOutOfBoundsexception{
//FindMaxArray code here that uses
Array processing
}
catch (NumberFormatException e1){ }
catch ( ArrayOutOfBoundsexception e2) {
}
A try block can be nested just like for
loop.
try
{ // allocation code here
public void DisplayNumbers() throws
NumberFormatException{
//display code here that uses number
formatting }
public int FindMaxArray( int a[] ,
int n) throws ArrayOutOfBounds
exception{
//FindMaxArray code here that uses
Array processing
}
catch (NumberFormatException e1){ }
catch ( ArrayOutOfBoundsexception e2) {
}
finally { // finally block
/* includes all house keeping code like
saving current state ,closing of all
open
objects and file and restoring the state
to a state that existed prior to
occurring of the
problem*/
} // end of finally block
Example
20.6: MultiCatchFinally.java A
Program to Show Multiple Catch
Statements and Finally Block
1. package com.oops.chap20;
2. import java.util.*;
3. public class MultiCatchFinally {
4. public static void main(String[]
args){
5. double mass,area,density=0.0;
6. boolean yesno=true;
7. try{ // create arrays for mass
,area,density
8. double [] massArray = new double[]
{200.00, 300.00,400.00,500.00};
9. double [] areaArray = new double
[]{ 20.0,30.0,40,0,0.0};
10. double [] densityArray = new
double [massArray. length];
11. int len = massArray.length;
12. //for( int i=0; i<len+1;i++){
13. for( int i=0; i<len;i++){
14. if( areaArray[i]==0) throw new
ArithmeticException(“Divide By Zero”);
15. else
16.
densityArray[i]=massArray[i]/areaArray[i
];}
17. System.out.println(“\n\t
mass\tarea\tdensity”);
18. for( int i=0; i<len;i++){
19.
System.out.println(“\t”+massArray[i]+”\t
”+areaArray[i]+”\t”+densityArray[i]);}
20. }catch(ArithmeticException e)
21. {System.out.println(“Divide By
Zero Exception has occurred ….”);}
22.
catch(ArrayIndexOutOfBoundsException e)
23. {System.out.println(“Array out
of Bounds Exception has occured ….”);}
24. finally{
25. System.out.println(“We are
inside finally block & exiting the
programme…….”);}
26. }// end of main
27. }//end of class
Run 1 We have commented out Line No.
12 to test array
//index out of bounds exception
OUTPUT1 :Divide By Zero Exception has
occurred ….
We are inside finally block &
exiting the programme…….
Run 2 We have commented out Line No.
13,14,and 15 to test Divide
//By Zero exception i.e
ArithmeticException
OUTPUT2: Divide By Zero Exception has
occured ….
We are inside finally block &
exiting the programme…….
N
o
.
7
:
N
o
.
1
2
:
Example
20.7: MultiCatchFinally.java a
Program to Show Multiple Catch
Statements and Finally Block
package com.oops.chap20;
import java.io.*;
import com.oops.chap20.OurOwnException;
import java.lang.Exception;
import java.util.*;
class CheckCredits extends
OurOwnException{
public void FindBal(String id,double
trAmt) throws OurOwnException{
double[] BanBal=new double[]
{2000.0,5000.00,900.00,90000.0};
String[] EmpIdNo=new String[]{
“50595”,”50596”,”50597”,”50598”};
for(int i=0;i<EmpIdNo.length;i++){
if( EmpIdNo[i].compareTo(id)==0)
{ System.out.println(“Bank balance”
+BanBal[i]);System.out.
println(“Trnsaction Amount “ +trAmt
);
if ( BanBal[i]- trAmt <1000.00)
throw new
OurOwnException(“Sorry Transaction can
not be
processed Bal<1000.00”);
else System.out.println(“Successful”);
}
else continue;
}// end of for
}// end of FindBal
}// end of CheckCredits class
class MyException {
public static void main(String[]
args)throws IOException{
String idNo, amt; boolean yesno=true;
double transAmt;// variables for input
data
BufferedReader input = new
BufferedReader (new InputStreamReader
(System.in));
System.out.println(“Enter id number of
Employee”);
String stg =
input.readLine();stg.trim();
System.out.print(“Enter Transaction
amount :”);
amt=input.readLine();amt.trim();
transAmt=Double.parseDouble(amt);
// make an object of CheckCredits class
CheckCredits obj=new CheckCredits();
// call FindBal
try{
obj.FindBal(stg,transAmt);
}catch(OurOwnException e){
System.out.println(“Inside catch block
- Our Own Exception”);
System.out.println(e.getMessage());}
}// end of main
}// end of class MyException
OUTPUT : Enter id number of Employee
50596
Enter Transaction amount :25000.00
Bank balance5000.0 Trnsaction Amount
25000.0
Inside catch block - Our Own Exception
Sorry Transaction cannot be processed
Bal<1000.00
20.11.1 Process
A process is a job in hand. We can also say
that this is a simple sequence of instructions
to be executed by the CPU. Operating system
creates several processes. CPU is then
scheduled to handle different processes
based on the priorities of the processes by
OS. OS switches CPU amongst processes
and allocates CPU time and completes all
the tasks. When process shifting takes place,
it is necessary to save the context of the
current execution like stack, variables,
status, etc. As context switching is involved,
processes are called heavyweight processes.
20.11.2 Threads
Java brings concurrent processing, not
parallel, just like OS does with its processes,
within the preview of programmers by
innovative and unique feature called
multithreaded programming. In
multithreaded programs, the main program
is run on a main thread but the main
program creates threads that run
independent and concurrent program flows.
It is the main program that creates and
starts the other three threads, as shown in
Figure 20.3. Once started, the three
subthreads run independently as per
priorities set and as per scheduling of CPU
concurrently sharing CPU time and other
common resources.
Threads are also called light weight
because they consume less memory
resources. Why because there is no context
switching involved in multithreaded
programming.
Note that run method is where the entire action for the
thread will take place. It is like the main() method. It
can declare its own variables, instantiate other classes.
Run is the entry point for any new thread that is created.
The Thread created ends when the run() ends.
Step 3: Create an object of ThreadTest in main().
This object is used to invoke the run method
class ThreadTestDemo{
public static void main(
String[] args) {
ThreadTest obj =new
ThreadTest();
Thrd.start();
setName
(stg);
setPrio
rity()
Example
20.9: FirstThreademo.java A
Program to Show How to Create and
Run Thread. Use Extends Feature to
Create Threads
1. package com.oops.chap20;
2. class FirstThread extends Thread{
3. public void run(){
4. // Thread executes the sequence
5. try{
6. for (int i=0;i<4;i++)
7. {System.out.println(“ thread1 :” +
i + “ : “);
8. Thread.sleep(600);
9. }
10.} catch(InterruptedException e )
11. {System.out.println(“thread1
interrupted”);}
12. System.out.println(“Exiting from
thread1”);
13. }//end of run
14. }//end of FirstThread
15. class SecondThread extends
Thread{
16. public void run(){
17. try{
18. for (int i=0;i<4;i++)
19. { System.out.println(“ thread2
:” + i + “ : “);
20. Thread.sleep(600);
21. }
22. }catch(InterruptedException e )
23. {System.out.println(“thread2
interrupted”);}
24. System.out.println(“Exiting from
thread2”);
25. }//end of run
26. }//end of SecondThread
27. public class FirstThreadDemo {
28. public static void main(String[]
args) {
29. //create an object of
FirstThread & SecondThread
30. FirstThread obj1 = new
FirstThread();
31. SecondThread obj2 = new
SecondThread();
32. //create the Thread and attach
it to object
33. Thread thread1 = new Thread(
obj1);
34. Thread thread2 = new Thread(
obj2);
35. //Run the thread by calling
start() which calls run()
36. thread1.start();
37. thread2.start();
38. try{
39. for (int i=0;i<4;i++)
40. { System.out.println(“
threadMain :” + i + “ : “);
41. Thread.sleep(1200);
42. }
43. }catch(InterruptedException e )
44. {System.out.println(“main thread
interrupted”);}
45. System.out.println(“Exiting from
main thread”);
46. }//end of main
47. }//end of FirstThreadDemo
Output: threadMain :0 :
thread1 :0 : thread2 :0 : thread2 :1
: thread1 :1 : threadMain :1
thread2 :2 : thread1 :2 : thread1 :3
: thread2 :3 : th readMain :2
Exiting from thread1 Exiting from
thread2 threadMain :3 :
Exiting from main thread
Li instantiate FirstThread and
ne SecondThread. These threads extend to
N Thread class.
os
.
30
&
31
:
Example
20.10: SecondThreadDemo.java A
Program to Show How to Create and
Run Thread. Use Extends Feature to
Create Threads
1. package com.oops.chap20;
2. class FirstThread2 implements
Runnable{
3. Thread thrd1;
4. FirstThread2(){
5. System.out.println(“Creating
FirstThread2”);
6. thrd1 = new
Thread(this,”FirstThread2”);
7. System.out.println(“Creating
FirstThread2”+ thrd1);
8. thrd1.start();
9. }
10. public void run(){
11. // FirstThread2 executes the
sequence
12. try{
13. for (int i=0;i<4;i++)
14. {System.out.println(“ thread1 :”
+ i + “ : “);
15. Thread.sleep(600);}
16. }catch(InterruptedException e )
17. {System.out.println(“thread1
interrupted”);}
18. System.out.println(“Exiting from
thread1”);
19. }//end of run
20. }//end of FirstThread
21. class SecondThread2 implements
Runnable{
22. Thread thrd2;
23. SecondThread2(){
24. System.out.println(“Creating
SecondThread2”);
25. thrd2 = new
Thread(this,”FirstThread2”);
26. System.out.println(“Creating
SecondThread2”+ thrd2);
27. thrd2.start();
28. }
29. public void run(){
30. System.out.println(“thread1
Details”);
31. System.out.println(“Name
:”+thrd2.getName());
32. System.out.println(“Priority
:”+thrd2.getPriority());
33. try{
34. for (int i=0;i<4;i++)
35. { System.out.println(“ thread2
:” + i + “ : “);
36. Thread.sleep(600);
37. }
38. }catch(InterruptedException e )
39. {System.out.println(“thread2
interrupted”);}
40. System.out.println(“Exiting from
thread2”);
41. }//end of run
42. }//end of SecondThread
43. public class ThreadsConstDemo {
44. public static void main(String[]
args) {
45. //create an object of
FirstThread2 & SecondThread2
46. new FirstThread2();
47. new SecondThread2();
48. try{
49. for (int i=0;i<4;i++)
50. { System.out.println(“
threadMain :” + i + “ : “);
51. Thread.sleep(1200);
52. }
53. }catch(InterruptedException e )
54. {System.out.println(“main thread
interrupted”);}
55. System.out.println(“Exiting from
main thread”);
56. }//end of main
57. }// end of ThreadRunnableDemo
Output: Creating FirstThread2
Creating
FirstThread2Thread[FirstThread2,5,main]
thread1 :0 :
Creating SecondThread2
Creating
SecondThread2Thread[FirstThread2,5,main]
threadMain :0 :
thread1 Details
Name :FirstThread2
Priority :5
thread2 :0 : thread1 :1 : thread2 :1
: thread1 :2 :
threadMain :1 : thread2 :2 : thread1
:3 : thread2 :3 :
Exiting from thread1 threadMain :2 :
Exiting from thread2
threadMain :3 : Exiting from main
thread
Line creates new thread by : new
Nos. FirstThread2();new Second
46 & Thread2();
47:
System.out.println(“thread1 Details”);
System.out.println(“Name
:”+thrd2.getName()); System.out.println
(“Priority :”+thrd2.getPriority());
20.12.2 Use of isAlive() and join()
Methods
The sleep() method introduced suspends
a thread for duration specified and CPU is
shifted to other waiting threads. The
selection of duration is arbitrary and CPU is
forcibly pulled out from thread after time
duration. This is not a satisfactory solution.
Java provides: final boolean
isAlive() method to test if the thread is
alive. Java also provides a more elegant
method called final void join() throws
InterruptedException. This is a non-
greedy method and it waits till the thread on
which it is called is terminated. Here the
calling thread waits till the specified thread
joins it.
Example
20.11: IsAliveJoinDemo.java A
Program to Show How to Create and
Run Thread. Use Extends Feature to
Create Threads
1. package com.oops.chap20;
2. import
com.oops.chap20.FirstThread2;
3. import1
com.oops.chap20.SecondThread2;
4. public class IsAliveJoinDemo {
5. public static void main(String[]
args) {
6. FirstThread2 obj1= new
FirstThread2();
7. SecondThread2 obj2 =new
SecondThread2();
8. // check if threads are alive.
thrd1&2 is objects of
First/SecondThread2
9.
System.out.println(obj1.thrd1.isAlive())
; //thrd1 is object of
FirstThread2
10.
System.out.println(obj2.thrd2.isAlive())
;
11. // wait for threads to finish.
Use join method
12. try{
13. System.out.println(“\nwaiting
for threads to finish”);
14. obj1.thrd1.join();
15. obj2.thrd2.join();
16. }catch(InterruptedException e )
17. {System.out.println(“main thread
interrupted”);}
18. System.out.println(“Exiting from
main thread”);
19. }//end of main
20. }// end of ThreadRunnableDemo
Output: Creating FirstThread2
Creating
FirstThread2Thread[FirstThread2,5,main]
thread1 :0 : Creating SecondThread2
Creating
SecondThread2Thread[FirstThread2,5,main]
True true
thread1 Details waiting for threads
to finish
Name :FirstThread2 Priority :5
thread2 :0 : thread1 :1 : thread2 :1
: thread1 :2 : thread2 :2 :
thread1 :3 : thread2 :3 : Exiting
from thread1Exiting from thread2
Exiting from main thread
1. package com.oops.chap20;
2. class MaxPriority implements
Runnable{
3. Thread thrd1;
4. MaxPriority(){
5. System.out.println(“Creating
MaxPriority”);
6. thrd1 = new
Thread(this,”MaxPriority”);
7.
thrd1.setPriority(Thread.MAX_PRIORITY);
8. System.out.println(“Creating
MaxPriority”+ thrd1);
9. thrd1.start();
10. }
11. public void run(){
12. System.out.println(“Maximum
Thread Details”);
13. System.out.println(“Name
:”+thrd1.getName());
14. System.out.println(“Priority
:”+thrd1.getPriority());
15. // MaxPriority executes the
sequence
16. try{
17. for (int i=0;i<4;i++)
18. {System.out.println(“ thread1 :”
+ i + “ : “);
19. Thread.sleep(600);}
20. }catch(InterruptedException e )
21. {System.out.println(“thread1
interrupted”);}
22. System.out.println(“Exiting from
thread1”);
23. }//end of run
24. }//end of FirstThread
25. class MinPriority implements
Runnable{
26. Thread thrd2;
27. MinPriority(){
28. System.out.println(“Creating
MinPriority”);
29. thrd2 = new
Threadthis,”FirstThread2”);
30.
thrd2.setPriority(Thread.MIN_PRIORITY+2)
;
31. System.out.println(“Creating
MinPriority”+ thrd2);
32. thrd2.start();
33. }
34. public void run(){
35. System.out.println(“minimum
thread Details”);
36. System.out.println(“Name
:”+thrd2.getName());
37. System.out.println(“Priority
:”+thrd2.getPriority());
38. try{
39. for (int i=0;i<4;i++)
40. { System.out.println(“ thread2
:” + i + “ : “);
41. Thread.sleep(600);
42. }
43. }catch(InterruptedException e )
44. {System.out.println(“thread2
interrupted”);}
45. System.out.println(“Exiting from
thread2”);
46. }//end of run
47. }//end of SecondThread
48. public class Priority {
49. public static void main(String[]
args) {
50. //create an object ofMaxPriority
& MinPriority
51. new MaxPriority();
52. new MinPriority();
53. try{
54. for (int i=0;i<4;i++)
55. { System.out.println(“
threadMain :” + i + “ : “);
56. Thread.sleep(600);
57. }
58. }catch(InterruptedException e )
59. {System.out.println(“main thread
interrupted”);}
60. System.out.println(“Exiting from
main thread”);
61. }//end of main
62. }// end of Priority.java
Output: Creating MaxPriority
Creating
MaxPriorityThread[MaxPriority,10,main]
Maximum Thread Details
Name :MaxPriority
Priority :10
thread1 :0 :
Creating MinPriority
Creating
MinPriorityThread[FirstThread2,3,main]
threadMain :0 :
minimum thread Details
Name :FirstThread2 Priority :3
thread2 :0 : thread1 :1 : thread2 :1
: thread1 :2 : threadMain :1 : thread2
:2 : thread1 :3 : thread2 :3 : Exiting
from th read1
threadMain :2 : Exiting from thread2
threadMain :3 :
Exiting from main thread
20.15 Synchronization
When multiple threads act on different
objects, we would call it multitasking. As per
priorities allocated and as per CPU
scheduling, the threads execute different
objects and produce results. There is no
problem in this case.
Suppose multiple threads act on the same
object. This could lead to problems. Let us
say that there are two threads, thread1 &
thread2, acting on the object, i.e., they will
concurrently execute the same run()
command. Each thread has only one job,
that of incrementing the counter and
sending it to the printer for printing. The
output we are expecting is: thread1
1001,thread2: 1001; thread:1002,
thread2: 1002 and so on. Remember
thread is on CPU and speed of execution is
of the order of nanoseconds and the printer
is a slow device. Let us say that counter has
an initial value of 1000. After incrementing
by thread1 to 1001 and before the count has
been printed, i.e., 1001, the control may pass
to thread2 due to sleep() or wait(),
etc., which will increment the counter to
1002. The printer will look for count and
print 1002 instead of 1001 which we
normally expect, thus leading to erroneous
results. A second scenario is that after
printing 1001, if the CPU is still with
thread1, it will increment once again and
print 1002, thus leading again to erroneous
results. Multiple threads working
independently on a single object and
plausible problems that can arise are shown
in Ex 20.6.
Example
20.13: SynchronisedDemo.java: A
Program to Show Use of
Synchronized Block for Solving
Problems of Multiple Threads
Acting on Single Object
1. package com.oops.chap20;
2. class Sync3 extends Thread{
3. Thread thrd;
4. Sync3(String stg){
5. super(stg);}
6. public void run(){
7. synchronized(this) {
8. try{
9. for(int i=1000;i<1010;i++)
10.
{System.out.println(this.getName() + (i)
+ “ : “);
11. Thread.sleep(500);
12. }
13. }catch(InterruptedException e )
14. {System.out.println(“thread1
interrupted”);}
15. System.out.println(“Exiting from
thread1”+this.getName());
16. }//end of try
17. }//end of run
18. }
19. public class SynchronisedDemo {
20. public static void main(String[]
args) {
21. //create an object ofMaxPriority
& MinPriority
22. Sync3 obj1 =new
Sync3(“Sync1”);obj1.start();
23. Sync3 obj2 = new
Sync3(“Sync2”);obj2.start();
24. }//end of main
25. }// end of class
SynchronisedDemo
Sync11000 : Sync20000 : Sync11001 :
Sync20001 : Sync11002 :
Sync20002 : Sync11003 : Sync20003 :
Sync11004 : Sync20004 :
Sync11005 : Sync20005 : Sync11006 :
Sync20006 : Sync11007 :
Sync20007 : Sync11008 : Sync20008 :
Sync11009 : Sync20009 : Exiting from
thread1Sync1 Exiting from thread1Sync2
1. package com.oops.chap20;
2. class Producer extends Thread{
3. // producer produces data and add
it to buffer based on the signal
4. StringBuffer buffer;
5. Producer(){ // constructor
6. buffer = new StringBuffer();}
7. public void run(){
8. // synchronize the buffer
9. synchronized(buffer)
10. {
11. //produce items
12. for( int i=1;i<=8;i++)
13. { try {
14. buffer.append(“Item”+i + “,”);
15. Thread.sleep(200);
16. System.out.println(“Buffer
Position :”+ i + “ Filled.”);
17. }catch(Exception e){}
18. }//end of for
19. buffer.notify();
20. }// end of synchronized block
21. }//// end of run
22. }// end of Producer
23. class Consumer extends Thread{
24. // Create a reference of
Producer class
25. Producer prod;
26. //Constructor
27. Consumer(Producer prod)
28. { this.prod=prod;}
29. public void run(){
30. synchronized(prod.buffer)
31. {// wait for notification from
Producer
32. try{
33. prod.buffer.wait();
34. }catch(Exception e){}
35. System.out.println(“Displaying
items from Buffer..”);
36. System.out.println(prod.buffer);
37. }//end of sync
38. }// end of run
39. }//end of class Consumer
40. public class
ProducerConsumerDemo extends Thread{
41. public static void main(String[]
args) throws Exception {
42. // create objects of producer
and consumer
43. Producer prod = new Producer();
44. Consumer cons = new
Consumer(prod);
45. // create threads for Producer
and Consumer
46. Thread thrdProd = new
Thread(prod);
47. Thread thrdCons = new
Thread(cons);
48. thrdCons.start();
49. thrdProd.start();
50. }// end of main()
51. }// end of class
ProducerConsumerDemo
Output:
Buffer Position :1 Filled. Buffer
Position :2 Filled.
Buffer Position :3 Filled. Buffer
Position :4 Filled.
Buffer Position :5 Filled. Buffer
Position :6 Filled.
Buffer Position :7 Filled. Buffer
Position :8 Filled.
Displaying items from Buffer.
Item1,Item2,Item3,Item4,Item5,Item6,Item
7,Item8
Exercise Questions
Objective Questions
1. i, ii and iii
2. iii
3. ii and iii
4. ii and iii
1. i, ii and iii
2. iii
3. ii and iii
4. ii, iii and iv
1. i and iii
2. iii
3. ii and iv
4. ii, iii and iv
1. i and ii
2. iii
3. ii and iv
4. ii, iii and iv
1. i, ii and iii
2. i, iii and iv
3. ii and iv
4. ii, iii and iv
1. i, ii and iii
2. i, iii and iv
3. i and iii
4. ii, iii and iv
Short-answer Questions
Java IO Files
LEARNING OBJECTIVES
21.1 Introduction
We have all heard about streams of water;
we call them springs flowing from top of
hills to plains. In Java, flow of data from
output device to computer system and
computer to any one of the output devices is
called Stream or IO streams.
This chapter will introduce you to
concepts of IOStreaming and stream
classes like ByteStream and Character
Stream classes. We will introduce you to the
concept of Random File IO. This chapter
also discusses in detail File IO and Errors
and Exceptions that are encountered while
dealing with file. The topics on file handling
presented includes input and output of
characters, Bytes, primitive data types and
Data Streams, and object Streams.
21.2 IO Streaming
In Java, IO streams are flow of bytes from
one input device to Memory and vice versa.
A stream is like a pipe. It can carry anything
in the pipe, be it primitive data, objects, etc.
Refer to Figure 21.1.
Figure 21.1 Streams – a concept
FileInputStream FileReader
FileOutputStream FileWriter
BufferedInputStream BufferedReader
BufferedOutputStream BufferedWriter
Reader Writer
BufferedReader BufferedWriter
CharArrayReader CharArrayWriter
FilterReader : Filter Writer:
PushbackReader PrintWriter
InputStreamReader OutputStreamWriter
FileReader FileWriter
PipedReader PipedWriter
StringReader StringWriter
Example
21.2: FileReaderWriter.Java A
Program to Copy a File Using
Character Streams. Obtain the
Input and Output File Names
Interactively from Keyboard. Use
Scanner Class
1. package com.oops.chap21;
2. import java.io.*;
3. import java.util.Scanner;
4. public class FileReaderWriter {
5. public static void main(String[]
args) {
6. String filename1,filename2;
7. Scanner scn=new
Scanner(System.in);
8. DataInputStream input = new
DataInputStream(System.in);
9. System.out.println(“Enter output
FileName :”);
10. filename1=scn.next();
11. System.out.println(“Enter
FileName for copy file :”);
12. filename2=scn.next();
13. try{
14. FileWriter fw1 = new
FileWriter(filename1);
15. FileWriter fw2 = new
FileWriter(filename2);
16. System.out.println(“Enter text <
enter . at end>”);
17. int ch;
18. while( (ch=
(char)input.read())!=’.’){
19. fw1.write(ch);
20. }
21. fw1.close();
22. FileReader fr1 = new
FileReader(filename1);
23. while((ch=fr1.read())!=-1)
24. fw2.write(ch);
25. fr1.close();
26. fw2.close();
27. //Now open filename3 and dispaly
the result
28. fr1=new FileReader(filename2);
29. System.out.println(“Displaying
the details from “+filename2);
30. while((ch=fr1.read())!=-1)
31. System.out.println((char)ch);
32. }catch(IOException e){}
33. }
34. }
Output : Enter output FileName
:citynames
Enter FileName for copy file
:citnamescopy
Enter text < enter . to end>
Hello India.
Displaying the details from
citnamescopy
Hello India
Lin defines filename1 and filename2 as
e String data type to accept the file names
No. interactively from the user.
6:
Input IO Remarks
1. package com.oops.chap21;
2. import java.util.*;
3. import java.io.*;
4. import javax.swing.JOptionPane;
5. public class DisDos {
6. public static void main(String[]
args) throws IOException{
7. int idNo;
8. double credits,debits,netPay;
9. System.out.println(“Enter Emp
idNo,credits,debits separated by
spaces”);
10. Scanner scn = new
Scanner(System.in);
11. idNo=scn.nextInt();
12. credits =scn.nextDouble();
13. debits=scn.nextDouble();
14. netPay=credits-debits;
15. FileOutputStream fileout = new
FileOutputStream(“DisDos”);
16. DataOutputStream dosfile= new
DataOutputStream(fileout);
17. dosfile.writeInt(idNo);
18. dosfile.writeDouble(credits);
19. dosfile.writeDouble(debits);
20. dosfile.writeDouble(netPay);
21. dosfile.close();
22. fileout.close();
23. //Now red data from DisDos file
24. FileInputStream filein = new
FileInputStream(“DisDos”);
25. DataInputStream disfile= new
DataInputStream(filein);
26.
JOptionPane.showMessageDialog(null,” Id
Number :” +disfile.readInt() +”\nCredits
:” +
27. disfile.readDouble()+”\t Debits
“ + disfile.readDouble() +”\t Net Pay
:”+
28. disfile.readDouble(),”Employee
Pay Bill”,JOptionPane.PLAIN_MESSAGE);
29. }
30. }
Output: Enter Emp idNo,credits,debits
separated by spaces
50595 25000.00 5000.00
1. package com.oops.chap21;
2. import java.io.*;
3. public class FileDirectory {
4. public static void main(String[]
args) throws IOException{
5. System.out.println(“ Getting File
Details……”);
6. File fobj = new
File(“/”,”Oopsjava/workspace/oopstech2/s
rc/com/chap21/DisDos.java”);
7. System.out.println(“File Name :” +
fobj.getName());
8. System.out.println(“File Absolute
path :” + fobj.getAbsolutePath());
9. System.out.println(“Parent:” +
fobj.getParent());
10. System.out.println(“File exists
or not:” + fobj.exists());
11.
if(fobj.isFile())System.out.println(“
Length “ + fobj.length());
12. System.out.println(“is
directory?” + fobj.isDirectory());
13. System.out.println(“ Getting
Directory Details……”);
14. File fobj2 = new
File(“/”,”Oopsjava/workspace/oopstech2/s
rc/com/chap21”);
15. if(fobj.exists())
16. { // get the listing of a
directory into a array
17. String arrList[] = fobj2.list();
18. int len=arrList.length;
19. System.out.println(“Displying the
Directory Listing……..”);
20. for ( int i=0; i<len;i++)
21. { System.out.println(arrList[i]);
22. File ftemp=new
File(“/Oopsjava/workspace/oopstech2/src/
com/chap21”,arrList[i]);
23. if ( ftemp.isFile())
24. System.out.println(“File :”+
ftemp.getName() + “length :” +
ftemp.length());
25. else System.out.println(“**”);
26. }//end of for
27. }// end of if
28. }//end of main
29. }//end of class
Output: Getting File Details……
File Name :DisDos.java
File Absolute path
:C:\Oopsjava\workspace\oopstech2\src\com
\chap21 \DisDos.java
Parent:\Oopsjava\workspace\oopstech2\src
\com\chap21
File exists or not:true
Length 1127
is directory?false
Getting Directory Details……
Displying the Directory Listing……..
FOS.java
File :FOS.javalength :715
CharByChar.java
File :CharByChar.javalength :976
ByteByByte.java
File :ByteByByte.javalength :178
1. package com.oops.chap21;
2. import java.io.*;
3. public class RandomAccess {
4. public static void main(String[]
args)throws IOException {
5. //create the object for RandomFile
6. RandomAccessFile randfile = new
RandomAccessFile(“raf.dat ”,”rw”);
7. try {
8. int idNo=50595;float sal
=20000.00F;boolean malefemale= true;
9. char cadre = ‘S’;
10. randfile.writeInt(idNo);
11. randfile.writeDouble(sal);
12. randfile.writeChar(cadre);
13. // go to beginning of file
14. randfile.seek(0);
15. System.out.println(“idno :”+
randfile.readInt());
16. System.out.println(“Salary :”+
randfile.readDouble());
17. System.out.println(“Cadre :”+
randfile.readChar());
18.
randfile.seek(randfile.length());//go to
end of file
19.
randfile.writeBoolean(malefemale);
20. randfile.seek(3);
21. System.out.println(“Malefemale
:”+ randfile.readBoolean());
22. randfile.close();
23. }catch( IOException e){}
24. }// end of main
25. }// end of class
Output : id no :50595
Salary :20000.0
Cadre :S
Malefemale :true
Line RandomAccessFile randfile = new
No. RandomAccessFile(“raf.dat”,”rw”)
6: ; opens random file in read write mode.
Line randfile.seek(randfile.length())
No. ;// go to end of file
18:
21.10.1 Serialization
21.10.2 De-serialization
1. package com.oops.chap21;
2. import java.io.*;
3. class Student implements
Serializable {
4. // member data or attributes
5. private int idNo = 50595;
6. private double totalMarks=990.0;
7. private String grade=”A”;
8. public double getMarks(){ return
totalMarks;}
9. public int getIdNo(){ return
idNo;}
10. public String getGrade(){ return
grade;}
11. public void DisplayData(Student
std) {
12. System.out.println(“Details from
Student are :”);
13. System.out.println(“idNo:” +
std.getIdNo());
14. System.out.println(“Total Marks:”
+ std.getMarks());
15. System.out.println(„Grade:“ +
std.getGrade());
16. }//end DisplayData
17. }// end of class
18. // Driver class
19. class SerializableDemo {
20. public static void main(String[]
args)throws IOException{
21. // create an object of Student
22. Student std = new Student();
23. System.out.println(“Displaying
Data from Student class…..”);
24. std.DisplayData(std);
25. FileOutputStream fosobj= new
FileOutputStream(“Stdobj.dat”);
26. ObjectOutputStream objoutstream =
new ObjectOutputStream (fosobj);
27. objoutstream.writeObject(std);
28. objoutstream.close();
29. System.out.println(“Reading from
Serialized Object Student….”);
30. FileInputStream fisobj= new
FileInputStream(“Stdobj.dat”);
31. ObjectInputStream objinstream =
new ObjectInputStream (fisobj);
32. try{
33. std =
(Student)objinstream.readObject();
34. }catch(ClassNotFoundException e)
{}
35. std.DisplayData(std);
36. objinstream.close();
37. }
38. }//end of class Student2bDemo
Output : Displaying Data from Student
class…..
Details from Student are : idNo:50595
Total Marks:990.0 Grade:A
Reading from Serialized Object
Student….
Details from Student are : idNo:50595
Total Marks:990.0 Grade:A
Lin objoutstream.writeObject(std);
e writes to file
No
.
27:
21.11 Summary
Exercise Questions
Objective Questions
1. i and iv
2. iii and iv
3. i and ii
4. i and iii
1. i and iv
2. iii and iv
3. i, ii and iv
4. i and iii
1. i, ii and iv
2. i, iii and iv
3. i and iii
4. ii, iii and iv
1. i, ii and iv
2. i and iii
3. i and iii
4. ii, iii and iv
1. i, ii and iv
2. i and iii
3. i and iii
4. ii, iii and iv
1. b
2. c
3. c
4. b
5. c
6. True
22
Networking in Java
LEARNING OBJECTIVES
TCP/IP protocols.
Inet addressing mechanism and URL connections.
TCP/IP sockets.
Client server applications.
22.1 Introduction
Java has been specially created for
networking. What do we mean by this? Java
supports a package called java.net which
defines several methods for connecting and
retrieving files by using common web-based
protocols. Java also allows us to create unix-
like sockets and allows us to implement
TCP/IP sockets.
In the previous chapter on Java IO
programming, you have been introduced to
Input and Output Stream. By attaching
those stream files with networking
protocols, you can write to files on the
Internet and retrieve data from files over the
Internet as if you are writing files on to a
disk.
This chapter covers the basics of
networking such as TCP/IP protocols and its
implementation through TCP/IP and
datagrams. URL connections and Inet
addressing mechanisms are also presented.
Client server application employing TCP/IPs
and sockets are discussed.
22.2.1 TCP/IP
A protocol is a set of rules to be followed by
cooperating systems on the Internet for
transferring data from one system to
another system. TCP/IP, i.e., Transmission
Control Protocol and Internet Protocol, are
standard protocols to be used for
transmission of data.
TCP/IP is a connection-oriented and
reliable service.
Connection oriented means the sender confirms if the
receiver has indeed received the data or not. If not
received, then the retransmission of data takes place.
TCP/IP is a point-to-point reliable communication, i.e.,
it is an acknowledged service that ensures correct
reception of data at receiver. TCP/IP has five layers, as
shown in Figure 22.3.
Java programs written come under Application Layer.
Hyper Text Transfer Protocol (HTTP) and File Transfer
Protocol (FTP) and Telnet are some of the widely used
protocols at the application layer.
Application Layer receives the data from IO streams of
sender and format data as streams of continuous bytes
and sends them to Transport layer, as shown in Figure
22.1.
Example
22.1: InetAddressDemo.java Write
a Program to Get Inetaddresses
and Local Host Name for a Specified
Web Site
Li catches (UnknownHostException e)
n
e
N
o.
14
:
URL Constructors
URL (String protocol, String host, int port,
String file) throws MalformedURLException.
URL (String protocol, String host, String
file) throws MalformedURLException.
URL (String urlString) throws
MalformedURLException.
URL Methods
String getFile()
String getHost()
int getPort()
String getProtocol()
Example
22.2: InetAddressDemo.java Write
a Program to Get InetAddresses and
Local Host Name for a Specified
Web Site
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type”
content=”text/html; charset=iso-8859-1”>
<title>Prof. Ramesh
Vasappanavara</title>
<style type=”text/css”>
<!−
…………………………………………………
</body>
</html>
Example
22.3: URLConnectionDemo.Java
Write a Program to Show Usage of
URLConnection Class Methods
Li InputStream inputstream =
ne vrCon.getInputStream(); while( (
N ch = inputstream.read())! = -1)
os read the input stream and prints content of
. web site character by character
26
&
27
:
c:\oopsjava\workspace\oopstech\src\co\oo
ps\chap22
1. package com.oops.chap22;
2. import java.io.*;
3. import java.net.*;
4. public class ClientDemo1 {
5. public static void main(String[]
args)throws IOException {
6. //create a client socket using
Socket class
7. Socket skt = new Socket (
“localhost” ,8345);
8. //Link IntputStream to socket
object skt
9. InputStream comobj = skt.
getInputStream();
10. //Use BufferedReader to get the
data from socket
11. BufferedReader bfrtobj =new
BufferedReader ( new
InputStreamReader(comobj));
12. //Receive messages
13. String stg;
14. while(( stg=bfrtobj.readLine())
!= null)
15. System.out.println(“\n Message
from Server” + stg);
16. //close all
17. skt.close(); bfrtobj.close();
18. }
19. }
Output: Message from Server :Welcome
client
Message from Server Networking
program run a great fun!
22.6.1 Client Server Two-way
Communication Program
In this section, we will handle two-way
communication between a server and a
client. Server stores two arrays. In one array
RollNumbers are stored and in the second
array academic grades are stored. Client
sends roll number and server checks for the
grade and sends them to client. Client then
displays the result. The concept is shown in
Figure 22.6.
package com.oops.chap22;
import java.io.*;
import java.util.*;
import java.net.*;
public class ClientDemo2 {
public static void main(String[]
args)throws IOException {
int id, index=0;String gr;
//socket to connect to server
Socket skt = new
Socket(“localhost”,5000);
// Create a BufferedInputStream to get
the data from the server
BufferedReader bufrserver=new
BufferedReader
( new
InputStreamReader(skt.getInputStream()))
;
//create buffer writer stream for
sending data to server
PrintWriter prwtr = new
PrintWriter(skt.getOutputStream(),true);
//continuously send roll number and get
grade from the server.
while ( true)
{ Scanner scn= new Scanner(System.in);
System.out.println(“\n Enter roll
number< 50595 to 50599>”);
id = scn.nextInt();
// send id to server
prwtr.println(id);
// get grade from the server
StringTokenizer stkn =new
StringTokenizer(bufrserver.readLine());
System.out.println(“Grade received from
server of “+ id + “ is :”+
stkn.nextToken());
}
}
}
22.6.2 Multiple Clients and Server Programs
Using Multithreads
In real life, there will be several clients
wishing to connect to server at the same
tine. For example, when results are declared,
several students rush in to connect to server.
The best way to handle such a situation is to
put each client on a separate thread. The
server can achieve the result by
ServerSocket servskt = new
ServerSocket (6000);
while( true) {
Socket clientskt =
servskt.accept();
Thread thrd = new
Thread(clientskt);}
package com.oops.chap22;
import java.io.*;
import java.util.*;
import java.net.*;
public class MultipleClientServer {
public static void main(String[]
args)throws IOException {
try {
//server socket
ServerSocket servskt = new ServerSocket
(4000);
int count=0; // counting thread
while ( true)
{// listen for a request
Socket clientskt = servskt.accept();
System.out.println(“\n Starting
thread No “+count);
//create a new thread by calling the
constructor of class CommThread
CommThread thrd = new
CommThread(clientskt,count);
thrd.start();
}//end of while
}catch(IOException e){}
}//end of main
}//end of class
class CommThread extends Thread
{ private Socket clientskt ; //
connected
private int count; // count for label
the thread
CommThread(Socket s , int i)
{clientskt=s; count=i;}
public void run()
{ boolean evenodd=true;
try
{ // Create a BufferedReaderStream to
get the data from the client
BufferedReader bufrclient=new
BufferedReader
( new
InputStreamReader(clientskt.getInputStre
am()));
//create buffer writer stream for
sending data to client
PrintWriter prwtr = new
PrintWriter(clientskt.getOutputStream
(),true);
// Serve in a continuous loop
while ( true)
{// receive the string data from
client
StringTokenizer stkn = new
StringTokenizer(bufrclient.readLine());
//get year
int num = new
Integer(stkn.nextToken()).intValue();
System.out.println(“\n Number Received
From Client “+ num);
//check even or odd
if ( num%2!=0)evenodd=false;
else evenodd=true;
//send evenodd to client
prwtr.println(evenodd);
System.out.println(“\n Number “+ num
+” is :”+ evenodd);
}
}catch(IOException e ){}
}
package com.oops.chap22;
import java.util.*;
import java.io.*;
import java.net.*;
public class MultipleclientsClient {
public static void main(String[]
args)throws IOException {
//socket to connect to server
Socket skt = new
Socket(“localhost”,4000);
// Create a BufferedInputStream to get
the data from the server
BufferedReader bufrserver=new
BufferedReader
( new
InputStreamReader(skt.getInputStream()))
;
//create buffer writer stream for
sending data to server
PrintWriter prwtr = new
PrintWriter(skt.getOutputStream(),true);
//continuously send number and get grade
from the server.
while ( true)
{ Scanner scn= new Scanner(System.in);
System.out.println(“\n Enter number<
50595 to 50599>”);
int id = scn.nextInt();
// send id to server
prwtr.println(id);
// get even or odd from the server
StringTokenizer stkn =new
StringTokenizer(bufrserver.readLine());
System.out.println(“EvenOdd received
from server of “+ id + “ is :”+
stkn.nextToken());
}}}
22.6.3 Client Server Program for File
Download from Server
Many a times we need to download a file
located in a server. The solved Example 4a
and 4b shows the technique to download file
from a remote server. As usual at server, we
need a server socket and a client-specific
socket. Then we need BufferedReader to
accept data from the client and
DataOutputStreamReader to send the
data to client.
22.7 Summary
Exercise Questions
Objective Questions
1. i, ii and iv
2. i, ii and iii
3. ii, iii and iv
4. i and iii
Short-answer Questions
1. b
2. c
3. a
4. a
5. c
6. a
7. b
8. c
9. d
10. b
11. a
23
LEARNING OBJECTIVES
1. import javax.swing.*;
2. public class SwingDemo {
3. public static void main(String[]
args) {
4. JFrame frame = new JFrame(“Swing
Demo”);
5. JPanel panel = new JPanel();
6. JButton button = new
JButton(“Button”);
7.
8. panel.add(button);
9. frame.setContentPane(panel);
10. frame.setVisible(true);
11. }
12. }
Output
As seen from the example above, we
instantiate the root container frame first in
line 4; we then instantiate the intermediate
container panel in line 5 and finally a button
widget in line 6. That is, we follow the top-
down approach during creation. But during
addition, we add the button to panel first in
line 7 then we add the panel to the frame in
line 8 and finally display the frame in line 9,
thus following the bottom-up approach.
The addition and creation rules will apply
to all programs discussed in this chapter.
1. import javax.swing.*;
2. public class SwingDemo {
3. public static void main(String[]
args) {
4. JFrame frame = new
DisplayFrame();
5. frame.setVisible(true);
6. }
7. }
8. class DisplayFrame extends JFrame{
9. DisplayFrame(){
10.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
11. setTitle(“Swing Demo”);
12. setSize(300, 150);
13. setLocation(100,100);
14. }
15. }
1. import javax.swing.*;
2. public class SwingDemo {
3. public static void main(String[]
args) {
4. JFrame frame = new
DisplayFrame();
5. frame.setVisible(true);
6. }
7. }
8. class DisplayFrame extends JFrame{
9. DisplayFrame(){
10.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
11. setTitle(“Swing Demo”);
12. setSize(300, 150);
13. setLocation(100,100);
14. JPanel panel = new
DisplayPanel();
15. getContentPane().add(panel);
16. }
17. }
18. class DisplayPanel extends
JPanel{
19. DisplayPanel() {
20. //Widgets will be added here
21. }
22. }
1. import javax.swing.*;
2. public class SwingDemo {
3. public static void main(String[]
args) {
4. JFrame frame = new
DisplayFrame();
5. frame.setVisible(true);
6. }
7. }
8. class DisplayFrame extends JFrame{
9. DisplayFrame(){
10.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
11. setTitle(“Swing Demo”);
12. setSize(300, 150);
13. setLocation(100,100);
14. JPanel panel = new
DisplayPanel();
15. getContentPane().add(panel);
16. }
17. }
18. c DisplayPanel extends JPanel{
19. DisplayPanel() {
20. JLabel label = new JLabel
21. (“Welcome to Java Swing” );
22. add(label);
23. }
24. }
23.4.2 JButton
The JButton object is used to display
buttons in Java. Buttons are very useful user
interface elements, which can be used for a
variety of user interactions. Figure 23.6
shows a typical use case scenario, wherein
the button "Click Me" is displayed using a
JButton object. Example 23.5 demonstrates
how to create and display JButton objects in
Java.
Figure 23.6 JButton
1. import javax.swing.*;
2. public class SwingDemo {
3. public static void main(String[]
args) {
4. JFrame frame = new
DisplayFrame();
5. frame.setVisible(true);
6. }
7. }
8. class DisplayFrame extends JFrame{
9. DisplayFrame(){
10.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
11. setTitle(“Swing Demo”);
12. setSize(300, 150);
13. setLocation(100,100);
14. JPanel panel = new
DisplayPanel();
15. getContentPane().add(panel);
16. }
17. }
18. class DisplayPanel extends
JPanel{
19. DisplayPanel() {
20. JButton button = new
JButton(“Click Me”);
21. add(button);
22. }
23. }
23.4.3 JCheckBox
The JCheckBox object is used to display
checkboxes in Java. Checkboxes allow users
to either select or deselect an item; they also
allow multiple items to be selected at the
same time. The figure below shows a typical
use case scenario, wherein three checkboxes
“Cricket”, “Football” and “Volleyball” are
displayed using a JCheckBox object.
Example 23.6 demonstrates how to create
and display JCheckBox objects in Java.
Figure 23.7 shows the output.
1. import java.awt.event.KeyEvent;
2. import javax.swing.*;
3. public class SwingDemo {
4. public static void main(String[]
args) {
5. JFrame frame = new
DisplayFrame();
6. frame.setVisible(true);
7. }
8. }
9. class DisplayFrame extends JFrame{
10. DisplayFrame(){
11.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
12. setTitle(“Swing Demo”);
13. setSize(400, 150);
14. setLocation(100,100);
15. JPanel panel = new
DisplayPanel();
16. getContentPane().add(panel);
17. }
18. }
19. class DisplayPanel extends
JPanel{
20. DisplayPanel() {
21. JCheckBox cb1 = new
JCheckBox(“Cricket”);
22.
cb1.setMnemonic(KeyEvent.VK_C);
23. cb1.setSelected(false);
24. JCheckBox cb2 = new
JCheckBox(“Football”);
25. cb2.setMnemonic(KeyEvent.VK_F);
26. cb2.setSelected(false);
27. JCheckBox cb3 = new
JCheckBox(“Volleyball”);
28. cb3.setMnemonic(KeyEvent.VK_V);
29. cb3.setSelected(false);
30. add(cb1);
31. add(cb2);
32. add(cb3);
33. }
34. }
1. import javax.swing.*;
2. public class SwingDemo {
3. public static void main(String[]
args) {
4. JFrame frame = new
DisplayFrame();
5. frame.setVisible(true);
6. }
7. }
8. class DisplayFrame extends JFrame{
9. DisplayFrame(){
10.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
11. setTitle(“Swing Demo”);
12. setSize(300, 150);
13. setLocation(100,100);
14. JPanel panel = new
DisplayPanel();
15. getContentPane().add(panel);
16. }
17. }
18. class DisplayPanel extends JPa
nel{
19. DisplayPanel() {
20. String[] cities = { “Delhi”,
“London”, “New York”, “Moscow”, “Mumbai”
};
21. JComboBox citylist = new
JComboBox(cities);
22. citylist.setSelectedIndex(2);
23. add(citylist);
24. }
25. }
1. import java.awt.*;
2. import javax.swing.*;
3. import javax.swing.border.Border;
4. public class SwingDemo {
5. public static void main(String[]
args) {
6. JFrame frame = new
DisplayFrame();
7. frame.setVisible(true);
8. }
9. } Figure 23.11 GridLayout
10. class DisplayFrame extends
JFrame{
11. DisplayFrame(){
12.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
13. setTitle(“Swing Demo”);
14. setSize(300, 150);
15. setLocation(100,100);
16. JPanel panel = new
DisplayPanel();
17. getContentPane().add(panel);
18. }
19. }
20. class DisplayPanel extends
JPanel{
21. DisplayPanel() {
22. setLayout(new GridLayout(3, 3));
23. for(int i = 1; i <= 9 ; i++ ){
24. add(new
CalcLabel(Integer.toString(i)));
25. }
26. }
27. class CalcLabel extends JLabel {
28. CalcLabel(String S){
29. Border black =
BorderFactory.createLineBorder(Color.BLA
CK);
30. setText(S);
31.
setHorizontalAlignment(CENTER);
32. setBorder(black);
33. }
34. }
35. }
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class SwingDemo {
5. public static void main(String[]
args) {
6. JFrame frame = new
DisplayFrame();
7. frame.setVisible(true);
8. }
9. }
10. class DisplayFrame extends
JFrame{
11. DisplayFrame(){
12.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
13. setTitle(“Swing Demo”);
14. setSize(300, 150);
15. setLocation(100,100);
16. JPanel panel = new
DisplayPanel();
17. getContentPane().add(panel);
18. }
19. }
20. class DisplayPanel extends
JPanel{
21. int count;
22. JLabel label;
23. JButton button;
24. DisplayPanel() {
25. count = 0;
26. button = new JButton(“Click
Me”);
27. label = new JLabel();
28. label.setText(“Count = “
+count);
29. button.addActionListener(new
HandleEvent());
30. add(button);
31. add(label);
32. }
33. class HandleEvent implements
ActionListener{
34. public void
actionPerformed(ActionEvent e) {
35. count ++;
36. label.setText(“Count = “
+count);
37. }
38. }
39. }
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class SwingDemo {
5. public static void main(String[]
args) {
6. JFrame frame = new
DisplayFrame();
7. frame.setVisible(true);
8. }
9. }
10. class DisplayFrame extends
JFrame{
11. DisplayFrame(){
12.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
13. setTitle(“Swing Demo”);
14. setSize(400, 150);
15. setLocation(100,100);
16. JPanel panel = new
DisplayPanel();
17. getContentPane().add(panel);
18. }
19. }
20. class DisplayPanel extends
JPanel{
21. JLabel label;
22. JCheckBox cb1;
23. JCheckBox cb2;
24. JCheckBox cb3;
25. DisplayPanel() {
26. cb1 = new
JCheckBox(“Cricket”);
27.
cb1.setMnemonic(KeyEvent.VK_C);
28. cb1.setSelected(false);
29. cb2 = new
JCheckBox(“Football”);
30.
cb2.setMnemonic(KeyEvent.VK_F);
31. cb2.setSelected(false);
32. cb3 = new
JCheckBox(“Volleyball”);
33.
cb3.setMnemonic(KeyEvent.VK_V);
34. cb3.setSelected(false);
35. JLabel display_label = new
JLabel();
36. display_label.setText(“Select
Favorite Game”);
37. label = new JLabel();
38. label.setText(“”);
39. HandleItemEvent handler = new
HandleItemEvent();
40. cb1.addItemListener(handler);
41. cb2.addItemListener(handler);
42. cb3.addItemListener(handler);
43. add(display_label);
44. add(cb1);
45. add(cb2);
46. add(cb3);
47. add(label);
48.
49. }
50. class HandleItemEvent implements
ItemListener{
51. public void
itemStateChanged(ItemEvent e) {
52. int index = 0;
53. Object source =
e.getItemSelectable();
54. if (source == cb1) {
55. index = 1;
56. } else if (source == cb2) {
57. index = 2;
58. } else if (source == cb3) {
59. index = 3;
60. }
61. if (e.getStateChange() ==
ItemEvent.DESELECTED) {
62. label.setText(“Game at index:
“ +index + “ Deselected”);
63. }
64. if (e.getStateChange() ==
ItemEvent.SELECTED) {
65. label.setText(“Game at index:
“ +index + “ Selected”);
66. }
67. }
68. }
69. }
1. import java.awt.*;
2. import java.awt.event.KeyEvent;
3. import java.awt.event.KeyListener;
4. import javax.swing.*;
5. public class SwingDemo {
6. public static void main(String[]
args) {
7. JFrame frame = new
DisplayFrame();
8. frame.setVisible(true);
9. }
10. }
11. class DisplayFrame extends
JFrame{
12. DisplayFrame(){
13.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
14. setTitle(“Swing Demo”);
15. setSize(300, 150);
16. setLocation(100,100);
17. JPanel panel = new
DisplayPanel();
18. getContentPane().add(panel);
19. }
20. }
21. class DisplayPanel extends
JPanel{
22. String msg = “”;
23. JLabel label;
24. DisplayPanel() {
25. label = new JLabel(msg);
26. label.addKeyListener(new
HandleKeyEvent());
27. label.setFocusable(true);
28. JLabel disp_label = new
JLabel(“Enter Text”);
29. add(disp_label);
30. add(label);
31. }
32. class HandleKeyEvent implements
KeyListener{
33. public void keyPressed(KeyEvent
ke) {
34. int key = ke.getKeyCode();
35. switch(key)
36. {
37. case KeyEvent.VK_HOME:
38. msg += “HOME”;
39. break;
40. case KeyEvent.VK_INSERT:
41. msg += “INSERT”;
42. break;
43. case KeyEvent.VK_DELETE:
44. msg += “DELETE”;
45. break;
46. case KeyEvent.VK_END:
47. msg += “END”;
48. break;
49. }
Listener
50. label.setText(msg);
51. }
52. public void
keyReleased(KeyEvent ke)
53. {
54. }
55. public void keyTyped(KeyEvent
ke)
56. { msg += ke.getKeyChar();
57. label.setText(msg);
58. }
59. }
60. }
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class SwingDemo {
5. public static void main(String[]
args) {
6. JFrame frame = new
DisplayFrame();
7. frame.setVisible(true);
8. }
9. }
10. class DisplayFrame extends
JFrame{
11. DisplayFrame(){
12.
setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
13. setTitle(“Swing Demo”);
14. setSize(300, 150);
15. setLocation(100,100);
16. JPanel panel = new
DisplayPanel();
17. getContentPane().add(panel);
18. }
19. }
20. class DisplayPanel extends
JPanel{
21. int count;
22. JLabel label;
23. JButton button;
24.
25. DisplayPanel() {
26. count = 0;
27. button = new JButton(“Click
Me”);
28. label = new JLabel();
29. label.setText(“Count = “
+count);
30. button.addMouseListener(new
HandleMouseEvent());
31. add(button);
32. add(label);
33. setBackground(Color.WHITE);
34. }
35. class HandleMouseEvent implements
MouseListener{
36. public void
mouseClicked(MouseEvent e) {
37. count++;
38. label.setText(“Count = “
+count);
39. }
40. public void
mouseEntered(MouseEvent e) {
41.
42. setBackground(Color.YELLOW);
43. }
44. public void
mouseExited(MouseEvent e) {
45. setBackground(Color.WHITE);
46.
47. }
48. public void
mousePressed(MouseEvent e) {
49.
50. }
51. public void
mouseReleased(MouseEvent e) {
52.
53. }
54. }
55. }
23.7 Applets
Applets are small java programs that are
transported from one computer system on
the network to another system. They cannot
be run independently but they need web
browser or program called appletviewer to
run on the system.
An applet, just like an application, can
perform lot of tasks such as computation,
taking user inputs, passing parameters,
display using Graphics-rich features, play
music and last but not least create
animations. But the beauty is that applet can
travel on computer from one location to
another embedded onto HTML Tags when
user imports them using Internet.
Example
23.15: HelloWorldApplet.java
With Html Tags Embedded in the
Main Java Programme. This Code
Can Only be Executed with
Appletviewer
1. /* <HTML>
2. <BODY>
3. <Applet
Code=”HelloWorldApplet.class” Height=320
Width=400>
4. </Applet>
5. </BODY>
6. </HTML>
7. */
8. import java.awt.*;
9. import java.applet.*;
10. import java.awt.Graphics.*;
11. public class HelloWorldApplet
extends Applet {
12. public void paint(Graphics g) {
13. g.drawString(«Hello There !This
is how Applets look & feel !», 65 , 95);
14. }
15. }
//HelloWorldApplet.java
1. import java.awt.*;
2. import java.applet.*;
3. import java.awt.Graphics.*;
4. public class HelloWorldApplet
extends Applet {
5. public void paint(Graphics g) {
6. g.drawString(“Hello There !This is
how Applets look & feel !”, 65, 95);
7. }
8. }
Compile: javac
HelloWorldApplet.java
In the same directory create a separate
html file called HelloWorldApplet.html
1. <HTML>
2. <BODY>
3. <Applet
Code=”HelloWorldApplet.class” Height=320
Width=400>
4. </Applet>
5. </BODY>
6. </HTML>
Running of program:
Appletviewer
HelloWorldApplet.html
Or go to icon of web browser in the
directory where html file has been created
and double press on the icon.
Example
23.17: HelloWorldJApplet.java:
Java Applet with Swing
import javax.swing.*;
import java.awt.*;
public class HelloWorldJApplet extends
JApplet {
public void init() {
//First Get Container object
Container
myContentPane=getContentPane();
// we have set the layout. we will use
flow layout
myContentPane.setLayout(new
FlowLayout());
//Prepare the lable to post on
myContentPane
JLabel message = new JLabel(“Welcome to
swing components in Java”);
//add label to myContentpane
myContentPane.add(message);
}
}
<html>
<title>HelloWorldJApplet</title>
<body>
<applet code=”HelloWorldJApplet.class”
width=400 height = 200>
</applet>
</body>
</html>
Applets
Applets are run by web browsers. They are designed to
work on the Internet.
The signature of applet is that it will not have main()
methods. Instead it will have init() methods.
Applets cannot be run independently. They need to be
embedded into HTML tags. HTML stands for Hyper
Text Mark Up Language.
Due to security restrictions, applets cannot read form
local files/disks or write to a disk.
Applets do not have any access to any other programs
residing in local computers.
23.7.6 Passing Arguments to Applets
The applet tag we have used to embed out
class in HTML tags is shown below:
<applet
code=”HelloWorldApplet”
width=”200” height=”200”>
</applet>. This is a simple tag. We will
now introduce you to a full-fledged HTML
file.
<APPLET
[CODEBASE = codebase_URL] //
directory of html file
CODE= “Applet class name” // for
example ”HelloWorldJApplet.class”
[ ALT = alternate_text]
[ NAME = applet _instance_name]
WIDTH=no of pixels
HEIGHT = no of pixels
[ ALLIGN = alignment] //TOP BOTTOM,
LEFT,RIGHT,MIDDLE etc
[VSPACE]= pixels] // used when align
LEFT or RIGHT is used
[HSPACE]=pixels] //used when TOP or
BOTTOM are used
>
[PARAM NAME = name1 VALUE = value1> ]
// used for parameters passing
[PARAM NAME = name2 VALUE = value2> ]
</APPLET>
Example
23.22: InputToApplet.java A
Program to Accept Bank Account
and Transaction Amount and Applet
Will Return Bank Balance After
Transaction
/*<HTML><BODY><Applet
Code=”InputToApplet.class” width=800
height =800></Applet></BODY></HTML> */
1. package com.oops.chap23;
2. import javax.swing.*;
3. import java.awt.*;
4. import java.awt.event.*;// for
action listener interface
5. public class SwingInputs extends
JApplet{
6. public void init() {
7. //First Get Container object
8. Container
myContentPane=getContentPane();
9. // we have set the layout. we will
use flow layout
10. myContentPane.setLayout(new
GridLayout(1,1));
11. //Prepare the lable to post on
myContentPane
12. JPanel panel = new
SwingPanel();
13. myContentPane.add(panel);
14. }
15. }
16. class SwingPanel extends
JPanel implements ActionListener{
17. String val1,val2,stg;
18. double bal=20000.00;
19. JTextField jtf1,jtf2,jtf3;
20. SwingPanel(){
21. JLabel label =new
JLabel(“Enter accountNo :”);
22. add(label);
23. jtf1=new JTextField(10);
24. jtf1.addActionListener(this);
25. add(jtf1); // converts jtf1 to
component
26. setLocation(100,100);
27. label =new JLabel(“Enter
Transaction Amount : “);add(label);
28. jtf2=new JTextField(10);
29. jtf2.addActionListener(this);
30. add(jtf2);
31. label =new JLabel(“\nBank
Balance “);add(label);
32. jtf3=new JTextField(10);
33. stg=String.valueOf(bal);
34. jtf3.setText(stg);
35. add(jtf3);
36. label = new JLabel(“Have a
Great Day ahead!”);
37. add(label);
38. }
39. public void
actionPerformed(ActionEvent e){
40. int
acn=Integer.parseInt(jtf1.getText());
41. double
amt=Double.parseDouble(jtf2.getText());
42. double banbal=bal-amt;
43. String
stg=String.valueOf(banbal);
44. jtf3.setText(stg);
45. }
46. }
Li imports java.awt.event.*;// for action
n listener interface
e
N
o.
4:
Li int
n acn=Integer.parseInt(jtf1.getText(
e )); double
N amt=Double.parseDouble(jtf2.getTex
os
t()); are used to get the text in String format
.
and convert them to basic data type using
4
parseInt and parseDouble.
0
&
41
:
23.8 Summary
3. JFrame is a
1. Top-level container
2. Intermediate container
3. A widget
4. Component
1. i and ii
2. ii, iii and iv
3. i, ii, iii and iv
4. i, ii and iii
Short-answer Questions
1. d
2. a
3. a
4. b
5. c
6. d
7. c
8. b
9. True
10. a
16. b
24
LEARNING OBJECTIVES
1. import java.util.Set;
2. import java.util.HashSet;
3. public class SetDemo {
4. public static void main(String[]
args) {
5. Set<String> PoolA=new HashSet<String>
();
6. PoolA.add(“India”);
7. PoolA.add(“Australia”);
8. PoolA.add(“South Africa”);
9. System.out.println(“PoolA: “ +PoolA);
10. Set<String> PoolB=new
HashSet<String>();
11. PoolB.add(“England”);
12. PoolB.add(“India”);
13. PoolB.add(“New Zealand”);
14. System.out.println(“PoolB: “
+PoolB);
15.
16. PoolA.retainAll(PoolB);
17. System.out.println(“Intersection
Operation PoolA: “ +PoolA);
18. PoolA.addAll(PoolB);
19. System.out.println(“Union Operation
PoolA: “ +PoolA);
20. System.out.println(“Subset
Operation: “
21. +PoolA.containsAll(PoolB));
22. }
23. }
24. /* Output
25. PoolA: [Australia, South Africa,
India]
26. PoolB: [England, New Zealand, India]
27. Intersection Opeartion PoolA:
[India]
28. Union Operation PoolA: [England, New
Zealand, India]
29. Subset Operation: true
30. */
24.5 Iterators
Iterator allows us to iterate over a collection
such as Set. The iterator interface is defined
in java.util.Iterator. The interface
defines three methods as seen below:
public interface Iterator {
public boolean hasNext();
public object next();
public void remove();
}
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class SetDemo {
public static void main(String[] args)
{
Set<String> set=new HashSet<String>
();
set.add(“Gautam”);
set.add(“Ramesh”);
set.add(“Anand”);
System.out.println(“HashSet Output”);
for(Iterator it = set.iterator();
it.hasNext(); ){
System.out.println(“String: “ +
it.next());
}
}
}
/*Output
HashSet Output String: Gautam String:
Ramesh String: Anand */
1. import java.util.ArrayList;
2. import java.util.LinkedList;
3. import java.util.ListIterator;
4. public class ListDemo {
5. public static void main(String[]
args) {
6. ArrayList<String> AList = new
ArrayList<String>();
7. LinkedList<String> LList = new
LinkedList<String>();
8. AList.add(new String(“Ramesh”));
9. AList.add(new String(“Anand”));
10. AList.add(new String(“Gautam”));
11. System.out.println(“ArrayList: “
+AList);
12. DemoArrayList(AList);
13. LList.add(new String(“Ramesh”));
14. LList.addFirst(new String(“Anand”));
15. LList.addLast(new String(“Gautam”));
16. System.out.println(“LinkedList: “
+LList);
17. System.out.print(”Reversed
LinkedList: ”);
18. ListIterator<String> it =
LList.listIterator(LList.size());
19. while(it.hasPrevious())
20. System.out.println(it.previous());
21. }
22. private static void
DemoArrayList(ArrayList<String> list){
23. String s = new String(”Gautam“);
24. System.out.println(”index: ”
+list.indexOf(s));
25. list.remove(s);
26. System.out.println(”ArrayList: ”
+list);
27. list.set(0, ”Thunder“);
28. System.out.println(”ArrayList: ”
+list);
29. }
30. }
31. /* Output
32. ArrayList: [Ramesh, Anand, Gautam]
33. index: 2
34. ArrayList: [Ramesh, Anand]
35. ArrayList: [Thunder, Anand]
36. LinkedList: [Anand, Ramesh, Gautam]
37. Reversed LinkedList: Gautam Ramesh
Anand
38. */
1. import java.util.Collections;
2. import java.util.ArrayList;
3. public class ListAlgorithmDemo {
4. public static void main(String[]
args) {
1. import java.util.Collection;
2. import java.util.Map;
3. import java.util.HashMap;
4. import java.util.Iterator;
5. import java.util.Set;
6. public class MapDemo{
7. public static void main(String[]
args){
8. Map<Object,String> map=new
HashMap<Object,String>();
9. map.put(new Integer(120400),
“Ramesh”);
10. map.put(new Integer(120401),
“Anand”);
11. map.put(new Integer(120402),
“Gautam”);
12. System.out.println(“Printing Keys:
“);
13. Set s = map.keySet();
14. for(Iterator itr =
s.iterator();itr.hasNext();)
15. System.out.println(itr.next());
16. System.out.println(“Printing Values:
“);
17. Collection c = map.values();
18. for(Iterator itr =
c.iterator();itr.hasNext();)
19. System.out.println(itr.next());
20. }
21. }
22. /* Output
23. Printing Keys: 120401 120400 120402
24. Printing Values: Anand Ramesh Gautam
25. */
1. import java.util.Map;
2. import java.util.HashMap;
3. import java.util.Set;
4. import java.util.Iterator;
5. public class MapDemo {
6. public static void main(String[]
args) {
7. Map<Object,String> map=new
HashMap<Object,String>();
8. map.put(new Integer(120400),
“Ramesh”);
9. map.put(new Integer(120401),
“Anand”);
10. map.put(new Integer(120402),
“Gautam”);
11. Set s=map.entrySet();
12. for(Iterator
it=s.iterator();it.hasNext();){
13. Map.Entry m =
(Map.Entry)it.next();
14. int rollno=(Integer)m.getKey();
15. String name=(String)m.getValue();
16. System.out.println(“Roll No:”+
rollno + “ Name:” +name );
17. }
18. }
19. }
20. /* Output
21. Roll No:120401 Name:Anand
22. Roll No:120400 Name:Ramesh
23. Roll No:120402 Name:Gautam
24. */
Class.forName(“sun.jdbc.odbc.JdbcOdbcDri
ver”);
Connection con =
DriverManager.getConnection
(“jdbc:odbc:oopsemp”,””,””);
oopsemp is the data
source name we have selected while
creating access table. User Name and
Pass word field are empty strings.
while (( rs.next()))
{
System.out.print(rs.getInt(reccount)+”
“);
System.out.print(rs.getString(reccount+1
)+ “ “);
System.out.print(rs.getString(reccount+2
)+” “);
System.out.println(rs.getFloat(reccount+
3)+” “);
}
1. package com.oops.chap24;
2. import java.sql.*;
3. public class AccessJDBCODBC {
4. public static void main(String[]
args) throws SQLException {
5. int reccount=1;
6. //Register the Driver
7. try{
8.
Class.forName(“sun.jdbc.odbc.JdbcOdbcDri
ver”);
9. }catch ( Exception e )
{System.out.println(“Unable to load
Driver”);}
10. Connection con =
DriverManager.getConnection(“jdbc:odbc:o
opsemp”,””,””);
11. //create sql statement
12. Statement stmt =
con.createStatement();
13. ResultSet rs =
stmt.executeQuery(“select * from
oopsemp24”);
14. System.out.println(“\nid name
Dept Salary”);
15. while (( rs.next()))
16.
{System.out.print(rs.getInt(reccount)+”
“);
17.
System.out.print(rs.getString(reccount+1
)+ “ “);
18.
System.out.print(rs.getString(reccount+2
)+” “);
19.
System.out.println(rs.getFloat(reccount+
3)+” “);
20. }
21. }
22. }
1. package com.oops.chap24;
2. import java.sql.*;
3. public class Connect{
4. public static void main(String
args[]){
5. try{
6. String userName = “”;
7. String password = “”;
8. String url =
“jdbc:mysql://localhost/oopsemp2”;
//database name
9. Class.forName
(“com.mysql.jdbc.Driver”).newInstance
();
10. Connection
conn=DriverManager.getConnection (url,
userName, password);
11. System.out.println (“Database
connection established”);
12. Statement st =
conn.createStatement();
13. ResultSet rs=st.executeQuery(“select
* from oopsemp3”);// table name
14. System.out.println(“\n output from
table :oopsemp3…”);
15. System.out.print(“------------------
--------\n”);
16. System.out.println(“| Sur Name |
Last Name |”);
17. System.out.println(“----------------
----------”);
18. while(rs.next())
19. {
20. String username=rs.getString(1);
21. String password2=rs.getString(2);
22. System.out.print(“\n| “+username);
23. System.out.print(“ | “+password2);
24. System.out.print(“ | “);
25. } // while
26. System.out.println(“\n--------------
------------”);
27. //Handle oopsemp4 table
28. rs=st.executeQuery(“select id,name
from oopsemp4 where salary>20000.0”);//
table name
29. System.out.println(“\n id & name for
salary>20000.00 from table :oopsemp4…”);
30. System.out.print(“------------------
--------\n”);
31. System.out.println(“|Employee id no
| Name |”);
32. System.out.println(“----------------
----------”);
33. while(rs.next())
34. {int userid=rs.getInt(1);
35. String name =rs.getString(2);
36. System.out.print(“\n| “+userid);
37. System.out.print(“ | “+name);
38. System.out.print(“ | “);
39. } // end of while
40. System.out.println(“\n--------------
------------”);
41. } catch(Exception ex)
{ex.printStackTrace();}
42. } //main
43. } // class
Output : Database connection established
output from table :oopsemp3…
--------------------------
| Sur Name | Last Name |
--------------------------
| ramesh | vasappanavara |
| Usha | vasappanavara |
| Anand | vasappanavara |
| Gautam | vasappanavara |
--------------------------
id & name for salary>20000.00 from table
:oopsemp4…
--------------------------
|Employee id no | Name |
--------------------------
| 50597 | Anand |
| 50597 | Gautam |
--------------------------
package com.oops.chap24;
import java.sql.*;
public class UpdateDB{
public static void main(String args[]){
try{
String userName = “system”;
String password = “oracle”;
String url = “jdbc:odbc:oopsempdsn”;
//database name
Class.forName
(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection conn =
DriverManager.getConnection (url,
userName, password);
System.out.println (“Database connection
established”);
Statement st = conn.createStatement();
//Handle oopsemp5 table
System.out.println(“\n Updating a record
in to database”);
st.executeUpdate(“update oopsemp5 set
salary = 35000 where idNo=50595”);
ResultSet rs=st.executeQuery(“select
idNo ,name, salary from oopsemp5”);//
table name
System.out.println(“\n idNo&name&salary
from table :oopsemp5…”);
System.out.print(“----------------------
------------------\n”);
System.out.println(“|Employee id no |
Name | Salary |”);
System.out.println(“--------------------
------------------”);
while(rs.next())
{int userid=rs.getInt(1);
String name =rs.getString(2);
float sal = rs.getFloat(3);
System.out.print(“\n| “+userid);
System.out.print(“ | “+name);
System.out.print(“ | “+ sal);
} // end of while
System.out.println(“\n------------------
--------”);
} catch(Exception ex)
{ex.printStackTrace();}
} //main
} // class
package com.oops.chap24;
import java.sql.*;
public class DeleteDB{
public static void main(String args[])
{
try{String userName = “system”;
String password = “oracle”;
String url = “jdbc:odbc:oopsempdsn”;
//database name
Class.forName
(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection conn =
DriverManager.getConnection (url,
userName, password);
System.out.println (“Database connection
established”);
Statement st = conn.createStatement();
//Handle oopsemp5 table
System.out.println(“\n Deleting records
to database”);
st.executeUpdate(“delete oopsemp5 where
idNo=50600”);
} catch(Exception ex)
{ex.printStackTrace();}
}
}
24.14.1 PreparedStatement
Statement carries out parsing every time
statement gets executed. So far there are no
repetitions of statements. What is if there is
loop in which a statement gets executed
several times thus wasting compiler time.
PreparedStatement, on the other
hand, is a pre-parsed and compiled
statement that needs not be compiled every
time a statement gets executed. Thus, it is
beneficial to use PreparedStatement if
multiple executions are expected.
//Handle oopsemp5 table
PreparedStatement st =
conn.prepareStatement (“update oopsemp5
set salary=? where idNo=?”);
System.out.println(“\n Updating a
record in to database”);
st.setFloat(1,50000.00f); // applies
to first ? mark
st.setInt(2,50595); // applies to
second ?
st.executeUpdate(“update oopsemp5 set
salary = 35000 where idNo=50595”);
1. package com.oops.chap24;
2. import java.sql.*;
3. public class PreparedDB{
4. public static void main(String
args[]){
5. try{
6. a. String userName = “system”;
7. String password = “oracle”;
8. String url = “jdbc:odbc:oopsempdsn”;
//database name
9. Class.forName
(“sun.jdbc.odbc.JdbcOdbcDriver”);
10. Connection conn =
DriverManager.getConnection (url,
userName, password);
11. System.out.println (“Database
connection established”);
12. //Handle oopsemp5 table
13. System.out.println(“Updating a
record in to database”);
14. PreparedStatement st =
conn.prepareStatement(“update oopsemp5
set salary = ? where idNo = ?”);
15. st.setFloat(1,50000); // applies to
first ? mark
16. st.setInt(2,50595); // applies to
second ?
17. st.executeUpdate();
18. Statement st1 =
conn.createStatement();
19. ResultSet
rs=st1.executeQuery(“select idNo ,name
,salary from oopsemp5”);// table name
20. System.out.println(“idNo & name &
salary :oopsemp5…”);
21. System.out.print(“------------------
------------------\n”);
22. System.out.println(“|Employee id no
| Name |Salary |”);
23. System.out.println(“----------------
--------------------”);
24. while(rs.next())
25. {
26. int userid=rs.getInt(1);
27. String name =rs.getString(2);
28. float sal = rs.getFloat(3);
29. System.out.print(“\n| “+userid);
30. System.out.print(“ | “+name);
31. System.out.print(“ | “+ sal);
32. } // end of while
33. System.out.println(“\n--------------
------------”);
34. } catch(Exception ex)
{ex.printStackTrace();}
35. } //main
36. } // class
24.15 Servlets
We are aware that applets are dynamic and
that they reside embedded on to web
browser and can extend the functionality of
the web browser across the Internet.
Servlets like applets are small server side
programs that reside on the web servers and
extend the web servers functionality across
the Internet. Hence, the name Servlets. As
an example, consider a server is hosting an
application for centralized inventory control
system for its multi-country multi-location
branches. The company provides
information about Inventory on real time
through web pages to all its branch offices.
The information must reflect the latest
position of the stock in the database.
Servlets offer best possible means to extend
the web server to client and in addition
provide advantages such as platform
independency, ability to interact with
applets, databases and sockets, etc.
http://localhost:8080/demo1/ServletWelco
me
1. import java.io.*;
2. import java.util.*;
3. import javax.servlet.*;
4. public class PostParamServlet extends
GenericServlet {
5. public void service(ServletRequest
req , ServletResponse res)
6. throws ServletException,IOException{
7. // print writer
8. PrintWriter pwtr = res.getWriter();
9. Enumeration enm =
req.getParameterNames();
10. // Display Parameter names and
values
11. while( enm.hasMoreElements()){
12. String stg = (String)
enm.nextElement();
13. pwtr.print(stg + “ = “);
14. String pval= req.getParameter(stg);
15. pwtr.println(pval);
16. }
17. pwtr.close();
18. }
19. }
Li Enumeration enm =
ne req.getParameterNames(); pushes the
N names and values contained in client message
o. into enumeration object enm. Using Line No.
10 12: while( enm.hasMoreElements()){
:
http://localhost:8080/demo2/PostParamSer
vlet
OUTPUT from server
studentname = ShraddaPandey
studentnumber = 50596
24.15.2 HttpServletRequest
Out of the two abstract classes, namely,
GenericServlet and HTTPServlet,
HttpServlet provides better interface and
is widely used. The important methods are:
Service() receives ServletRequest and
ServletResponse object that provide access to stream
inputs of type character based or byte based.
Service requests for HttpServlet are get and post. Get
request gets the information from the server and post
sends data to a server such as information from form or
authentication details, etc. HttpServelet defines
doGet() and doPost() methods which are called by
service() method. Interfaces HttpServletrequest
and HttpservletResponse handle doGet() and
DoPost() and organize client server interaction.
Whenever doGet() or doPost() methods
are called, object of HttpServletRequest is
created by the server and passed on to
service() method as an argument. The
service() method executes the service
request and makes the response ready for
dispatch to client. A few of the important
methods supported by HttpServletRequest
interface are shown in Table 24.9.
24.15.3 HttpServletResponse
The main job of HttpServletResponse is
to prepare the response to be sent to the
client on receipt of HttpServletRequest
Object. The web servers that is executing the
servlet makes an object of
HttpServletResponse and hands it over
to service() method. A few of the
important methods are presented in Table
24.10.
Example 24.18:
SubjectGetServlet.java A Program to
Show Usage of HTTP Get Request
Step 1: Create HTML File:
SubjectGetServlet.html in the Directory
C:\PROGRA~1\APACHE~1\TOMCAT~1.0\
webapps\Demo3\WEB-INF\classes>
1. <html>
2. <body>
3. <center>
4. <form name=”Form1”
5.
action=”http://localhost:8080/Demo3/Subj
ectGetServlet”>
6. <B>Subject:</B>
7. <select name=”subject” size=”1”>
8. <option
value=”Maths”>Mathematics</option>
9. <option
value=”Physics”>Physics</option>
10. <option
value=”Chemistry”>Chemistry</option>
11. </select>
12. <br><br>
13. <input type=submit
value=”Submit”>
14. </form>
15. </body>
16. </html>
DropDown List. User selects any one
subject from options at Line Nos. 7, 8, and 9.
Step 2: Create Servlet program
SubjectGetServlet.java in the directory:
C:\PROGRA~1\APACHE~1\TOMCAT~1.0\
webapps\Demo3\WEB-INF\classes>
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SubjectGetServlet
extends HttpServlet {
5. public void doGet(HttpServletRequest
req,HttpServletResponse res)
6. throws ServletException, IOException
{
7. String
subject=req.getParameter(“subject”);
8. res.setContentType(“text/html”);
9. PrintWriter pwtr=res.getWriter();
10. pwtr.println(“<B>The selected
subject is: “);
11. pwtr.println(subject);
12. pwtr.close();
13. }
14. }
L shows SubjectGetServlet extending to
i HttpServlet
n
e
N
o.
4:
C:\PROGRA~1\APACHE~1\TOMCAT~1.0\webapps\
Demo3\WEB-INF\classes>javac
SubjectGetServlet.java
Apcode.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class Apcode extends
HttpServlet {
5. public void doPost(HttpServletRequest
req, HttpServletResponse res)
6. throws ServletException, IOException
{
7. String text =
req.getParameter(“text”);
8. String translation = translate(text);
9. res.setContentType(“text/html”);
10. ServletOutputStream out =
res.getOutputStream();
11. out.println(“<html>”);
12. out.println(“<body>”);
13. out.println(“<head><title>Apcode
Coder</title></head>”);
14. out.println(“<h1>Apcode
Coder</h1>”);
15. out.println(“<p>Text to code:”);
16. out.println(“<form action=\”Apcode\”
method=\”post\”>”);
17. out.println(“<textarea name=\”text\”
ROWS=8 COLS=55>”);
18. out.println(translation);
19. out.println(“</textarea>”);
20. out.println(“<p><input
type=\”submit\” value=\”code\”>”);
21. out.println(“</form>”);
22. out.println(“</body>”);
23. out.println(“</html>”);
24. }
25. public void doGet(HttpServletRequest
req, HttpServletResponse res)
26. throws ServletException, IOException
{
27. doPost(req, res);
28. }
29. String translate(String input) {
30. StringBuffer output = new
StringBuffer();
31. if (input!= null) {
32. for (int i = 0; i < input.length();
i++) {
33. char inChar = input.charAt(i);
34. if ((inChar >= ‘A’) & (inChar <=
‘Z’)) {
35. inChar += 13;
36. if (inChar > ‘Z’)
37. inChar -= 26;
38. }
39. output.append(inChar);
40. }
41. }
42. return output.toString();
43. }
44. }
Introspection
A Java program can discover the beans property through
a process known as introspection.
A class called Introspector uses core reflection API For
introspection to work; we need to follow certain naming
conventions and some specific rules so that
introspection can identify these properties.
A bean information class implements the BeanInfo
interface. ABeanInfo class explicitly lists those bean
features that are to be exposed to application builder
tools.
Properties are the appearance and behaviour
characteristics of a bean. Beans expose properties so
they can be customized at design time. Properties can be
changed at design time by customizers or property
editors.
Bean events can be used for communication between
bean components. A listener bean receiving information
has to register with source bean.
Persistence enables beans to save and restore their state.
Example 24.20:
Welcomebean.java A Java Beans
Example to Demonstrate the Use of
NetBeans and Beans Components
24.17 Summary
Exercise Questions
Objective Questions
1. i and ii
2. i and iii
3. i and iv
4. iii and iv
1. i and ii
2. i and iii
3. i and iv
4. iii and iv
1. i and ii
2. i and iii
3. i and iv
4. iii and iv
1. i and ii
2. i, ii and iv
3. i and iv
4. iii and iv
1. i, ii and iii
2. i, ii and iv
3. ii, iii and iv
4. i, iii and iv
1. i and ii
2. i and iii
3. i and iv
4. ii, iii and iv
1. c
2. d
3. a
4. b
5. b
6. c
7. d
8. d
9. False
Appendix A
ASCII Table
First read the row, say row No. 6 and then
the column, say column No. 5, then the
decimal number is 65. From the table
intersection, 6 and 5 shows Hex = 41, Oct
101, and character = A.
Appendix B
Number Systems
Introduction
Decimal System: We use the decimal
system in our daily lives. The allowable
digits in decimal system are:
NetBeans IDE
Installation
Netbeans 6.9 is an open source and is
available at several locations on the Internet.
One such location is www.netbeans.org.
Down-load and install it on your computer.
Step 1: The first screen that opens on
execution of Netbeans package is as shown
below:
Step 2: File new java java Application
Step 3: Select Project Name, Location and
folder and select Create Main Class and Set
Main Project.
Step 4: Enter the java code in the program
template provided by Netbeans:
Step 5: Select run command from the task
bar:
Acknowledgements
Ramesh Vasappanavara
Anand Vasappanavara
Gautam Vasappanavara
Copyright © 2011 Dorling Kindersley (India) Pvt. Ltd.
Licensees of Pearson Education in South Asia
No part of this eBook may be used or reproduced in any
manner whatsoever without the publisher's prior written
consent.
This eBook may or may not include all assets that were part of
the print version. The publisher reserves the right to remove
any material in this eBook at any time.
ISBN 9788131754559
ePub ISBN 9789332512030
Head Office: A-8(A), Sector 62, Knowledge Boulevard, 7th
Floor, NOIDA 201 309, India
Registered Office: 11 Local Shopping Centre, Panchsheel Park,
New Delhi 110 017, India