Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

IntroductiontoJava-StudentGuide

The document is a personal copy of a Java programming course guide issued to ARITRA SARKAR at NIIT Kolkata Jadavpur Centre on 07/01/2019. It covers various aspects of Java, including its features, object-oriented principles, and practical applications, while emphasizing the importance of Java in developing portable applications. The course aims to equip students with the skills to create both command-line and graphical user interface applications using Java.

Uploaded by

biswas.sapta81
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

IntroductiontoJava-StudentGuide

The document is a personal copy of a Java programming course guide issued to ARITRA SARKAR at NIIT Kolkata Jadavpur Centre on 07/01/2019. It covers various aspects of Java, including its features, object-oriented principles, and practical applications, while emphasizing the importance of Java in developing portable applications. The course aims to equip students with the skills to create both command-line and graphical user interface applications using Java.

Uploaded by

biswas.sapta81
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 180

R

KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Introduction to Java
Student Guide
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
Trademark Acknowledgements
A
R
IT
All products are registered trademarks of their respective organizations.
R

All software is used for educational purposes only.


-A
01
02
30
52
00
19
R

Introduction to Java SG/18-M03-V1.0


Copyright ©NIIT. All rights reserved.

No part of this publication may be reproduced, stored in retrieval


system or transmitted in any form, or by any means, electronic,
mechanical, photocopying, recording or otherwise, without the
prior written permission of the publisher.

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
COURSE DESIGN - STUDENT GUIDE

Table of Contents

About This Course Prologue

Chapters Description

Objectives Rationale

R
Content

KA
Objectives

Text Entry Profile

R
SA
Graphics Exit Profile

Tables Conventions

A
Notes
R
IT
Just a minute
R
-A

Practice Questions
01

Summary
02
30

Solutions to Practice Questions


52

Glossary
00

Appendix
19

Objectives
R

Attainment Feedback (OAF)

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Table of Contents

About This Course

Prologue ------------------------------------------------------------------------------------ i
Description ---------------------------------------------------------------------------- i
Rationale------------------------------------------------------------------------------- i
Objectives ----------------------------------------------------------------------------- i

R
Entry Profile-------------------------------------------------------------------------- ii

KA
Exit Profile --------------------------------------------------------------------------- ii
Conventions ------------------------------------------------------------------------------ iii

R
SA
Chapter 1 – Overview of Java

A
R
Introducing Java ----------------------------------------------------------------------- 1.3
IT
Identifying the Features of Java -------------------------------------------------- 1.3
R

Java Architecture ------------------------------------------------------------------- 1.4


-A

Identifying the Building Blocks of a Java Program ----------------------------- 1.8


01

Defining a Class -------------------------------------------------------------------- 1.8


Identifying Data Types ----------------------------------------------------------- 1.10
02

Identifying Class Members ------------------------------------------------------- 1.11


30

Defining a Package ---------------------------------------------------------------- 1.19


Accessing Class Members ------------------------------------------------------------ 1.22
52

Using Objects ---------------------------------------------------------------------- 1.22


00

Using Access Specifiers ---------------------------------------------------------- 1.23


Using Access Modifiers ---------------------------------------------------------- 1.26
19

Practice Questions --------------------------------------------------------------------- 1.30


R

Summary -------------------------------------------------------------------------------- 1.31

Chapter 2 – Implementing Operators

Working with Operators -------------------------------------------------------------- 2.3


Using the Arithmetic Operators -------------------------------------------------- 2.4
Using the Assignment Operators ------------------------------------------------- 2.4
Using the Comparison Operators ------------------------------------------------- 2.5
Using the Logical Operators ------------------------------------------------------ 2.7
Using the Unary Operators -------------------------------------------------------- 2.8

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the Bitwise Operators------------------------------------------------------- 2.9
Using the Shift Operators --------------------------------------------------------- 2.13
Using the Ternary Operator ------------------------------------------------------ 2.15
Using Operator Precedence ---------------------------------------------------------- 2.16
Identifying the Order of Precedence--------------------------------------------- 2.16
Implementing Precedence Using Parentheses ---------------------------------- 2.17
Practice Questions --------------------------------------------------------------------- 2.18
Summary -------------------------------------------------------------------------------- 2.19

Chapter 3 – Working with Conditional and Loop Constructs

R
KA
Working with Conditional Constructs---------------------------------------------- 3.3

R
Using the if Construct -------------------------------------------------------------- 3.3

SA
Using the if…else Construct ------------------------------------------------------ 3.4
Using the switch Construct -------------------------------------------------------- 3.6
Working with Loop Constructs ------------------------------------------------------ 3.8

A
Using the for construct ------------------------------------------------------------- 3.8
R
Using the while Construct --------------------------------------------------------- 3.9
IT
Using the do…while Construct -------------------------------------------------- 3.10
R

Practice Questions --------------------------------------------------------------------- 3.12


-A

Summary -------------------------------------------------------------------------------- 3.13


01
02

Chapter 4 – Working with Arrays, Enums, and Strings


30
52

Manipulating Arrays ------------------------------------------------------------------- 4.3


Creating Arrays --------------------------------------------------------------------- 4.3
00

Accessing Arrays ------------------------------------------------------------------- 4.6


19

Manipulating Enums ------------------------------------------------------------------ 4.10


Declaring Enums ------------------------------------------------------------------- 4.10
R

Accessing Enums ------------------------------------------------------------------ 4.11


Manipulating Strings------------------------------------------------------------------ 4.13
Using String Class ----------------------------------------------------------------- 4.13
Using StringBuilder and StringBuffer Classes --------------------------------- 4.19
Practice Questions --------------------------------------------------------------------- 4.22
Summary -------------------------------------------------------------------------------- 4.23

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Chapter 5 – Implementing Inheritance and Polymorphism

Implementing Inheritance ------------------------------------------------------------ 5.3


Identifying the Various Types of Inheritance ----------------------------------- 5.3
Inheriting a Class ------------------------------------------------------------------- 5.5
Inheriting an Interface ------------------------------------------------------------- 5.9
Implementing Polymorphism ------------------------------------------------------- 5.13
Static Polymorphism -------------------------------------------------------------- 5.13
Dynamic Polymorphism ---------------------------------------------------------- 5.14
Practice Questions --------------------------------------------------------------------- 5.17

R
KA
Summary -------------------------------------------------------------------------------- 5.18

R
Chapter 6 – Handling Errors

SA
A
Handling Exceptions ------------------------------------------------------------------- 6.3
R
Exploring Exceptions -------------------------------------------------------------- 6.3
IT
Identifying Checked and Unchecked Exceptions ------------------------------ 6.5
R

Implementing Exception Handling ----------------------------------------------- 6.7


-A

User-defined Exceptions---------------------------------------------------------- 6.14


Using the assert Keyword ------------------------------------------------------------ 6.17
01

Understanding Assertions -------------------------------------------------------- 6.17


02

Implementing Assertions --------------------------------------------------------- 6.17


Practice Questions --------------------------------------------------------------------- 6.19
30

Summary -------------------------------------------------------------------------------- 6.20


52
00

Chapter 7 – Working with Regular Expressions


19
R

Processing Strings Using Regex ----------------------------------------------------- 7.3


Working with the Pattern and Matcher Classes -------------------------------- 7.3
Working with Character Classes ------------------------------------------------- 7.7
Working with Quantifiers --------------------------------------------------------- 7.8
Practice Questions --------------------------------------------------------------------- 7.12
Summary -------------------------------------------------------------------------------- 7.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Chapter 8 – Working with Streams

Working with Input Stream ---------------------------------------------------------- 8.3


Using the FileInputStream Class-------------------------------------------------- 8.3
Using the BufferedInputStream Class -------------------------------------------- 8.5
Using the FileReader Class -------------------------------------------------------- 8.7
Using the BufferedReader Class -------------------------------------------------- 8.8
Working with Output Stream ------------------------------------------------------- 8.11
Using the FileOutputStream Class ----------------------------------------------- 8.11
Using the BufferedOutputStream Class ----------------------------------------- 8.13

R
KA
Using the BufferedWriter Class-------------------------------------------------- 8.15
Using the FileWriter Class-------------------------------------------------------- 8.16

R
Practice Questions --------------------------------------------------------------------- 8.18

SA
Summary -------------------------------------------------------------------------------- 8.19

Solutions to Practice Questions


A
R
IT
R

Solutions to Practice Questions ------------------------------------------------------ S.1


-A

Chapter 1 ----------------------------------------------------------------------------- S.1


Chapter 2 ----------------------------------------------------------------------------- S.1
01

Chapter 3 ----------------------------------------------------------------------------- S.1


02

Chapter 4 ----------------------------------------------------------------------------- S.1


Chapter 5 ----------------------------------------------------------------------------- S.2
30

Chapter 6 ----------------------------------------------------------------------------- S.2


52

Chapter 7 ----------------------------------------------------------------------------- S.2


Chapter 8 ----------------------------------------------------------------------------- S.2
00
19

Glossary
R

Glossary --------------------------------------------------------------------------------- G.1

Appendix

Case Study 1: Hangman Game-------------------------------------------------------A.2


Case Study 2: EmployeeBook Application -----------------------------------------A.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
ABOUT THIS COURSE

R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Prologue

Description
The Introduction to Java course helps the students to get familiar with the Java programming language. It
discusses the classes, objects, strings, and arrays. In addition, the course discusses how to create graphical
user interfaces. Further, it discusses how to implement inheritance, polymorphism, error handling, and event
handling.
The course explains how to create a Java application. It focuses on enabling the students to create both, CUI-

R
based application and GUI-based application, by using Java. It provides details on declaring variables and

KA
literals and using arrays. In addition, the course discusses how to use conditional and looping statements.
Further, the course describes how to create nested classes, override methods, and create interfaces and

R
packages in Java.

SA
Rationale
A
R
Today, there are varied electronic devices available in the market. To work with these electronic devices,
IT
different applications are used. These applications are developed by using different programming languages,
such as C, C++, Java, and C#. However, the applications developed by using programming languages like C
R

and C++ do not support cross-platform portability.


-A

Java is an object oriented programming language that helps to develop real-life portable applications. We
01

can create both, CUI-based application and GUI-based application, by using Java. The code reusability
02

feature of Java enables software developers to upgrade the existing applications without rewriting the entire
code of the application.
30
52

Objectives
00

After completing this course, the students will be able to:


19

 Get familiar with Java


R

 Implement operators
 Work with conditional and loop constructs
 Work with arrays, enums, and strings
 Implement inheritance and polymorphism
 Handle errors
 Work with regular expressions
 Work with streams

NIIT About This Course i

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Entry Profile
The students who want to take this course should have basic knowledge of logic building and effective
problem solving.

Exit Profile
After completing this course, the students will be able to develop object-based applications in Java.

R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

ii About This Course NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Conventions

Convention Indicates…

Note

Just a minute

R
KA
R
SA
Placeholder for an activity

A
R
IT
R
-A
01
02
30
52
00
19
R

NIIT About This Course iii

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Overview of Java
CHAPTER 1

NIIT Introduction to Object-Oriented Programming 1.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The principles of object-oriented programming, such as modularity and reusability, are quite popular as they
help in reducing the complexity of programs. In order to implement such principles in real world
applications, such as library management and inventory management, you need to make use of an object-
oriented language, such as Java.
This chapter focuses on the fundamentals and building blocks of the Java programming language. In
addition, it explains how to access the class members.

Objectives

R
In this chapter, you will learn to:

KA
 Get familiar with Java
 Identify the building blocks of a Java program

R
 Access class members

SA
A
R
IT
R
-A
01
02
30
52
00
19
R

1.2 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Introducing Java
Sam works as a programmer at DailyGames Incorporation. He has been assigned the responsibility of
creating a jumbled word game named Classic Jumble Word. At the start of this game, the player should be
presented with a menu that provides various options, such as playing the game or reading game instructions.
When the game starts, the player should be presented with a jumbled-up word from a list of words that is
provided in the application. Then, the player needs to identify the correct word corresponding to the given
word. As per the requirements, the game must be compatible across various operating systems, such as
Windows and Linux. Moreover, the code of the game should be efficiently written to ensure minimum
complexity.
To cater to the preceding requirements, Sam uses the Java programming language. The creator of Java is the

R
Sun Microsystems’ chief programmer, James Gosling. In 1991, he and his team started a project to develop

KA
software for controlling and programming consumer electronic devices, such as televisions, by using a
device, a handheld remote control. Gosling liked the basic syntax and object-oriented features of C++.

R
Therefore, he framed his new language on the same lines as that of C++. The result was a new programming

SA
language called Oak, later renamed as Java, which could run on heterogeneous platforms.
Due to its powerful features and underlying architecture, Java is used widely as a programming language to

A
create efficient console or Graphical User Interface (GUI) based applications that can run on a single
R
computer or on a network of computers.
IT
R

Identifying the Features of Java


-A
01

Java provides powerful features that make it a popular and widely used programming language. Some of
these features are:
02

 Simple: When an object of a class is created, memory needs to be allocated. Later on, when the object is
30

no longer required, the allocated memory to the object should be released. In Java, memory allocation
and deallocation happens automatically. The process of automatically deallocating memory is called
52

garbage collection.
00
19

Note
One of the major problem areas in most of object-oriented languages, such as C++, is
R

to handle memory allocation. Programmers need to handle memory in the program


explicitly for optimum utilization. To handle memory allocation, they use pointers that
enable a program to refer to a memory location of the computer. However, Java does
not support pointers and consists of the built-in functionality to manage memory.

 Object-oriented: Java is an object-oriented language and it incorporates the various characteristics of an


object-oriented language, such as inheritance and polymorphism. In Java, the entire program code must
be encapsulated inside a class. Even the most basic program in Java must be written within a class.
Furthermore, Java uses objects to refer to real world entities, such as a game or a game player..

NIIT Overview of Java 1.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
 Platform independence: In Java, when you compile an error-free code, the compiler converts the
program to a platform independent code, known as the bytecode. Thereafter, the Java Virtual Machine
(JVM) interprets this bytecode into the machine code that can be run on that machine. Converting a Java
program into bytecode makes a Java program platform independent because any computer installed with
the JVM can interpret and run the bytecode.

Note
Each platform needs to have its own JVM to interpret and run bytecode for that
platform.

R

KA
Portable: Portability refers to the ability of a program to run on any platform without changing the
source code of the program. The programs developed on one computer can run on another computer,

R
which might have a different operating system. Java enables the creation of cross-platform programs by
converting the programs into Java bytecode.

SA
 Distributed: Java can be used for the development of those applications that can be distributed on
multiple machines in a network, such as the Internet. These applications can be used by multiple users

A
from multiple machines in a network. For this purpose, Java supports the various Internet protocols, such
R
as Transmission Control Protocol and Internet Protocol (TCP/IP) and Hyper Text Transfer Protocol
IT
(HTTP).

R

Secure: Java has built-in security features that ensure that a Java program gains access to only those
resources of a computer that are essential for its execution. This ensures that a Java program executing
-A

on a particular machine does not harm it.


01

 Robust: Java provides various features, such as memory management and exception handling, which
make it a robust programming language. These features ensure that the Java applications run securely
02

and effectively on a machine and do not crash a machine if minor errors are encountered.
30

 Multithreaded: Java provides the concept of multithreading that allows a program to simultaneously
execute multiple tasks by using threads. A thread is the smallest unit of execution in a Java program.
52
00

Java Architecture
19

The Java architecture defines the components that are essential to carry out the creation and execution of
R

code written in the Java programming language. The various components of the Java architecture are:
 Source file
 Class file
 JVM
 Application Programming Interface (API)

1.4 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The various components in the Java architecture are shown in the following figure.

R
KA
R
SA
A
R
IT
Various Components in the Java Architecture
R
-A

Source File
01

Java is a robust programming language that enables developers to build a wide variety of applications for
02

varying purposes. In order to write a Java program or an application, you need to write certain code. A Java
application contains the source code that enables an application to provide its desired functionalities. This
30

source code is saved in a source file with the extension, .java.


52

Class File
00

Once created, a .java file is compiled to generate the .class file. A class file contains the bytecode that is
19

generated by the compiler. Further, this class file can be executed by any machine that supports the Java
Runtime Environment (JRE).
R

JVM
The JVM is an application that is responsible for executing Java programs on a computer. It resides in the
Random Access Memory (RAM) and is specific for every platform, such as Sun and Macintosh. The
bytecode generated during the compilation of a program is the machine language of the JVM. JVM is
responsible for executing the bytecode and generating the machine specific code for the machine on which
the Java program needs to be executed.

NIIT Overview of Java 1.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The major components of JVM are:
 Class loader
 Execution engine and Just-In-Time (JIT) compiler
 Bytecode verifier

Class Loader
The class loader loads the class files required by a program that needs to be executed. The classes are loaded
dynamically when required by the running program.

Execution Engine and JIT Compiler

R
The Java execution engine acts as an interpreter that interprets the bytecode one line after another and

KA
executes it. The line-by-line interpretation is a time-consuming task and reduces the performance of a
program. To enhance the performance, the JIT compiler has been introduced in the JVM. The JIT compiler

R
compiles the bytecode into machine executable code, as and when needed, which optimizes the performance

SA
of a Java program.

Bytecode Verifier
A
R
Before being executed by the JVM, the bytecode is verified by using the bytecode verifier. The bytecode
IT
verifier ensures that the bytecode is executed safely and does not pose any security threat to the machine.
R

API
-A

The Java API is a collection of software components, such as classes, interfaces, and methods, which
01

provides various capabilities, such as GUI, Date and Time, and Calendar. The related classes and interfaces
02

of the Java API are grouped into packages.


30
52

Note
00

A package is a container of classes.


19
R

1.6 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one of the following features of Java allows a program to simultaneously
execute multiple tasks?
1. Multithreading
2. Portability
3. Distributed

R
4. Garbage collection

KA
Answer:

R
1. Multithreading

SA
A
R
IT
R
-A
01
02
30
52
00
19
R

NIIT Overview of Java 1.7

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Identifying the Building Blocks of a Java Program
Consider the scenario of DailyGames. In order to develop the Classic Jumble Word application and achieve
its desired functionality, Sam needs to build a Java program. A program in Java comprises the following
building blocks:
 Classes
 Data types
 Class members
 Packages

R
KA
Defining a Class

R
A class defines the characteristics and behavior of an object. For example, if you create a gaming application,

SA
each game that a user can play from the application can be considered as an object of the Games class. Each
game has common characteristics, such as the number of players, game category, and score. These
characteristics are known as the member variables, and the behavior is specified by methods. Any concept

A
that you need to implement in a Java program is encapsulated within a class. A class defines the member
R
variables and methods of objects that share common characteristics. Further, all the games have common
IT
methods, such as calculating score, starting the game, and displaying game instructions.
R

The following code snippet shows how to declare a class:


-A

class <ClassName>
01

{
//Declaration of member variables
02

//Declaration of methods
}
30
52

Note
00

In Java, a semicolon is used to mark the end of a statement.


19
R

In the preceding code snippet, the word, class, is a keyword in Java that is used to declare a class; and
<ClassName> is the name given to the class.

Sam can use the following code snippet to create the ClassicJumble class to develop the Classic Jumble
Word game:

class ClassicJumble {
//Declaration of member variables
//Declaration of methods
}

1.8 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
There are certain rules that should be followed to name Java classes. A program will raise error if these rules
are not followed. Some of these rules are:
 The name of a class should not contain any embedded space or symbol, such as ?, !, #, @, %, &, {}, [], :,
;, “, and /.
 A class name must be unique.
 A class name must begin with a letter, an underscore (_), or the dollar symbol ($). Or, it must begin with
an alphabet that can be followed by a sequence of letters or digits (0 to 9), ‘$’, or ‘_’.
 A class name should not consist of a keyword.
While naming a class, you should adhere to the following class naming conventions that improve the
readability of a program:
 The class name should be a noun.

R
KA
 The first letter of the class name should be capitalized.
 If the class name consists of several words, the first letter of each word should be capitalized.

R
Keywords are the reserved words with a special meaning for a language, which express the language

SA
features. Keywords cannot be used to name variables or classes. Java is a case-sensitive language, and the
keywords should be written in lowercase only. The following table lists the Java keywords.

A
abstract boolean break
R class
IT
R

case catch char do


-A

const continue default final


01

double else extends goto


02
30

finally float for instanceof


52

if implements import native


00

int interface long protected


19

new package private static


R

public return short synchronized

strictfp super switch transient

this throw throws while

try void volatile

enum assert byte

Set of Keywords in Java

NIIT Overview of Java 1.9

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
After defining a class, you need to save the file before it can be executed. The following naming conventions
should be followed for naming a Java file:
 A file name must be unique.
 A file name cannot be a keyword.
 If a class is specified as public, the file name and class name should be the same.
 If a file contains multiple classes, only one class can be declared as public. The file name should be the
same as the class name that is declared public in the file.
 If a file contains multiple classes that are not declared public, any file name can be specified for the
file.

R
Note

KA
In Java, class names are case-sensitive. For example, vehicle is not the same as
Vehicle.

R
SA
Identifying Data Types
A
R
IT
While working with an application, you need to store and manipulate varying data. For example, in the
R

Classic Jumble Word game, the game score is a numeric value and the player name is a string. To handle
-A

such varying data in an application, Java supports various data types. There are eight primitive data types in
Java, which are further grouped into the following categories:
01

 Integer type: Can store integer values. The four integer data types are:
02

 byte
 short
30

 int
52

 long
The following table lists the integer primitive data type, its data types, size, range, and default values.
00
19

Group Data Type Size Range Default


R

Value

Integer byte 1 byte -27 to 27-1 0

short 2 bytes -215 to 215 -1 0

int 4 bytes -231 to 231-1 0

long 8 bytes -263 to 263-1 0

The Details of the Integer Primitive Data Type

1.10 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
 Floating point type: Can store decimal numbers. The two floating point types are:
 float
 double
The following table lists the floating point primitive data type, its data types, size, range, and default
values.

Group Data Type Size Range Default


Value

Floating point float 4 bytes 3.4e-038 to 3.4e+038 0.0

R
double 1.7e-308 to 1.7e+308

KA
8 bytes 0.0

R
The Details of the Floating Point Data Type

SA
 Boolean type: Can store only the values, true and false.
 Character type: Can store a single character, such as a symbol, letter, and number. In the character
type, there is one data type, char. To a character data type, 2 bytes of memory is allocated.

A
R
IT
Note
R

To store string values, you need to use built-in classes, such as, String,
-A

StringBuilder, and StringBuffer.


01
02

Wrapper Classes
30

Variables that are declared by using the primitive data types are not objects. The primitive data types, such as
int and char, are not a part of the object hierarchy. Therefore, in order to use the primitive data types as
52

objects, Java provides wrapper classes. A wrapper class acts like an object wrapper and encapsulates the
primitive data types within the class so it can be treated like an object.
00

The various wrapper classes, such as Boolean, Character, Integer, Short, Long, Double, and Float,
19

are provided by the java.lang package. These classes are useful when you need to manipulate primitive
R

data types as objects.

Identifying Class Members


In Java, a class can contain the following members:
 Variables
 Methods
 Objects
 Inner classes

NIIT Overview of Java 1.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Variables
A variable is used essentially as a container for the storage of varying kinds of data. The main use of a
variable is to store and manipulate data or values that are used in Java programs. A variable represents a
name that refers to a memory location where some value is stored. You can assign varying values to a
variable during program execution. However, the data type of the value must be the same as the data type of
the variable. In Java, each variable that is used in a program must be declared with a data type.
A variable needs to be declared before it is accessed. The declaration of a variable informs the compiler
about the variable name and the type of value stored in it. The following code snippet shows how to declare a
variable:

<type> <variablename>; // Single variable of given type.

R
<type> <variable1name,variable2name.....variable_n_name>;// Multiple
variables of given type.

KA
For example, in the Classic Jumble Word game, upon the start of the game, the user needs to be presented

R
with a menu. The menu will present the user with the options to determine if the user wishes to play the

SA
game, read game instructions, or exit. The user can enter 1, 2, or 3 to refer to the preceding choices. In such a
case, you can use a variable named choice to store user input to determine the course of the execution of the
game. You can use the following code snippet to declare a variable:

A
int choice;
R
IT
You can refer to a variable by using its name in a program. You can assign values to a variable during
R

declaration or after the declaration of the variable. For example, you can use the following code snippet to
-A

declare the variable, num1 and num2, to calculate the sum of two numbers:
01

int num1, num2;


02

The following code snippet shows how to assign values to a variable:


30

<type> <variablename>=<value>; // During declaration.


<variablename>=<value> // After declaration.
52

For example, you can use the following code snippet to assign values to the variables, num1 and num2:
00

int num1, num2; // Declaration of variables.


19

num1 = 5; // Assigning values to the variables.


num2 =10;
R

The following code snippet can be used to assign a value to a variable at the time of its declaration.

int num1=5;
You can also assign the same value to more than one variable in a single statement. The following code
snippet shows the assignment of the same value to more than one variable:

a=b=c=3;

In the preceding code snippet, the integer value, 3, is first assigned to c, then to b, and finally to a.

1.12 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Note
By default, when a member variable is declared in a class but not initialized, it is
assigned a default value. For example, an integer member variable is assigned the
value, 0, by default.

Note
In Java, the rules for naming a variable are similar to the rules for naming a class.

R
KA
To understand the type of values that a variable can contain, you need to understand the concept of literals.

R
A literal is a value that is assigned to a variable or constants in a Java program. A literal contains a sequence

SA
of characters, such as digits, alphabets, or any other symbol, which represents the value to be stored. The
various types of literals in Java are:

A
 Integer literals: Are non-fractional numeric values. The numerical values can be represented in the
R
decimal, octal, and hexadecimal notation. In order to represent an octal number, it is preceded by zero.
IT
In order to represent hexadecimal numbers, they are prefixed by 0x. For example, n=0567 is integer
literal represented in the octal notation whereas n=0x124 represents an integer literal in hexadecimal
R

notation.
-A

 Floating point literals: Are numeric values that contain a fractional part. The floating point literals
01

contain a decimal and an integer part. For example, z=2.2 represents a floating point literal.
 Character literals: Are represented inside a pair of single quotation marks. For example, x='k' is a
02

character literal.
30

 String literals: Are enclosed in a pair of double quotation marks. For example, x="James" is a string
literal.
52

 Boolean literals: Are the literals that can contain the values, true or false. For example, x= false is a
00

boolean literal.
19

 Binary literals: Are the literals that can be used to express the primitive integer data types into binary
form. In order to specify these literals, you need to prefix the binary number with 0b or 0B. For
R

example, 0b101.

Note
The integer and floating point literals can also contain the ‘_’ character.

NIIT Overview of Java 1.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Methods
A method is a set of statements that is intended to perform a specific task. For example, a compute()
method can be used for computing the score. Moreover, methods provide encapsulation and are also essential
to refer to the data members and access them. A method consists of two parts, method declaration and
method body.
The syntax for defining a method is:

<Access specifier> <Return type> <Method name>(Parameter list) //method


declaration
{
<Method body> // body of the method
}

R
KA
In the preceding syntax, the first line depicts the method declaration and the contents within the curly braces
depict the method body. According to the preceding syntax, the various elements of a method are:

R
 Access specifier: Determines the extent to which a method can be accessed from another class.

SA
 Return type: A method can also return a value. The return type specifies the data type of the value
returned by a method. Some methods do not return any value. Such methods should use the void return
type. The value to be returned by the method is specified with the keyword, return.
 Method name: Is a unique identifier and is case-sensitive.
A
R
IT
 Parameter list: A method may or may not contain a parameter list depending upon its functionality. The
parameter list consists of a list of parameters separated by commas. Parameters are used to pass data to a
R

method. The parameter list is written between parentheses after the method name. The parentheses are
-A

included even if there are no parameters.


01

 Method body: This contains the set of instructions that perform a specific task. The variables declared
inside the method body are known as local variables.
02

While adding a method to a class, you should adhere to the following method naming conventions:
30

 The method names should be verb-noun pairs.


52

 The first letter of the method should be in lowercase.


 If the method name consists of several words, the first letter of each word, except the first word, should
00

be capitalized.
19

Consider the following code snippet:


R

class ClassicJumble {
int score;
public int startGame(){
int choice;

System.out.println("***********JUMBLE GAME************");
System.out.println("GAME MENU");
System.out.println("Please select an option from the menu");
System.out.println("1. Play Game");
System.out.println("2. Instructions");
System.out.println("3. Quit Game");
System.out.println("\nEnter your choice: ");

1.14 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.


return choice;
compute();
}
}

In the preceding code snippet, a method named startGame() is defined. This method displays the game
menu options for the Classic Jumble Word game application and returns the choice of the user. To get the
input from a user, you can use the Scanner class in Java. This class is contained in the java.util package
and must be imported in a program before it is used. The following code snippet can be used to import the
Scanner class in a Java program:

import java.util.Scanner;

R
KA
The variable, score, is defined inside the class body, but outside the startGame() method. Such variables,
which are defined inside the class body without the static modifier but outside the body of any method inside

R
a class, are called instance variables. The scope of the instance variables spans across the entire class, and

SA
they can be used by the class methods. The variables defined inside a method of a class are called local
variables. The scope of local variables is within the block of code in which they are defined. They are local
to the block of code and are not accessible outside the method.

A
R
IT
Note
R

The static modifier is explained later in the chapter.


-A
01

To execute a method, you need to invoke the same. When a method is invoked from a Java program, the
02

control is transferred to that method. The syntax for calling a method is:
30

<Method name>(argument list);


52

The argument list is to be specified if the method uses a parameter list in its implementation. The following
code snippet can be used to invoke the startGame() method:
00

startGame();
19

Usually, an application involves the invoking of multiple methods. Further, a method may also be invoked
R

by another method. The invoked methods are managed by a stack. For example, in the Classic Jumble Word
application, the startGame() method is the first to be executed after the main() method, and it displays
the game menu to the user. The startGame() method will further invoke the compute() method that will
identify the game menu input by the user and respond accordingly.

NIIT Overview of Java 1.15

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure represents the stack of method calls for the main(), startGame(), and compute()
methods.

R
KA
R
SA
A
R
IT
The Stack of Method Calls
R

In object-oriented languages, when you instantiate a class, special methods called constructors are
-A

automatically called. Constructors are methods that have the same name as that of the class and have no
return type. Constructors are used to construct an object of a class and initialize it.
01

Consider the following code snippet:


02

class ClassicJumble
30

{
52

int score;
ClassicJumble()
00

{
score= 10 ;
19

}
}
R

In the preceding code snippet, a constructor named ClassicJumble is created. This constructor will
initialize the score member variable with the value, 10, whenever an object is created. Classes can also
have parameterized constructors. You can pass parameter values to such constructors. These parameter
values are usually assigned to the attributes of the class before creating an object of the class. The syntax for
declaring a parameterized constructor is:

className (datatype parameter1, datatype parameter2..)


{
// code to construct the object
}

1.16 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
For example, you can create a parameterized constructor for the Square class, as shown in the following
code snippet:

class Square
{
int length;
Square(int l)
{
length = l ;
}
int area()
{
return length*length;
}

R
}

KA
Objects

R
SA
An object is an instance of a class and has a unique identity. The identity of an object distinguishes it from
other objects. Classes and objects are closely linked to each other. While an object has a unique identity, a
class is an abstraction of the common properties of various objects. To create an object, you need to declare,

A
and then, instantiate an object. Declaring an object creates a variable that will hold the reference to the
R
object. The following code snippet shows how to declare an object of the class:
IT
class_name object_name;
R
-A

When you declare an object, the memory is not allocated to it. To allocate memory to the object, you need to
instantiate the object by using the new operator. The new operator allocates memory to an object. It also
01

returns a reference to that memory location in the object variable. The following code snippet shows how to
create an object:
02

object_name= new class_name();


30

You can declare and instantiate an object in a single statement. You can use the following code snippet to
52

declare and instantiate an object, GameObject, of the ClassicJumble class in a single statement:
00

ClassicJumble GameObject = new ClassicJumble();


19

You can use the following code snippet to create three game objects of the ClassicJumble class:
R

ClassicJumble GameObject1 = new ClassicJumble();


ClassicJumble GameObject2 = new ClassicJumble();
ClassicJumble GameObject3 = new ClassicJumble();

NIIT Overview of Java 1.17

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Note
After importing the Scanner class, you need to create its object by using the following
code snippet:

Scanner <objectname> = new Scanner(System.in);

Then, the predefined methods of the Scanner class, such as nextInt() and
nextLine() can be used to read an integer or a string value, respectively. The
following code snippet can be used to read a string value and store it in a string
reference named option:

R
KA
String option = <objectname>.nextLine();

R
Inner Classes

SA
In Java, a class can also contain another class. Such a class is known as an inner class or a nested class. The
class that contains the inner class is known as an outer class. The concept of an inner class is shown in the

A
following figure. R
IT
R
-A
01
02
30
52

The Concept of an Inner Class


00

The concept of inner classes has the following benefits:


19

 It improves encapsulation as a class can be hidden inside another class.


R

 It provides a better readability.


 It is useful for logically grouping classes.
The following code snippet demonstrates an inner class:

class outerclass
{

class innerclass
{

}
}

1.18 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following types of inner classes can be created in Java:
 Regular inner class: A regular inner class has complete access to all the members of the outer enclosing
class. It is contained within the outer class.
 Static nested class: A static nested class is like a regular inner class. It is defined with the keyword,
static. However, in order to create an object of the inner class, it is not necessary to instantiate the
outer class.
 Method-local inner class: A method-local inner class is a class that is defined inside a method
contained in the outer class. A method local inner class also needs to be instantiated inside the method in
which it is defined.
 Anonymous inner class: An anonymous inner class is an inner class that has no name.

R
KA
Defining a Package

R
A package is a collection of classes. A package provides the space essentially used to organize classes that

SA
are related to each other. You can create multiple packages to organize multiple categories of classes, as per
the requirement. Moreover, packages ensure that the non-related classes with the same name do not conflict
with each other. A class can belong only to one package. For example, a package named GameConsole can

A
be used to create and store a class named Game1. This will ensure that the Game1 class does not conflict with
R
any that has the same name and is stored somewhere else. The following syntax is used to define a package:
IT
package <package_name>;
R
-A
01

Note
Packages are represented and stored by Java as directories in the file system.
02
30
52
00
19
R

NIIT Overview of Java 1.19

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure represents the concept of packages in Java.

R
KA
R
SA
A
R
IT
R
-A
01
02
30
52

The Concept of Packages


00

In the preceding figure, the packages, PersonalVehicles and CargoVehicles, represent the category of
19

those vehicles that are used for personal use and commercial transport, respectively. The
PersonalVehicles package contains the Bike and Car classes. The CargoVehicles package contains the
R

Ship and the Truck classes that further comprise their respective class members and methods.

1.20 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one of the following types of literals can be specified only by values, true or
false?
1. String
2. Boolean
3. Integer

R
4. Floating point

KA
Answer:

R
2. Boolean

SA
A
R
IT
R
-A
01
02
30
52
00
19
R

NIIT Overview of Java 1.21

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Accessing Class Members
The class members describe the characteristics and behavior of an object. You may need to hide or protect
certain class members from other classes in a Java application. In other words, you may want to restrict
access to sensitive data that belongs to a class so that it is not modified. Moreover, restricting access to the
members of a class is a way of achieving information hiding or encapsulation and ensuring that the intended
functionality of a class is not modified.
For example, in the Classic Jumble Word game application, you might need to hide sensitive information
outside the ClassicJumble class, such as the jumbled-up words to be displayed to the game user. To cater
to such requirements and improve the security of a class, you can use access specifiers and modifiers in Java.

R
The access specifiers and modifiers provided in the Java programming language are used to identify the part

KA
of the class, such as data members and methods that needs to be accessed by other class objects. Further, it is
also useful for deciding the behavior of data members when they are used in other classes and objects.

R
SA
Using Objects

A
Objects are used to access the members of a class. You can access the data members of a class by specifying
R
the object name followed by the dot operator and the data member name. The following code snippet shows
IT
how to access the data members of a class:
R

object_name.data_member_name
-A

In the preceding code snippet, object_name refers to the name of the object and data_member_name
01

refers to the name of the data variable inside the class that you want to access.
02

To access data members of the ClassicJumble class, such as choice, and access the member through the
object, obj1, you can use the following code snippet:
30

class ClassicJumble {
52

int choice=1;
00

public static void main(String[] args) {


ClassicJumble obj1 = new ClassicJumble();
19

System.out.println(obj1.choice);
R

}
}

Note
Whenever you execute a Java application, the main() method is the first to be
executed by the JVM.

1.22 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Similar to variables, the member method of a class is also accessed by using objects, as shown in the
following code snippet:

class ClassicJumble {
int choice;
void show()
{
System.out.println(choice);
}
public static void main(String[] args) {
ClassicJumble obj1 = new ClassicJumble();
obj1.show();
}
}

R
KA
In the preceding code snippet, the ClassicJumble class contains the show() method that displays the
value of the variable, choice. The show() method is called by the object, obj1.

R
SA
Using Access Specifiers

A
An access specifier controls the access of class members. The various types of access specifiers in Java are:
R
 private
IT
 protected
R

 public
-A
01

The private Access Specifier


The private access specifier allows a class to hide its member variables and member methods from other
02

classes. Therefore, the private members of a class are not visible outside a class. They are visible only to the
30

methods of the same class. Therefore, the data remains hidden and cannot be altered by any method other
than the member methods of the class. If a variable or method is declared private, it can be accessed only
52

within its enclosing class. A top level class cannot be declared private in Java. However, an inner class can
be declared private.
00

The following code snippet shows how to declare a private data member of a class:
19

private <data type> <variable name>;


R

The following code snippet shows how the private access specifier can be implemented in the
ClassicJumble class for the score variable:

class ClassicJumble {
private int score;
void show()
{
}
}

NIIT Overview of Java 1.23

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code snippet, the score variable has been specified with the private access specifier.
The score variable can be accessed anywhere in the ClassicJumble class, but it is not accessible to
other classes.

The protected Access Specifier


The members of a class that are preceded with the protected access specifier are accessible to all the
classes within the package and by the subclasses outside the package. The protected access specifier
becomes important while implementing inheritance..

Note

R
Inheritance will be discussed in detail in the later chapters.

KA
R
The following statement shows how to declare a member as protected:

SA
protected <data type> <name of the variable>;

A
Consider the following code snippet: R
class ClassicJumble {
IT
protected int score;
R

void show()
{
-A

}
01

}
02

In the preceding code snippet, the score variable is declared as protected. It can, therefore, be accessed
within the ClassicJumble class from the classes that will inherit the from ClassicJumble class. It can
30

also be accessed within the classes of the package that contains the ClassicJumble class.
52

The public Access Specifier


00

The members of a class that are preceded with the public access specifier are accessible by the classes
19

present within the package or outside the package. You can access a public class, data member, or method
within the class in which they are defined, from the classes defined in the same package or outside the
R

package. The following code snippet shows how to declare a data member of a class as public:

public <data type> <variable name>;

The following code snippet shows how the public access specifier can be implemented in the
ClassicJumble class for the choice variable:

class ClassicJumble {
public int choice;
void show()
{
System.out.println(choice);
}
}

1.24 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code snippet, the choice variable has been specified with the public access specifier.
The choice variable can be accessed anywhere in the ClassicJumble class. It is also accessible in the
package in which the ClassicJumble class is created, or in a package that is different from the one where
the ClassicJumble class exists.
In addition to the public, private, and protected access specifiers, the class members can have a
default access. If you do not specify any of the preceding access specifiers, the scope of data members and
methods is default or friendly. A class, variable, or a method with a friendly access can be accessed only by
the classes that belong to the package in which they are present.

Note

R
The variables inside a method cannot be specified with any access specifier.

KA
R
SA
The following figure can be used to understand the usage of access specifiers in Java.

A
R
IT
R
-A
01
02
30
52
00
19
R

An Overview of the Usage of Access Specifiers

NIIT Overview of Java 1.25

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The accessibility of the variables mentioned in the preceding figure is described in the following table.

Variable Access specifier Accessible by

color public Vehicle, Car, Bicycle, Ship,


and Truck classes

speed private Vehicle class

model protected Vehicle, Car, and Ship


classes

R
KA
year default access All the classes of the
PersonalVehicles package

R
SA
The Usage of Access Specifiers

A
Note R
The hierarchy for the access specifiers arranged from the least restrictive level to the
IT
most restrictive level is public, protected, default access, and private.
R
-A
01
02

Using Access Modifiers


30

Access modifiers are useful to determine or define the manner in which data members and methods are
52

utilized in other classes and objects. The access modifiers determine how the members are used and modified
00

by other classes. In comparison to the access modifiers, access specifiers define the accessibility of the data
members of a class. The various modifiers permitted in Java are::
19

 final
R

 static
 abstract
 native
 synchronized
 transient
 volatile
 strictfp

1.26 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
final
The final keyword is applicable to methods, variables, and classes. The final keyword cannot be used
with an interface in Java. When used with a data member, the final keyword represents that the data
member definition or value cannot be further replaced or modified. For example, consider a variable that has
been assigned a specific value. If you try to modify the value of a variable that is declared as final, it will
cause compile-time errors. Furthermore, a class that is declared as final cannot be used for the purpose of
inheritance, and a method declared as final cannot be overridden.

Note
An interface is a collection of abstract methods and data members. They are covered in

R
detail in a later chapter.

KA
R
SA
Note
Method overriding is discussed in a later chapter.
A
R
IT
R

static
-A

The static keyword is applicable to methods, variables, and inner classes. The static keyword is used to
01

denote those class variables and methods that belong specifically to a class and not to any of its particular
objects. Therefore, if any method modifies the value of a static variable, it can be seen by all the other
02

instances. The static variables are allocated only once. Therefore, when an instance of a class is destroyed,
30

the static variable is not destroyed and remains available to other instances of that class.
52

A static method associates the data members with a class and not with the objects of the class. Therefore, all
the objects of a class share the same static data members and methods. A static method is a class method and
00

can be invoked before the instance of a class is created.


19

For example, the main() method is a static method and can be invoked without creating an instance of the
class to which the main() belongs.
R

abstract
The abstract keyword is essentially used for the declaration of those classes that define only the common
properties and behavior that can be utilized in other classes. A class declared as abstract cannot be
instantiated. The abstract class contains the declaration of methods. You can also use the abstract keyword
with methods. An abstract method is declared without its implementation details. An abstract method is
overridden by classes that inherit an abstract class.

NIIT Overview of Java 1.27

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
For example, for the Classic Jumble word application, you can create an abstract class named Game with
abstract methods, as shown in the following code snippet:

abstract class Game {


int score;
abstract void startGame();
abstract void jumble();
abstract void play_again();
abstract void compute();

native

R
The native keyword can be specified only with methods to notify the compiler that the method

KA
implementation is not written in the Java programming language but in another language, such as C or C++.
The native keyword with a method indicates that the method needs to be imported in the JRE and as it is

R
present outside the JRE.

SA
The following code snippet shows how to declare a native modifier:

A
public native void nativeMethod(var1, var2, . . .) ; R
IT
Note
R

The native method makes a program platform dependent. In addition, writing native
-A

methods must be avoided. They are used when you have an existing code in another
01

language and do not want to rewrite the code in Java.


02

synchronized
30

The synchronized keyword is used for methods to control their access in a multithreaded programming
52

environment. A thread represents the smallest unit of execution within a process. In the multi-threaded
environment of Java, each thread defines a separate path of execution.
00

The synchronized keyword can be used in a multithreaded program to ensure that only a single thread is
19

allowed access to a shared resource when two or more threads need access to that resource at the same time.
A synchronized block of code restricts its execution by one or more threads at the same time. For example,
R

when synchronization is applied to a variable, then, only one thread at a time can access the variable.

transient
In Java, the properties and state of an object can be saved by using a technique named serialization. The
keyword, transient, can be used to control serialization as it specifies the object properties that can be
excluded from serialization. The object properties or attributes marked as transient will not be saved to
disk.

1.28 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
volatile
The volatile keyword is used with a variable to specify that its value is updated almost every time it is
accessed. Therefore, the volatile keyword prevents the Java compiler from tracking the changes that are
made to a variable that is specified as volatile. In case of a multithreaded program, the volatile variable
specifies that its value can be modified by multiple threads at undetermined intervals.

strictfp
The strictfp keyword can be used with a method or a class. This keyword specifies that the floating point
calculations carried out in a class are as per the specifications of Java. This keyword can be used to ensure
that the floating point computations can result precisely on varying platforms.

R
KA
R
SA
Just a minute:
Which one of the following options is called automatically when a class is instantiated?
1. Constructor
A
R
2. Variable
IT
R

3. Abstract method
-A

4. Package
01

Answer:
02

1. Constructor
30
52

Activity 1.1: Creating and Executing a Class


00
19
R

NIIT Overview of Java 1.29

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following options is the correct extension of a Java source file?
a. .jav
b. .java
c. .JAVA
d. .class

2. Which one of the following keywords controls the access to a block of code in a multithreaded
programming environment?

R
KA
a. synchronized
b. native

R
c. volatile

SA
d. abstract

3. Which one of the following keywords is used to inform the compiler that the method has been coded in a
programming language other than Java?
A
R
IT
a. synchronized
native
R

b.
-A

c. volatile
d. abstract
01
02

4. Which one of the following access specifiers represents the least restrictive level of access?
a. private
30

b. public
52

c. protected
00

d. default access
19

5. Which one of the following literals is specified by using single quotation marks?
R

a. string
b. character
c. float
d. integer

1.30 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
 Java provides powerful features that make it a popular and widely used programming language. Some of
these features are:
 Simple
 Object-oriented
 Platform independence
 Portable

R
Distributed

KA
 Secure
 Robust

R
 Multithreaded

SA
 The various components of the Java architecture are:
 Source file

A
 Class file R
 JVM
IT
 API
R

 A program in Java comprises the following building blocks:


-A

 Classes
01

 Data types
02

 Class members
 Packages
30

 A class defines the characteristics and behavior of an object.


52

 Keywords are the reserved words with a special meaning for a language, which express the language
features.
00

 There are eight primitive data types in Java, which are further grouped into the following categories:
19

 Integer type
R

 Floating point type


 Boolean type
 Character type
 A wrapper class acts like an object wrapper and encapsulates the primitive data types within the class so
it can be treated like an object.
 In Java, a class can contain the following members:
 Variables
 Methods
 Objects
 Inner classes

NIIT Overview of Java 1.31

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
 A variable represents a name that refers to a memory location where some value is stored.
 A method is a set of statements that is intended to perform a specific task.
 Constructors are used to construct an object of a class and initialize it.
 An object is an instance of a class and has a unique identity.
 A package is a collection of classes.
 Objects are used to access the members of a class.
 An access specifier controls the access of class members. The various types of access specifiers in Java
are:
 private
 protected

R
 public

KA
 Access modifiers determine or define how the data members and methods are used in other classes and
objects.

R
 The various modifiers permitted in Java are:

SA
 final
 static
 abstract

A
 native
R
IT
 synchronized
 transient
R

 volatile
-A

 strictfp
01
02
30
52
00
19
R

1.32 Overview of Java NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Implementing Operators
CHAPTER 2

NIIT Introduction to Object-Oriented Programming 1.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Operators allow you to perform various mathematical and logical calculations, such as adding and
comparing numbers.
In addition, if there are multiple operations that need to be performed in an expression, each operator in an
expression is evaluated in a predetermined order called operator precedence.
This chapter discusses different types of operator used in Java. In addition, it discusses operator precedence.

Objectives

In this chapter, you will learn to:

R
 Work with operators

KA
 Use operator precedence

R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

2.2 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Working with Operators
In the Classic Jumble Word game, Sam needs to calculate the number of attempts in which a user gives the
correct answer for a jumbled word. To implement this, the application should validate the user input and
increment the counter by one on each attempt the user provides an incorrect input. For such calculations and
comparisons, Java provides various types of operators. An operator is a special symbol that is combined with
one or more operands to perform specific operations, and then return a result.
Consider the following expression:

X+Y

R
In the preceding expression, X and Y are operands, and + is an operator. The following figure shows the

KA
operator and operands used in the preceding expression.

R
SA
A
R
IT
R
-A
01
02

The Operator and Operands


30

The following types of operators are supported in Java:


52

 Arithmetic operators
 Assignment operators
00

 Comparison operators
19

 Logical operators
R

 Unary operators
 Bitwise operators
 Shift operators
 Ternary operator

NIIT Implementing Operators 2.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on operands.
The following table describes the arithmetic operators.

Operator Operator Description Example


Name (In the following examples, the
value of Y is assumed to be 20 and
the value of Z is assumed to be 2)

R
+ Plus Used to add two numbers. Y+Z;

KA
will return the value, 22.

R
- Minus Used to subtract two Y-Z;

SA
numbers. will return the value, 18.

* Multiply Used to multiply two Y*Z;


numbers.
A will return the value, 40.
R
IT
/ Divide Used to divide one number by Y/Z;
R

another. will return the value, 10.


-A
01

% Modulus Used to find the remainder Y%Z;


after dividing the two will return the value, 0.
02

numbers.
30

The Arithmetic Operators


52
00

Using the Assignment Operators


19

The assignment operators can be categorized into:


R

 Simple assignment operator


 Complex assignment operator

Simple Assignment Operator


At times, during the programming, you want to assign a value to a variable. For this, you need to use the
simple assignment operator, =.
Consider the following code snippet in which the variable, x, is assigned the value, 5:

x=5;

2.4 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Complex Assignment Operator
In Java, arithmetic operators can be combined with simple assignment operators. These operators are called
complex assignment operators. The complex assignment operators are also known as arithmetic assignment
operators. The benefits of these operators are that they are shorthand for their equivalent long forms. For
example, in the expression, x = x+4, the + arithmetic operator adds 4 to the variable, x, and then assigns
the result to the variable, x. The preceding expression is equivalent to the expression, x += 4.
The following table describes the complex assignment operators.

Operator Description Example


(In the following examples, the value

R
of X is assumed to be 20 and the

KA
value of Y is assumed to be 2)

+= X+=Y;

R
Used to add two numbers
and assign the result to a X will have the value, 22.

SA
variable.
-= Used to subtract two X-=Y;
numbers and assign the
A
X will have the value, 18.
R
result to a variable.
IT
*= Used to multiply two X*=Y;
R

numbers and assign the X will have the value, 40.


-A

result to a variable.
01

/= Used to divide one number X/=Y;


by another and assign the X will have the value, 10.
02

result to a variable.
30

%= Used to find the remainder X%=Y;


X will have the value, 0.
52

and assign the result to a


variable.
00

The Complex Assignment Operators


19
R

Using the Comparison Operators


Comparison operators are used to compare two values and perform an action on the basis of the result of that
comparison. Whenever you use a comparison operator, the expression results in the boolean value, true or
false.

NIIT Implementing Operators 2.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table describes the commonly-used comparison operators.

Operator Operator Description Example


Name (In the following examples, the value X is
assumed to be 20 and the value of Y is
assumed to be 25)

< Less than boolean Result;


Used to check whether the
value of the left operand is less Result = X < Y;
than the value of the right Result will have the value, true.
operand.

R
KA
> Greater boolean Result;
Used to check whether the
than value of the left operand is Result = X > Y;

R
greater than the value of the Result will have the value, false.

SA
right operand.
<= Less than boolean Result;
Used to check whether the

A
or equal value of the left operand is less R Result = X <= Y;
to than or equal to the value of Result will have the value, true.
IT
the right operand.
R

>= Greater boolean Result;


Used to check whether the
-A

than or value of the left operand is Result = X >= Y;


01

equal to greater than or equal to the Result will have the value, false.
value of the right operand.
02

== Equal to boolean Result;


Used to check whether the
30

value of the left operand is Result = X == Y;


52

equal to the value of the right Result will have the value, false.
operand.
00

!= Not equal boolean Result;


Used to check whether the
19

to value of the left operand is not Result = X != Y;


equal to the value of the right Result will have the value, true.
R

operand.

The Comparison Operators


In addition to the preceding listed operator, there is one more comparison operator called the instanceof
operator. The instanceof operator is used to test whether an object is an instance of a specific class at
runtime or not.
The syntax of the instanceof operator is:

op1 instanceof op2

2.6 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding syntax, op1 is the name of an object and op2 is the name of a class. The instanceof
operator returns the true value if the op1 object is an instance of the op2 class. It returns the false value if
the op1 object is not an instance of the op2 class.

Using the Logical Operators


Logical operators are used to evaluate operands and return a boolean value.
The following table describes the logical operators.

R
Operator Operator Description Example

KA
Name

&& boolean Result=(5> 10&&

R
Logical AND Used to compare two
23<56);

SA
boolean expressions and
returns true if both the Result will have the value,
boolean expressions are false.

A
true. R
|| Logical OR Used to compare two boolean Result=(5> 10||
IT
boolean expressions and 23<56);
R

returns false if both the Result will have the value,


-A

boolean expressions are true.


false, else returns true if
01

any one of the boolean


02

expression is true.
30

The Logical Operators


52
00

Note
19

A boolean expression is an expression that results in a boolean value, that is, TRUE
R

or FALSE. For example, the boolean expression 5>3 will evaluate to TRUE.

NIIT Implementing Operators 2.7

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the Unary Operators
An operator that requires one operand is called a unary operator. The following table describes the unary
operators.

Operator Operator Description Example


Name

+ Unary Plus Indicates a positive X = +1;


operator value. Assigns the positive

R
value, 1, to the

KA
variable, X.

R
- Unary Indicates a negative X = -1;

SA
Minus value. Assigns the negative
operator
value, -1, to the

A
R variable, X.

++ X++;
IT
Increment Increments the value by
operator 1.
R

Increments the value


of X by 1.
-A
01

-- Decrement Decrements the value by X--;


operator 1.
02

Decrements the
value of X by 1.
30

! Logical Inverts the value. boolean Y=false;


52

Complement boolean X=!Y;


operator
00

Assigns the value,


19

true, to the variable,


X.
R

The Unary Operators


The increment and decrement operators can be applied in the prefix and postfix forms.

Prefix Form
In the prefix form, the operator precedes the operand. In this form, the value is incremented or decremented
before it is assigned to the operand.
Consider the following code snippet:

n=5;
m=++n;

2.8 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once the preceding statements are executed, the values of both, m and n, will be 6. This is because it will first
increment the value of n by 1, and then assign it to the variable, m.

Postfix Form
In the postfix form, the operator follows the operand. In this form, the value is incremented or decremented
after it has been assigned to the operand.
Consider the following code snippet:

n=5;
m=n++;

Once the preceding statements are executed, the value of n will be 6 and the value of m will be 5. This is

R
because the value of n will be first assigned to m, and then the value of n will be incremented by 1.

KA
R
Using the Bitwise Operators

SA
Bitwise operators are used for the manipulation of data at the bit level. The bitwise operators operate on the
individual bits of their operands. The operands can be of various data types, such as int, short, long,

A
char, and byte. When you use a bitwise operator, the operands are first converted into their binary
R
equivalents, and then the bitwise operator operates on the bits. The result in binary form is then converted
IT
into its decimal equivalent.
R

Bitwise operators can be categorized into:


-A

 Bitwise AND
01

 Bitwise OR
02

 Bitwise NOT
 Bitwise XOR
30
52

Bitwise AND Operator


00

The bitwise AND operator (&) performs an AND operation on two operands. The AND operator produces 1
if both bits are 1 else 0 in all other cases. The following table lists the bitwise AND operation results that are
19

obtained for the different combination of operands.


R

Operand 1 Operand 2 Operand 1 & Operand 2

0 0 0

0 1 0

1 0 0

1 1 1

The Bitwise AND Operation Results

NIIT Implementing Operators 2.9

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure displays the bitwise AND operation for 2 and 3.

R
KA
R
SA
The Bitwise AND Operation for 2 and 3

A
R
Bitwise OR Operator
IT
The bitwise OR operator (|) performs the OR operation on two operands. The OR operator gives the result,
R

0, if both bits are 0, else 1 in all other cases. The following table lists the bitwise OR operation results that
-A

are obtained for the different combination of operands.


01
02

Operand 1 Operand 2 Operand 1 | Operand 2


30

0 0 0
52

0 1 1
00

1 0 1
19

1 1 1
R

The Bitwise OR Operation Results

2.10 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure displays the bitwise OR operation for 2 and 3.

R
KA
R
SA
The Bitwise OR Operation of 2 and 3

A
R
Bitwise NOT Operator
IT

The bitwise NOT operator (~) is a unary operator and performs the NOT operation on each bit of binary
R

number. It is also called Bitwise complement. The NOT operator inverts or complements each of the bits of a
-A

binary number.
01

The following table lists the bitwise NOT operation results that are obtained for different operands.
02
30

Operand 1 ~Operand 1
52

0 1
00

1 0
19

The Bitwise NOT Operation Results


R

NIIT Implementing Operators 2.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure displays the bitwise NOT operation for 2.

R
KA
R
SA
The Bitwise NOT Operation for 2

A
Bitwise XOR Operator
R
IT
The bitwise XOR (^) operator performs the XOR operation on two operands. The XOR operator applied on
R

two bits results in 1, if exactly one bit is 1, else 0 in all other cases. The following table lists the bitwise
-A

XOR operation results that are obtained for the different combinations of operands.
01
02

Operand 1 Operand 2 Operand 1 ^ Operand 2


30

0 0 0
52

0 1 1
00

1 0 0
19

1 1 1
R

The Bitwise XOR Operation Results

2.12 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure displays the bitwise XOR operation for 2 and 3.

R
KA
R
SA
The Bitwise XOR Operation for 2 and 3

A
R
IT
Using the Shift Operators
R
-A

A shift operator is used to shift the bits of its operand either to the left or to the right. The various types of
shift operators are:
01

 Right shift operator (>>)


02

 Left shift operator (<<)


 Unsigned right shift operator (>>>)
30
52

Right Shift Operator


00

The right shift operator shifts all the bits of a binary number in the right direction. The syntax for the right
shift operator is:
19

operand >> num


R

In the preceding syntax, num specifies the number of positions to shift the bits in the binary number. For
example, in the 5>>2 expression, 2 is the number of times the bits have to be shifted to the right, and 5 is
the operand in which the bits are shifted.
The binary representation of 5 in 8 bits is 00000101. The >> operator shifts the bits of this binary number to
the right by 2 positions. Therefore, the two rightmost bits are discarded. The result you get is 00000001,
which is the binary representation of 1. The result is 1 in the decimal representation.

NIIT Implementing Operators 2.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure displays the right shift operation of the 5>>2 expression.

The Right Shift Operation

R
KA
Left Shift Operator

R
The left shift operator, <<, shifts all the bits of a binary number in the left direction. The syntax for the left

SA
shift operator is:

operand << num

A
In the preceding syntax, num specifies the number of positions to shift the bits in binary number. For
R
example, you have the expression, 5<<2. Here, 2 is the number of times the bits have to be shifted to the left
IT
and 5 is the operand. The binary representation of 5 in 8 bits is 00000101. The << operator shifts the bits of
R

this binary number to the left by 2 positions. Therefore, you get the result, 00010100, which is binary of 20.
-A

The following figure displays the left shift operation of the 5<<2 expression.
01
02
30
52
00
19
R

The Left Shift Operation

Unsigned Right Shift Operator


The unsigned right shift operator (>>>) is used to shift the bits of a binary number to the right. The operator
fills the leftmost bits of a binary value with 0, irrespective of whether the number has 0 or 1 at the leftmost
bit. The unsigned shift operator is generally used with the 32 and 64 bit binary numbers. For example, you
have the number –2. The binary representation of 2 in 32-bit is 00000000 00000000 00000000
00000010. Therefore, the 32-bit binary representation of –2 is 11111111 11111111 11111111
11111110.

Similarly, –2 >>>24 is 00000000 00000000 00000000 11111111. This is the binary representation of
255. Therefore, -2>>>24 is equal to 255.

2.14 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the Ternary Operator
The ternary operator is used to evaluate an expression. The operator works on a logical expression and two
operands. It returns one of the two operands depending on the result of the expression.
The syntax of ternary operator is:

boolean_expression ? expression 1 : expression 2

In the preceding syntax, if boolean_expression evaluates to true, expression 1 is returned, else


expression 2 is returned.
Consider the following code snippet:

R
KA
int a = 1;
int b = 2;
int result;

R
result = a > b ? a : b;

SA
In the preceding code snippet, if the condition is true, the ternary operator assigns the value of the variable, a,
to the variable, result. Otherwise, it assigns the value of the variable, b to the variable, result.

A
R
IT
R

Just a minute:
-A
01

Which one of the following operators is used to find the remainder and assign the
result to a variable?
02

1. %
30

2. %=
52

3. /
00

4. /=
19

Answer:
R

2. %=

Activity 2.1: Working with Operators

NIIT Implementing Operators 2.15

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using Operator Precedence
Java defines a set of rules for using operators. These rules specify the order in which the expression will be
evaluated, when there are multiple operators in an expression. For example, if there are two operators in an
expression, such as + and *, then the multiplicative arithmetic operator will be evaluated first as it has higher
precedence than the additive arithmetic operator. However, precedence rules can be overridden by using the
parentheses.

Identifying the Order of Precedence

R
Consider the expression, 45+90/5*6. To compute the result of the expression, each operator in an

KA
expression needs to be evaluated in a predetermined order called operator precedence. Operators with a
higher precedence are applied before operators with a lower precedence.

R
SA
The following table lists the operator precedence with their categories sorted from the highest precedence to
the lowest precedence.

Operators Category
A Associativity
R
IT
++expr, -- Unary postfix increment and postfix decrement Right to Left
R

expr operator
-A

expr++, Unary prefix increment, prefix decrement, plus, minus, Right to Left
01

expr--,+, -, logical NOT, and bitwise inversion


!, ~
02
30

*, /, % Multiplicative arithmetic operators Left to Right


52

+, - Additive arithmetic operators Left to Right


00

<<, >>, >>> Shift operators Left to Right


19

>, <, <=, >=, Comparison operators and the instanceof operator Left to Right
R

instanceof

==, != Comparison equality operators Left to Right

& Bitwise AND operator Left to Right

^ Bitwise XOR operator Left to Right

| Bitwise OR operator Left to Right

&& Logical AND operator Left to Right

|| Logical OR operator Left to Right

2.16 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Operators Category Associativity

=, +=, -=, *=, Assignment operators and arithmetic assignment Right to Left
/=, %= operators

The Operator Precedence


Operators on the same line have equal precedence. If an expression has two or more operators of equal
precedence, operators are evaluated on the basis of their associativity.

Implementing Precedence Using Parentheses

R
KA
Parentheses are often used to obtain the desired results as they can override the order of precedence. For
example, consider the following code snippet:

R
3 * 5 + 2;

SA
In the preceding code snippet, the result of the expression will be 17, because first 3 will be multiplied by 5,
and then 2 will be added to the result. In this case, precedence of the * operator is higher than the + operator.

A
R
However, you can apply the parenthesis on the preceding code, as shown in the following code snippet:
IT
3 * (5 + 2);
R

In the preceding code snippet, the result of the expression will change to 21 as first 2 will be added to 5, and
-A

then result will be multiplied by 3. In this case, the precedence of parenthesis is higher than the precedence
01

of operator.
02
30
52
00
19
R

NIIT Implementing Operators 2.17

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following operators is used to find the remainder after dividing two numbers?
a. Plus operator
b. Minus operator
c. Modulus operator
d. Multiply operator

2. Which one of the following operators is used to test whether an object is an instance of a specific class at
run time?

R
KA
a. Ternary operator
b. instanceof operator

R
c. Unary operator

SA
d. Shift operator

3. Which one of the following operators is used to get output as true, if both expressions are true?

A
a. Logical AND
R
IT
b. Logical OR
R

c. Bitwise NOT
-A

d. Bitwise OR
01

4. Which one of the following options denotes the correct output of the expression, 7-2*16/8?
02

a. 6
b. 10
30

c. 3
52

d. 4
00

5. Which one of the following operators is used to find the remainder after dividing the two numbers?
19

a. +
R

b. /
c. %
d. &&

2.18 Implementing Operators NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
 Operators allow you to perform various mathematical and logical calculations, such as adding and
comparing numbers.
 Arithmetic operators are used to perform arithmetic operations on operands like addition, subtraction,
multiplication, and division.
 Assignment operators can be categorized to simple assignment operator and complex assignment
operator.
 The simple assignment operator is used to assign a value to the variable.

R
 Arithmetic operator, when combined with the simple assignment operator are called complex

KA
assignment operator. The various complex assignment operators are +=, -=, *=, /=, and %=.
 Comparison operators are used to compare two values and perform an action on the basis of the result of

R
that comparison. The various relational operators are <, >, <=, >=, ==, and !=.

SA
 The instanceof operator is used to test whether an object is an instance of a specific class at run
time.

A
Logical operators are used to evaluate operands and return a boolean value. The various logical
R
operators are && and ||.
IT
 Unary operator operates on one operand. The various unary operators are unary plus, unary minus,
R

increment operator, decrement operator, and logical complement operator.


-A

 Bitwise operators are used for the manipulation of data at the bit level. The various bitwise operators are
bitwise AND (&), bitwise OR (|), bitwise NOT (~), and bitwise XOR (^).
01

 Shift operators are used to shift the bits of its operand either to the left or to the right. The various shift
02

operators are right shift (>>), left shift (<<), and unsigned shift operator (>>>).
30

 The ternary operator is used to evaluate an expression. The operator works on a logical expression and
two operands. It returns one of the two operands depending on the result of the expression.
52

 An expression can have multiple operators and each operator is evaluated in order of its precedence.
00

 Parentheses are often used to obtain the desired results as they can override the order of precedence.
19
R

NIIT Implementing Operators 2.19

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with Conditional


and Loop Constructs
CHAPTER 3

NIIT Introduction to Object-Oriented Programming 1.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In a Java program, the statements are executed in a sequential order. This order can be changed by using the
conditional and looping constructs.
The conditional construct executes the selective block of statements according to the value of the expression.
In addition, Java provides the loop construct that makes a set of statements of a program to be repeated a
certain number of times. The statement execution continues till the condition set for the loop remains true.
When the condition becomes false, the loop terminates and the control moves to the statements following the
loop construct.
This chapter discusses the various types of the conditional constructs used in the Java programming
language. In addition, it focuses on the different types of loop constructs supported by Java.

R
Objectives

KA
R
In this chapter, you will learn to:

SA
 Work with conditional constructs
 Work with loop constructs

A
R
IT
R
-A
01
02
30
52
00
19
R

3.2 Working with Conditional and Loop Constructs NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Working with Conditional Constructs
In your daily life, you take various decisions that are based on certain conditions. For example, if it is
raining, you will take an umbrella. In the same way, you can incorporate the decision making techniques in
the Java programming language. The decision making technique can be implemented in the Java programs
by using the following conditional constructs:
 The if construct
 The if…else construct
 The switch construct

R
KA
Using the if Construct

R
The if construct executes statements based on the specified condition. For example, in the Classic Jumble

SA
Word game, you needs to display the message, You are correct !!!!, if a user identifies the correct
word for the corresponding jumbled word that is displayed on the screen. To implement the preceding
functionality, you can use the if construct. The syntax for the if construct is:

A
if(expression)
R
IT
{
//statement(s)
R

}
-A

In the if construct, statement(s) followed by the if statement will be executed, when expression
01

evaluates to true. However, if expression evaluates to false, statement(s) will be skipped.


02

The if construct can contain either a single statement or multiple statements. It is not mandatory to enclose
the single statement within a pair of braces. However, the multiple statements must be enclosed within a pair
30

of braces.
52

In the preceding example, you can use the following code snippet:
00

if(jumbleWord.equals(userWord))
{
19

System.out.println("You are correct !!!!");


}
R

In the preceding code snippet, the if statement will compare values of two string references, jumbleWord
and userWord. The jumbleWord reference is used to store the jumbled word and the userWord reference is
used to store the word entered by the user. If both the objects have same values, it will execute the print
statement and will display the message, You are correct !!!!, otherwise it will skip the print statement.

Note
The equals() method is a method of the String class that compares the values of
two string objects.

NIIT Working with Conditional and Loop Constructs 3.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Sometimes, there is a need to check the condition based on another condition. For example, in the preceding
scenario of the Classic Jumble Word game, you want to check whether a user enters the word or not, and
then want to compare the user’s input with the jumbled word.
To achieve the preceding requirement, Java supports the nested if construct. The syntax of the nested if
construct is:

if(condition)
{
if(condition)
{
//statement(s)
}
}

R
KA
In the preceding example, you can use the following code snippet:

if(userWord.length()!=0)

R
{

SA
if(jumbleWord.equals(userWord))
{
System.out.println("You are correct !!!!");

A
} R
}
IT
In the preceding code snippet, the first if statement compares the length of the string object stored in the
R

userWord reference with 0. If the length of the string object is not equal to 0, the second if construct gets
-A

executed.
01

The second if statement compares the textual values of the userWord and jumbleWord references. If both
the values are same, the message printed will be You are correct !!!!.
02
30

Note
52

The length() method is a method of the String class that returns the length of the
string reference variable.
00
19
R

Using the if…else Construct


In the preceding example of the Classic Jumble Word game, you want to modify the existing code to display
the message, You are incorrect !!!!, if a user enters the incorrect word for the corresponding jumbled
word. For this, you can modify the existing code by using the if…else construct.
The if…else construct executes statements based on the specified condition.

3.4 Working with Conditional and Loop Constructs NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The syntax for the if…else construct is:

if(expression)
{
//statement(s)
}
else
{
//statement(s)
}

In the if…else construct, statement(s) followed by the if statement will be executed, when
expression evaluates to true. However, if expression evaluates to false, statement(s) followed by the
else statement will be executed.

R
KA
Both, the if construct and the else construct, can contain either a single statement or the multiple
statements.

R
In the preceding example, you can modify the existing code by using the following code snippet:

SA
if(jumbleWord.equals(userWord))
{

A
System.out.println("You are correct !!!!"); R
}
else
IT
{
R

System.out.println("You are incorrect !!!!");


-A

}
01

In the preceding code snippet, the if statement compares the textual values of the jumbleWord and
userWord references. If both the textual values are same, the message printed will be You are correct
02

!!!!. Otherwise, the message printed will be You are incorrect !!!!.
30

Nesting of the if…else constructs is possible in both, the if and else blocks. The syntax of the nested
if…else construct is:
52

if(expression) //Line 1
00

{
if(expression) //Line 2
19

{
//statement(s)
R

}
else
{
//statement(s)
}
}
else
{
if(expression) //Line 3
{
//statement(s)
}

NIIT Working with Conditional and Loop Constructs 3.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
else
{
//statement(s)
}
}
In the preceding syntax, if line 1 evaluates to true, line 2 gets executed. If line 2 evaluates to true,
statements(s) within the if construct gets executed. Otherwise, statement(s) within the else
construct gets executed. However, if line 1 evaluates to false, the else construct gets executed. In the else
construct, if the line 3 evaluates to true, statement(s) within the if construct gets executed. Otherwise,
statement(s) within the else construct gets executed.

R
Using the switch Construct

KA
In the example of Classic Jumble Word game, you want to display the following menu when the game starts:

R
1. Play Game

SA
2. View Instructions
3. Exit Game

A
Thereafter, you want a user to enter a choice, such as 1, 2, or 3. On the basis of the user’s input, you want the
R
corresponding methods, which implement the functionality for each input, to be invoked. For this, you can
IT
use the switch construct.
R

The switch construct evaluates an expression for multiple values. The switch statement is followed by an
-A

expression that tests the value of the expression against a list of values, which can be the integer, character,
01

or string constants. The syntax for the switch construct is:


02

switch(expression)
{
30

case Expr_1: //statement(s)


break;
52

case Expr_2: //statement(s)


break;
00

.
.
19

.
case Expr_N: //statement(s)
R

break;
default: //statement(s)
}

In the switch construct, expression given in the switch statement is compared with each case constant.
If the case constant matches with expression, the control is moved to the statement following the
matched case constant. Otherwise, the control is moved to the default statement.
The break statement causes the program flow to exit from the switch construct. This skips the execution of
the remaining case structure by terminating the execution of the switch construct.

3.6 Working with Conditional and Loop Constructs NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding example, you can use the following code snippet:

switch(choice)
{
case 1: playGame();
break;
case 2: instructGame();
break;
case 3: exitGame();
break;
default: System.out.println("Invalid option.");
}

In the preceding code snippet, if the value of choice is 1, the playGame() method will be invoked.

R
KA
Note

R
In the switch construct, the case constants and the value of the switch expression

SA
must have the same data type.

A
R
IT
R

Just a minute:
-A
01

Which one of the following values can be accepted by the switch construct?
02

1. Boolean
30

2. Float
52

3. Double
00

4. Character
19

Answer:
R

4. Character

Activity 3.1: Working with Conditional


Constructs

NIIT Working with Conditional and Loop Constructs 3.7

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Working with Loop Constructs
A looping statement enables you to execute the same statements for a certain number of times. For this, you
do not need to write the statements repeatedly. You can enclose the statements within the loop construct and
the loop construct executes the statements till the specified condition is met. Java supports the following loop
constructs:
 The for loop
 The while loop
 The do…while loop

R
KA
Using the for Construct

R
Consider the example of the Classic Jumble Word game, you want to implement a functionality in which a

SA
user should guess the correct word in five attempts only. If the user fails to guess the word in five attempts,
the game will be terminated. For this, you can use the for loop construct. The syntax for the for loop
construct is:

A
for(initialization; condition; increment/decrement)
R
{
IT
//statement(s)
R

}
-A

In the for loop construct, the initialization statement is executed first. It is executed only once at the
01

beginning of the loop. Thereafter, the condition statement is executed for each iteration. If the condition
statement evaluates to true, statement(s) followed by the for statement are executed. However, if the
02

condition statement evaluates to false, the loop gets terminated. Finally, the increment/decrement
30

statement is executed that increments or decrements the loop. The loop continues executing statement(s)
until the conditional statement evaluates to false.
52

In the preceding example, you can use the following code snippet:
00

for(count=0;count<5;count++)
19

{
//statement(s)
R

In the preceding code snippet, the count variable is initialized with 0. The loop will continue executing
statement(s) till the value of the count variable is less than 5.
You can create an infinite loop by keeping all the three statements blank, as displayed in the following code
snippet:

for ( ; ; )
{
//statement(s)
}

In the preceding code snippet, statement(s) will continue executing infinitely.

3.8 Working with Conditional and Loop Constructs NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
At times, after certain iterations, you need to exit from the loop. To achieve this, Java provides the break
statement. The break statement stops the execution of the remaining statements within the body of the loop.
In addition, Java provides the continue statement. The continue statement skips all the statements
following the continue statement and moves the control back to the loop statement.
The following code snippet depicts the use of the break statement within the for loop:

for(count=0;count<10;count++)
{
if(count==7)
{
break;
}
System.out.println(count);

R
}

KA
In the preceding code snippet, the loop will print the value of count from 0 to 6. Thereafter, the loop will be

R
terminated, when the value of count will be 7.

SA
The following code snippet depicts the use of the continue statement within the for loop:

for(count=0;count<10;count++)
{
A
if(count==3)
R
IT
{
R

continue;
}
-A

System.out.println(count);
01

}
02

In the preceding code snippet, the loop will print the value of count from 0 to 9 except 3 because the control
will be moved back to the for statement, when the value of count will be 3.
30
52

Note
00

Java supports one more type of the for loop known as the for-each loop. This will be
covered in later chapters.
19
R

Using the while Construct


In the preceding example, you can implement the similar functionality with the help of the while loop
construct.
The while loop construct provides the similar functionality of the for loop construct. However, the syntax
for the while loop construct is different from the for loop construct.

NIIT Working with Conditional and Loop Constructs 3.9

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The syntax for the while loop construct is:

while(expression)
{
//statement(s)}

In the while loop construct, statement(s) followed by the while statement will be executed, when the
expression evaluates to true. The loop continues executing statement(s) until the expression evaluates to
false.
In the preceding example, you can use the following code snippet of the while loop:

int count=0;
while(count<5)

R
{

KA
//statement(s)
count++;
}

R
SA
In the preceding code snippet, the count variable is initialized with 0. The loop will continue executing
statement(s) till the value of the count variable is less than 5.

A
R
Note
IT
You must initialize the variable before using it in the expression statement of the
R

while loop.
-A
01

You can also create an infinite loop by using the while loop construct, as displayed in the following code
02

snippet:
30

while(true)
{
52

//statement(s)
}
00
19

Using the do…while Construct


R

Consider the example of the Classic Jumble Word game, you want the menu of the game to be displayed at
least once, and then it will be on the user’s choice whether the user wants to display the menu again or not.
For this, you should use the do…while loop construct.
The do…while loop construct places the condition at the end of the loop, which makes statement(s) to be
executed at least once. The syntax for the do…while loop construct is:

do
{
//statement(s)

}while(expression);

3.10 Working with Conditional and Loop Constructs NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the do…while construct, statement(s) are executed at least once. Thereafter, statement(s) are
executed if the expression evaluates to true. The loop continues executing statement(s) until the
expression evaluates to false.
In the preceding example, you can use the following code snippet:

do
{
//statement(s)

}while(choice.equals(“Y”));

In the preceding code snippet, statement(s) gets executed at least once. Thereafter, statement(s) gets

R
executed if the textual value of string object is equal to Y.

KA
You can also create an infinite loop by using the do…while loop construct, as displayed in the following

R
code snippet:

SA
do
{
//statement(s)
}while(true);
A
R
IT
In the preceding code snippet, statement(s) will continue executing infinitely.
R
-A
01
02

Just a minute:
30

The ________ loop construct contains the condition at the end.


52

Answer:
00

do…while
19
R

Activity 3.2: Working with Loop Constructs

NIIT Working with Conditional and Loop Constructs 3.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. State whether the following statement is true or false.
The if construct can be used to check multiple conditions.

2. Predict the output of the following code snippet:

int num1 = 5, num2 = 5, sum;


sum = num1 + num2;
if(sum>10)
{

R
System.out.println("True");

KA
}
else

R
{
System.out.println("False");

SA
}

3. Which one of the following constructs is the looping construct?


A
a. if…else
R
IT
b. break
R

c. switch
-A

d. for
01

4. State whether the following statement is true or false.


02

The increment/decrement expression is evaluated at each iteration of the for loop.


30

5. What will be the output of the following code snippet:


52

int i=10,j=20;
00

while(i++<--j)
{
19

}
R

System.out.println(i+" "+j);

3.12 Working with Conditional and Loop Constructs NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
 The decision making technique can be implemented in the Java programs by using the following
conditional constructs:
 The if construct
 The if…else construct
 The switch construct
 The if construct executes statements based on the specified condition.

R
 The if construct can contain either a single statement or multiple statements.

KA
 Java supports the nested if construct.
 The if…else construct executes the statements within the if block if the expression evaluates to true,

R
otherwise the else block gets executed.

SA
 The if construct and the else construct can contain either a single statement or the multiple statements.
 Nesting of the if…else constructs is possible in both, the if and else blocks.
 The switch construct evaluates an expression for multiple values.
A
R
 The switch statement is followed by an expression that tests the value of the expression against a list of
IT
values, which can be the integer, character, or string constants.
R

 Java supports the following loop constructs:


-A

 The for loop


01

 The while loop


02

 The do…while loop


 In the for loop construct, the initialization statement is executed first.
30

 Thereafter, the conditional statement is executed for each iteration.


52

 Finally, the increment/decrement statement is executed that increments or decrements the loop.
00

 The loop continues executing statement(s) until the conditional statement evaluates to false.
 The break statement causes the program flow to exit from the construct.
19

 The continue statement skips all the statements following the continue statement and moves the
R

control back to the loop statement.


 In the while loop construct, statement(s) followed by the while statement will be executed, when
the expression evaluates to true.
 The do…while loop construct places the condition at the end of the loop, which makes statement(s)
to be executed at least once.
 You can create an infinite loop by using for, while, and do…while loop constructs.

NIIT Working with Conditional and Loop Constructs 3.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with Arrays,


Enums, and Strings
CHAPTER 4

NIIT Introduction to Object-Oriented Programming 1.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
At times, a program needs to use a number of variables. The declaration and initialization of these variables
makes the program large and complex. In addition, it is difficult to keep track of so many variables. To
overcome this problem, you need a single variable that can store multiple similar values. This can be
achieved by using arrays. An array is a group of similar variables that are referred by a common name.
Arrays can hold either primitive data type or object references. Arrays offer a convenient means of grouping
the related information.
There can be a situation when you need to restrict a user to select from a fixed set of predefined values. For
this, you can use the enumerated list, which contains items. To create an enumerated list, Java provides
enum. An enum is used to define a fixed set of constants.
Consider another situation where you need to store a sequence of characters, such as employee name and
department name. For this, you can use strings. To store the strings, Java provides various built-in classes,

R
such as String, StringBuilder, and StringBuffer. In addition, these classes provide the functionality

KA
to perform various operations, such as comparing two strings, concatenating two strings, and changing the
case of a string.

R
SA
This chapter discusses the manipulation of arrays, enums, and strings in Java.

Objectives
A
R
IT
In this chapter, you will learn to:
R

 Manipulate arrays
-A

 Manipulate enums
01

 Manipulate strings
02
30
52
00
19
R

4.2 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Manipulating Arrays
In the Classic Jumble Word game, you need to store 100 different words that will be used in the game.
Therefore, to store these values, you need to declare 100 variables. This is because a variable can store only
one value at a time. However, it is difficult to keep track of 100 variables in a program which makes the
program code long and complex. Therefore, in such a situation, you need to declare a variable that can store
100 words. This can be achieved by declaring an array variable.
An array is a collection of elements of a single data type stored in adjacent memory locations. You can
access an array element by specifying the name and the subscript number of the array. The subscript number
specifies the position of an element within the array. It is also called the index of the element. The first
element of an array has an index, 0, and the last element has an index one less than the size (number of

R
elements in an array) of the array.

KA
The following figure shows the array of employeeID.

R
SA
A
R
IT
R
-A

The Array of employeeID


01

In the preceding figure, you can see that the first element is stored in the index number, 0, while the fifth
02

element is stored in the index number, 4, which is one less than the size of the array.
In order to use arrays, you need to know how to create and access them.
30
52

Creating Arrays
00

You can create the following types of arrays:


19

 One-dimensional array
R

 Multidimensional array

One-dimensional Array
A one-dimensional array is a collection of elements with a single index value. A one-dimensional array can
have multiple columns but only one row.
The creation of a one-dimensional array involves two steps:
1. Declare an array.
2. Assign values to the array.

NIIT Working with Arrays, Enums, and Strings 4.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Declaring an Array
An array needs to be declared before it can be used in a program. You can declare a one-dimensional array
by using the following syntax:

arraytype arrayname[] = new arraytype[size];

In the preceding syntax, arraytype specifies the type of element to be stored in array, arrayname specifies
the name of the array, using which the elements of the array will be initialized and manipulated, and [size]
specifies the size of the array.
The following code snippet declares an array to store three string values:

String jumbledWords[] = new String[3];

R
The preceding code snippet creates an array of String, jumbledWords, which can store three elements with

KA
the index of elements ranging from 0 to 2.

R
Assigning Values to the Array

SA
You can assign values to each element of the array by using the index number of the element. For example,
to assign the value, alpep, to the first element of the array, you can use the following code snippet:

A
jumbledWords[0] = “alpep”;
R
IT
You can also assign values to the array at the time of declaration. For this, you are not required to specify the
R

size of the array, as shown in the following code snippet:


-A

String jumbledWords[] = {“alpep”,”argneo”,”rgaeps”};


01

In the preceding code snippet, jumbledWords is a one-dimensional array. The values, alpep, argneo, and
02

rgaeps, are stored in the array, as shown in the following figure.


30
52
00
19
R

The Values Stored in the jumbledWords Array

Multidimensional Array
Multidimensional arrays are arrays of arrays. An array having more than one dimension is called a
multidimensional array. The commonly used multidimensional array is a two-dimensional array where you
can have multiple rows and columns. For example, to store an employee name against each employee id, you
need to create a two-dimensional array.

4.4 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure shows a two-dimensional array.

R
A Two-dimensional Array

KA
The creation of a two-dimensional array involves two steps:

R
1. Declare an array.

SA
2. Assign values to the array.

Declaring an Array

A
You can declare a two-dimensional array by using the following syntax:
R
IT
arraytype arrayname[][] = new arraytype[rowsize][columnsize];
R

In the preceding syntax, arraytype specifies the type of element to be stored in array, arrayname specifies
-A

the name of the array, using which the elements of the array will be initialized and manipulated,
01

rowsize specifies the number of rows, and columnsize specifies the number of columns.
02

The following code snippet declares a two-dimensional array:


30

String[][] words = new String[4][2];


52

The preceding code snippet creates an array of String, words, which contains four rows and two columns.
00

Assigning Values to the Array


19

You can assign values to each element of the array by using the index number of the element. For example,
to assign the value, alpep, to the 0th row and the 0th column and apple to the 0th row and the 1st column,
R

you can use the following code snippet:

words[0][0] = “alpep”;
words[0][1] = “apple”;
You can also assign values to the array at the time of declaration, as shown in the following code snippet:

String[][] jumbledWords = new String[][] {


{“elapp”,“apple”},{ “argneo”,”orange”},{“agrspe”,“grapes”}};

NIIT Working with Arrays, Enums, and Strings 4.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The preceding code snippet stores string values in a two-dimensional array, jumbledWords, as shown in the
following figure.

R
KA
The Values Stored in the jumbledWords Array

R
SA
A
Just a minute:
R
IT
Identify the total number of elements, if an array is declared as:
R

int [] arr = new int [5];


-A

1. 3
01

2. 4
02

3. 5
30

4. 6
52

Answer:
00

3. 5
19
R

Accessing Arrays
To perform various manipulations on the array, you need to access the following types of arrays:
 One-dimensional array
 Two-dimensional array

One-dimensional Array
To access a one-dimensional array, the following syntax is used:

arrayname[index];

4.6 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding syntax, arrayname specifies the name of the array and index specifies the location of the
array element.
Consider the following code snippet:

String jumbledWords[] = {“alpep”,”argneo”,”rgaeps”};


System.out.println(jumbledWords[0]);

In the preceding code snippet, the jumbledWords array stores the various jumbled words. The statement,
System.out.println(jumbledWords[0]);, accesses the element stored in the first index and displays
it. However, if you want to display all the elements stored in the array, you can use the for loop, as shown in
the following code snippet:

String jumbledWords[] = {“alpep”,”argneo”,”rgaeps”};

R
for(int i=0;i<3;i++)

KA
System.out.println(jumbledWords[i]);

In the preceding code snippet, the for loop is used to traverse through all the elements in the array. For this,

R
you need the index of each array element. Therefore, in the for loop, the value of i is initialized with 0 and

SA
iterated till one less than length of the array. However, if you do not know the total number of elements in the
array, then traversing through the entire array will be difficult. This can be simplified by using the length

A
property of an array. This property returns the length of an array. The following code snippet is used to
R
traverse through the array using the for loop and the length property:
IT
String jumbledWords[] = {“alpep”,”argneo”,”rgaeps”};
R

for(int i=0;i<jumbledWords.length;i++)
-A

System.out.println(jumbledWords[i]);
01

In the preceding code snippet, the jumbledwords.length property returns 3, which is the length of the
array.
02

While traversing an array using the for loop, you need to use a variable. This variable undergoes three
30

operations: initialization, comparison, and increment. This is an error-prone approach, if any one of the
operations is not handled properly. Therefore, to avoid the occurrence of errors, Java provides the
52

for-each loop to iterate through an array. This loop increases the readability and simplifies the code as you
need not take care of the three operations, which are handled by the Java language implicitly. The syntax of
00

the for-each loop to use in an array is:


19

for(type var: arrayobject)


R

In the preceding syntax, type is the data type or reference type of the var variable and arrayobject is the
name of the array object. The type of the variable should be similar to the type of the data stored in
arrayobject. The colon (:) within the for-each loop is read as ‘in’. The syntax is read as type var in
arrayobject.

The following code snippet is used to display all the elements stored in the array using the for-each loop:

String[] jumbledWords = {“alpep”,”argneo”,”rgaeps”};


System.out.println(“Elements stored in array are: “);
for (String i : jumbledWords)
{
System.out.println(i);
}

NIIT Working with Arrays, Enums, and Strings 4.7

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code snippet, jumbledWords is an array object that holds the string object. Every time the
for loop is executed, each element of the array is assigned to the reference variable, i, which further gets
displayed.

Two-dimensional Array
To access the two-dimensional array, the following syntax is used:

arrayname[row][column];

In the preceding syntax, arrayname specifies the name of the array, and row and column specify the
location of the array element. Consider the following code snippet:

R
String[][] jumbledWords = new String[][] {
{“elapp”,”apple”},{“argneo”,”orange”},{“agrspe”,”grapes”}};

KA
System.out.println(jumbledWords[0][0]);

R
SA
In the preceding code snippet, the jumbledWords array is a two-dimensional array that stores the jumbled
word and their corresponding correct word in each row. The jumbledWords[0][0] code accesses the
element stored at the row index, 0, and the column index, 0, and displays it. However, if you want to display

A
all the elements, you can use the for loop, as shown in the following code snippet: R
IT
String[][] jumbledWords = new String[][]{
{“elapp”,”apple”},{“argneo”,”orange”},{“agrspe”,”grapes”}};
R

System.out.println(“Elements stored in array are: “);


-A

for (int i=0; i<2; i++)


{
01

for (int j=0; j<2; j++)


{
02

System.out.print(jumbledWords[i][j]);
}
30

}
52

In the preceding code snippet, the for loops are used to iterate through the array, jumbledWords. The outer
for loop is used to iterate the array row-wise and the inner for loop is used to iterate the array column-wise.
00

The preceding code snippet can be modified to use the length property, as shown in the following code
19

snippet:
R

int a[][] = {{1,2},{4,3}};


for(int i=0; i<a.length; i++)
{
for(int j=0; j<a[i].length; j++)
System.out.println(a[i][j]);
}

In the preceding code snippet, a.length is used to calculate the total number of rows and a[i].length is
used to calculate the total number of columns in the array.

4.8 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Further, you can use the following code snippet to display all the elements stored in the two-dimensional
array using the for-each loop:

String[][] jumbledWords = new String{“elapp”,”apple”},{ “argneo”,”orange”},{


“agrspe”,”grapes”}};;

System.out.println(“Fruits are: “);


for (String[] i : jumbledWords)
{
for (String j : i)
{
System.out.println(j);
}
}

R
KA
In the preceding code snippet, the for-each loop is used to iterate through the array, jumbledWords. The
array variable, i, is used to store the row data and the variable, j, is used to store the column data of each ith

R
row.

SA
A
R
IT
R
-A
01
02
30
52
00
19
R

NIIT Working with Arrays, Enums, and Strings 4.9

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Manipulating Enums
In the Classic Jumble Word game, Sam wants the application to restrict a player from choosing the category
of words from the given categories, such as fruit, country, or animal. To achieve the preceding task, Sam
needs to create a predefined list of values. In Java, a list of predefined values can be created using enum.
An enum is a special type of a class, which can have constructors, methods, and instance variables. In order
to use enum, you need to know how to declare and access it.

Declaring Enums

R
KA
You need to declare an enum to define a fixed set of constant. The following syntax is used to declare an
enum:

R
enum enum-name{constant 1, constant 2,. . . . ,constant n};

SA
In the preceding syntax, enum-name is the name of the enum and constant 1, constant 2, and
constant n are the constants in the enum.

A
For example, to create an enumerated list, Mango, you need to use the following code snippet:
R
IT
enum Mango{Carrie, Fairchild, Haden};
R

In the preceding code snippet, Mango is the name of the enum and Carrie, Fairchild, and Haden are the
-A

enum constants, which refer to the variety of the mango.


01
02

Note
30

An enum can be declared either inside the class or outside the class.
52
00

In Java, enums are similar to classes. Enums can have constructors, variables, and methods. However, you
cannot create an instance of an enum using the new keyword. The enum constructors get invoked when the
19

enum constants are created, as these constants are treated as objects. For example, consider the following
code snippet:
R

class MangoVarities{
enum Mango{Carrie(10), Fairchild(9), Haden(12);
private int price;
Mango(int p)
{
price = p;
}
int getPrice()
{
return price;
}
}
}

4.10 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code snippet, the constructor accepts the price of mango and assigns the value to the
instance variable, price. The getPrice()method returns the price of the mango.

Accessing Enums
Once have declared an enum, you can access it. You can either use an enum name or enum reference to
access enum constants. An enum reference creation is similar to a variable creation. You need to use the
following syntax to access an enum:

enum-name.enum-constant
or

R
enum-refernce.enum-constant

KA
In the preceding syntax, enum-name is the name of the enum and enum-constant is the enum constant.
enum-reference is the enum reference variable.

R
SA
Note
An enum-reference is similar to class reference.
A
R
IT
R

Consider the following code snippet to access an enum constant and store it in an enum reference:
-A

Mango p = Mango.Carrie;
01

In the preceding code snippet, an enum constant, Carrie, is accessed using the enum name, Mango. The
02

accessed enum constant is assigned to an enum reference, p.


To access all the values stored in an enum, Java provides the values() method. This method returns all the
30

enum constants stored in an enum. For example, consider the following code snippet:
52

enum Mango{Carrie, Fairchild, Haden};


00

class EnumTest{
public static void main(String args[]){
19

for(Mango p:Mango.values())
System.out.println(p);
R

}
}

In the preceding code snippet, the for-each loop is used to traverse through the enum, Mango. The
values() method is used to return the enum constants stored in the enum.
To access the methods defined in an enum, you can use the following code snippet:

enum Mango{Carrie(10), Fairchild(9), Haden(12);


private int price;
Mango(int p)
{
price = p;
}

NIIT Working with Arrays, Enums, and Strings 4.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
int getPrice()
{
return price;
}
}
class EnumTest{
public static void main(String args[]){
Mango p = Mango.Carrie;
System.out.println(p.getPrice());
}
}

In the preceding code snippet, when the statement, Mango p = Mango.Carrie, is executed, the enum
constructor is invoked and the value, 10, is assigned to the member variable, price. Therefore, when the

R
getPrice() method is called, the value, 10, is returned.

KA
R
SA
Just a minute:

A
Which method is used to return all the values stored in an enum?R
1. allValues()
IT
2. getValues()
R

3. valueOf()
-A

4. values()
01

Answer:
02
30

4. values()
52
00
19
R

4.12 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Manipulating Strings
In the Classic Jumble Word game, Sam wants a user to enter the name before playing the game. Thereafter,
the name should appear with the message, “Welcome [user name]”. To implement this functionality, there is
a need to store the name of the user, and then append the name with the welcome message. Here, the name
and welcome message are string values. To manipulate string, Sam can use the classes, such as String,
StringBuilder, and StringBuffer, provided by Java. These classes will enable a user to store string
literals. In addition, these classes provide various methods for string manipulations.

Using String Class

R
KA
To store string literals, you can use the String class in the java.lang package. The following code snippet
is used to create a string object:

R
SA
String s1 = new String(“Hello”);

The preceding code snippet creates a new string object in the heap memory, with a value, Hello, and assigns
it to reference variable, s1. In addition, it creates another string object with the value, Hello, in the string
A
constant pool.
R
IT
R

Note
-A

In JVM, a special memory named string constant pool is used to store string literals.
01
02
30
52

Note
Heap memory is an area within the JVM where objects are stored.
00
19
R

You can also create a string object by using the following code snippet:

String s1 = “Hello”;
The preceding code snippet creates a new string object with a value, Hello, in the string constant pool and
assigns it to the reference variable, s1.
In Java, String class is an immutable class. This means that once a string object is created, you cannot
change its value. However, the reference variables of the String class are mutable.

NIIT Working with Arrays, Enums, and Strings 4.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
For example, consider the following figure.

s1 Hello

String reference variable


Memory

R
The String Reference Variable Referring to the String Object

KA
In the preceding figure, s1 is a string reference variable, which refers to the string object with the value,
Hello.

R
SA
If you append the string literal, World, to the string reference variable, s1, then a new string object, Hello
World, is created in the memory and the variable, s1, will refer to the new string object. However, the string
object, Hello, still exists in the memory but has no reference, as shown in the following figure.

A
R
IT
R
-A
01

Hello
02
30

s1 Hello World
52

String reference variable


00
19

Memory
R

The String Reference Variable Referring to the New String Object


Thus, every time you manipulate a string object, a new string object is created in the memory. Therefore the
String class is called as an immutable class.

4.14 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the some of the most commonly used methods of the String class.

Method Description Example

int length() Returns the length of a String str = “newstring”;


string object. int len = str.length();
System.out.println(len);
Output:
9

R
char Returns the character at String str = “Fruit”;

KA
charAt(int index) the specified index, char result = str.charAt(3);
which ranges from 0 to
System.out.println(result);

R
the length of string object

SA
-1. Output:
i

void Copies characters from a


A
String Str1 = new String(“Welcome
R
getChars(int srcBegi source string object into to java”);
IT
n,int srcEnd, the destination character
char[] dst, char[] Str2 = new char[6];
R

array. The first character


int dstBegin) Str1.getChars(8, 10, Str2, 0);
-A

to be copied is at index
srcBegin, the last System.out.print(“Value Copied =
01

character to be copied is “);


02

at index srcEnd-1. The System.out.println(Str2);


character is copied into
30

dst, starting at index, Output:


dstbegin. Value Copied = to
52

boolean String str1 = “Fruit”;


00

Compares the current


equals(object obj) string object with the String str2 = “Fruit”;
19

other string and returns


a boolean value. boolean result =
R

str1.equals(str2);
System.out.println(result);
Output:
true

NIIT Working with Arrays, Enums, and Strings 4.15

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description Example

int compareTo(String Compares the current String str1 = “fruits”;


str) string object with String str2 = “fruits are good”;
another string. If the
strings are same, the int result = str1.compareTo( str2
);
return value is 0, else the
return value is non-zero. System.out.println(result);
Output:
-9

R
KA
boolean Tests whether a string String Str = new String(“Welcome
startsWith(String starts with the specified to Java”);

R
prefix) prefix or not. If the System.out.print(“Value returned

SA
character sequence :”);
represented by the
System.out.println(Str.startsWith(
argument is a prefix of

A
“Welcome”));
the string, the return R
value is true. Output:
IT
Otherwise, it is false. Value returned :true
R
-A

boolean Tests if the string object String Str = new String(“Welcome


endsWith(String ends with the specified to Java”);
01

suffix) suffix. Returns true if System.out.print(“Value Returned


02

the character sequence :”);


represented by the System.out.println(Str.endsWith(“J
30

argument is a suffix of ava”));


the character sequence
52

represented by this Output:


00

object. Otherwise, it is Value Returned: true


false.
19

int indexOf(int ch) Returns the index of the String Str = new String(“Welcome
R

first occurrence of the to Java”);


specified character System.out.print(“Index Found at:”
within a string. If the );
character is not found,
System.out.println(Str.indexOf(
the method returns –1. 'o' ));
Output:
Index Found at:4

4.16 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description Example

int lastIndexOf(int Returns the index of the String Str = new String(“Welcome
ch) specified character to Java”);
occurring last in the System.out.print(“Last Index
string. If the character is Found at :” );
not found, the method,
System.out.println(Str.lastIndexO
indexOf(), returns –1. f( 'o' ));
Output:

R
Last Index Found at :9

KA
String subString(int Returns a substring of a String Str = new String(“Welcome
beginindex) to Java”);

R
string. The substring

SA
begins with the character System.out.print(“Value
at the specified index and Returned:” );
extends to the end of the
System.out.println(Str.substring(

A
main string. 10) );
R
Output:
IT

Value Returned: Java


R
-A

String concat(String Concatenates the String str1 = “Hello “;


str)
01

specified string to the String str2 = “Everybody”;


end of the string object.
02

System.out.println(str1.concat(st
30

r2));
52

Output:
Hello Everybody
00

String replace(char String Str = new String(“Welcome


19

Replaces the occurrence


oldChar,char of a specified character to Java”);
newChar)
R

by a new specified System.out.print(“Value


character. Returns the Returned:” );
string derived from the
System.out.println(Str.replace('o
string by replacing every ', 'T'));
occurrence of oldChar
with newChar. Output:
Value Returned:WelcTme tT Java

NIIT Working with Arrays, Enums, and Strings 4.17

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description Example

String toUpperCase() Converts the string to String Str = new String(“Welcome


uppercase and returns it. to Java”);
System.out.print(“Value
Returned:”);
System.out.println(Str.toUpperCa
se());
Output:

R
Value Returned: WELCOME TO JAVA

KA
String toLowerCase() Converts the string into String Str = new String(“WELCOME
TO JAVA”);

R
lowercase and returns it.

SA
System.out.print(“Value
Returned:” );
System.out.println(Str.toLowerCa

A
se());
R
Output:
IT

Value Returned: welcome to java


R
-A

String trim() Removes white space String Str = new String(“


WELCOME TO JAVA”);
01

from both ends of a


string object and returns System.out.print(“Value Returned
02

the trimmed string. :”);


30

System.out.println(Str.trim() );
52

Output:
Value Returned :WELCOME TO JAVA
00

char[] toCharArray() String Str = new String(“WELCOME


19

Returns a newly
allocated array whose TO JAVA”);
R

length is the length of System.out.print(“Value


this string and whose Returned: “ );
content are initialized to
char ch[] = Str.toCharArray();
contain the character
sequence represented by System.out.println(ch);
this string. Output:
Value Returned: WELCOME TO JAVA

4.18 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description Example

String Returns the string int a = 10;


valueOf(Object obj) representation of the Double b = 2.00;
specified argument.
Returns null if the char[] arr = {'a', 'b'};
argument is null. The System.out.println(“Return Value
valueOf() method is a : “ + String.valueOf(a) );
static method. System.out.println(“Return Value
: “ + String.valueOf(b) );

R
Output:

KA
Return Value : 10

R
Return Value : 2.0

SA
boolean Compares this string String Str1 = new
equalsIgnoreCase(Str with another string and String(“fruits”);

A
ing anotherString) ignores case R String Str2 = new
considerations. String(“FRUITS”);
IT
System.out.println(“Return = “+
R

Str1.equalsIgnoreCase(Str2));
-A

Output:
01

Return = true
02

The String Class Methods


30
52

Using StringBuilder and StringBuffer Classes


00

You can also use the StringBuilder and StringBuffer classes to work with strings. These classes are
19

mutable classes as they do not create any new string object when manipulated. Therefore, when you need to
do various manipulations, such as appending, concatenating, and deleting with string literals, you should use
R

StringBuilder and StringBuffer.

The following code snippet initializes a string object to a StringBuilder reference:

StringBuilder s1= new StringBuilder(“Hello”);

NIIT Working with Arrays, Enums, and Strings 4.19

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the some of the most commonly used methods of the StringBuilder class.

Method Description Example

StringBuilder StringBuilder sb = new


Appends the argument
append(String StringBuilder(“Fruits “);
to the string builder.
obj) sb.append(“are good for health”);
System.out.println(sb);
Output:
Fruits are good for health

R
KA
StringBuilder Deletes the sequence StringBuilder str = new
delete(int from start to end in the StringBuilder(“fruits are very good”);
start, int

R
char sequence. str.delete(10, 15);
end)

SA
System.out.println(“After deletion = “
+ str);

A
Output:
R
After deletion = fruits are good
IT
StringBuilder Inserts the second StringBuilder str = new
R

insert(int argument into the string StringBuilder(“fruitsgood”);


-A

offset, builder. The first


String obj) str.insert(6, “ are “);
01

argument indicates the


System.out.print(“After insertion =
index before which the
“);
02

data is to be inserted.
System.out.println(str.toString());
30

Output:
52

After insertion = fruits are good


StringBuilder str = new
00

StringBuilder The sequence of


reverse() StringBuilder(“fruits”);
characters in the string
19

builder is reversed. System.out.println(“reverse = “ +


str.reverse());
R

Output:
reverse = stiurf
The StringBuilder Class Methods

4.20 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one of the following String class methods is used to copy characters from a
source string object into the destination character array?
1. charAt()
2. getChars()
3. toCharArray()

R
4. substring()

KA
Answer:

R
2. getChars()

SA
A
R
IT
Note
R

StringBuffer class has the same methods as that of the StringBuilder class.
-A

However, the methods in StringBuffer class are synchronized.


01
02
30

Activity 4.1: Manipulating Arrays and Strings


52
00
19
R

NIIT Working with Arrays, Enums, and Strings 4.21

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following options is the correct declaration of an array?
a. int [10] list;
b. int list[10];
c. int list = new int[10];
d. int[ ] list = new int[10];

2. Consider the following code snippet:

R
int Number1 = 0;

KA
int Number2 = 0;
int[] Array1 = new int [] {2,3,4,5,6,7,8,9,10,11};
for (int Ctr : Array1)

R
{

SA
if (Ctr%2 == 1)
{
Number1++;

A
} R
else
{
IT
Number2++;
R

System.out.print(Ctr);
}
-A

}
01

What will be the output of the preceding code snippet?


02

a. 3,5,7,9,11
30

b. 2,4,6,8,10
52

c. 2,5,7,9,10,11
d. 3,4,7,9,10,11
00

Which one of the following String class methods returns the output as true if both strings are equal?
19

3.
a. equals()
R

b. compareTo()
c. append()
d. subString()

4. Which one of the following String class methods is used to convert the calling String object to a new
character array?
a. trim()
b. toCharArray()
c. valueOf()
d. getChars()

4.22 Working with Arrays, Enums, and Strings NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
 An array is a collection of elements of a single data type stored in adjacent memory locations. You can
access an array element by specifying the name and the subscript number of the array.
 The subscript number specifies the position of an element within the array. It is also called the index of
the element.
 The various types of array are one-dimensional array and multidimensional array.
 A one-dimensional array is a collection of elements with a single index value. A one-dimensional array
can have multiple columns but only one row.

R
 Multidimensional arrays are arrays of arrays. A multidimensional array can have multiple columns and

KA
rows.
 To display all the elements stored in the array, you can use the for loop.

R
 To know the total number of elements in the array, you can use the length property.

SA
 Java provides the for-each loop to iterate through an array.
 In Java, a list of predefined values can be created using enum.

A
R
An enum is a special type of a class, which can have constructors, methods, and instance variables.
IT
 An enum can be declared either inside the class or outside the class.

R

In Java, enums are similar to classes.


-A

 To access enum constants, you can either use an enum name or enum reference.
 To store string literals, you can use the String class in the java.lang package.
01

 In Java, String class is an immutable class. This means that once a string object is created, you cannot
02

change its value.


30

 Every time you manipulate a string object, a new string object is created in the memory.
 StringBuilder and StringBuffer classes are mutable classes as they do not create any new string
52

object when manipulated.


00
19
R

NIIT Working with Arrays, Enums, and Strings 4.23

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Implementing
Inheritance and
Polymorphism
CHAPTER 5

NIIT Introduction to Object-Oriented Programming 1.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In Java, classes can be related to each other and reused in various scenarios within an application. The
process of creating a new class by acquiring some features from an existing class is known as inheritance.
In addition, polymorphism is the ability to redefine a function in more than one form. In OOPs, you can
implement polymorphism by creating more than one function of the same name within a class. The
difference between the functions lies in the number, types, or sequence of parameters passed to each
function.
In this chapter, you will learn how to implement inheritance and polymorphism in Java.

Objectives

R
KA
In this chapter, you will learn to:
 Implement inheritance

R
 Implement polymorphism

SA
A
R
IT
R
-A
01
02
30
52
00
19
R

5.2 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Inheritance
In an object oriented programming language, such as Java, you can reuse or extend the functionalities and
capabilities of an existing class in a new class if both the classes have similarities amongst themselves. A
class can inherit the features of a related class and add new features, as per the requirement. This allows the
sharing and reuse of code and helps in making the code of an application more organized and efficient by
reducing redundancy.
Consider the scenario of the Classic Jumble Word game. Ricky, the Project Manager, has asked Sam to
implement different levels to the game. These levels need to be based upon the maximum number of
attempts that can be availed by a player. Further, with each subsequent level, more sets of functionality will
be added to the game, such as a timer and score. The timer will specify a time limit within which the player

R
will be required to identify the correct word. As the player will play the game, the value of the timer will be

KA
decremented. If the player is unable to identify the correct word in the time specified by the timer, the game
will terminate. Furthermore, with the change in the complexity level of the game, there will be a variation in

R
how the player scores are computed.

SA
In order to enhance the game functionality, Sam can recode the entire application. However, this will
introduce redundancy in the code and consume a large amount of time. As some of the required sets of

A
functionality are common to all levels, such as displaying the menu and instructions, Sam should reuse the
R
existing code. Thereafter, he should add the new desired functionality to the existing functionalities. For this,
IT
Sam decides to implement the inheritance feature of Java. In Java, inheritance can be implemented through
classes and interfaces. In inheritance, the class that inherits the data members and methods from another class
R

is known as the subclass or derived class. The class from which the subclass inherits the features is known as
-A

the superclass or base class.


01
02

Note
Interfaces are similar to classes, but they contain only constant variables and abstract
30

methods.
52
00
19

Identifying the Various Types of Inheritance


R

Java supports the following types of inheritance:


 Single level inheritance
 Multilevel inheritance
 Hierarchical inheritance

NIIT Implementing Inheritance and Polymorphism 5.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Single Level Inheritance
In single level inheritance, a single subclass derives the functionality of an existing superclass. The following
figure explains the concept of single level inheritance.

R
KA
R
The Concept of Single Level Inheritance

SA
In the preceding figure, there are two classes, Person and Employee. The class, Employee, is the subclass
that is inherited from the superclass, Person.

A
R
Multilevel Inheritance
IT

In multilevel inheritance, a subclass inherits the properties of another subclass. The following figure explains
R

the concept of multilevel inheritance.


-A
01
02
30
52
00
19
R

The Concept of Multilevel Inheritance


In the preceding figure, the class, Person, is a superclass for the class, Employee, and the class, Employee,
is a superclass of the class, Manager. You can include any number of levels in multilevel inheritance.

5.4 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Hierarchical Inheritance
In hierarchical inheritance, one or more subclasses are derived from a single superclass. The following figure
shows the concept of hierarchical inheritance.

R
KA
R
The Concept of Hierarchical Inheritance

SA
In the preceding figure, the subclasses, Employee and Student, inherit the properties of a single
superclass, Person.

A
R
IT
Inheriting a Class
R
-A

Inheritance signifies the relationship between a superclass and its subclass. In order to inherit a class, you
need to use the extends keyword. For example, if you have a superclass named Books and a subclass
01

named PaperBooks that share common functionalities and properties with the superclass, such as printing
the book details and author name, total number of pages, and price. In order to implement single level
02

inheritance for the Books class, you can use the following code:
30

class Books
52

{
int page_num;
00

String authorname, name;


float price;
19

public Books()
R

{
page_num = 50;
authorname = "Andrew Jones";
name = "The Living Ideas";
price = 15.78f;
}

public void displayInfo()


{
System.out.println("The name of the book is " + name);
System.out.println("The price of the book is " + price);
System.out.println("The author name is " + authorname);
System.out.println("The total number of pages is " + page_num);

NIIT Implementing Inheritance and Polymorphism 5.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
}
}

class PaperBooks extends Books


{

int shippingcharges = 10;

public void printInfo()


{
displayInfo();//Calling the method of Book class.
System.out.println("The total shipping charges are" +
shippingcharges);
}

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

R
PaperBooks pb = new PaperBooks();

SA
pb.printInfo();

A
} R
In the preceding code, PaperBooks is a subclass of the superclass class, Books. The subclass uses the
IT
various properties, such as author name and price. In addition, it uses the displayInfo() method. The
R

output of the preceding code is:


-A

The name of the book is The Living Ideas


01

The price of the book is 15.78


The author name is Andrew Jones
02

The total number of pages is 50


The total shipping charges are $10
30

Inheritance can also be implemented by using abstract classes. An abstract class is a class that contains one
52

or more abstract methods. An abstract class cannot be instantiated but can be inherited by other classes by
using the extends keyword. When an abstract class is inherited by a subclass, the subclass must provide the
00

implementation of all the abstract methods defined in the abstract class. The abstract class acts as a blueprint
19

for other classes. You can define an abstract class by using the following syntax:
R

<access_specifier> abstract class <abstract_class_name>


{
//variables
// abstract and concrete methods
}

In the preceding syntax, <access_specifier> specifies the access specifiers, such as public and
private. abstract and class are keywords. <abstract_class_name> specifies the name of the
abstract class.
You can declare an abstract method by using the following syntax:

abstract return-type methodname(parameter-list);

5.6 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding syntax, abstract is a keyword. return-type specifies the type of value returned by the
method. methodname specifies the name of the method and parameter-list specifies the list of the
parameters that can be accepted by the method.
Consider the scenario of a game console. Each of the games in the game console must offer functionalities to
play the game, compute the score, display the score, and exit the game. However, some of these
functionalities, such as play the game and compute the score, will vary for every game. However, some of
the functionalities, such as display the score and exit the game, will remain the same for all the games. For
example, the Badminton game will have a different mechanism to compute the score in comparison to the
TableTennis game. However, both the games will display the score in a similar manner. Therefore, for the
game console, you can create an abstract class named GameConsole. This class will contain concrete
methods for the functionalities that are common to all the games, such as displayScore(). The
functionalities that need to be implemented differently by every game, such as computeScore(), will be

R
declared as abstract methods. Therefore, the game classes, such as Badminton, which will inherit the

KA
GameConsole class, will provide the implementation of these abstract methods.

R
Consider the following code:

SA
abstract class GameConsole
{
int score;
void displayScore()
A
R
{
IT
System.out.println("The displayScore method.");
}
R

abstract void computeScore();


-A

abstract void playGame();


}
01

class Badminton extends GameConsole


02

{
30

void playGame()
{
52

System.out.println("Starting the Badminton Game...");


}
00

void computeScore()
{
19

System.out.println("Implementing the abstract method of the


Gameconsole class.");
R

}
}

class GameDemo
{
public static void main(String args[])
{
Badminton obj1 = new Badminton();
obj1.playGame();
obj1.computeScore();
obj1.displayScore();

}
}

NIIT Implementing Inheritance and Polymorphism 5.7

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the GameConsole class is an abstract class that declares the abstract methods,
playGame() and computeScore(), which will be used to start the game and compute the score. The
Badminton class inherits the GameConsole abstract class and provides its specific implementation for the
computeScore() and playGame() abstract methods. Further, in the main() method, an object, obj1, of
the Badminton class is created and the methods are invoked.
Sometimes, within a method or a constructor, there may be a need to refer to the object that has invoked it.
Moreover, in your program, sometimes you may have a requirement where the class variables and the
method or constructor variables have the same name. In order to cater to the preceding requirements, Java
provides the this keyword. In addition, it helps to differentiate between the member and the local variables
of a method or constructor in case the member and the local variables of a method have the same name. For
example, consider the following code:

R
class Vehicle

KA
{
int max_speed = 210;

R
Vehicle(int max_speed)
{

SA
max_speed = max_speed;
}
public void showmaxspeed()
{
A
R
System.out.println("The top speed is " + max_speed);
IT
}
}
R

class MainClass {
-A

public static void main(String args[])


{
01

Vehicle a = new Vehicle(250);


a.showmaxspeed();
02

}
}
30

In the preceding code, the member variable and the parameter for the constructor of Vehicle share the same
52

name, max_speed. In such a scenario, when the object, a, is created, the value, 250, is assigned to it.
00

However, when the showmaxspeed() method is invoked, the value of the class variable, max_speed, is
displayed as 210. This is because the member variable is hidden by the parameter of the constructor. To
19

overcome this problem, you can access the member variable by using the following code snippet:
R

Vehicle (int max_speed)


{
this.max_speed = max_speed;
}

In addition to this keyword, Java provides the super keyword to refer to the member variables and
methods of the superclass in a subclass. For example, consider the following code:

class Vehicle
{
int max_speed = 210;
public void showmaxspeed()
{
System.out.println("The top speed is " + max_speed);

5.8 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
}
}
class Car extends Vehicle
{
int max_speed = 180;
public void showmaxspeed_vehicle()
{
System.out.println("The top speed of CAR is " + max_speed);
System.out.println("The top speed of VEHICLE is " + super.max_speed);
}
}
class MainClass
{
public static void main(String args[])

R
{

KA
Vehicle a = new Vehicle();
Car b = new Car();
b.showmaxspeed_vehicle();

R
}

SA
}

In the preceding code, both, Vehicle and Car, have a member variable named max_speed. In order to

A
access the value of the max_speed variable of the Vehicle class in the Car class, the super keyword is
R
used.
IT
R

Note
-A

The super keyword followed by () can also be used to invoke the constructor of the
01

superclass from the constructor of a subclass. However, in such a scenario, super();


should be the first statement.
02
30

Inheriting an Interface
52
00

Consider a scenario of the Classic Jumble Word game where each of the games in the console can be played
at various levels. With each subsequent level, the game will become more challenging for a player. However,
19

for each game and level, it is necessary to offer some common functionality, such as taking input from the
R

player and calculating the score. However, the implementation will vary as per the level at which the game
will be played. For example, while playing the game at the first level, the player has no time restrictions and
no score is displayed. At the second level, there will be a specific number of attempts to identify the correct
word. At this level, the score will depend upon the number of attempts in which the player identifies the
jumbled word correctly.
Furthermore, at the next level, there will be a restriction regarding the time in which the player has to guess a
jumbled word correctly. In this case, the score will depend upon how quickly the player gives the correct
answer.
Therefore, at all these levels, the implementation of how the score is calculated varies. In such a scenario,
you can create a blueprint that outlines the necessary functionalities to be implemented at all the levels but
does not specify their actual implementation. The classes that use the blueprint must provide the
implementation of the functionalities listed in the blueprint. In Java, such a blueprint is known as an

NIIT Implementing Inheritance and Polymorphism 5.9

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
interface. The interface will serve as a service contract that all the classes that are implementing the interface
will have to follow. If the classes do not follow the contract, the code will not compile.
Interfaces contain a set of abstract methods and static data members. By default, all the methods specified in
an interface are public and abstract, and all the variables are public, static, and final. You can
define an interface by using the following syntax:

interface <interfacename>
{
//interface body
static final <data type> <variablename>;
public return-type methodname(parameter-list);
}

R
In the preceding syntax, interface, static, final, and public are keywords. <interfacename>

KA
specifies the name of the interface. return-type specifies the type of value returned by the method.
methodname specifies the name of the method and parameter-list specifies the list of the parameters

R
that can be accepted by the method. <data type> and <variablename> specify the type of data and the

SA
name of the variable, respectively.
You can implement an interface in one or more class. A class that implements an interface must provide the

A
implementation of all the methods declared in that interface. You can implement an interface in a class by
R
using the following syntax:
IT
class <class_name> implements <interfacename>
R

{
//Defining the method declared in the interface.
-A
01

public return-type methodname(parameter-list)


{
02

//Body of the method


}
30

}
52

Note
00

A class can extend another class and implement an interface at the same time.
19
R

Note
If you need to inherit both, a class and an interface, in another class, then, in the class
definition, the extends keyword must precede the implements keyword. For example,
class TicTacToe extends Game implements GameInterface.

In the preceding syntax, class, public, and implements are keywords. return-type specifies the type
of value returned by the method. methodname specifies the name of the method and parameter-list
specifies the list of the parameters that can be accepted by the method.

5.10 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
While working with interfaces, the following points should be considered:
 An interface cannot be instantiated.
 An interface cannot have a constructor.
 An interface can itself extend multiple interfaces.
 An interface contains only abstract methods and static and final variables.
Consider the scenario of the Classic Jumble Word game. You can create an interface named Games to
declare the common functionalities for each of the games in the console, as shown in the following code
snippet:

public interface Games


{

R
String msg = "Welcome ";

KA
public void score();
}
class ClassicJumble implements Games

R
{

SA
void gamelist()
{
// Display the main list of games

A
} R
void userinput()
IT
{
R

//Accept player input


-A

}
public void score()
01

{
02

/* Some code to be added */


}
30

/* Some code to be added */


}
52

In the preceding code snippet, the interface, Games, declares a final variable, msg, and abstract method,
00

score(). The ClassicJumble class implements the interface and provides the implementation of all the
19

abstract methods declared in the interface, Games.


R

Further, an interface can also extend an interface, by using the following syntax:

interface <interface_name> extends <interface1, interface2,…interfaceN>

In the preceding syntax, an interface is extending multiple interfaces by using the extends keyword.
When an interface extends another interface, the class that is implementing the interfaces must define all the
methods that are declared in both the interfaces.

NIIT Implementing Inheritance and Polymorphism 5.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one of the following keywords is used to represent an object of the current
class?
1. super

2. this

3. interface

R
4. abstract

KA
Answer:

R
2. this

SA
A
R
IT
R
-A
01
02
30
52
00
19
R

5.12 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Polymorphism
Polymorphism is an OOP feature that enables an entity to exist in multiple forms. In Java, polymorphism has
the following two types:
 Static polymorphism
 Dynamic polymorphism

Static Polymorphism

R
In case of static polymorphism, an entity, such as a method, can exist in multiple forms. This means that one

KA
or more methods can exist with the same name but with a different argument list. This type of
polymorphism, when exhibited by methods, is known as method overloading. For example, a method named

R
calculate can be overloaded by using the following code snippet:

SA
calculate( int x, int y)
{
/* Some code to be added */
}
A
R
IT
calculate (float x, int y, int z)
{
R

/* Some code to be added */


-A

}
01

calculate (int x, float y)


{
02

/* Some code to be added */


}
30

calculate (float y, int x)


52

{
/* Some code to be added */
00

}
19

In the preceding code snippet, the calculate() method implements polymorphism by existing in multiple
forms. Each of the forms of the calculate() method differs from the other in terms of method signature.
R

During compilation, the compiler will bind the function call. For example, compute (0.75,8,10) with the
compute (float x, int y, int z) method. Whereas, the compiler will bind the compute (81,102),
statement to the compute(int x, int y) method.

Note
The method signature comprises a method’s name and parameter list.

NIIT Implementing Inheritance and Polymorphism 5.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
While implementing method overloading, it is important to consider the following points about overloaded
methods:
 They differ in the type and/or number of their arguments.
 They differ in the sequence of their parameters.
 They differ in the data types of their parameters.

Note
If two methods have the same signature but different return types, the methods are not
overloaded.

R
KA
Dynamic Polymorphism

R
SA
In Java, if a superclass and subclass contain methods with the same name, the version to be invoked will be
decided by the JVM at runtime. Such a decision to invoke the appropriate method is known as dynamic
polymorphism. Dynamic polymorphism is implemented in Java by method overriding. Method overriding
A
enables a subclass to provide its own implementation of a method that already has an implementation defined
R
in its superclass. To override a method present in the superclass, the subclass method should have the same
IT
name, same parameters, and same return type as the method in the superclass.
R

Consider the following code:


-A

class Person
01

{
public void showDetails()
02

{
30

System.out.println("In the Person class");


}
52

}
class Employee extends Person
00

{
public void showDetails()
19

{
System.out.println("In the Employee class");
R

}
}
class Student extends Person
{
public void showDetails()
{
System.out.println("In the Student class");
}
}
class Method_Override
{
public static void main(String args)
{
Person P = new Person();

5.14 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Employee E = new Employee();
Student S = new Student();
Person ref;
ref = P;
ref.showDetails(); // calls the showDetails method of the Person
class
ref = E;
ref.showDetails(); // calls the showDetails method of the Employee
class
ref = S;
ref.showDetails();// calls the showDetails method of the Student
class
}
}

R
In the preceding code, the Student and Employee classes extend the Person class. The Person and

KA
Employee classes override the showDetails() method of the Person class. Further, in the main()

R
method, the objects of the Student, Employee, and Person classes are created. Also, a reference, ref, has
been created for the Person class. The reference is used to further invoke the showDetails() method. The

SA
invoked method depends upon the object being referred to by the reference at runtime.
It is important to consider the following points while implementing overriding:
 Private methods cannot be overridden, as they are not accessible in subclasses.
A
R
 Final methods cannot be overridden.
IT

 An overridden method cannot be granted more restrictive access rights in a subclass than it is assigned in
R

case of a superclass. For example, if a method is specified with the public access specifier in a
-A

superclass, it cannot be specified as protected in a subclass.


01
02
30
52
00
19
R

NIIT Implementing Inheritance and Polymorphism 5.15

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
What will be the output of the following code?

public class MethodDemo


{
void print()
{
System.out.println("Print1");
}
void print(String a)

R
{

KA
System.out.println("Print2");
}

R
String print()

SA
{
System.out.println("Print3");
return "Print3";
}
public static void main(String args[])
A
R
{
IT
MethodDemo obj=new MethodDemo();
obj.print();
R

}
-A

}
01

1. Print1
02

2. Compile-time error
30

3. Print2
52

4. Print3
00

Answer:
19

2. Compile-time error
R

Activity 5.1: Implementing Inheritance and


Polymorphism

5.16 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following classes is used to define concrete methods and declare methods without any
implementation?
a. Subclass
b. Superclass
c. Abstract class
d. Final class

2. Which one of the following keywords is used to implement an interface?

R
KA
a. implements
b. extends

R
c. super

SA
d. final

3. Which one of the following types of inheritance allows a subclass to inherit from another subclass?
A
a. Multiple inheritance
R
IT
b. Multilevel inheritance
R

c. Single level inheritance


-A

d. Multipath inheritance
01

4. In which one of the following options, one or more subclasses are derived from a single superclass?
02

a. Single level inheritance


b. Instantiation
30

c. Multiple inheritance
52

d. Hierarchical inheritance
00

5. Which one of the following options allows a method to exist in multiple forms?
19

a. Polymorphism
R

b. Encapsulation
c. Inheritance
d. Abstraction

NIIT Implementing Inheritance and Polymorphism 5.17

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
 A class can inherit the features of a related class and add new features, as per the requirement.
 In inheritance, the class that inherits the data members and methods from another class is known as the
subclass or derived class.
 The class from which the subclass inherits the features is known as the superclass or base class.
 In single level inheritance, a single subclass derives the functionality of an existing superclass.
 In multilevel inheritance, a subclass inherits the properties of another subclass.
 In hierarchical inheritance, one or more subclasses are derived from a single superclass.

R
KA
 An abstract class is a class that contains one or more abstract methods.
 An abstract class cannot be instantiated but can be inherited by other classes by using the extends

R
keyword.

SA
 Interfaces contain a set of abstract methods and static and final data members.
 A class that implements an interface must provide the implementation of all the methods declared in that
interface.
A
 In Java, polymorphism has the following two types:
R
IT
 Static polymorphism
R

 Dynamic polymorphism
-A

 In case of static polymorphism, an entity, such as a method, can exist in multiple forms.
 Dynamic polymorphism is implemented in Java by method overriding.
01

 To override a method present in the superclass, the subclass method should have the same name, same
02

parameters, and same return type as the method in the superclass.


30
52
00
19
R

5.18 Implementing Inheritance and Polymorphism NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Handling Errors
CHAPTER 6

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
An error is a condition that causes a disruption in the execution of a program. An error can be a result of
circumstances, such as incorrect code or insufficient memory resources. Errors in a Java program are
categorized into two types, compile-time errors and
run-time errors. The compile-time errors occur when the syntax of a programming language are not followed.
For example, in Java, if you use a keyword name as a variable name, a compile-time error will be raised by
the compiler.
The run-time errors occur during the execution of a program. For example, if the program runs out of
memory, it results in a run-time error. Such an error is known as an exception. An exception can lead to the
termination of an application. Dealing with such abnormal behavior is called exception handling.
In addition, to create an error free code, you need to validate the program. In order, to validate the program
you need to test various assumptions. For this, Java provides assertions.

R
KA
This chapter discusses the common methods that you can use to handle exceptions. In addition, it also
discusses the use of assertions in Java.

R
SA
Objectives

A
In this chapter, you will learn to:
R
IT
 Handle exceptions
R

 Use the assert keyword


-A
01
02
30
52
00
19
R

6.2 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Handling Exceptions
In the Classic Jumble Word game, if the player enters an incorrect menu option, such as a string value
instead of an integer value, the game terminates abnormally. The abnormal termination of an application can
have severe consequences in a real-time or a business application that provides a vital functionality to an
organization. Therefore, it is essential to handle and prevent the abnormal termination. In order to prevent the
abnormal termination in the Classic Jumble Word game, Sam wants to implement a functionality, such that
the game application displays an appropriate message whenever an abnormal termination occurs.
To cater to the preceding requirement, Sam should implement exception handling. The term exception in
Java indicates an abnormal event that occurs during the program execution and disrupts the normal flow of
instructions. For example, if you divide a number by zero or open a file that does not exist, an exception is

R
raised. In Java, exceptions can be handled either by the Java run-time system or by a user-defined code. Java

KA
supports various built-in classes and exception handlers to deal with exceptions.

R
SA
Exploring Exceptions

A
When a run-time error occurs, an exception is thrown by the JVM which can be handled by an appropriate
R
exception handler. The Java run-time system proceeds with the normal execution of the program after an
exception is handled. If no appropriate exception handler is found by the JVM, the program is terminated.
IT
R

There are several built-in exceptions that have been identified in Java. In order to deal with these exceptions,
Java has various built-in exception classes.
-A
01
02
30
52
00
19
R

NIIT Handling Errors 6.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
These built-in classes are organized in a hierarchical manner, as shown in the following figure.

R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

The Exception Hierarchy

6.4 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The Throwable Class
The Throwable class is the base class of exceptions in Java. You can throw only those exception objects
that are derived from the Throwable class. The following two classes are derived for the Throwable class:
 Exception
 Error

The Exception Class


The Exception class represents the conditions that a program should handle. The Exception class has
various subclasses, such as classNotFoundException, IllegalAccessException, and
RuntimeException. The ClassNotFoundException exception is thrown when a class is being referred,

R
but no definition for the same is found. The IllegalAccessException exception is thrown when a

KA
particular method is not found.

R
The Error Class

SA
The Error class defines the exceptions related to the Java run-time environment. For example,
OutOfMemoryError is an error that occurs when there is insufficient system memory to execute a program.

A
R
Identifying Checked and Unchecked Exceptions
IT
R

Java exceptions are categorized into the following types:


-A

 Checked exceptions
01

 Unchecked exceptions
02

Checked Exceptions
30

These are the invalid conditions that occur in a Java program due to the problems, such as accessing a file
52

that does not exist or referring a class that does not exist. The checked exceptions are the objects of the
Exception class or any of its subclasses excluding the RuntimeException and Error class. For example,
00

a checked exception IOException is raised, when a program tries to read from a file that does not exist. The
checked exceptions make it mandatory for a programmer to handle them. If a checked exception is not
19

handled, then a compile-time error occurs.


R

The following table lists the most commonly used checked exceptions.

Exception Cause of Creation

ClassNotFoundException Is thrown when the Java run-time system is unable to find


the referred class.

IllegalAccessException Is thrown when you refer an object, class, variable,


constructor, or a method that is not accessible.

NIIT Handling Errors 6.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exception Cause of Creation

InstantiationException Is thrown when you try to create an instance of a class by


using the newInstance() method, but the referred class
cannot be instantiated.

NoSuchMethodException Is thrown when a particular method cannot be found.

The Checked Exceptions in Java

Unchecked Exceptions

R
The unchecked exceptions occur because of programming errors. Therefore, the compiler does not force a

KA
programmer to handle these exceptions. Such errors should be handled by writing bug free codes. However,
there are times such situations cannot be eradicated. For example in a calculator application, if you divide a

R
number by zero, an unchecked exception is raised.

SA
The following table lists the various unchecked exceptions and their causes of creation.

Exception
A
Cause of Creation
R
IT
ArithmeticException Occurs when you make an arithmetic error,
R

such as dividing a number by zero.


-A

ArrayIndexOutOfBoundsException
01

Occurs when an attempt is made to access an


array element beyond the index of the array.
02

ArrayStoreException Occurs when you assign an element to an array


30

that is not compatible with type of data that


52

can be stored in that array.


00

ClassCastException Occurs when you assign a reference variable


of a class to an incompatible reference
19

variable of another class.


R

IllegalArgumentException Occurs when you pass an argument of


incompatible data type to a method.

NegativeArraySizeException Occurs when you create an array with a


negative size.

NullPointerException Occurs when an application tries to use an


object without allocating memory to it or calls
a method of a null object.

6.6 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exception Cause of Creation

NumberFormatException Occurs when you want to convert a string in an


incorrect format to a numeric format.

The Unchecked Exceptions in Java

Implementing Exception Handling


When an unexpected error occurs, Java creates an exception object. After creating the exception object, Java

R
sends it to the program by throwing the exception. The exception object contains information about the type
of error and the state of the program when the exception occurred. You need to handle the exception by using

KA
an exception handler and processing the exception. You can implement exception handling in a program by
using the following keywords and blocks:

R
 try

SA
 catch
 throw
 throws
A
R
 finally
IT
 try-with-resources
R
-A

Using try and catch Blocks


01

A try block encloses the statements that might raise an exception and defines one or more exception
02

handlers associated with it. If an exception is raised within the try block, the appropriate exception handler
that is associated with the try block processes the exception.
30

In Java, the catch block is used as an exception handler. A try block must have at least one catch block
52

that follows the try block, immediately. The catch block specifies the exception type that you need to
catch.
00

You can declare the try and the catch block by using the following syntax:
19

try
R

{
// Statements that can cause an exception.
}

catch(exceptionname obj)
{
// Error handling code.
}

In the preceding syntax, the catch block accepts the object of the Throwable class or its subclass that
refers to the exception caught, as a parameter. When the exception is caught, the statements within the
catch block are executed.

NIIT Handling Errors 6.7

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider a scenario in which you need to accept two integers from a user, performs their addition, and
displays the result. For this, you can use the following code:

import java.util.Scanner;
public class Addition {

public static void main(String[] args) {

int num1, num2, result;


Scanner obj1 = new Scanner(System.in);

System.out.println("Enter the 1st number");


num1 = obj1.nextInt();
System.out.println("Enter the 2nd number");

R
num2 = obj1.nextInt();

KA
result = num1+num2;
System.out.println("The result is "+result);

R
}
}

SA
While executing the preceding code, if the user provides an input other than an integer value, an exception is
raised and the program terminates abnormally. To overcome this, you can implement exception handling in
the preceding code by using the try-catch block as shown in the following code:
A
R
IT
import java.util.Scanner;
public class Addition
R

{
-A

public static void main(String[] args)


{
01

int num1, num2, result;


String snum1, snum2;
02

Scanner obj1 = new Scanner(System.in);


try
30

{ // monitor the try block for exceptions


System.out.println("Enter the 1st number");
52

snum1 = obj1.next();
System.out.println("Enter the 2nd number");
00

snum2 = obj1.next();
19

num1=Integer.parseInt(snum1);
num2=Integer.parseInt(snum2);
R

result = num1+num2;
System.out.println("The result is "+result);
}
catch(Exception e) /*the catch block catches the exception raised
in the try block and handles it*/
{
System.out.println("Please input only numeric
values..!!");
}

}
}

6.8 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the try block is used to monitor the user input. If the user enters an input that is not
an integer value, such as a char or a string, an exception is raised. However, the exception is successfully
handled by the catch block that catches the exception raised in the try block. Once the exception is caught,
the message, Please input only numeric values..!! is displayed and the abnormal termination of
the program is handled, successfully.

Note
The parseInt() method is a static method defined inside the Integer wrapper class. It
is used to convert a numeric string value, such as 12, to an integer value.

R
A try block can have multiple catch blocks. This is required when a code within the try block is capable

KA
of raising multiple exceptions. You can declare multiple catch blocks with a single try statement by using
the following code snippet:

R
SA
try
{
// statements

A
} R
catch(exceptionname1 obj1)
{
IT
//statements to handle the exception
R

}
-A

catch(<exceptionname2 obj2)
01

{
//statements to handle the exception
02

}
catch(exceptionnameN objN)
30

{
//statements to handle the exception
52

}
00

In the preceding code snippet, when the statements in the try block raise an exception, the matching catch
block corresponding to the raised exception is executed. Further, the execution continues after the try-catch
19

block. While working with multiple catch statements, it is important to follow the exception hierarchy, such
R

that the subclasses must appear prior to the superclasses. If the exception hierarchy is not followed, a
compile-time error is generated.
Consider the following code:

public class Division


{
public static void main(String[] args)
{
int num1, num2, result;
Scanner obj1 = new Scanner(System.in);
try
{ // monitor the try block for exceptions
System.out.println("Enter the 1st number");
num1 = obj1.nextInt();

NIIT Handling Errors 6.9

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
System.out.println("Enter the 2nd number");
num2 = obj1.nextInt();
result = num1 / num2;
System.out.println("The result is " + result);
} catch (Exception e)
{
System.out.println("Please input only numeric values..!!");
} catch (ArithmeticException e) /*the catch block catches the
exception raised in the try block and handles it */
{
System.out.println("Division performed by zero...");
}
}
}

R
KA
The preceding code will generate a compile-time error as the exception hierarchy is not followed. Therefore,
in the preceding code ArithmeticException should be caught before Exception.

R
throw

SA
You can throw an exception explicitly, by using the throw keyword. For example, you need to throw an
exception when a user enters an incorrect login ID or a password. The throw keyword causes the
A
termination of the normal flow of control of the Java code and stops the execution of the subsequent
R
statements. The throw keyword transfers the control to the nearest catch block that handles the type of
IT
exception being thrown. If no appropriate catch block exists, the program terminates.
R

You can throw an exception by using the following syntax:


-A
01

throw ThrowableObj

In the preceding syntax, ThrowableObj is an object of the Throwable class or a subclass of the
02

Throwable class, such as an Exception class. The ThrowableObj object is created by using the new
30

operator. The Java compiler gives an error if the ThrowableObj object does not belong to a valid
Exception class.
52

Consider the following code that demonstrates the implementation of the throw statement:
00

public class ThrowDemo


19

{
void display()
R

{
throw new RuntimeException();
}

public static void main(String[] args)


{
ThrowDemo obj1 = new ThrowDemo();
try
{
obj1.display();
} catch (RuntimeException e)
{
System.out.println("Runtime Exception raised");
}

6.10 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
}
}

Note
An exception can be handled either in the method that raises the exception or in the
calling method.

In the preceding code, the statement, throw new RuntimeException is used to throw a
RuntimeException object and the calling method, main() handles the exception raised in the display()

R
method.

KA
The throw keyword can also be used inside a catch block to rethrow an exception. Exceptions are rethrown

R
if a method causing the error wants to pass the error handling responsibilities to the exception handlers in

SA
some other methods. You can use the following code snippet to rethrow an exception:

catch(Exception e)
{
System.out.println("Exception Raised");
A
R
throw e;
IT
}
R

In the preceding code snippet, the exception goes to the catch block of the next higher context ignoring the
-A

catch blocks of the same try block. You can use the following code to catch the RuntimeException
exception and rethrow the exception to the outer handler:
01

class RethrowException
02

{
30

static void compute()


{
52

try
{
00

throw new RuntimeException ("My Exception");


}
19

catch(RuntimeException e)
{
R

System.out.println("Exception caught in compute() method");


throw e; // Rethrow the Exception.
}
}

public static void main(String args[])


{
try
{
compute();
}
catch(RuntimeException e)
{
System.out.println("Exception caught:" + e);

NIIT Handling Errors 6.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
}
}
}

In the preceding code, the catch block in the compute() method rethrows the RuntimeException
exception to the catch block defined in the main() method.

throws
The throws keyword is used by a method to specify the types of exceptions that the method can throw. If a
method is capable of raising a checked exception that it does not handle, then the method must specify that
the exception is handled by the calling method. This is done by using the throws keyword.
The throws keyword lists the checked exceptions that a method can throw. You can use the following

R
syntax to declare a method that specifies a throws keyword:

KA
<access_specifier> <modifier> <return_type> <method_name> (<arg_list>) throws

R
<exception_list>

SA
In the preceding syntax, <access_specifier> <modifier> specifies the access specifiers and modifiers,
such as public and static, respectively. <return_type> specifies the type of value returned by the

A
method. <method_name> specifies the name of the method. (<arg_list>) specifies the arguments that the
R
method can accept and throws <exception_list> specifies the exceptions that the method can throw.
IT
Consider the following code that demonstrates the implementation of the throws statement:
R

public class ThrowsDemo


-A

{
01

void display() throws Exception


{
02

throw new Exception();


}
30

public static void main(String[] args) {


52

ThrowsDemo obj1 = new ThrowsDemo();


00

try
{
19

obj1.display();
}
R

catch (Exception e)
{
System.out.println("Runtime Exception raised");
}
}
}

In the preceding code, the display() method declares that an Exception class exception can be generated.
Therefore, the try-catch blocks have been defined to catch the exception in the main() method.

6.12 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
finally
During the execution of a Java program, when an exception is raised, the rest of the statements in the try
block are ignored. Sometimes, it is necessary to execute certain statements irrespective of whether an
exception is raised. The finally block is used to execute these required statements. The statements
specified in the finally block are executed after the control has left the try-catch block.
You can use the following syntax to declare the try and finally block:

try
{
// Block of code
}
finally

R
{

KA
// Block of code that is always executed irrespective of an exception being
raised.

R
}

SA
In the preceding syntax, the try and the finally blocks are declared.
If there is a catch block associated with the try block, the finally block is written after the catch block.
The following code snippet shows how to declare the try, catch, and finally blocks:
A
R
IT
try
{
R

// Block of code.
-A

}
catch(execptionname1 obj1)
01

{
System.out.println("Exception1 has been raised");
02

}
catch(exceptionname2 obj2)
30

{
System.out.println("Exception2 has been raised");
52

}
finally
00

{
// Block of code that is always executed irrespective of an
19

exception being raised or not.


}
R

In the preceding code snippet, the try, catch, and the finally block are declared.
The finally block executes irrespective of whether or not an exception is raised. If an exception is raised,
the finally block executes even if none of the catch blocks match the exception.

try-with-resources
The try-with-resources statement is similar to the try block. However, it is essentially used to declare and
automatically close the objects, such as the file streams and database connections after the execution of the
try block finishes. Such objects are known as resources. In order to be handled by the try-with-resources
statement, the resource must implement the java.lang.AutoCloseable interface.

NIIT Handling Errors 6.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The try-with-resources block ensures that one or more system resources are released when they are no
longer required. Consider a scenario where you are monitoring code that deals with the opening of a resource
inside a try block. You have also specified the instructions to execute in a finally block. If the try block
raises an exception, then the statements in the finally block are executed. In case, if the finally block
also encounters an exception, then the object will never be closed. In such a case, to make your application
more efficient and deal with the improper resource management, the try-with-resources statement can be
used.
You can use the following syntax to declare the try-with-resources statement:

try( [resource-declaration 1];


[resource-declaration n];
)

R
KA
{
//code to be executed
}

R
//after the try block, the resource is closed

SA
In the preceding syntax, multiple resources separated with “;” can be declared with the try statement.
The following code snippet shows how to implement the try-with-resources statement:
A
R
try (BufferedReader br = new BufferedReader(new FileReader("<file_path>")))
IT
{
return br.readLine();
R

}
-A

In the preceding code snippet, BufferedReader is declared as a resource and is used to read data from a
01

file provided at the location specified by <file_path>. The class BufferedReader is a built-in class that
02

implements the java.lang.AutoCloseable interface. The preceding code snippet ensures that the br
instance of BufferedReader is closed after the execution of the try block. You can also achieve the
30

preceding result by specifying a finally block and including the statements to close the instance in it.
However, using the try-with-resources statement reduces code and improves the readability of code.
52
00

User-defined Exceptions
19

In addition to the built-in exceptions, you can create customized exceptions, as per the application
R

requirements. To create a user-defined exception, you need to perform the following steps:
 Create an exception class.
 Implement user-defined exception.

Creating an Exception Class


If you want to create a new user-defined exception, then the class should extend the Throwable class or its
subclasses.

6.14 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code snippet:

public class AgeException extends RuntimeException


{
public AgeException()
{
System.out.println("Invalid value for age");
}

AgeException(String msg)
{
super(msg);

R
}

KA
}

In the preceding code snippet, the AgeException class is created. The AgeException class extends

R
RuntimeException which is a subclass of the Exception class. The constructor of the AgeException()

SA
class prints the message to state that an invalid age value has been entered. In addition, it has an overloaded
constructor which accepts string objects.

Implementing User-defined Exception A


R
IT
Consider the following code to demonstrate the implementation of a user-defined exception:
R

import java.util.*;
-A

public class ValidateAge


01

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

{
int age;
30

Scanner obj1 = new Scanner(System.in);


System.out.println("Enter the age: ");
52

age = obj1.nextInt();
if (age <= 0){
00

try
{
19

throw new AgeException();


}
R

catch (AgeException e)
{
System.out.println("Exception raised");

}
}
else
{
System.out.println("Age entered is " + age);
}

NIIT Handling Errors 6.15

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, if the entered age is less than or equal to 0, the user-defined exception,
AgeException is thrown. When the exception is thrown, the constructor defined in the class of the
user-defined exception is invoked and the Invalid value for age message is displayed.
For example, when the age is specified as 12, the following output is displayed:

Age entered is 12

When the age is specified as 0, the following output is displayed:

Invalid value for age


Exception raised

R
KA
Just a minute:

R
SA
Which one of the following keywords lists the checked exceptions that a method can
throw?

A
1. throws R
2. throw
IT
3. catch
R
-A

4. finally
01

Answer:
02

1. throws
30
52

Activity 6.1: Exception Handling


00
19
R

6.16 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the assert Keyword
Assertions are statements in Java that enable you to test any assumptions that you make regarding a program
during its execution. The assumptions in a program can be simple facts, such as the range of a number should
be between 10 and 20 or a number cannot be greater than 100. For example, in an application that computes
interest, you are certain that the time period cannot be less than or equal to 0. In such a scenario, you can use
an assertion to validate your code and confirm that your application does not use an incorrect value for the
time period. You can implement assertions by using the assert keyword provided in Java.

Understanding Assertions

R
KA
Assertions are used during the testing of a program. They enable you to test the assumptions made in a
program during its execution. For example, a particular program may require the value being passed to a

R
method, to be positive. You can test this by asserting that the value being passed to that particular method is

SA
greater than zero by using an assert keyword.
Assertions in Java provide the following benefits:

A
 By using assertions, data can be validated easily. For example, in a method that performs division, you
R
can use an assertion to validate at run-time if that method is performing division by zero.
IT
 By using assertions, you can confirm whether the program is working as expected.
R

 By using assertions, the task of debugging is simplified as assertions can easily indicate the source and
-A

the reason for an error.


01

Implementing Assertions
02
30

The assert keyword is used to implement assertions. You can declare an assertion by using the following
syntax:
52

assert expressionA;
00
19

Note
R

Before you can successfully implement assertions in your code, you need to enable
them in the Java environment.

In the preceding syntax, expressionA is a boolean expression. During the execution of program,
expressionA in the assert statement is tested. If expressionA returns true, then:
 The assertion made in the program is true.
 The program execution continues uninterruptedly.
 No action takes place.
However, if expressionA returns false, then the assertion made in the program fails. The program throws
an AssertionError object and the program execution terminates.

NIIT Handling Errors 6.17

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code:

public class ValidateAge


{
public static void main(String[] args)
{
int age;
Scanner obj1 = new Scanner(System.in);
System.out.println("Enter the age: ");
age = obj1.nextInt();
assert(age>0)&&(age<130);
System.out.println("The entered age is: " +age);
}
}

R
KA
In the preceding code, an assertion is placed is place to check that the value of age is greater than 0, but less
than 130. While executing the code, if the value of the variable age is less than or equal to 0 or greater than

R
130, the program terminates with the following assertion error:

SA
Exception in thread "main" java.lang.AssertionError
You can also declare assertion by using the following syntax:

A
assert expression1 : expression2;
R
IT
In the preceding syntax, expression1 is a boolean expression and expression2 is an error message value
R

that is displayed if the assertion fails. expression2 is passed to the constructor of the AssertionError
-A

class, if expression1 returns false. The AssertionError constructor converts the value in
expresion2 into a string format and displays the message if the assertion fails.
01
02
30

Just a minute:
52

Which one of the following errors is generated if an assertion does not hold true?
00

1. AssertionError
19

2. IllegalAccess
3. TypeMismatch
R

4. IllegalAssertion
Answer:
1. AssertionError

Activity 6.2: Implementing Assertions

6.18 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which of the following options is the superclass of all the exception objects?
a. Error
b. Throwable
c. RuntimeException
d. Exception

2. Which one of the following options represents invalid conditions that occur in a Java program due to

R
problems, such as database problems?

KA
a. Checked exception
b. Unchecked exception

R
c. Assertion

SA
d. Postconditions

3. Which one of the following checked exceptions occurs when you try to create an object of an abstract
class or an interface by using the newInstance() method?
A
R
IT
a. ClassNotFoundException
IllegalAccessException
R

b.
-A

c. InstantiationException
NoSuchMethodException
01

d.
02

4. Which one of the following options is used to implement assumptions in a Java program?
a. assertion
30

b. asserts
52

c. assert
00

d. invariant
19

5. Which one of the following keywords is used to enclose the statements that might raise an exception?
R

a. try
b. catch
c. throw
d. finally

NIIT Handling Errors 6.19

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
 When a run-time error occurs, an exception is thrown by the JVM which can be handled by an
appropriate exception handler.
 To deal with these exceptions, Java provides various built-in exception classes.
 The Throwable class is the base class of exceptions in Java.
 The Exception class represents the conditions that a program should handle.
 The Error class defines the exceptions related to the Java run-time environment.

R
 Java exceptions are categorized into the following types:

KA
 Checked exceptions
 Unchecked exceptions

R
 You can implement exception handling in a program by using the following keywords and blocks:

SA
 try
 catch

A
 throw R
 throws
IT
 finally
R

 try-with-resources
-A

 A try block encloses the statements that might raise an exception and defines one or more exception
handlers associated with it.
01

 In Java, the catch block is used as an exception handler.


02

 A try block must have at least one catch block that follows the try block, immediately.
30

 You can throw an exception explicitly, by using the throw keyword.



52

The throws keyword is used by a method to specify the types of exceptions that the method can throw.
 The statements specified in the finally block are executed after the control has left the try-catch block.
00

 The try-with-resources block ensures that one or more system resources are released when they are no
19

longer required.
 In addition to the built-in exceptions, you can create customized exceptions, as per the application
R

requirements.
 Assertions are statements in Java that enable you to test any assumptions that you make regarding a
program during its execution.
 You can implement assertions by using the assert keyword provided in Java.

6.20 Handling Errors NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with Regular


Expressions
CHAPTER 7

NIIT Introduction to Object-Oriented Programming 1.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
At times, you need to develop applications that provide a functionality, such as search or filter, which
requires processing of strings. To develop such applications, you need to write lengthy code, which is a time-
consuming task. To solve this issue, Java supports regular expressions also known as regex. Regular
expressions allow you to match a character sequence with another string.
At times, you want to develop applications that can be used worldwide. These applications should be able to
display various pieces of information, such as text, currency, and date, according to the region where they are
deployed. To meet this requirement, Java supports localization.
In this chapter, you will learn about processing strings using regular expressions and implementing
localization.

R
Objectives

KA
R
In this chapter, you will learn to:

SA
 Process strings using regex

A
R
IT
R
-A
01
02
30
52
00
19
R

7.2 Working with Regular Expressions NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Processing Strings Using Regex
Consider a scenario where you need to develop a Java application that provides the functionality to search
the text, hello, in a particular file. To accomplish this task, Java provides a support for regular expressions. A
regular expression is a string that defines a character sequence called pattern. This pattern can be matched
against another string. To work with regular expressions, Java provides two classes, Pattern and Matcher,
in the java.util.regex package.
In addition, Java provides character classes to work with a set of characters. Further, to identify the number
of occurrences of a pattern in a string, Java supports quantifiers.

R
Note

KA
In regular expressions, a group of characters enclosed within square brackets is

R
called a character class.

SA
A
Working with the Pattern and Matcher Classes R
IT
The Pattern class represents a compiled regular expression. As the Pattern class does not define any
R

constructor, the Pattern class reference is obtained by using the static method, compile(), of the
Pattern class.
-A
01

The following code snippet is used to create a reference of the Pattern class:
02

Pattern myPattern = Pattern.compile("Expression");

In the preceding code snippet, the regular expression, Expression, is passed to the compile() method,
30

which returns the object of the Pattern class. Then, the Pattern object is used to create a Matcher object,
52

as shown in the following code snippet:


00

Matcher myMatcher = myPattern.matcher("Expression");


19

To compare the two expressions, the Matcher class provides the matches() method. The
matches()method returns the value, true, if the expression in the matcher object matches the pattern
R

specified in the pattern object. Otherwise, it returns the value, false. The following code snippet shows the
usage of the matches() method:

boolean myBoolean = myMatcher.matches();

NIIT Working with Regular Expressions 7.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the Pattern class.

Method Description Example

String pattern() Is used to return the String s1 = "pattern";


compiled regular Pattern myPattern =
expression. Pattern.compile(s1);
String s2 =
myPattern.pattern();
System.out.println(s2);

R
Output:

KA
pattern

R
String[] Is used to split the Pattern pattern =

SA
split(CharSequence input, given input sequence Pattern.compile(":");
int limit) based on the pattern String[] split =
and the limit. pattern.split("One:two:three"

A ,2);
R
for (String element : split)
IT
{
R
-A

System.out.println("element =
" + element);
01

}
02

Output:
30

element = One
52

element = two:three
00

static boolean Is used to compile the boolean matches =


matches(String given regular Pattern.matches("is", "is");
19

regex,CharSequence input) expression and attempt System.out.println("matches =


to match the given " + matches);
R

input against it.


Output:
matches = true

The Methods of the Pattern Class

7.4 Working with Regular Expressions NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the Matcher class.

Method Description Example

Matcher appendReplace Is used to process the input Pattern pattern=


ment(StringBuffer sb, character sequence specified Pattern.compile("John");
String replacement) in a matcher by adding the Matcher matcher=
input character sequence to pattern.matcher("John does
the StringBuffer this, and John does that");
StringBuffer s3 = new
variable. If the match
StringBuffer();
specified in Pattern is while(matcher.find())

R
found in Matcher, then it is {

KA
replaced by the replacement matcher.appendReplacement(s3,
string and is appended to the "sam");

R
StringBuffer variable. System.out.println(s3.toString
());

SA
Further, the remaining
}
character sequence is
truncated. Output:

A sam
R
IT
sam does this, and sam
R

StringBuffer appendTa Is used to process the input Pattern pattern=


-A

il(StringBuffer sb) character sequence specified Pattern.compile("John");


01

in Matcher by adding the Matcher matcher=


input character sequence to pattern.matcher("John does
02

the StringBuffer this, and John does that");


StringBuffer s3 = new
variable. If the match
30

StringBuffer();
specified in Pattern is while(matcher.find())
52

found in Matcher, then it is {


replaced by the replacement matcher.appendReplacement(s3,
00

string and is appended to the "sam");


StringBuffer variable. System.out.println(s3.toString
19

Further, the remaining ());


}
R

character sequence is matcher.appendTail(s3);


appended. System.out.println(s3.toString
());
Output:
sam
sam does this, and sam
sam does this, and sam does
that

NIIT Working with Regular Expressions 7.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description Example

String replaceAll(Str Is used to replace every Pattern pattern=


ing replacement) subsequence of the input Pattern.compile("John");
sequence that matches the Matcher matcher=
pattern with the given pattern.matcher("John does
replacement string. this, and John does that");
String s2 =
matcher.replaceAll("sam");
System.out.println("replaceAll
= " + s2);
Output:

R
KA
replaceAll = sam does this,
and sam does that

R
String replaceFirst(S Is used to replace the first Pattern pattern=

SA
tring replacement) subsequence of the input Pattern.compile("John");
sequence that matches the Matcher matcher=
pattern with the given pattern.matcher("John does
replacement string.
A this, and John does that");
R String s2 =
IT
matcher.replaceFirst("sam");
System.out.println("replaceFir
R

st = " + s2);
-A

Output:
01

replaceFirst = sam does this,


02

and John does that


30

int start(int group) Is used to return the start Pattern pattern =


index of the subsequence Pattern.compile("a");
52

captured by the given group Matcher matcher =


during the match operation. pattern.matcher("This is a
00

text");
while(matcher.find())
19

{
System.out.println("Match
R

started at:"+ matcher.start(0)


);
}
Output:
Match started at:8

7.6 Working with Regular Expressions NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description Example

int end(int group) Is used to return the offset Pattern pattern =


after the last character of Pattern.compile("a");
the subsequence is captured Matcher matcher =
by the given group during pattern.matcher("This is a
the match operation. text");
while(matcher.find())
{
System.out.println("Match
ended at:"+ matcher.end(0));
}

R
Output:

KA
Match ended at:9

R
The Methods of the Matcher Class

SA
Working with Character Classes
A
R
Consider a scenario where you need to search certain words in a file that can have the prefix “ a”, “b”, or “c”
IT
and suffix “at”, such as, bat and cat. For this, regular expressions provide character classes. The character
R

class specifies the characters that will successfully match a single character from a given input string.
-A

The following table lists the constructs of the character class.


01
02

Construct Description
30

[def] Match succeeds if the given input string starts with the
characters: d, e, or f.
52

[^def]
00

Match succeeds if the given input string starts with any


character except d, e, or f (negation).
19

[a-zA-Z] Match succeeds if the given input string starts with any
R

character between a to z or A to Z, inclusive (range).

[b-e[n-q]] Match succeeds if the given input string starts with any
character between b to e or n to q.

[a-z&&[abc]] Match succeeds if the given input string starts with


characters: a, b, or c (intersection).

[a-z&&[^bcd]] Match succeeds if the given input string starts with any
character between a to z, except b, c, and d : [ae-z]
(subtraction).

NIIT Working with Regular Expressions 7.7

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Construct Description

[a-z&&[^n-p]] Match succeeds if the given input string starts with any
character between a to z and not n to p: [a-mq-z]
(subtraction).

The Constructs of the Character Class


Consider the following code that demonstrates the use of the character class:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegx

R
{

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

R
Pattern myPattern = Pattern.compile("[abc]at");
Matcher myMatcher = myPattern.matcher("bat");

SA
boolean myBoolean = myMatcher.matches();
if(myBoolean)
System.out.println("Expression Matched");
else
A
System.out.println("Expression Not Matched");
R
IT
}
}
R
-A

Once the preceding code is executed, the following output is displayed:


01

Expression Matched
02

In the preceding code, myBoolean, will have the value, true, only when the first letter matches one of the
characters defined by the character class.
30
52

Working with Quantifiers


00

Consider a scenario where you want to specify the number of times a character or a sequence of characters
19

appears in an expression. For example, you want to find the occurrence of the characters, Ro, in the
expression, “When in Rome, do as the Romans”. To accomplish this task, a regular expression provides
R

quantifiers that help you specify the number of occurrences of a string matched with the specified string. In
addition, quantifiers enable you to easily select a range of characters in the files. Quantifiers are of the
following three types:
 Greedy: Is used to match with the longest possible string that matches the pattern.
 Reluctant: Is used to match with the shortest possible string that matches the pattern.
 Possessive: Is used to match the regular expression with the entire string. It matches only when the
whole string satisfies the criteria.

7.8 Working with Regular Expressions NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table describes the different types of quantifiers.

Greedy Reluctant Possessive Description

X? X?? X?+ X, once or not at all

X* X*? X*+ X, zero or more times

X+ X+? X++ X, one or more times

X{n} X{n}? X{n}+ X, exactly n times

R
X{n,} X{n,}? X{n,}+

KA
X, at least n times

X{n,m} X{n,m}? X{n,m}+

R
X, at least n times but not more

SA
than m times

The Types of Quantifiers

A
Consider the following code snippet to test the occurrence of the word beginning with Ro in the expression,
R
When in Rome, do as the Romans:
IT
String text="When in Rome, do as the Romans ";
R

String textSplit[]=text.split(" ");


-A

Pattern myPattern=Pattern.compile("Ro.+");
for(int i=0;i<textSplit.length;i++)
01

{
Matcher myMatcher=myPattern.matcher(textSplit[i]);
02

boolean myBoolean =myMatcher.matches();


System.out.println(myBoolean);
30

}
52

In the preceding code snippet, the split() method splits the expression “When in Rome, do as the
Romans”. Thereafter, the pattern, Ro, is compared with each split expression. The
00

System.out.println(myBoolean); statement prints the value, true, if the first two characters of the
19

word are “Ro”.


R

Consider the following code that accepts the pattern and matcher from the user:

import java.util.regex.*;
import java.util.*;
public class PatternMethods
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the desired pattern: ");
String pattern = input.nextLine();
System.out.println("Enter the text: ");
String matcher = input.nextLine();
Pattern myPattern2 = Pattern.compile(pattern);

NIIT Working with Regular Expressions 7.9

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Matcher myMatcher2 = myPattern2.matcher(matcher);
Boolean myBoolean2 = myMatcher2.matches();
boolean b = myBoolean2;
if (b == true)
{

System.out.println("I found the text:" + myMatcher2.group() + "\n"


+ "Starting at:" + myMatcher2.start() + "\n"
+ "Ending at index:" + myMatcher2.end());

}
else if (b == false)
{
System.out.println("No match found");

R
}

KA
}
}

R
SA
While executing the preceding code, if you provide the pattern as .*Friday and matcher as XFriday, then
the following output will be displayed:

A
I found the text:XFriday R
Starting at:0
Ending at index:7
IT
R

The preceding output is generated as the pattern uses the greedy quantifier. Since the quantifier is greedy,
-A

initially, the entire input string is consumed. Because the entire input string does not match with the pattern,
the matcher traverses back by one letter at a time, until the rightmost occurrence of “Friday” has been
01

found. At this point, the match succeeds and the search ends.
02

While executing the preceding code, if you provide the pattern as .*?Friday and matcher as XFriday, then
the following output will be displayed:
30

I found the text:XFriday


52

Starting at:0
Ending at index:7
00

The preceding output is generated as the pattern uses the reluctant quantifier. Since the quantifier is reluctant,
19

initially, no character of the input string is consumed. Thereafter, the characters of the string are consumed
one by one.
R

While executing the preceding code, if you provide the pattern as .*+Friday and matcher as XFriday, then
the following output will be displayed:

No match found
The preceding output is generated as the pattern uses the possessive quantifier. Since the quantifier is
possessive, initially, the entire input string is consumed. Because this quantifier does not traverse back, it
fails to find a match.

7.10 Working with Regular Expressions NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one the following methods is used for compiling the given regular expression
and attempting to match the given input against the specified pattern?

1. static boolean matches(String regex,CharSequence input)

2. Pattern pattern()

3. static Pattern compile(String regex,int flags)

R
KA
4. Matcher appendReplacement(StringBuffer sb,String replacement)

R
Answer:

SA
1. static boolean matches(String regex,CharSequence input)

A
R
IT
Activity 7.1: Processing Strings Using
R

Regex
-A
01
02
30
52
00
19
R

NIIT Working with Regular Expressions 7.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following pattern class methods is used to return the regular expression from which the
pattern was compiled?
a. String pattern()
b. static boolean matches(String regex,CharSequence input)
c. static Pattern compile (String regex)

2. Which one of the following quantifiers is used to match with the shortest possible string that matches the
pattern?

R
a. Greedy

KA
b. Reluctant

R
c. Possessive

SA
3. Identify the correct option by using which the match succeeds if the given input string starts with any
character between a and z, except b, c, and d.
a. [a-z&&[abc]]
A
R
b. [b-z&&[^bcd]]
IT
c. [a-z&&[^n-p]]
R

d. [abc]
-A
01

4. Identify the correct option that is used to match the pattern with the longest possible string.
a. Greedy
02

b. Reluctant
30

c. Possessive
52
00
19
R

7.12 Working with Regular Expressions NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
 Regular expressions allow you to match a character sequence with another string.
 A regular expression is a string that defines a character sequence called pattern.
 To work with regular expressions, Java provides two classes, Pattern and Matcher, in the
java.util.regex package.
 Java provides character classes to work with a set of characters.
 To identify the number of occurrences of a pattern in a string, Java supports quantifiers.

R
 The Pattern class represents a compiled regular expression.

KA
 As the Pattern class does not define any constructor, the Pattern class reference is obtained by using
the static method, compile(), of the Pattern class.

R
 The character class specifies the characters that will successfully match a single character from a given

SA
input string.
 A regular expression provides quantifiers that help you specify the number of occurrences of a string
matched with the specified string.
 Quantifiers are of the following three types:
A
R
IT
 Greedy
R

 Reluctant
-A

 Possessive
01
02
30
52
00
19
R

NIIT Working with Regular Expressions 7.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with Streams


CHAPTER 8

NIIT Introduction to Object-Oriented Programming 1.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Most programs accept input from the user, process the same, and produce the output. Therefore, all
programming languages support the reading of input from an input stream, such as a file, and display the
output from an output stream, such as a console. Java handles all the input and output operations in the form
of streams that act as a sequence of bytes or characters traveling from a source to a destination. When a
stream of data is being sent, it is said to be written; and when a stream of data is being received, it is said to
be read.
This chapter focusses on reading the data from an input stream and writing the same to an output stream.

Objectives

R
KA
In this chapter, you will learn to:
 Work with input stream

R
 Work with output stream

SA
A
R
IT
R
-A
01
02
30
52
00
19
R

8.2 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Working with Input Stream
Consider a scenario where you need to develop a Java application that converts the documents from one
format into another, such as .txt into .pdf. To develop such an application, you need to read data from an
input stream, such as a file. The data can be read in the form of bytes or characters from these streams. For
this, Java provides the InputStream class and its subclasses. To read data in the form of characters, Java
provides the Reader classes inside the java.io package. The following figure shows the class hierarchy of
the java.io package.

java.io

R
(package)

KA
R
SA
InputStream Reader
(class) (class)

A
R
IT
FileInputStream FilterInputStream BufferedReader InputStreamReader
R

(class) (class) (class) (class)


-A
01

BufferedInputStream FileReader
02

(class) (class)
30
52

The Input Stream Class Hierarchy


00

The FileInputStream and FilterInputStream classes are subclasses of the InputStream class. The
BufferedInputStream class is a subclass of the FilterInputStream class. The BufferedReader and
19

InputStreamReader classes are the subclasses of the Reader class. The FileReader class is the subclass
R

of the InputStreamReader class.

Using the FileInputStream Class


The FileInputStream class is used to read data and the steams of bytes from the file. The
FileInputStream class provides various constructors that can be used to create an instance.

NIIT Working with Streams 8.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the constructors of the FileInputStream class.

Constructor Description

FileInputStream(File file) It creates an instance of FileInputStream by


opening a connection to an actual file, file, in the
file system.

FileInputStream(FileDescriptor It creates an instance of FileInputStream by


fdObj) using the file descriptor, fdObj, which represents
an existing connection to an actual file in the file

R
system.

KA
FileInputStream(String name) It creates FileInputStream by opening a

R
connection to an actual file specified in the name

SA
parameter.

The Constructors of the FileInputStream Class

A
The following table lists the methods of the FileInputStream class with their description.
R
IT
Method Description
R
-A

int read() Is used to read a byte of data from the input stream.
01

FileDescriptor getFD() Is used to return the FileDescriptor object that


02

represents the connection to the actual file in the file


system.
30

The Methods of the FileInputStream Class


52

Consider the following code to read the data from a file using the FileInputStream class:
00

import java.io.FileInputStream;
19

import java.io.IOException;
public class FileInputStreamDemo
R

public static void main(String[] args)


{
int i;
char c;
try (FileInputStream f = new FileInputStream("D:\\Files\\File.txt"))
{
while ((i = f.read()) != -1)
{
c = (char) i;
System.out.print(c);
}
}

8.4 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
catch (IOException ex)
{
System.out.println(ex);
}
}
}

In the preceding code, the FileInputStreamDemo class is created that is reading data from the File.txt
file by using the read() method. The System.out.print(c); statement prints the bytes of data present
in the file.

Using the BufferedInputStream Class

R
KA
The BufferedInputStream class is used to perform the read operations by using a temporary storage,
buffer, in the memory. A buffer is used to store the retrieved data when the first system call to read data is

R
made. In addition, for every subsequent request to read data, the buffer is used to retrieve data by a program

SA
instead of making system calls. The retrieval of data by using a buffer instead of a system call is much faster;
and hence, it improves the efficiency of the program. The BufferedInputStream class provides various
constructors that can be used to create an instance. The following table lists the constructors of the

A
BufferedInputStream class. R
IT
Constructor Description
R
-A

BufferedInputStream(InputStream in) It creates an instance of BufferedInputStream and


01

saves the specified InputStream arguments in the in


parameter for later use.
02

BufferedInputStream(InputStream in, It creates an instance of


30

int size) BufferedInputStream with the specified buffer


52

size, and saves the InputStream argument in the in


parameter for later use.
00

The Constructors of the BufferedInputStream Class


19

The following table lists the methods of the BufferedInputStream class with their description.
R

Method Description

int available() Is used to return an estimate of the number of bytes


that can be read from this input stream without
blocking the next invocation of a method for this input
stream.

void mark(int readlimit) Is used to mark the present position in the stream.
Subsequent calls to reset() will attempt to
reposition the stream to this point.

NIIT Working with Streams 8.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description

void reset() The reset() method returns the stream to the


marked point.

boolean markSupported() Is used to test if this input stream supports


the mark() and reset() methods.

void close() Is used to close the input stream and release any
system resource associated with the stream. Once the
stream is closed, further read(), available(),
reset(), or skip() invocation will throw

R
IOException.

KA
int read(byte[] b,int off,int len) Is used to read bytes from the input stream into the

R
specified byte array, starting from the given offset.

SA
long skip(long n) Is used to skip over n bytes of data from this input
stream.

A
R
The Methods of the BufferedInputStream Class
IT
Consider the following code of BufferedInputStream that prints the output on the console:
R
-A

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
01

import java.io.IOException;
02

public class BufferedInputStreamDemo


{
30

public static void main(String[] args)


{
52

String s = "This is a BufferedInputStream Demo Program";


byte buf[] = s.getBytes();
00

try(ByteArrayInputStream in = new ByteArrayInputStream(buf);


19

BufferedInputStream f = new BufferedInputStream(in)){


R

int c;
while ((c = f.read()) != -1)
{
System.out.print((char) c);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}

8.6 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the BufferedInputStreamDemo class has been created. The
System.out.print((char) c); statement prints the output on the console.

Note
A ByteArrayInputStream class allows you to create a buffer in memory that will be
used as InputStream. The input source is a byte array.

Using the FileReader Class

R
The FileReader class is used for reading characters from a file, but it does not define any method of its

KA
own. It derives all the methods from its base classes, such as the Reader and InputStreamReader classes.
The FileReader class provides various constructors that can be used to create an instance. The following

R
table lists the constructors of the FileReader class.

SA
Constructor Description

A
R
FileReader(File file) It creates an instance of FileReader that reads
IT
from the file specified in the file parameter.
R

FileReader(FileDescriptor fd)
-A

It creates an instance of FileReader that reads


from the specified FileDescriptor class.
01

FileReader(String fileName)
02

It creates an instance of FileReader that reads


from the file with the name specified by the
30

fileName parameter.
52

The Constructors of the FileReader Class


00

Consider the following code that reads data from the file:
19

import java.io.FileReader;
import java.io.IOException;
R

class FileReaderDemo {
public static void main(String args[])
{
try (FileReader f = new FileReader("D:\\Files\\file.txt "))
{
char[] a = new char[50];
f.read(a);
for (char c : a)
{
System.out.print(c);
}
}

NIIT Working with Streams 8.7

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
catch (IOException e)
{
System.out.println(e);
}
}
}

In the preceding code, the FileReaderDemo class has been created that reads the data from the file,
file.txt. The System.out.print(c); statement prints the output on the console.

Using the BufferedReader Class

R
The BufferedReader class is used to read the text from a character-input stream, such as a file, console,

KA
and array, while buffering characters. As the data is buffered, the read operation becomes more efficient
using the BufferedReader class. There are various constructors provided by the BufferedReader class

R
that can be used to create an instance. The following table lists the constructors of the BufferedReader

SA
class.

A
Constructor Description
R
BufferedReader(Reader in)
IT
It creates an instance of BufferedReader that
uses a default-sized input buffer.
R
-A

BufferedReader(Reader in, int sz) It creates an instance of BufferedReader that


01

uses an input buffer of the specified size.


02

The Constructors of the BufferedReader Class


The following table lists the commonly used methods of the BufferedReader class with their description.
30
52

Method Description
00

void mark(int readAheadLimit) Is used to mark the present position in the stream.
19

Subsequent calls to reset() will attempt to


R

reposition the stream to this point.

boolean markSupported() Is used to tell whether this stream supports the


mark() operation.

String readLine() Is used to read a line of text. A line is considered to


be terminated by any one of a line feed ('\n'), a
carriage return ('\r'), or a carriage return followed
immediately by a linefeed.

8.8 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description

boolean ready() Is used to tell whether this stream is ready to be


read. A buffered character stream is ready if the
buffer is not empty, or if the underlying character
stream is ready.
The Methods of the BufferedReader Class
Consider the following code that accepts two numbers from the user by using the BufferedReader class
and prints the sum of these two numbers:

import java.io.*;

R
KA
public class BufferedReaderDemo
{

R
public static void main(String args[]) throws IOException

SA
{
try(BufferedReader br = new BufferedReader(new
InputStreamReader(System.in))){

System.out.println("Enter First number");


A
R
String s = br.readLine();
IT
System.out.println("Enter Second number");
String s1 = br.readLine();
R

int i = Integer.parseInt(s);
-A

int i1 = Integer.parseInt(s1);
int i3 = i + i1;
01

System.out.println("Sum=" + i3);
}
02

}
30

In the preceding code, an object of the BufferedReaderDemo class has been created that wraps an
52

InputStreamReader class to read data from the console. The readLine() method accepts the input from
00

the user and stores it in the string variables, s and s1, respectively. Thereafter, the string value is converted
into the integer value by using the parseInt() method, which is the static method of the Integer class.
19

Further, the System.out.println("Sum=" + i3); statement prints the output.


R

NIIT Working with Streams 8.9

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one of the following methods is used to ensure that the close() method of the
FileInpuStream class is called when there are no more references to it?

1. finalize()

2. ready()

3. reset()

R
KA
4. close()

R
Answer:

SA
1. finalize()

A
R
IT
R
-A
01
02
30
52
00
19
R

8.10 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Working with Output Stream
Consider a scenario where you need to develop a Banking application. In this application, you need to
implement a set of functionality to maintain a log for every transaction performed in the application. For this,
you need to write the data to an output stream, such as a file. The data can be written in the form of bytes or
characters to these streams. To write the data in the form of bytes, Java provides the OutputStream classes.
To write the data in the form of characters, Java provides the Writer classes inside the java.io package.
The following figure shows the class hierarchy of the java.io package.

java.io

R
KA
(package)

R
SA
OutputStream Writer
(class) (class)

A
R
IT
FilterOutputStream FileOutputStream BufferedWriter OutputStreamWriter
R

(class) (class) (class) (class)


-A
01
02

BufferedOutputStream FileWriter
(class) (class)
30
52

The Output Stream Class Hierarchy


00

The FileOutputStream and FilterOutputStream classes are the subclasses of the


OutputStream class. The BufferedOutputStream class is subclass of the FilterOutputStream class.
19

The BufferedWriter and OutputStreamWriter classes are the subclasses of the Writer class. The
R

FileWriter class is the subclass of the OutputStreamWriter class.

Using the FileOutputStream Class


The FileOutputStream class is used for writing data, byte by byte, to a file. The instance creation of
FileOutputStream class is not dependent on a file on which the writing needs to be done. If the file does
not exist, then it will create a file before opening it for the output operation. If the file is in the read-only
mode, then it will throw an error. The FileOutputStream class provides various constructors that can be
used to create an instance.

NIIT Working with Streams 8.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the constructors of the FileOutputStream class.

Constructor Description

FileOutputStream(File file, It creates an instance of FileOutputStream


boolean append) that writes the file represented by the specified
File object. If the append parameter is true,
then bytes will be written at the end of the file.
Otherwise, bytes will be written at the beginning.

FileOutputStream(FileDescriptor fdObj) It creates an instance of FileOutputStream

R
that writes to the file descriptor, which

KA
represents an existing connection with the actual
file.

R
FileOutputStream(String name) It creates an instance of FileOutputStream

SA
that writes to the file with the name specified by
the name parameter.

FileOutputStream(String name,
A
It creates an instance of FileOutputStream
R
boolean append) that writes to the file with the name specified in
IT
the name parameter. If the append parameter is
R

true, then bytes will be written at the end of the


-A

file. Otherwise, bytes will be written at the


beginning.
01
02

The Constructors of the FileOutputStream Class


The following table lists the commonly used methods of the FileOutputStream class with their
30

description.
52
00

Method Description
19

FileDescriptor getFD() Is used to return the file descriptor associated with this
stream.
R

void write(int b) Is used to write the specified byte to this file output stream.

The Methods of the FileOutputStream Class


Consider the following code to write the data to a file using the FileOutputStream class:

import java.io.*;
public class FileOutputStreamDemo
{
public static void main(String[] args) throws IOException
{
boolean bool;
long pos;

8.12 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
String s = "This is a FileOutputStream Program";
byte buf[] = s.getBytes();
try (FileOutputStream fos = new
FileOutputStream("D:\\Files\\File.txt "))
{
for (int i = 0; i < buf.length; i++)
{
fos.write(buf[i]);
}
}
catch (Exception e)
{
System.out.println(e);
}

R
}

KA
}

In the preceding code, the FileOutputStreamDemo class has been created. The fos.write(buf[i]);

R
statement writes the data into the file.

SA
Using the BufferedOutputStream Class
A
R
The BufferedOutputStream class writes bytes to an output stream using a buffer for increased efficiency.
IT
The BufferedOutputStream class provides various constructors that can be used to create an instance.
R

The following table lists the constructors of the BufferedOutputStream class.


-A
01

Constructor Description
02

BufferedOutputStream(OutputStream out) It creates an instance of the buffered output


30

stream that writes data to the specified output


stream.
52

BufferedOutputStream(OutputStream out,
00

It creates an instance of the buffered output


int size) stream to write data to the specified output
19

stream with the specified buffer size.


R

The Constructors of the BufferedOutputStream Class

NIIT Working with Streams 8.13

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the commonly used methods of the BufferedOutputStream class with their
description.

Method Description

void flush() Is used to flush the buffered output stream.


This forces any buffered output bytes to be
written out to the output stream.

void write(byte[] b, int off, int len) Is used to write len bytes from the byte
array. It starts writing from the offset

R
value, off, to the buffered output stream.

KA
The Methods of the BufferedOutputStream Class

R
Consider the following code of the BufferedOutputStream class that prints the output on the console:

SA
import java.io.BufferedOutputStream;
import java.io.IOException;

public class BufferedOutputStream


A
R
{
IT
public static void main(String[] args)
{
R

try (BufferedOutputStream b = new BufferedOutputStream(System.out))


-A

{
String s = "This is a BufferedOutputStream Demo Program";
01

byte buf[] = s.getBytes();


02

b.write(buf);
b.flush();
30

}
52

catch (IOException e)
{
00

System.out.println(e);
}
19

}
}
R

In the preceding code, the BufferedOutputStream class has been created. The b.write(buf);
statement prints the output on the console.

8.14 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the BufferedWriter Class
The BufferedWriter class can be used to write text to an output stream. This class writes relatively large
chunks of data to an output stream at once. The BufferedWriter class provides various constructors that
can be used to create an instance. The following table lists the constructors of the BufferedWriter class.

Constructor Description

BufferedWriter(Writer out) It creates an instance of BufferedWriter that uses


a default-sized output buffer.

R
BufferedWriter(Writer out, int

KA
It creates an instance of BufferedWriter that uses
size) an output buffer of the given size.

R
The Constructors of the BufferedWriter Class

SA
The following table lists the commonly used methods of the BufferedWriter class with their description.

A
Method
R
Description
IT
void newLine() Is used to write a line separator that is defined by the
R

system property, line.separator.


-A
01

void write(char[] cbuf, int off, Is used to write a portion of an array of characters.
int len)
02

The Methods of the BufferedWriter Class


30

Consider the following code to write the data to the console using the BufferedWriter class:
52

import java.io.BufferedWriter;
00

import java.io.IOException;
import java.io.OutputStreamWriter;
19

public class BufferedWriterDemo


R

{
public static void main(String args[])
{
try (BufferedWriter b = new BufferedWriter(new
OutputStreamWriter(System.out)))
{
String fruit[] = {"Apple", "Banana", "Grapes"};
b.write("Different types of fruit are:" + "\n");
for (int i = 0; i < 3; i++)
{
b.write(fruit[i] + "\n");
b.flush();
}
}

NIIT Working with Streams 8.15

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
catch (IOException e)
{
System.out.println(e);
}
}
}
The output of the preceding code is:

Different types of fruit are:


Apple
Banana
Grapes

In the preceding code, an array of fruits has been created. Then, an object of BufferedWriter has been

R
created that wraps the OutputStreamWriter class to write data to the console output stream. The write()

KA
method writes the string to the console.

R
SA
Using the FileWriter Class

A
The FileWriter class writes character data to a file. This class does not define any methods of its own. It
R
derives all methods from its base classes, such as the Writer and the OutputStreamWriter classes.
IT
The FileWriter class provides various constructors that can be used to create an instance. The following
R

table lists the constructors of the FileWriter class.


-A
01

Constructor Description
02

FileWriter(File file) It creates an instance of the FileWriter object


30

from a File object.


52

FileWriter(File file,boolean append) It creates an instance of the FileWriter object


from a File object. If the second argument is true,
00

then characters will be written at the end of the file.


Otherwise, characters will be written at the
19

beginning of the file.


R

FileWriter(FileDescriptor fd) It creates an instance of the FileWriter object


associated with a file descriptor.

FileWriter(String fileName,boolean a It creates an instance of the FileWriter object


ppend) with a given file name. If the second argument is
true, then characters will be written at the end of
the file. Otherwise, characters will be written at the
beginning of the file.

The Constructors of the FileWriter Class

8.16 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code that writes the data to the file:

import java.io.FileWriter;
import java.io.IOException;

class FileWriterDemo
{
public static void main(String args[])
{
try (FileWriter f = new FileWriter("D:\\Files\\file.txt "))
{
String source = "This is FileWriter Program";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);

R
f.write(buffer);

KA
}
catch (IOException e)

R
{
System.out.println(e);

SA
}
}
}

A
R
In the preceding code, the FileWriterDemo class has been created that writes data to the file.txt file.
IT
The f.write(buffer); statement writes the data to the file.
R
-A
01

Just a minute:
02

Which one of the following FileWriter constructors will you use if there is a
30

requirement to append data at the end of a new file?


52

1. FileWriter(File file)

2. FileWriter(File file,boolean append)


00

3. FileWriter(FileDescriptor fd)
19

4. FileWriter(String fileName,boolean append)


R

Answer:
4. FileWriter(String fileName,boolean append)

Activity 8.1: Working with Input Stream and


Output Stream

NIIT Working with Streams 8.17

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following constructors of the FileOutputStream class is used to write bytes at the
end of a given file?
a. FileOutputStream(File file,boolean append)
b. FileOutputStream(FileDescriptor fdObj)
c. FileOutputStream(File file)
d. FileOutputStream(String name,boolean append)

R
2. State whether the following statement is true or false.

KA
The markSupported() method is used to test whether the input stream supports the mark() and
reset() methods.

R
SA
3. Which one of the following methods is used to return the estimate number of bytes that can be read from
an input stream?
a. available()
b. reset()
A
R
read()
IT
c.
d. ready()
R
-A

4. Which one of the following classes does not have its own methods and inherits the methods of the
01

InputStreamWriter class?
a. FileWriter
02

b. BufferedWriter
30

c. BufferedOutputStream
52

d. FileOutputStream
00

5. Which one of the following classes does not have its own methods and inherits the methods of the
InputStreamReader class?
19

a. FileReader
R

b. BufferedReader
c. BufferedInputStream
d. FileInputStream

8.18 Working with Streams NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
 Java handles all the input and output operations in the form of streams that act as a sequence of bytes or
characters traveling from a source to a destination.
 When a stream of data is being sent, it is said to be written; and when a stream of data is being received,
it is said to be read.
 To read data in the form of characters, Java provides the Reader classes inside the java.io package.
 The FileInputStream class is used to read data and the steams of bytes from the file.
 The BufferedInputStream class is used to perform the read operations by using a temporary storage,

R
buffer, in the memory.

KA
 The FileReader class is used for reading characters from a file, but it does not define any method of its

R
own.

SA
 The BufferedReader class is used to read the text from a character-input stream, such as a file,
console, and array, while buffering characters.
 To write the data in the form of bytes, Java provides the OutputStream classes.

A
To write the data in the form of characters, Java provides the Writer classes inside the java.io
R
package.
IT
 FileOutputStream is used for writing data, byte by byte, to a file.
R

 The BufferedOutputStream class writes bytes to an output stream using a buffer for increased
-A

efficiency.
01

 The BufferedWriter class can be used to write text to an output stream.


02

 The FileWriter class writes character data to a file. This class does not define any methods of its own.
30
52
00
19
R

NIIT Working with Streams 8.19

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Solutions to Practice Questions

Chapter 1

1. b. .java
2. a. synchronized
3. b. native
4. b. public

R
5. b. character

KA
R
Chapter 2

SA
1. c. Modulus operator
A
2. b. instanceof operator
R
IT
3. a. Logical AND
R

4. c. 3
-A

5. c. %
01
02

Chapter 3
30
52

1. True
2. False
00

3. d. for
19

4. True
R

5. 16 14

Chapter 4

1. d. int[ ] list = new int[10];


2. b. 2,4,6,8,10
3. a. equals()
4. b. toCharArray()

NIIT S.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Chapter 5

1. c. Abstract class
2. a. implements
3. b. Multilevel inheritance
4. d. Hierarchical inheritance
5. a. Polymorphism

Chapter 6

R
KA
1. b. Throwable

R
SA
2. a. Checked exception
3. c. InstantiationException
4. c. assert
A
5. a. try
R
IT
R

Chapter 7
-A
01

1. True
02

2. a. String pattern()
30

3. b. Reluctant
4. b. [b-z&&[^bcd]]
52

5. a. Greedy
00
19

Chapter 8
R

1. a. FileOutputStream(File file,boolean append)


2. True
3. a. available()
4. a. FileWriter
5. a. FileReader

S.2 NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Glossary

accessing a file that does not exist or referring a


A class that does not exist.
Abstract class Comparison operators
An abstract class is a class that contains one or Comparison operators are used to compare two
more abstract methods. values and perform an action on the basis of the
result of that comparison.
Arithmetic operators
Constructors

R
Arithmetic operators are used to perform

KA
arithmetic operations on operands. Constructors are methods that have the same
name as that of the class and have no return
Array

R
type.

SA
An array is a collection of elements of a single
continue
data type stored in adjacent memory locations.
The continue statement skips all the
Assertions
A
statements following the continue statement
R
Assertions are statements in Java that enable and moves the control back to the loop
IT
you to test any assumptions that you make statement.
regarding a program during its execution.
R
-A

E
01

B Enum
02

Bitwise operators
An enum is used to define a fixed set of
30

Bitwise operators are used for the manipulation constants.


of data at the bit level.
52

Error
break
00

An error is a condition that causes disruption in


The break statement stops the execution of the the execution of a program.
19

remaining statements.
Event handler
R

Bytecode
An event handler is a method that is invoked by
In Java, when you compile an error-free code, an event listener when the event is generated.
the compiler converts the program to a
Event listener
platform independent code, known as the
bytecode. An event listener listens for a specific event
and gets notified when the specific event
occurs.
C Event source
Checked exceptions An event source is an object that generates an
event.
These are the invalid conditions that occur in a
Java program due to the problems, such as
NIIT G.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exception which optimizes the performance of a Java
program.
The term, exception, in Java indicates an
abnormal event that occurs during the program
execution and disrupts the normal flow of
instructions. K
Keywords

G Keywords are the reserved words with a special


meaning for a language, which express the
Garbage collection language features.
The process of automatically deallocating

R
memory is called garbage collection.
L

KA
Logical operators

R
I

SA
Logical operators are used to evaluate operands
if and return a boolean value.
The if construct executes statements based on
the specified condition.
A
R
M
IT
if-else
R

The if-else construct executes statements Method


-A

based on the specified condition. A method is a set of statements that is intended


to perform a specific task.
01

Inheritance
Method overriding
02

The process of creating a new class by


acquiring some features from an existing class Method overriding enables a subclass to
30

is known as inheritance. provide its own implementation of a method


that already has an implementation defined in
52

instanceof
its superclass.
The instanceof operator is used to test
00

Multidimensional arrays
whether an object is an instance of a specific
19

class at runtime or not. Multidimensional arrays are arrays of arrays.


R

J O
Java Virtual Machine Object
Java Virtual Machine interprets the bytecode An object is an instance of a class and has a
into the machine code that can be run on that unique identity.
machine.
One-dimensional array
JIT compiler
A one-dimensional array is a collection of
The JIT compiler compiles the bytecode into elements with a single index value.
machine executable code, as and when needed,

G.2 NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Operators
U
Operators allow you to perform various
mathematical and logical calculations, such as Unary operator
adding and comparing numbers. An operator that requires one operand is called
a unary operator.
Unchecked exceptions
P The unchecked exceptions occur because of
Polymorphism programming.
Polymorphism is the ability to redefine a
function in more than one form.

R
KA
S

R
SA
Shift operator
A shift operator is used to shift the bits of its
operand either to the left or to the right.

A
Subclass
R
IT
In inheritance, the class that inherits the data
R

members and methods from another class is


-A

known as the subclass or derived class.


01

Superclass
02

The class from which the subclass inherits the


features is known as the superclass or base
30

class.
52

switch
The switch construct evaluates an expression
00

for multiple values.


19
R

T
Ternary operator
The ternary operator works on a logical
expression and two operands. It returns one of
the two operands depending on the result of the
expression.
Thread
A thread is the smallest unit of execution in a
Java program.

NIIT G.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Appendix

NIIT Introduction to Object-Oriented Programming 1.1

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Case Study 1: Hangman Game
ProGame Inc. is an emerging game development organization based in the US. The office of the organization
is located in Santa Monica, California. The total employee count of the organization is 55. Recently, the
business has seen growth and the organization has gained new clientele. As a new client deal, the
organization has gained a project to develop a game console, which has games, such as Hangman and
Scramble. The management has assigned the responsibility of developing the game console to Peter, the
Senior Programmer. The management wants the game code to be simple. In addition, the game must be
robust and compatible across various operating systems, such as Windows and Linux.

Initially, Peter decides to develop the game console interface and the Hangman game. The game console

R
interface should have the options to play different games and exit the game console. The Hangman game is a

KA
single player game. At the start of this game, the player should be presented with a menu. Using the menu, a
player can decide whether to play the game, read the game instructions, or exit the game. If the player

R
decides to play the game, a series of blank dashes needs to be displayed. The player will then have to

SA
correctly guess an alphabet for each blank displayed. After guessing all the blanks correctly, the player needs
to be notified about the result and should also be asked whether to continue playing the game or not. If the
player decides to continue, then another series of blank dashes need to be displayed, and this process should
continue until the player decides to exit.
A
R
IT
R
-A
01
02
30
52
00
19
R

A.2 NIIT

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Case Study 2: EmployeeBook Application
Alchem Inc. is an emerging company in Singapore. The company provides software development services to
its clients. The company has 35 diligent employees. Recently, the company has seen a huge growth in its
clientele. Due to a large number of projects, the company has decided to hire around 100 employees in the
present quarter and 50 employees in the next quarter. In order to organize the details of an ever rising count
of employees in an efficient manner, the management has asked Shawn, the Head of the IT department, to
create an application to store and update the employee details. The application should be robust and
platform-independent as the company utilizes a Windows and Linux-based infrastructure.

The application should be menu-based. It must provide the functionality to store employee data that includes

R
the employee ID, employee name, department, designation, date of joining, date of birth, and marital status.

KA
If the employee is married, the date of anniversary must also be stored. In addition, the application should
provide the functionality to view the records.

R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

NIIT A.3

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Objectives Attainment Feedback

Introduction to Java
Name: Batch: Date:

The objectives of this course are listed below. Please tick whether the objectives were achieved by you
or not. Calculate the percentage at the end, fill in your name and batch details, and return the form to
your coordinator.

R
KA
S. No. Objectives Yes No

R
SA
1. Get familiar with Java

2. Identify the building blocks of a Java program


A
R
IT
 
R

3. Access class members


-A
01

4. Work with operators


02

5. Use operator precedence


30
52

6. Work with conditional constructs


00
19

7. Work with loop constructs


R

8. Manipulate arrays

9. Manipulate enums

10. Manipulate strings

11. Implement inheritance

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
S. No. Objectives Yes No

12. Implement polymorphism

 
13. Handle exceptions

14. Use the assert keyword

15. Process strings using regex

R
KA
16. Work with input stream

R
SA
17. Work with output stream

Percentage: ( # of Yes/17) * 100


A
R
IT
R
-A
01
02
30
52
00
19
R

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/01/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.

You might also like