Fundamentals of Java - CPINTL
Fundamentals of Java - CPINTL
of Java
Fundamentals of Java
Learners Guide
No part of this book may be reproduced or copied in any form or by any means graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
or transferred without the prior written permission of copyright owner Aptech Limited.
APTECH LIMITED
Contact E-mail: [email protected]
Aptech Ltd. designs its courses using a sound instructional design model from conceptualization
to execution, incorporating the following key aspects:
Scanning the user system and needs assessment
Needs assessment is carried out to find the educational and training needs of the learner
Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG*
analyzes these on a monthly basis to understand the emerging technology training needs for
the Industry.
The skill requirements are then mapped with the learner profile (user system) to derive the
Learning objectives for the different roles.
Needs analysis and design of curriculum
The Learning objectives are then analyzed and translated into learning tasks. Each learning
task or activity is analyzed in terms of knowledge, skills and attitudes that are required to
perform that task. Teachers and domain experts do this jointly. These are then grouped in
clusters to form the subjects to be covered by the curriculum.
In addition, the society, the teachers, and the industry expect certain knowledge and skills
that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving,
positive attitude etc. These competencies would cover both cognitive and affective domains.
A precedence diagram for the subjects is drawn where the prerequisites for each
subject are graphically illustrated. The number of levels in this diagram is determined
by the duration of the course in terms of number of semesters etc. Using the precedence
diagram and the time duration for each subject, the curriculum is organized.
The content outlines are developed by including additional topics that are required for the
completion of the domain and for the logical development of the competencies identified.
Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized
in a meaningful sequence.
The detailed instructional material Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.
Strategies for delivery of instruction
Careful consideration is given for the integral development of abilities like thinking, problem
solving, learning-to-learn etc. by selecting appropriate instructional strategies (training
methodology), instructional activities and instructional materials.
The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the
instructional process by specially including creative activities with group interaction between
the students and the trainer. The positive aspects of web based learning acquiring information,
organizing information and acting on the basis of insufficient information are some of the
aspects, which are incorporated, in the instructional process.
Assessment of learning
The learning is assessed through different modes tests, assignments & projects. The
assessment system is designed to evaluate the level of knowledge & skills as defined by the
learning objectives.
Evaluation of instructional process and instructional materials
*TAG Technology & Academics Group comprises members from Aptech Ltd., professors from
reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software
Majors & representatives from regulatory organizations/forums.
Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology
trends. The group interfaces with the representatives of the TAG thrice a year to review and
validate the technology and academic directions and endeavors of Aptech Ltd.
Aptech New Products Design Model
Key Aspects
1
Evaluation of
Scanning the user
Instructional
system and needs
Processes and
assessment
Material
2 6
Need Analysis
Assessment of
and design of
learning
curriculum
3 Design and
5
Strategies for
development of
delivery of
instructional
instructions
material 4
A little learning is a dangerous thing,
but a lot of ignorance is just as bad
Preface
The book, Fundamentals of Java, aims to teach the basics of the Java programming language. The Java
programming language was created by Sun Microsystems Inc. which was merged in the year 2010 with
Oracle USA Inc. The merged company is now formally known as Oracle America Inc.
The Java programming language has undergone several reformations since its inception. This book
intends to familiarize the reader with the latest version of Java, that is, Java SE 7. Java SE 7 introduces
several new features as well as provides enhancements on the earlier versions. The book begins with
an introduction to the basic concepts of Java programming language and the NetBeans IDE. The book
proceeds with the explanation of the various Java features and constructs such as classes, methods,
objects, loops, inheritance, interfaces, and so on. The book concludes with an explanation of the concept
of exceptions and exception handling in Java.
This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring
you the best and the latest in Information Technology. The process of design has been a part of the ISO
9001 certification for Aptech-IT Division, Education Support Services. As part of Aptechs quality drive,
this team does intensive research and curriculum enrichment to keep it in line with industry trends.
Design Team
Nothing is a waste of time if you
use the experience wisely
Table of Contents
Sessions
1. Introduction to Java 1
Learning is not compulsory
but neither is survival
Session - 1
Introduction to Java
Welcome to the Session, Introduction to Java.
This session explains the various methodologies that have been adopted
over a period of time for solving problems and developing applications. It
proceeds to introduce object-oriented paradigm as a solution to develop
applications that are modeled to real-world entities, that is, objects.
Further, the session explains the concept of an object and a class in the
object-oriented programming. It introduces Java as an object-oriented
programming language (OOP) and a platform to develop platform
independent applications. Finally, the session explains the various
components of the Java platform.
1.1 Introduction
The most prominent use of computers is to solve problems quickly and accurately. The solution adopted
to solve a problem is provided as a sequence of instructions or specifications of activity which enables a
user to achieve the desired result. For example, a problem could be about how to obtain a particular food
item from a restaurant with the least effort. Placing an order to the nearest restaurant over the phone for
the food item is one of the solutions to this problem.
The knowledge of a domain plays an important role while solving a problem. A domain is defined as the
field of business or technology to which a problem belongs. For example, in the restaurant scenario, the
knowledge of all the restaurants in nearby area forms the domain knowledge.
The knowledge about the restaurant as well as the type of food served can also be considered as domain
knowledge in this case. Having a good knowledge of the domain helps to solve the problem quickly.
In the scenario described, if the restaurant specializes in Mexican cuisine and you call them to order
Chinese food, then it would be a waste of time and effort. Here, if you had known the name of the
nearest restaurant that serves only Chinese food, it would have saved your time and effort. Hence, having
adequate domain knowledge before designing a problem solution is always recommended.
The solution for solving a problem in the field of information technology is achieved by developing
software applications. A software application can be defined as a collection of programs that are written
in high-level programming languages to solve a particular problem. In other words, it is a collection of
pre-written programs to solve specific application needs of end users.
Figure 1.1 shows the development of software application as a solution for managing various operations
in a banking domain. These operations are related to accounts, customers, payments, and various other
transactions that are carried out in a banking domain.
Concepts
As shown in figure 1.1, the development of software application is done using a programming language.
A programming language is used as a medium for communicating the instruction to the computer. The
programming language enforces a particular style of programming that is referred to as a programming
paradigm.
The object-oriented programming paradigm basically divides the application development process into
three distinct activities. These are as follows:
Object-oriented Analysis (OOA) This process determines the functionality of the system. In other
words, it determines the purpose of developing an application.
Object-oriented Design (OOD) This is the process of planning a system in which objects interact with
each other to solve a software problem.
Object-oriented Programming (OOP) This is the process that deals with the actual implementation
of the application.
Figure 1.4 shows different activities involved in the object-oriented software development.
Abstraction Is a design technique that focuses only on the essential features of an entity for a
specific problem domain.
Encapsulation Is a mechanism that combines data and implementation details into a single unit
called class. It also secures the data through a process called data hiding where a user cannot
manipulate the data directly.
Inheritance Enables the developer to extend and reuse the features of existing classes and
create new classes. The new classes are referred to as derived classes.
Concepts
Breed
Color
Age
An object also executes actions. Thus, the actions that a Dog can perform are as follows:
Concepts
Barking
Eating
Running
The concept of objects in the real-world can be extended to the programming world where software
objects can be defined.
Like its real-world counterpart, a software object has state and behavior. The state of the software
object refers to its characteristics or attributes, whereas the behavior of the software object comprises
its actions.
Figure 1.6 shows a software object, such as a Car with its state and behavior.
They map attributes and actions of real-world entities with state and behavior of software objects.
Figure 1.7 shows a car (any car in general) as a class and a Toyota car (a specific car) as an object or
instance created for that class.
Class Object
Class is a conceptual model Object is a real thing
Class describes an entity Object is the actual entity
Class consists of fields (data members) and Object is an instance of a class
functions
Table 1.1: Difference Between a Class and an Object
1.2 Java
Java is one of the most popular OOP language. It helps programmers to develop wide range of applications
that can run on various hardware and Operating System (OS). Java is also a platform that creates an
environment for executing Java application.
Java was initially developed to cater to small-scale problems, but was later found capable of addressing
large-scale problems across the Internet. Very soon, it gained in popularity and was adopted by millions
of programmers all across the world. Today, Java applications are built for a variety of platforms that
range from embedded devices to desktop applications, Web applications to mobile phones, and from
large business applications to supercomputers.
run on any machine and the result was the evolution of Java. It was initially called Oak, but was
later renamed to Java.
It emerged as a Web technology that added dynamic capabilities to the Web pages. In other words,
it allowed the developer to publish Web pages with Java code in it. Later, Java gained popularity
and served as ideal software for network computers.
Simple Java programming language inherits its syntax from its predecessor programming
languages, such as C/C++. This helps the programmers to adapt to the basics of Java language
quickly, without any extra skills and extensive trainings.
Also, Java eliminates the use of pointers, operator overloading, and multiple inheritance features
supported by its predecessor languages. These features added more complexity to programs and
hence, were removed from Java.
Object-oriented Though, Java was influenced from its predecessor languages, but it was not
developed to be compatible with other languages. As a result, Java team was able to design and
incorporate a clean, reusable, and real-world approach for developing objects.
Java is based on the object model. Object model is defined by means of classes and objects that
are used to address the solutions closer to the real-world problem domains. In other words, it is a
pure OOP language that uses classes and objects. Even, the application development in Java starts
with a class designing.
Figure 1.10 shows the features of object-oriented programming paradigm supported by Java
programming language.
Concepts
Robust - The robust nature of Java is incorporated with strong memory management and
exception handling mechanism.
In C and C++ languages, dynamic memory allocation/deallocation was done manually by
programmers through pointers. For example, if programmer released memory that was being used
by some other program or forgets to deallocate the occupied memory, then it resulted in memory
related errors. However, Java eliminates these problems by automatically handling memory
allocation and deallocation. Objects are created in memory using new operator, whereas unused
objects are automatically destroyed using garbage collection mechanism.
Java also supports exception handling mechanism which stops the abnormal termination of code.
For example, operations such as dividing a number by zero or reading from a file before opening it,
can lead to exceptions at runtime. This exception handling mechanism is used to manage runtime
errors in Java program.
Java provides a strict compile-time checking at first level, followed by a run-time checking at second
level. The compile-time checking ensures that variables declared in Java program contain specific
type of data, whereas, run-time checking ensures the purity of Java code during execution. This
reduces runtime errors and helps in developing reliable applications.
Secure - Java applications are designed for distributed environments. This makes security an
important factor for consideration. The security checks applied at different layers ensures that the
Java programs are protected against malicious codes. For example, whenever any program is
downloaded from network, there is always a danger that the downloaded code might be a virus.
The virus might gather personal information, such as passwords or credit card details from the
local file system.
On the other hand, Java programs that are accessed on the network are known as applets. Applets
are Java codes executed within a browser. Java applies security to applets by placing them in a
sandbox. The sandbox model is based on a principle that ensures it should not have direct access
to files or resources available on the local system.
Apart from applets, Java Virtual Machine (JVM) which is a runtime environment for executing Java
programs applies its own security features to Java language. It ensures that the code loaded in JVM
for execution is well-formed and conforms to Java standards.
Architecture Neutral and Portable - One of the major programming issues faced by the
programmers is the portability of code. Portability means running the same code on different
platforms with different OS and processor. For example, a Java program executing successfully on
a system, may malfunction due to changes or upgrades in OS or processor in the future. Java
Concepts
solves the portability problem by converting the application into architecture neutral bytecode
during compilation. The bytecode is an optimized set of instructions that can be executed on any
platform on which the JVM is installed.
Apart from architecture neutral bytecode, Java has defined language specifications independent
of the hardware platform. Language specifications, such as size of the primitive data types and
operators are defined by Java.
This ensures that a change in OS, processor, and system resources does not lead to the malfunctioning
of the code. For example, in C language, an integer variable occupies either 16 bits or 32 bits
depending on the platform on which it is being executed. In Java, an integer variable, always
occupies 32 bits on whichever machine the code is executed. This feature satisfies the major goal
of Java language which is Write once, run anywhere.
Dynamic Java application is a collection of classes. During execution, the classes are stored in a
separate file and are loaded as and when required by the Java interpreter. This means that at
runtime an application can dynamically decide which classes it requires and accordingly load them
to expand its functionality. This gives a new perspective to Java for designing and developing
applications.
JVM Programming languages, such as C and C++, translates the compiled code into an
executable binary code, which is machine dependent. In other words, the resulting executable
code is for a specific microprocessor which executes it. In Java, the compiled code is not translated
into an executable code. It is instead compiled and converted into a bytecode which is an
intermediate form closer to machine representation. In other words, the Java bytecode is an
optimized set of instructions executed by the Java runtime environment. This environment is
known as JVM.
The JVM is an execution engine which creates a platform independent execution environment for
Concepts
executing Java compiled code. The JVM is also known as a virtual machine because it is an imitation
of a Java processor on the physical machine.
There are different implementations of JVM available for different platforms, such as Windows,
Unix, and Solaris. Thus, the execution of same bytecode by different implementations of JVM on
various platform results in code portability and platform independence.
Figure 1.12 shows the execution of same bytecode with different implementations of JVM on
various platforms.
Java API - Java platform is not dependent on specific OS for application execution and provides
its own comprehensive set of standard class libraries. The Java API is a large collection of ready-
made software components. These components are classes and interfaces that are grouped into
libraries. Each library with related classes and interfaces provide powerful capabilities to the
applications. The library is also referred to as a package in Java.
For example, the Swing library provides classes for User Interface (UI) components. Similarly, the
Input/Output (I/O) library provides the standard interface for reading and writing data into files
stored in the system.
different editions of Java platform which are bundled with related sets of API. The bundled APIs help in
developing and executing applications on Java platform.
Java Standard Edition (Java SE) - Java SE is a base platform for other editions. Developers use
the Java SE platform to develop console and networking applications for desktop computers.
Java Enterprise Edition (Java EE) - Java EE is built on top of Java SE platform. The Java EE
platform provides a standard specification for developing and deploying distributed, scalable, and
multi-tier enterprise applications. The enterprise applications are large
server-side business applications with complex business logics.
Java Mobile Edition (Java ME) - Java ME is a robust platform for developing embedded Java
applications for consumer electronic devices, such as mobiles, Personal Digital Assistants (PDAs),
TV set-top boxes, and so on.
JRE JRE provides JVM and Java libraries that are used to run a Java program.
JDK Java Development Kit (JDK) is a binary software development kit released by Oracle
Corporation. It is an implementation of Java and distributed for different platforms, such as
Windows, Linux, Mac OS X, and so on.
The JDK contains a comprehensive set of tools such as compilers and debuggers that are used to
develop Java applications. It also includes the JRE which creates an environment for executing Java
applications.
Figure 1.14 shows the different components of Java SE platform.
Development Tools The Java platform provides different tools that form the foundation of JDK.
The development tools include tools used for compiling, running, debugging, and documenting a
Java application.
Figure 1.15 shows some of the development tools provided by JDK.
Concepts
API The Java API provides the core functionality of the Java programming language. They offer
ready-made classes that provide functionalities ranging from basic objects to networking to XML
generation to database access.
Deployment Tools The JDK provides software, such as Java Web Start and Java Plug-In used for
deploying the developed applications to end users.
User Interface Toolkits The user interface toolkits, such as Abstract Window Toolkit (AWT),
Swing, and Java2D enables the developer to create graphical interfaces in a Java application.
Integration libraries Integration libraries enable developers to access and manipulate database
and remote objects in an application. These libraries include APIs, such as Java Naming and
Directory Interface (JNDI), Java Remote Method Invocation (RMI), Java Database Connectivity
(JDBC), and so on.
Release Implementation
JDK 1.0 Creation of packages with classes in the standard library
JDK 1.1 Included an event delegation model for Graphical User
Interface (GUI) package AWT, JavaBeans, and Java Database
Connectivity (JDBC) API
JDK 1.2 (Java 2) Included a new graphical API, named Swing. Also added
APIs for reflection and collection framework (based on data
Concepts
structure)
JDK 1.3 Included a directory interface to lookup for components,
named, Java Naming and Directory Interface (JNDI)
JDK 1.4 Included regular expression API, assertions, exception
chaining, channel-based I/O API, an XML API for parsing and
processing
Release Implementation
JDK 1.5 Included new features in the language such as for-each
loop, generics, annotations, and auto-boxing
JDK 1.6 Included script language, visual basic language support, and
improvements in the GUI
Table 1.2: JDK Releases
1.7.1 Java SE 7
Java SE 7 is the new major release of Java with internal version number as 1.7. The significant changes of
Java SE 7 have been made at the language and API level.
The lists of new features that are incorporated in the language are as follows:
The decision-making construct, switch statement can use the String class in the conditional
expression.
The integer types can be assigned with a binary number value. To specify a binary value, prefix the
number with b or B. For example, a byte type is declared and assigned a binary number, byte
numByte = 0b00100001;.
Java SE 7 supports the use of underscore character ( _ ) between the digits of a numeric value.
This feature improves the readability of code. For example, long ssnNumber = 1234 _
5678 _ 9101 _ 2345L;.
While handling exceptions in code, an expandable try statement called try-with-resources can be
used for automatic resource management. For example, a resource can be a file which needs to
be closed after the program is finished. The use of try-with-resource statement ensures that the
resources in Java program are closed.
Prior to Java SE 7, generic declarations informed the compiler about the type of elements a
collection will hold.
For example, a generic collection of type String was declared as,
List<String> nameList = new ArrayList<String>();
Now, in Java SE 7, the type arguments provided to the constructor of a generic class declaration can
Concepts
In Java SE 7, compiler warnings generated for varargs methods has been improved.
Similarly, at API level, Java SE 7 enhances NIO framework and also adds a new framework named
Fork/Join. The Fork/Join framework supports parallel programming which is a technique that uses one
or more processors for executing the tasks concurrently. Thus, Fork/Join framework allows creating and
running concurrent tasks in a multiple processor environment.
1. On download page, click Download button under Java with Java Platform (JDK) 7u11. This opens Java
SE Development Kit 7 Downloads Web page.
Figure 1.17 shows the Java SE Development Kit 7 Downloads Web page for downloading the JDK.
Figure 1.18 shows the Java SE Development Kit 7 Downloads Web Page with license acceptance.
Concepts
Table 1.3 lists the common directories that are part of the typical JDK installation.
Directory Description
bin Contains tools that are used for developing a Java
application, such as compiler and JVM
db Contains a relational database named Apache Derby
include Contains header files that are used to interact with C
applications
jre Represents the JRE used by the JDK
Table 1.3: Common Directories of JDK Installation
PATH
The PATH variable is set to point to the location of Java executables (javac.exe and
java.exe). This is necessary so that the javac and java command can be executed from any
directory without having to type the full path.
The command for setting the path in DOS or Command Prompt window is as follows:
C:\>set path=<drivename>:\<installation_folder>\bin
To set the value for the PATH variable permanently on the system, perform the following steps in
Windows 7:
1. Right-click My Computer icon on the desktop and then, click Properties from the context menu.
2. Click Advanced system settings link on the left tab. This displays the System Properties dialog
box.
3. Under Advanced tab, click Environment Variables.
4. In the System variables area, select the PATH variable and then, click Edit button to enter the JDK
installation folder path.
5. Type path of the bin folder in the Variable Value text box. For example, the path can be: C:\
Concepts
WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.7.0\bin.
CLASSPATH
CLASSPATH is an environment variable that specifies the location of the class files and libraries needed
by the Java compiler (javac) to compile applications.
The command for setting CLASSPATH in DOS is as follows:
C:\>set CLASSPATH=<drivename>:\<installation_folder>
To set CLASSPATH variable in Windows 7, perform the following steps:
1. Right-click My Computer icon on the desktop and click Properties from the context menu.
2. Click Advanced system settings link on the left tab. This displays the System Properties dialog
box.
3. Under Advanced tab, click Environment Variables.
4. In the System variables area, click New button.
5. Type CLASSPATH in Variable Name and then, type C:\<jdk _ installation _ folder> in the
Variable Value.
6. Click OK.
Concepts
Term Description
(A) a-1, b-2, c-3, d-4 (C) a-2, b-1, c-4, d-3
(B) a-4, b-3, c-2, d-1 (D) a-3, b-4, c-1, d-2
3. Which of the following statements are true regarding Java platform and its components?
4. Which of the following edition provides a standard specification for developing and deploying
distributed, scalable, and multi-tier applications?
5. Java SE 7 supports the use of _____ character between the digits of a numeric value.
Concepts
1.9.1 Answers
1. B
2. B
3. A
4. B
5. D
Concepts
Summary
The development of application software is performed using a programming language that
enforces a particular style of programming, also referred to as programming paradigm.
In structured programming paradigm, the application development is decomposed into a hierarchy
of subprograms.
In object-oriented programming paradigm, applications are designed around data, rather than
focusing only on the functionalities.
The main building blocks of an OOP language are classes and objects. An object represents a
real-world entity and a class is a conceptual model.
Java is an OOP language as well a platform used for developing applications that can be executed
on different platforms. Java platform is a software-only platform that runs on top of the other
hardware-based platforms.
The editions of Java platform are Java SE, Java EE, and Java ME.
The components of Java SE platform are JDK and JRE. JRE provides JVM and Java libraries that are
used to run a Java program. JDK includes the necessary development tools, runtime environment,
and APIs for creating Java programs.
Concepts
Try it Yourself
1. Check the directory structure of JDK 1.7 on your local system. Also, identify and list the various tools
provided by JDK 1.7. Prepare a table displaying the list of tools with their appropriate description and
commands to invoke the tools.
2. Find all the possible errors that might be generated due to incorrect use of PATH and CLASSPATH
variables. Also, identify the appropriate steps that can be taken to fix those errors. Note these errors
and solutions in a Notepad file.
Concepts
This session explains the basic structure of a Java class. It proceeds and
explains the step by step procedure to write a Java program in a text
editor. Further, the session explains NetBeans Integrated Development
Environment (IDE) and its various components. Finally, the session
demonstrates how to write and execute a Java application program using
NetBeans IDE and provides an overview of writing comments in Java
programs.
2.1 Introduction
Java is a popular OOP language that supports developing applications for different requirements and
domain areas. Some of the applications that can be developed using Java language are as follows:
Applets programs that are small Java codes embedded within an HTML page and executed within
a browser.
Server-side Web applications that are executed in the browsers. The Web applications developed
in Java contain components, such as Servlets, Java Server Pages (JSP), Java Server Faces (JSF), and
so on.
JavaBeans components are used to share the functionality between the various layers of an
application.
Enterprise applications using Enterprise components, such as Enterprise JavaBeans (EJB) are
designed to be used for distributed computing.
All types of applications can be developed in a simple text editor, such as Notepad or in an environment
that provides necessary tools to develop a Java application. The environment is called as Integrated
Development Environment (IDE). The IDE is a software application that contains various tools, such as
source editor, a compiler/interpreter, debugger, navigator, and so on. These tools help you to develop the
software applications under a single environment. One such type of IDE is NetBeans IDE that is primarily
used for developing Java applications.
package A package defines a namespace that stores classes with similar functionalities in them.
The package keyword identifies name of the package to which the class belongs. It also identifies
visibility of the class within the package and outside the package.
The concept of package is similar to folder in the OS. As folders are created to store related files in
the system, similarly packages are used to group similar classes and interfaces in Java. In Java, all
classes belongs to a package. If the package statement is not specified, then the class belongs to
the default package.
For example, all the user interface classes are grouped in the java.awt or java.swing pack-
ages. Similarly, all the classes related to Input/Output functionalities are found in the java.io or
java.nio packages.
import The import keyword identifies the classes and packages that are used in a Java class.
Concepts
They help to narrow down the search performed by the Java compiler by informing it about the
classes and packages used in the class. In Java, it is mandatory to import the required classes,
before they are used in the Java program.
There are some exceptions wherein the use of import statement is not required. They are as
follows:
The import statement is not required for classes present in the java.lang package. This is
because java.lang package is the default package included in the entire Java program.
You do not need to import classes, if they are located in the same package. For example, if
the current package is com.java.company, any class present in this package can access the
other classes without using the import statement.
Classes that are declared and used along with their package name do not require the
import statement. For example, java.text.NumberFormat nf = new java.text.
NumberFormat();.
class The class keyword identifies a Java class. It precedes the name of the class in the
declaration. Also, the public keyword indicates the access modifier that decides the visibility of
the class. The public modifier means that the class is visible outside the package. Class name and
file name should match.
variables Variables are also referred to as instance fields or instance variables. They represent
the state of objects. They are known as instance variables because each instance or object of the
class contains its own copy of instance variables.
methods Methods are functions that represent some action to be performed on an object.
Code is written within methods. They are also referred to as instance methods.
constructors Constructors are also methods or functions that are invoked during the creation
of an object. They are basically used to initialize the objects.
The step by step explanation of the different parts of Java program is as follows:
Step 1: Class Declaration
The syntax to declare a class is as follows:
Syntax:
class <class_name> {
}
where,
class is a keyword and <classname> is the class name.
The entire class definition and its members must be written within the opening and closing curly braces,
{ }. In other words, the class declaration is enclosed within a code block. Code blocks are defined within
braces. The braces inform the compiler about the beginning and end of a class. The area between the
braces is known as the class body and contains the code for that class.
In Code Snippet 1, class Helloworld { }, HelloWorld is the name of the class.
Step 2: Write the main method
The main() method is the entry point for an application. In other words, all Java applications begins
execution by invoking the main() method.
The syntax to write the main() method is as follows:
Syntax:
Concepts
// block of statements
where,
public: Is a keyword that enables the JVM to access the main() method.
static: Is a keyword that allows a method to be called from outside a class without creating an instance
of the class.
void: Is a keyword that represents the data type of the value returned by the main() method. It informs
the compiler that the method will not return any value.
args: Is an array of type String and stores command line arguments. String is a class in Java and
stores group of characters.
Step 3: Write desired functionality
In this step, actionable statements are written within the methods. Code Snippet 1 illustrates the use
of a built-in method, println()that is used to display a string as an output. The string is passed as a
parameter to the method.
System.out.println(Welcome to the world of Java);
System.out.println() statement displays the string that is passed as an argument. System is the
predefined class and provides access to the system resources, such as console and out is the output
stream connected to the console.
Step 4: Save the program
Save the file with a .java extension. The name of the file plays a very important role in Java. A .java
extension is a must for a Java program. In Java, the code must reside in a class and hence, the class name
and the file name should be same in most of the cases.
To save the HelloWorld.java program, click FileSave As in Notepad and enter HelloWorld.
java in the File name box. The quotation marks are provided to avoid saving the file with extension
HelloWorld.java.txt.
Concepts
Figure 2.2 shows the Save As dialog box to save the HelloWorld.java file.
To compile the HelloWorld.java program from the Windows platform, the user can click Start menu,
choose Run, and enter the cmd command to display the Command Prompt window.
Figure 2.4 shows the Command Prompt window with the current directory. Normally, the current
directory is the home directory of the user.
Option Description
-classpath Specifies the location for the imported classes (overrides the
CLASSPATH environment variable)
-d Specifies the destination directory for the generated class files
-g Prints all debugging information instead of the default line number
and file name
-verbose Generates message while the class is being compiled
-version Displays version information
sourcepath Specifies the location of the input source file
-help Prints a synopsis of standard options
Table 2.1: Options for javac Command
For example, javac -d c:\ HelloWorld.java will create and save HelloWorld.class file in the
C:\ drive.
Note - If the source file defines more than one classes, then after compilation, each class is compiled
into the separate .class file. The file that can be given for execution to JVM is the class with the
main() method defined in it.
The JVM is at the heart of the Java programming language and is responsible for executing the .class
file or bytecode file. The portability feature of the .class file has made the principle of Java write once,
run anywhere possible. The .class file can be executed on any computer or device, that has the JVM
implemented on it.
Figure 2.6 shows the components of JVM involved in the execution of the compiled bytecode.
Figure 2.7 shows the output of the Java program on the Command Prompt window.
Options Description
classpath Specifies the location for importing classes (overrides the
CLASSPATH environment variable)
-v or -verbose Produces additional output about each class loaded and each
source file compiled
-version Displays version information and exits
-jar Uses a JAR file name instead of a class name
-help Displays information about help and exits
-X Displays information about non-standard options and exits
Table 2.2: Options for java Command
robust IDE that helps developers to create cross-platform desktop, Web, and mobile applications using
Java. As compared to an editor, such as Notepad, the coding in NetBeans IDE is completed faster because
of its features, such as code completions, code template, and fix import. It also supports debugging of an
application in the source editor.
Some of the benefits of using NetBeans IDE for Java application development are as follows:
Builds IDE plug-in modules and supports rich client applications on the NetBeans platform.
Provides graphical user interface for building, compiling, debugging, and packaging of applications.
Menu Bar
Folders View
Components View
Output View
Concepts
Figure 2.8 shows the various elements in the NetBeans IDE 7.1.2.
Menu Bar
The menu bar of NetBeans IDE contains menus that have several sub-menu items, each providing
a unique functionality.
Concepts
Menu Description
File Displays commands for using the project and the NetBeans IDE
Edit Provides commands for editing
View Provides options to display the document in different views
Navigate Provides options for navigation in the project
Source Provides options for overriding methods, fixing imports, and
inserting try-catch blocks
Refactor Allows to change the structure of the code and reflect changes
made to the code
Run Compiles the source files, executes the application, and generate
packaged build output, such as JAR or WAR file
Debug Inserts breakpoints, watches, and attaches the debugger
Profile Used for profiling an application with the help of a profiler which
examines the time and memory usage of the application
Team Used for versioning application that helps to keep the backup of
the files and tracing the modified source code files. It also allows
Concepts
Menu Description
Window Provides options to select or close any window
Help Provides guidance on how to use NetBeans IDE effectively
Table 2.3: Menus in NetBeans IDE
Folder View
The folder view shows the structure of files associated with Java applications. This view contains
Projects window, Files window, and Services window.
Figure 2.10 shows the folder view in the NetBeans IDE.
Element Description
Projects Window Displays the project content, such as Source Packages and Libraries
Source Packages folder contains the Java source code
for the project
Libraries comprise resources required by the project,
such as source files and Javadoc files
Files Window Shows the directory structure of all files and folders present in the
Concepts
project
Services Window Displays information about database drivers, registered servers,
and Web services
Table 2.4: Elements in Folder View
Component View
The component window is used for viewing components in the NetBeans IDE. The Navigator
window serves as a tool that displays details of the source files of the currently opened project.
The elements used in the source are displayed here in the form of a list or an inheritance tree.
Figure 2.11 shows the Navigator window in the NetBeans IDE.
Table 2.5 lists and explains the elements of the code and design view.
Element Description
Source Source Editor is a text editor of NetBeans IDE. With Source Editor,
the user can create, edit, and view the source code
Design Helps in designing the form and dragging controls on to the form,
so as to have a view of the interface
Table 2.5: Elements in Code and Design View
Output View
The Output view displays messages from the NetBeans IDE. The Output window shows compilation
errors, debugging messages, and Javadoc comments. The output of the program is also displayed
in the Output window.
Figure 2.13 shows the Output window
.
Figure 2.13: Output Window
Java SE - Supports all standard features that are necessary for Java SE development.
Concepts
Java EE - Provides tools for developing Java SE and Java EE applications. This download option
also includes GlassFish Server Open Source Edition and Apache Tomcat software.
PHP - Provides tools for PHP 5.x development, Zend, and Symfony Framework support.
All -This is a full download option, which contains all the runtimes and technologies available for
the NetBeans IDE.
To download the NetBeans IDE 7.1.2, perform the following steps:
1. Type http://netbeans.org/downloads/7.1.2/index.html in the Address bar of the Web
browser.
Figure 2.14 shows the download Web page for the NetBeans 7.1.2 IDE.
4. At the JUnit License Agreement page, decide if you want to install JUnit and click the appropriate
option, click Next.
5. At the NetBeans IDE installation page, do the following:
a. Select either the default installation directory or specific directory where the NetBeans IDE
needs to be installed.
b. During the installation, NetBeans IDE asks the path of the default JDK installation available
on the system. After the JDK installation path is specified, click Next to continue with the
installation. In case, if the installation wizard does not find compatible JDK, then the
installation gets terminated. In that case, you need to install the required JDK before
restarting the installation.
6. The GlassFish Server Source Edition 3.1.2 installation page is displayed. You can either select the
default location or specify another location to install the GlassFish Server.
7. To install the Apache Tomcat Server, on the installation page, either select the default location or
specify another location and then, click Next.
8. The Summary page is opened. The list of components that are to be installed is displayed, verify
the list to check if you have sufficient space for the installation.
9. Click Install to install the NetBeans IDE on the system.
10. After the installation is completed, click Finish to complete and close the setup page.
6. Click Browse and select the appropriate location on the system to set the project location.
Figure 2.16 shows the Name and Location page in the wizard.
Figure 2.16: New Java Application Wizard Name and Location Page
7. Click Finish.
Concepts
Figure 2.18 shows the NetBeans IDE with the modified code.
Concepts
Figure 2.19 shows the Output window that displays the directory structure of the HelloMessageApp
application.
Beginning-of-line comment
This type of comment can be placed before the code (on a different line).
End-of-line comment
This type of comment is placed at the end of the code (on the same line).
Concepts
// Comment text
Code Snippet 2 shows the different ways of using single-line comments in a Java program.
Code Snippet 2:
...
// Declare a variable
int a = 32;
int b // Declare a variable
...
...
/*
* This code performs mathematical
* operation of adding two numbers.
*/
int a = 20;
int b = 30;
int c;
c = a + b;
...
Concepts
/*
* The program prints the welcome message
* using the println() method.
*/
package hellomessageapp;
/**
*
Concepts
* @author vincent
*/
c. A Javadoc comment ends with double asterisk and a forward slash (**/)
2. Match the following menus in the NetBeans IDE against their corresponding description.
Menu Description
(A) a-1, b-2, c-3, d-4 (C) a-2, b-1, c-4, d-3
(B) a-4, b-3, c-2, d-1 (D) a-3, b-4, c-1, d-2
Concepts
3. Which of these statements about compiling and executing a Java program are true?
c. The Java interpreter checks for the syntax, grammar, and data types of the program
4. _______ defines a namespace that stores classes with similar functionalities in them.
(A) /* */ (C) //
2.7.1 Answers
1. A
2. D
3. B
4. A
5. B
Concepts
Summary
The Java programming language is designed around object-oriented features and begins with a
class design.
A Java class structure contains the following components namely, package, import, class name,
variables, and methods.
Java programs can be written in a text editor, such as Notepad or in an IDE, such as NetBeans.
The entry point for a Java console application is the main() method.
The javac.exe compiles the source code into a .class file. Similarly, the java.exe command is used
to interpret and run the Java bytecodes.
NetBeans is a free and robust IDE that helps developers to create cross-platform desktop, Web,
and mobile applications using Java.
Comments are used to document the Java program and are not compiled by the compiler. There
are three styles of comments supported by Java namely, single-line, multi-line, and Javadoc
Concepts
Try it Yourself
1. Write the Java program to print a welcome message on two lines.
For example,
Hello,
Welcome to the world of Java
2. For the statement public static void main (String[] args), observe the output for
the following:
a. Delete the keyword static and check whether any error occurs while compiling or
executing the code.
b. Delete the keyword public and observe the effect during the execution.
c. Change the order of public static and write static public and observe the effect of
changing the convention in the Java program.
d. Explain the significance of the main() method in the Java Program.
3. Consider the following code:
class HelloWorld {
public static void main(String args) {
System.out.println(Hello World!);
}
}
Find the errors in the code and fix them, so that the program can be compiled and executed
successfully.
Concepts
This session focuses on the usage of variables, literals, data types, and
operators in Java programs. It provides a clear understanding of the
different data types available in Java. Further, the session explains the
different types of operators and their implementations in Java. Finally, it
explains the implicit and explicit conversion techniques.
3.1 Introduction
The core of any programming language is the way it stores and manipulates the data. The Java programming
language can work with different types of data, such as number, character, boolean, and so on. To work
with these types of data, Java programming language supports the concept of variables. A variable is like
a container in the memory that holds the data used by the Java program. It is an identifier whose value
can be changed.
A variable is associated with a data type that defines the type of data that will be stored in the variable.
Java is a strongly-typed language which means that any variable or an object created from a class must
belong to its type and should store the same type of data. The compiler checks all expressions variables
and parameters to ensure that they are compatible with their data types. In case, if any error or mismatch
is found, then they must be corrected during compile time. This reduces the runtime errors that occur in
other languages due to data type mismatch.
3.2 Variables
A variable is a location in the computers memory which stores the data that is used in a Java program.
Figure 3.1 depicts a variable that acts as a container and holds the data in it.
A variable declaration begins with data type and is followed by variable name and a semicolon. The data
type can be a primitive data type or a class.
In the code, the statements declare an integer variable named rollNumber, and a character variable
called gender. These statements instruct the Java runtime environment to allocate the required amount
of memory for each of the variable. These variables will hold the type of data specified for each of
them.
Additionally, each statement also provides a name that can be used within the program to access the
values stored in each of the variables.
Variable names may consist of Unicode letters and digits, underscore ( _ ), and dollar sign ($).
A variables name must begin with a letter, the dollar sign ($), or the underscore character ( _ ).
The convention, however, is to always begin your variable names with a letter, not $ or _ .
Concepts
Variable names in Java are case-sensitive (for example, the variable names number and Number
refer to two different variables).
If a variable name comprises a single word, the name should be in lowercase (for example, velocity
or ratio).
If the variable name consists of more than one word, the first letter of each subsequent word
should be capitalized (for example, employeeNumber and accountBalance).
Table 3.1 shows some examples of valid and invalid Java variable names.
...
int rollNumber = 101;
char gender = M;
...
In the code, variable rollNumber is an integer variable, so it has been initialized with a numeric value
101. Similarly, variable gender is a character variable and is initialized with a character M. The values
Concepts
assigned to the variables are called as literals. Literals are constant values assigned to variables directly
in the code without any computation.
Here, the variable rollNumber is declared first and then, according to the need of the variable in the
code, it has been initialized with the numeric literal 101.
Code Snippet 4 shows the different ways for declaring and initializing variables in Java.
Code Snippet 4:
In the code, the declarations, int x, y, z; and int a=5, b, c=10; are examples of comma separated list of
variables. The declaration int num1 = num2 = 10; assigns same value to more than one variable at the
time of declaration.
Concepts
Note - In Java, a variable must be declared before it can be used in the program. Thus, Java can be
referred to as strongly-typed programming language.
Instance variables
Static variables
Local variables
Static variables These are also known as class variables. Only one copy of static variable is
Concepts
maintained in the memory that is shared by all the objects belonging to that class. These fields are
declared using the static keyword and inform the compiler that only one copy of this variable
exists irrespective of number of times the class has been instantiated.
Local variables The variables declared within the blocks or methods of a class are called local
variables. A method represents the behavior of an object. The local variables are visible within
those methods and are not accessible outside them. A method stores it temporary state in local
variables. There is no special keyword available for declaring a local variable, hence, the position
of declaration of the variable makes it local.
Note - A block begins with an opening curly brace ({) and ends with a closing curly brace (}).
are global and local. In Java, the two major scopes of a variable are defined either within a class or within
a method.
The variables declared within the class can be instance variables or static variables. The instance variables
are owned by the objects of the class. Thus, their existence or scope depends upon the object creation.
Similarly, static variables are shared between the objects and exists for the lifetime of a class.
The variables defined within the methods of a class are local variables. The lifetime of these variables
depends on the execution of methods. This means memory is allocated for the variables when the
method is invoked and destroyed when the method returns. After the variables are destroyed, they are
no longer in existence.
Methods also have parameters. Parameters are the variables declared with the method. They hold values
passed to them during method invocation. The parameter variables are also treated as local variables
which means their existence is till the method execution is completed.
Figure 3.4 shows the scope and lifetime of variables x and y defined within the Java program.
When you define a variable in Java, you must inform the compiler what kind of a variable it is. That is,
whether it will be expected to store an integer, a character, or some other kind of data. This information
tells the compiler how much space to allocate in the memory depending on the data type of a variable.
Thus, the data types determine the type of data that can be stored in variables and the operation that
can be performed on them.
In Java, data types fall under two categories that are as follows:
byte - Used to store small amount of data. This is a signed 8-bit type and can store values ranging
from -128 to 127. It is useful when working with a stream of data from a network or file. This data
type is also useful when working with raw binary data that may not be compatible with Javas
other built-in types. byte keyword is used to declare a byte variable. For example, byte val;
short - This data type is least used. It is a signed 16-bit type and can store values ranging from -
32,768 to 32,767. This type is mostly applicable to 16-bit computers. This data type is used to store
smaller numbers, for example, employee number. short keyword is used to declare a short
variable.
int This is the most commonly used data type for storing whole numbers. It is a signed 32-bit
type, and can store values ranging from -2,147,483,648 to 2,147,483,647. It is the most versatile
and efficient data type. It can be used to store the total salary being paid to all the employees of
the company. int keyword is used to declare an integer variable.
long - It is a signed 64-bit type, and can store values ranging from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. It is useful when an int type is not large enough to hold the desired
value. The range of value a long data type can store is quite large for example, population of a
country. long keyword is used to declare long variables for storing large numeric values.
float This type supports a single precision value with 32-bit storage. They are useful when a
number needs a fractional component, but with less precision. For example, the representation of
money in dollars and cents need floating-point values. The float keyword is used to store float
values. For example, float squRoot, cubeRoot;
double - This type supports a double precision with 64-bit storage. The double precision is faster
on processors that are optimized for mathematical calculations. This data type is useful when
accuracy is required to be maintained while performing calculations. The double keyword is used
to store large-valued numbers. For example, double bigDecimal;
Concepts
Unicode is a 16-bit character set, which contains all the characters commonly used in information
processing. It is an attempt to consolidate the alphabets of the worlds various languages into a single
and international character set.
...
String str = A String Data;
...
The statement, String str creates an String object and is not of a primitive data type. When you
enclose a string value within double quotes, the Java runtime environment automatically creates an
object of String type. Also, once the String variable is created with a value A String Data, it
will remain constant and you cannot change the value of the variable within the program. However,
initializing string variable with new value creates a new String object. This behavior of strings makes
them as immutable objects.
Code Snippet 6 demonstrates the use of different data types in Java.
Code Snippet 6:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Concepts
}
}
Here, variables of type int, float, char, double, and boolean are declared. A float value needs
to have the letter f appended at its end. Otherwise, by default, all the decimal values are treated
as double in Java. Values are assigned to each of these variables and are displayed using the
System.out.println() method.
The output of the code is shown in figure 3.6.
Concepts
3.4 Literals
A literal represents a fixed value assigned to a variable. It is represented directly in the code and does not
require computation.
Figure 3.8 shows some literals for primitive data types.
Concepts
A literal is used wherever a value of its type is allowed. However, there are several different types of
literals. Some of them are as follows:
Integer Literals
Integer literals are used to represent an int value, which in Java is a 32-bit integer value. In a program,
integers are probably the most commonly used type. Any whole number value is considered as an integer
literal.
Integers literals can be expressed as:
Decimal values have a base of 10 and consist of numbers from 0 through 9. For example,
int decNum = 56;.
Hexadecimal values have a base of 16 and consist of numbers 0 through 9 and letters A
through F. For example, int hexNum = 0X1c;.
Binary values have a base of 2 and consist of numbers 0 and 1. Java SE 7 supports binary
literals. For example, int binNum = 0b0010;.
An integer literal can also be assigned to other integer types, such as byte or long. When a
literal value is assigned to a byte or short variable, no error is generated, if the literal value
is within the range of the target type. Integer numbers can be represented with an optional
uppercase character (L) or lowercase character (l) at the end, which tells the computer to
treat that number as a long (64-bit) integer.
Floating-point Literals
Floating-point literals represent decimal values with a fractional component. Floating-point literals have
several parts.
Whole number component, for example 0, 1, 2,....., 9.
Decimal point, for example 4.90, 3.141, and so on.
Exponent is indicated by an E or e followed by a decimal number, which can be positive or
negative. For example, e+208, 7.436E6, 23763E-05, and so on.
Type suffix D, d, F, or f.
Floating-point literals in Java default to double precision. A float literal is represented by F or f appended
to the value, and a double literal is represented by D or d.
Boolean Literals
Concepts
Boolean literals are simple and have only two logical values - true and false. These values do not
convert into any numerical representation. A true boolean literal in Java is not equal to one, nor
does the false literal equals to zero. They can only be assigned to boolean variables or used in
expressions with boolean operators.
Character Literals
Character literals are enclosed in single quotes. All the visible ASCII characters can be directly enclosed
within quotes, such as g, $, and z. Single characters that cannot be enclosed within single quotes are
used with escape sequence.
Null Literals
When an object is created, a certain amount of memory is allocated for that object. The starting address
of the allocated memory is stored in an object variable, that is, a reference variable. However, at times,
it is not desirable for the reference variable to refer that object. In such a case, the reference variable is
assigned the literal value null. For example, Car toyota = null;.
String Literals
String literals consist of sequence of characters enclosed in double quotes. For example, Welcome to
Java, Hello\nWorld.
Underscore cannot be placed before or after the binary or hexadecimal identifiers, such as b or x.
Table 3.3 list shows valid and invalid placement of underscore character.
Concepts
Code Snippet 7:
Note - The hexadecimal escape sequence starts with \u followed by 4 hexadecimal digits. The octal
escape sequence comprises 3 digits after back slash. For example,
\xyy
where x can be any digit from 0 to 3 and y can be any digit from 0 to 7.
where,
final: Is a keyword and denotes that the variable is declared as a constant.
Code Snippet 9 demonstrates the code that declares the constant variables.
Code Snippet 9:
In the code, a constant variable PI is assigned the value 3.14159, which is a fixed value. The variable
radius stores the radius of the circle. The code calculates area of the circle and displays the output.
The output of the code is shown in figure 3.11.
Note - The final keyword can also be applied at method or class level. When applied to a method, then
it cannot be overridden. When applied to a class declaration, then that class cannot be extended.
Java SE 5.0 introduced enumerations. An enumeration is defined as a list that contains constants. In
previous languages, like C++, enumeration was a list of named integer constants, but in Java, enumeration
is a class type. This means it can contain instance variables, methods, and constructors. As a result,
the concept of enumeration has been expanded in Java. The enumeration is created using the enum
keyword.
The syntax to create an enumeration is as follows:
Syntax:
enum enum-name {
constant1, constant2, . . . , constantN
}
Though, enumeration is a class in Java, you do not use new operator to instantiate it. Instead, declare a
variable of type enumeration to use it in the Java program. This is similar to using primitive data types.
The enumeration is mostly used with decision-making constructs, such as switch-case statement.
Code Snippet 10 demonstrates the declaration of enumeration in a Java program.
Code Snippet 10:
printf()
format()
These methods behave in a similar manner. The format() method uses the java.util.Formatter
class to do the formatting work.
*/
public static void main(String[] args) {
int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
System.out.print(The sum of );
System.out.print(num1);
System.out.print( and );
System.out.print(num2);
System.out.print( is );
System.out.print(sum);
System.out.println(.);
int num3 = 2;
sum = num1 + num2 + num3;
System.out.println(The sum of + num1 + , + num2 + and + num3 + is + sum
+ .);
}
}
The sum variable is formatted twice. In the first case, the print() method is used for each instruction
which prints the result on the same line. In the second case, the println() method is used to convert
each data type to string and concatenate them to display as a single result.
The output of the code is shown in figure 3.13.
Concepts
// Negative infinity
q = -10.0 / 0.0;
System.out.printf(-10.0/0.0 = %7.2e %n, q);
Flag Description
- Left justify the argument
+ Include a sign (+ or -) with this argument
0 Pad this argument with zeros
Flag Description
, Use locale-specific grouping separators
( Enclose negative numbers in parenthesis
Table 3.6: Types of Flags in Java
width: Indicates the minimum number of characters to be printed and cannot be negative.
precision: Indicates the number of digits to be printed after a decimal point. Used with floating-point
numbers.
conversion character: Specifies the type of argument to be formatted. For example, b for boolean,
c for char, d for integer, f for floating-point, and s for string.
The values within [] are optional. The only required elements of format specifier are the % and a
conversion character.
Code Snippet 13 demonstrates the format() method.
Code Snippet 13:
Method Description
nextByte() Returns the next token as a byte value
nextInt() Returns the next token as an int value
nextLong() Returns the next token as a long value
nextFloat() Returns the next token as a float value
nextDouble() Returns the next token as a double value
Table 3.7: Methods of Scanner class
Code Snippet 14 demonstrates the Scanner class methods and how they can be used to accept values
from the user.
Code Snippet 14:
System.out.println(Enter a number:);
// Accepts integer value from the user
Concepts
3.8 Operators
All programming languages provide some mechanism for performing various operations on the data
stored in variables. The simplest form of operations involves arithmetic (like adding, dividing, and so on)
or comparing between two or more variables. A set of symbols is used to indicate the kind of operation
to be performed on data. These symbols are called operators.
Consider the expression:
Z = X + Y;
Concepts
The + symbol in the statement is called the Operator and the operation performed is addition. This
operation is performed on the two variables X and Y, which are called as Operands. The combination of
both the operator and the operands, Z = X + Y, is known as an Expression.
Assignment Operator
Arithmetic Operator
Unary Operator
Conditional Operator
Logical Operator
Assignment Operator
Bitwise Operator
...
x = 10; // Assigns the value 10 to variable x
x += 5; // Increments the value of x by 5
x -= 5; // Decrements the value of x by 5
Operator Description
+ Addition - Returns the sum of the operands
- Subtraction - Returns the difference of two operands
* Multiplication - Returns the product of operands
/ Division Returns the result of division operation
% Remainder - Returns the remainder from a division operation
Table 3.8: Arithmetic Operator
Code Snippet 16 demonstrates the use of arithmetic operators.
Code Snippet 16:
...
x = 2 + 3; // Returns 5
y = 8 5; // Returns 3
x = 5 * 2; // Returns 10
x = 5/2; // Returns 2
y = 10 % 3; // Returns 1
...
Unary operators require only one operand. They perform various operations such as incrementing/
decrementing the value of a variable by 1, negating an expression, or inverting the value of a boolean
variable.
Operator Description
+ Unary plus - Indicates a positive value
- Unary minus - Negates an expression
++ Increment operator - Increments the value of a variable by 1
-- Decrement operator - Decrements the value of a variable by 1
! Logical complement operator - Inverts a boolean value
Table 3.9: Unary Operator
The ++ and -- operators can be applied before (prefix) or after (postfix) the operand. The statements
++variable and variable++ both result in incrementing the value of the variable by 1. The only
difference is that the prefix version (++variable) will increment the value before evaluating, whereas
the postfix version (variable++) will first evaluate and then, increment the original value.
Code Snippet 17 demonstrates the use of unary operators.
Code Snippet 17:
...
int i = 5;
int j = i++; // i=6, j=5
int k = ++i; //i=6,k=6
i = - i ; //now i is -6
boolean result = false; //result is false
result = !result; //now result is true
...
Operator Description
Concepts
Operator Description
>= Greater than or equal to - Checks if the value on the left is
greater than or equal to the value on the right
<= Less than or equal to Checks if the value on the left is less
than or equal to the value on the left
Table 3.10: Conditional Operators
Code Snippet 18 demonstrates the use of conditional operators.
Code Snippet 18:
Operator Description
&& Conditional AND - Returns true only if both the expressions
are true
|| Conditional OR - Returns true if either of the expression is
true or both the expressions are true
Table 3.11: Logical Operators
Code Snippet 19 demonstrates the use of logical operators.
Code Snippet 19:
Operator Description
& Bitwise AND - compares two bits and generates a result of 1 if
both bits are 1; otherwise, it returns 0
| Bitwise OR - compares two bits and generates a result of 1 if
the bits are complementary; otherwise, it returns 0
^ Exclusive OR - compares two bits and generates a result of 1 if
either or both bits are 1; otherwise, it returns 0
~ Complement operator - used to invert all of the bits of the
operand
>> Shift Right operator - Moves all bits in a number to the right
by one position retaining the sign of negative numbers
<< Shift Left operator - Moves all the bits in a number to the left
by the specified position
Table 3.12: Bitwise Operators
Code Snippet 20 demonstrates the use of bitwise operators.
Code Snippet 20:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int value1 = 10;
int value2 = 20;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}
Concepts
As someCondition variable evaluates to true, the value of value1 variable is assigned to the result
variable. Thus, the program prints 10 on the console.
Order Operator
1. Parentheses like ( )
2. Unary Operators like +, -, ++, --, ~, !
3. Arithmetic and Bitwise Shift operators like *, /, %, +, -, >>, <<
4. Relational Operators like >, >=, <, <=, ==, !=
5. Conditional and Bitwise Operators like &, ^, |, &&, ||,
6. Conditional and Assignment Operators like ?:, =, *=, /=, +=, -=
Table 3.13: Precedence of Operators
Parentheses are used to change the order in which an expression is evaluated. Any part of an expression
enclosed in parentheses is evaluated first.
For example, consider the following expression:
2*3+4/2 > 3 && 3<5 || 10<9
The evaluation of the expression based on its operators precedence is as follows:
1. (2*3+4/2) > 3 && 3<5 || 10<9
First the arithmetic operators are evaluated.
2. ((2*3)+(4/2)) > 3 && 3<5 || 10<9
Division and Multiplication are evaluated before addition and subtraction.
3. (6+2) >3 && 3<5 || 10<9
4. (8 >3) && [3<5] || [10<9]
Next to be evaluated are the relational operators all of which have the same precedence. These are
therefore evaluated from left to right.
5. (True && True) || False
The last to be evaluated are the logical operators. && takes precedence over ||.
Concepts
6. True || False
7. True
12+4-30
4. Finally, the expression is evaluated from left to right.
6 30
The result is -14.
The primitive numeric data types that can be implicitly cast are as follows:
...
double dbl = 10;
long lng = 100;
int in = 10;
dbl = in; // assigns the integer value to double variable
lng = in; // assigns the integer value to long variable
...
an error message.
...
float a = 21.3476f;
int b = (int) a + 5;
...
The float value in a is converted into an integer value 21. It is then, added to 5, and the resulting value,
26, is stored in b. This type of conversion is known as truncation. The fractional component is lost when
a floating-point is assigned to an integer type, resulting in the loss of precision.
Concepts
Operator Description
(A) a-1, b-2, c-3, d-4 (C) a-2, b-1, c-4, d-3
(B) a-4, b-3, c-2, d-1 (D) a-3, b-4, c-1, d-2
2. Which of the following operators is used to change the order of evaluation while evaluating an expression?
4. Match the following data types with the values that can optimally fit in that data type.
a. byte 1. 5000
b. char 2. 48999.988
c. double 3. F
c. int 4. 256
(A) a-1, b-2, c-3, d-4 (C) a-2, b-1, c-4, d-3
(B) a-4, b-3, c-2, d-1 (D) a-3, b-4, c-1, d-2
5. You want the output to be displayed as, floatTest=1.0, dblTest=1.0, and sum=2. Can you
arrange the steps in sequence to achieve the same?
System.out.println(dblTest= + dblTest);
a.
int sum = (int)(dblTest + floatTest);
b. System.out.println(sum= + sum);
boolean boolTest = true;
c.
float floatTest = 3.14f;
System.out.println(floatTest= + floatTest);
d.
dblTest = (double)( boolTest?1:0);
double dblTest = 0.000000000000053;
e.
floatTest = (float)(boolTest?1:0);
(A) c, e, d, a, b (C) c, d, e, b, a
(B) e, c, d, a, b (D) e, c, b, a, d
Concepts
3.10.1 Answers
1. C
2. B
3. D
4. B
5. A
Concepts
Summary
Variables store values required in the program and should be declared before they are used. In
Java, variables can be declared within a class, method, or within any block.
Data types determine the type of values that can be stored in a variable and the operations that
can be performed on them. Data types in Java are divided mainly into primitive types and
reference types.
A literal signifies a value assigned to a variable in the Java program. Java SE 7 supports the use of
the underscore characters (_) between the digits of a numeric literal.
The output of the Java program can be formatted using three ways: print() and println(), printf(),
format(). Similarly, the Scanner class allows the user to read or accept values of various data types
from the keyboard.
Operators are symbols that help to manipulate or perform some sort of function on data.
Parentheses are used to change the order in which an expression is evaluated.
The type casting feature helps in converting a certain data type to another data type. The type
casting can be automatic or manual and should follow the rules for promotion.
Concepts
2.
3. Try it Yourself
1. Write a program that declares variables of different data types. During declaration, try to use some
invalid variable names in the program and observe the compiler errors generated for the same.
Concepts
4.1 Introduction
A Java program consists of a set of statements, which are executed sequentially in the order in which
they appear. However, in some cases, the order of execution of statements may change based on the
evaluation of certain conditions. The change in the flow of statements is achieved by using different
control flow statements.
There are three categories of control flow statements supported by Java programming language. These
are as follows:
Iteration Statements - These types of statements are also referred to as looping constructs. They
allow the program to repeat a particular set of statements for certain number of times.
Branching Statements - These types of statements are referred to as jump statements. They
either allow the program to skip or continue execution of the looping statements. The program is
executed in a non-linear fashion.
if statement
switch-case statement
4.2 if Statement
The if statement is the most basic form of decision-making statement. The if statement evaluates a
given condition and based on the result of evaluation executes a certain section of code. If the condition
evaluates to true, then the statements present within the if block gets executed. If the condition
evaluates to false, the control is transferred directly to the statement outside the if block.
Concepts
if (condition) {
}
Concepts
where,
condition: Is the boolean expression.
statements: Are instructions/statements enclosed in curly braces. These statements are executed
when the boolean expression evaluates to true.
Code Snippet 1 demonstrates the code that performs conditional check on the value of a variable using
the if statement.
Code Snippet 1:
public class CheckNumberValue {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int first = 400, second = 700, result;
result = first + second;
The program tests the value of the variable, result and accordingly calculates value for the variable,
second. If the value of result is greater than 1000, then the value of the variable second is incremented
by 100. If the evaluation of condition is false, the value of the variable second is not incremented.
Finally, the value of the variable second gets printed on the console.
The output of the code is shown in figure 4.2.
Concepts
For example, Code Snippet 1 is rewritten in Code Snippet 2 to illustrate this concept.
Code Snippet 2:
The main disadvantage of omitting braces is that if another statement is added to the body of the if
statement, without enclosing the statements in curly braces, it would result in wrong output.
if (condition) {
else {
Code Snippet 3 demonstrates the code that checks whether a number is even or odd.
Code Snippet 3:
In the code, the variable, number is divided by 2 to obtain the remainder of the division. This is done
by using the % (modulus) operator which returns the remainder after performing the division. If the
remainder is 0, the message Number is even is printed. Otherwise, the message Number is odd
is printed.
The output of the code is shown in figure 4.3.
Concepts
The if statement must be within the same block as the else and it should not be
already associated with some other else statement.
The syntax to use the nested-if statements is as follows:
Syntax:
if(condition) {
if(condition)
true-block statement(s);
else
false-block statement(s);
}
else {
false-block statement(s);
}
Code Snippet 4 demonstrates the use of nested-if statement and checks whether a number is divisible
by 3 as well as 5.
Code Snippet 4:
import java.util.*;
public class NumberDivisibility {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Concepts
} else {
System.out.println(Number is not divisible by 3);
} // End of outer if-else statement
}
}
The code declares a variable num and stores an integer value accepted from the user. The code contains
an outer if statement, if(num % 3 == 0) and an inner if statement, if (num % 5 == 0). Initially,
the outer if statement is evaluated. If it evaluates to false, then the inner if-else statement is
skipped and the final else block is executed. If the outer if statement evaluates to true, then its
body containing the inner if-else statement is evaluated. In other words, evaluation of the inner if
statement depends on the result of the outer if statement.
The output of the code is shown in figure 4.4.
Concepts
if(condition) {
else if (condition) {
else {
}
Concepts
Figure 4.5 shows the flow of execution for the if-else-if ladder.
If the code satisfies a given condition, then the statements within that else if condition are executed.
After execution of the statements, the control breaks and remaining if conditions are bypassed for
evaluation. If none of the condition is satisfied, then the final else statement, also known as the default
else statement is executed.
The output of the code is shown in figure 4.6.
The switch-case statement contains a variable as an expression whose value is compared against
different values. It can have a number of possible execution paths depending on the value of expression
provided with the switch statement. The expression to be evaluated can contain different primitive
data types, such as byte, short, int, and char.
From Java SE 7, the switch-case statement also supports the use of strings and can be passed as an
expression for the switch statement. The String class is used for creating string values in the Java
program.
Apart from strings, it also supports objects of few classes present in the Java API. The classes are
Character, Byte, Short, and Integer and are referred to as wrapper classes. A wrapper class encloses
or wraps the primitive data type into an object of that type. For example, the wrapper class, Integer
allows you to use int value as object, that is, Integer y = new Integer(52);. It also supports the
use of enumerated types as expression.
The syntax for using the switch-case statement is as follows:
Syntax:
switch (<expression>) {
casevalue1:
// statement sequence
break;
casevalue2:
// statement sequence
break;
...
...
...
casevalueN:
// statement sequence
break;
default:
// default statement sequence
}
Concepts
where,
switch: The switch keyword is followed by an expression enclosed in parentheses.
case: The case keyword is followed by a constant and a colon. Each case value is a unique literal. The
case statement might be followed by a code sequence that is executed when the switch expression
and the case value match.
default: If no case value matches the switch expression value, execution continues at the default
clause. This is the equivalent to the else of the if-else-if statement.
break: The break statement is used inside the switch-case statement to terminate the execution of
the statement sequence. The break statement is optional. If there is no break statement, execution flows
sequentially into the next cases. Sometimes, multiple cases can be present without break statements
between them. The use of break statement makes the modification in code easier and with less error.
Figure 4.7 shows the flow of execution for the switch-case statement.
When the break statement is encountered, it terminates the switch-case block and control switches
to the statements following the block. The break statement must be provided with each case, as without
them switch blocks fall through. This means even after the matching case is executed; all other cases
following the matching case are also executed, until a break statement is encountered.
In the code, value of the expression, choice is compared with the literal value in each of the case
statement. Here, case 3 is executed, as its value is matching with the expression. Finally, the control
moves out of the switch-case, due to the presence of the break statement. The program will not
perform any action, if no matching case is found or the default statement is not present.
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if (year % 4 == 0) {
numDays = 29;
} else {
numDays = 28;
}
break;
default:
System.out.println(Invalid Month);
} // End of switch-case statement
System.out.println(Month: + month);
In the code, the value of expression, month is compared through each case, till a break statement or
end of the switch-case block is encountered.
Concepts
break;
Concepts
case Monday:
System.out.println(Second Day of the Week);
break;
case Tuesday:
System.out.println(Third Day of the Week);
break;
case Wednesday:
System.out.println(Fourth Day of the Week);
break;
case Thursday:
System.out.println(Fifth Day of the Week);
break;
case Friday:
System.out.println(Sixth Day of the Week);
break;
case Saturday:
System.out.println(Seventh Day of the Week);
break;
default:
System.out.println(Invalid Day);
}// End of switch-case statement
}
}
In the code, the statement String day=Monday creates an object named day of type String and
initializes it. Then, the object is passed as an expression to the switch statement. The value of this
expression, that is Monday, is compared with the value of each case statement. If a matching case is
not found, then the default statement is executed.
Concepts
Case-sensitive values The value of String variable that is matched with the case literals is
case sensitive. This means, if a String value Monday is matched with the case labeled
MONDAY:, then it will not be treated as a matched value. Hence, in that case, the default
statement will be executed.
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Cards card = Cards.Diamond;
In the code, the enum, card is passed as an expression to the switch statement. Each case statement
has an enumeration constant associated with it and does not require it to be qualified by the enumeration
name.
This is because during compilation, the switch statement with an enum, implicitly understands the type
of constants used with the case statements.
Concepts
case pm:
System.out.println(Good Evening);
break;
} // End of inner switch-case statement
break;
default:
System.out.println(Invalid Day);
} // End of the outer switch-case statement
}
}
Concepts
In the code, the variable, day is used as an expression with the outer switch statement. It is compared
with the list of cases provided with the outer switch-case statements. If the value of day variable
matches with Sunday or Monday, then the inner switch-case statement is executed. The inner
switch statement compares the value of hour variable with case constants am or pm.
The switch-case statement differs from the if statement, as it can only test for equality. The
if statement can test any type of boolean expression. In other words, the switch-case
statement looks only for a match between the value of the expression and one of its case
constants.
No two case constants in the same switch statement can have identical values, except the nested
switch-case statements.
A switch statement is more efficient and executes faster than a set of nested-if statements.
if switch-case
Each if statement has its own logical Each case refers back to the original value of the
expression to be evaluated as true or expression in the switch statement
false
The variables in the expression may The expression must evaluate to a byte, short,
evaluate to a value of any type char, int, or String
Only one of the blocks of code is If the break statement is omitted, the execution
executed will continue into the next block
Concepts
System.out.printf(Equal System.out.printf(Equal
a. +value); c. +value); {
}
else{ }
else
System.out.println(value + System.out.println(value +
Not Equal ); Not Equal );
} }
int value = 100; int value = 100;
boolean bool = false; boolean bool = false;
if((bool==true) && if((bool==true) &&
((value==100)==200)) { ((value+=100)==200))
{
System.out.printf(Equal System.out.printf(Equal
b. +value); d. +value);
} }
else{ else
{
System.out.println(value + System.out.println(value +
Not Equal ); Not Equal );
} }
Concepts
(A) a (C) c
(B) b (D) d
2. You are using the switch-case statement to display the output value is ten. Which of the
following code will help you to achieve this?
int value = 10;
int value = 10;
switch(value)
switch(value)
{
{
case 10:
case 10:
System.out.println(value
is ten ); System.out.println(value is
ten );
break;
case 20:
a. case 20: c.
System.out.println(value is
System.out.println(value twenty );
is twenty );
default:
break;
System.out.println(Invalid
default: value );
System.out. break;
println(Invalid value );
}
}
int value = 10;
int value = 10;
switch(value)
switch(value)
{
{
case 10:
case 10:
System.out.println(value
is ten ); System.out.println(value is
ten );
case 20:
case 20:
b. System.out.println(value d.
is twenty ); System.out.println(value is
twenty );
break;
default:
default:
break;
System.out.
println(Invalid value ); System.out.println(Invalid
Concepts
value );
break;
}
}
(A) a (C) b
(B) c (D) d
4. The _____ statement is used inside the switch-case statement to terminate the execution of the
statement sequence.
Construct Syntax
if(condition) {
// one or more statements
} else if (condition) {
a. if 1. // one or more statements
Concepts
} else {
// one or more statements
}
if(condition) {
if(condition)
true-block statement(s);
else
b. if-else 2. false-block statement(s);
}
else {
false-block statement(s);
}
if (condition) {
// one or more statements;
c. nested-if 3. } else {
// one or more statements;
}
if (condition){
d. if-else-if 4. // one or more statements;
}
(A) a-3, b-2, c-4, d-1 (C) a-1, b-2, c-4, d-3
(B) a-4, b-3, c-2, d-1 (D) a-4, b-1, c-2, d-3
Concepts
4.5.1 Answers
1. C
2. A
3. B
4. D
5. B
Concepts
Summary
A Java program is a set of statements, which are executed sequentially in the order in which they
appear.
The three categories of control flow statements supported by Java programming language include:
conditional, iteration, and branching statements.
The if statement is the most basic decision-making statement that evaluates a given condition and
based on result of evaluation executes a certain section of code.
The if-else statement defines a block of statements to be executed when a condition is evaluated
to false.
The multiple if construct is known as the if-else-if ladder with conditions evaluated sequentially
from the top of the ladder.
The switch-case statement can be used as an alternative approach for multiple selections. It is
used when a variable needs to be compared against different values. Java SE 7 supports strings
and enumerations in the switch-case statement.
A switch statement can also be used as a part of another switch statement. This is known as
nested switch-case statements.
Concepts
Try it Yourself
1. Lifemaxi is an insurance company situated in Leeds, United Kingdom. It has employed insurance
agents that provide information to the customers about the various policies and loan amount. To
speed their business and also help agents to solve the customer queries, the company has decided
to design a software application in Java.
You being a developer in the team have been assigned the task to develop the Java application. The
application should help a loan agent to calculate whether the customer is eligible for loan or not.
The criterias that are required to be considered to automate the loan policy are as follows:
Personal
Age category Gender Profession Loan amount eligible
assets
16 -25 M/F Self-Employed / Professional >25000 10000/ Professional 15000
26 - 40 M Self-Employed / Professional > 40000 25000/ Female 30000
41 - 60 M/F Self-Employed / Professional > 50000 40000
35000 Age * 100/
> 60 M/F Self-Employed / Retired > 25000
Retired 25000 Age * 100
2. Write a program that accepts a letter as an input and checks whether the entered letter is a vowel
or a consonant.
3. Write a program that accepts a deposit amount from the user and calculates the amount of interest
earned in a year. The bank pays the following interest rate depending on the amount deposited:
a. 4% for deposits of up to 2000
b. 4.5% for deposits of up to 7000
c. 5% for deposits of more than 7000
Concepts
5.1 Introduction
A computer program consists of a set of statements, which are usually executed sequentially. However,
in certain situations, it is necessary to repeat certain steps to meet a specified condition.
For example, if the user wants to write a program that calculates and displays the sum of the first 10
numbers 1, 2, 3. . , 10. Then, one way to calculate the same is as follows:
1+2=3
3+3=6
6+4=10
10+5=15
15+6=21
. . .
. . .
and so on.
This technique is suitable for relatively small calculations. However, if the program requires adding the
first 200 numbers, it would be tedious to add up all the numbers from 1 to 200 using the mentioned
technique. In such situations, iterations or loops come to our rescue.
Figure 5.1 shows the program that displays the multiples of 10.
while statement
do-while statement
for statement
for-each statement
Concepts
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Concepts
In the code, an integer variable, num is declared to store a number. The variable num is initialized to 1 and
is used in the while loop to start multiplication from 1.
The conditional expression num <= 5 is evaluated at the beginning of the while loop. This ensures
that the body of the loop is executed only if the conditional expression evaluates to true. In this case,
as the value in the variable, num is less than 5, hence, the statements present in the body of the loop is
executed. The first statement within the body of the loop calculates the product by multiplying num with
10. The next statement prints this value. The last statement num++ increments the value of num by 1. The
loop continues as long as the value of num is less than or equal to 5. The execution of the loop stops when
condition becomes false, that is, when the value of num reaches 6.
Concepts
As shown in the code, the value of num1 is incremented and the value of num2 is decremented. These
values are then compared with one another. The loop repeats till the value of num1 is equal to or greater
than num2. Thus, upon exit num1 will hold a value that is midway between the original values of num1
and num2.
The output of the code is shown in figure 5.4.
The value of the variables used in the expression must be set at some point before the while
loop is reached. This process is called the initialization of variables and has to be performed once
before the execution of the loop. For example, num = 1;
The body of the loop must have an expression that changes the value of the variable which is a
part of the loops expression. For example, num++; or num--;
In the code, the conditional expression is set to a boolean value, true. The loop never terminates as the
expression always returns a true value. This leads to an infinite loop.
The program executing the loop infinitely must be terminated manually or a break statement should be
used to terminate such loops.
statement(s);
}
while (expression);
where,
expression: A conditional expression which must return a boolean value, that is, true or false.
Concepts
Figure 5.5 shows the flow of execution for the do-while loop.
do {
sum = sum + num;
num++;
} while (num <= 10);
In the code, two integer variables, num and sum are declared and initialized to 1 and 0 respectively. The
loop block begins with a do statement. The first statement in the body of the loop calculates the value
of sum by adding the current value of sum with num and the next statement in the loop increments the
value of num by 1. Next, the condition, num <= 10, included in the while statement is evaluated. If the
condition is met, the instructions in the loop are repeated. If the condition is not met (that is, when the
value of num becomes 11), the loop terminates and the value in the variable sum is printed.
The output of the code is shown in figure 5.6.
Concepts
If the expression is true, then the body of the loop is executed and if the expression is false, then the
loop terminates. Lastly, the iteration portion of the loop is executed. This expression usually increments
or decrements value of the control variable. In the next iteration, again the condition section is evaluated
and depending on the result of evaluation the loop is either continued or terminated.
Code Snippet 5 demonstrates the use of for statement for displaying the multiples of 10.
Code Snippet 5:
In the initialization section of the for loop, the num variable is initialized to 1. The condition statement,
num <= 5, ensures that the for loop executes as long as num is less than or equal to 5. The increment
statement, num++, increments the value of num by 1. The increment/decrement expression is evaluated
after the first round of iteration and continues till the condition evaluates to false. Finally, the loop
terminates when the condition becomes false, that is, when the value of num becomes equal to 6.
The output of the code is shown in figure 5.8.
Concepts
In the code, the variable num is not required further in the program, so, it has been declared inside the
for statement. This restricts the scope of the variable, num to the for statement. The scope of variable
completes when the loop terminates. The output of the program will be same as Code Snippet 5.
Code Snippet 7 demonstrates the use of for loop to print the addition table for two variables using the
comma operator.
Code Snippet 7:
As shown in the code, three integer variables i, j, and max are declared. The variable max is assigned a
value 10. Further, within the initialization section of the for loop, the i variable is assigned a value of
0 and j is assigned the value of max, that is, 10. Thus, two parameters are initialized using a comma
operator. The condition statement, i <= max, ensures that the for loop executes as long as i is less than
or equal to max that is 10. The loop exits when the condition becomes false, that is, when the value of i
becomes equal to 11. Finally, the iteration expression again consists of two expressions, i++, j--. After
each iteration, i is incremented by 1 and j is decremented by 1. The sum of these two variables which is
always equal to max is printed.
Concepts
/*
* The for loop starts with num value 1 and
* continues till value of flag is not true
*/
for (; !flag; num++) {
System.out.println(Value of num: + num);
if (num == 5) {
flag = true;
}
} // End of for loop
}
}
The for loop in the code continues to execute till the value of the variable flag is set to true.
The output of the code is shown in figure 5.10.
.....
for( ; ; ) {
System.out.println(This will go on and on);
}
.....
The code will print This will go on and on until the loop is terminated manually. The break
statement can be used to terminate such loops. Infinite loops make the program run indefinitely for
a long time resulting in the consumption of all resources and stopping the system. Thus, it is a good
practice to avoid using such loops in a program.
When the number of user inputs in a program is not known beforehand, an infinite loop can be used
in a program, where it will wait indefinitely for user input. Thus, when a user input is received, system
processes the input, and again starts executing the infinite loop.
var: Is an iteration variable that stores the elements from the collection. The for-each loop traverses
from beginning to end and in each iteration the element is retrieved and stored in the var variable.
The enhanced for loop continues till all the elements from a collection are retrieved.
Table 5.1 shows the method for retrieving elements from an array object using enhanced for loop and
its equivalent for loop.
Table 5.1: Enhanced for Loop and its Equivalent for Loop
/*
* For each iteration, the inner for loop will execute from col = 1
* and will continue, till the value of col is less than or equal to row
*/
for (col = 1; col <= row; col++) {
System.out.print( * );
} // End of inner for loop
System.out.println();
} // End of outer for loop
}
}
In the code, the outer for loop starts with the counter variable row whose initial value is set to 1. As
the condition, row < 5 is evaluated to true, the body of the outer for loop gets executed. The body
contains an inner for loop which starts with the counter variables value col set to 1. The iteration of
the inner loop executes till the value of col is less than or equal to the value of row variable. Once the
value of col is greater than row, the inner for loop terminates.
Then, the control moves to the outer for loop and the value of the variable row is incremented by 1. The
outer loop continues, till the value of row is not greater than 5. For each iteration of the outer loop, the
inner for loop is reinitialized and continues till the condition evaluates to false.
The output of the code is shown in figure 5.11.
Concepts
while/for do-while
Loop is pre-tested. The condition is checked Loop is post-tested. The condition is checked after
before the statements within the loop are the statements within the loop are executed.
executed.
The loop does not get executed if the The loop gets executed at least once even if the
condition is not satisfied at the beginning. condition is not satisfied at the beginning.
Table 5.2: Difference Between while/for and do-while
In the code, the user is prompted to enter a number, and this is stored in the variable, number. This is
repeated 10 times. However, if the user enters the number zero, the loop terminates and the control is
passed to the next statement after the loop.
Concepts
The output of the code is shown in figure 5.12 with different values entered by the user.
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int cnt, square, cube;
Concepts
The code declares a variable cnt and uses the for statement which contains the initialization, termination,
and increment expression. In the body of the loop, the value of cnt is divided by 3 and the remainder is
checked. If the remainder is 0, the continue statement is used to skip the rest of the statements in the
body of the loop. If remainder is not 0, the if statement evaluates to false, and the square and cube
of cnt is calculated and displayed.
The output of the code is shown in figure 5.13.
Concepts
System.out.println(Hello);
// Break out of outer loop
break outer; }
System.out.println(This is the outer loop.);
}
System.out.println(Good - Bye);
}
}
In the code, the loop will execute for five times. The first two times it displays the sentence This is the
outer loop. In the third round of iteration the value of i is set to 2. Thus, it enters the if statement
and prints Hello. Next, the break statement is encountered and the control passes to the label named
outer:. Thus, the loop terminates and the last statement is printed.
The output of the code is shown in figure 5.14.
if (j > i) {
System.out.println();
2. You want the output to be displayed as 95 91 87 83. Can you arrange the steps in sequence to
achieve the same?
a. System.out.println(i);
b. i++;}
c. int i = 100;
d. i -= 5;
(A) c, e, d, a, b (C) e, c, a, d, b
(B) a, c, d, e, b (D) d, e, c, a, b
a. do-while statement tests the condition after the first iteration of the loop
In do-while, if the condition is true, the control passes back to the top of the
b.
loop
c. In do-while, if the condition is true, the loop terminates
Description Loop
(A) a-3, b-4, c-1, d-2 (C) a-2, b-1, c-3, d-4
(B) a-1, b-2, c-3, d-4 (D) a-4, b-3, c-1, d-2
5. The one or more expressions used in for statement are separated by the ____ operator.
Concepts
(A) ; (C) ,
5.8.1 Answers
1. B
2. A
3. B
4. D
5. C
Concepts
Summary
Loops enable programmers to develop concise programs, which otherwise would require
thousands of lines of program statements.
The loop statements supported by Java are namely, while, do-while, and for.
The while loop is used to execute a statement or a block of statements until the specified
condition is true.
The do-while statement checks for condition at the end of the loop rather than at the beginning
to ensure that the loop is executed at least once.
The for loop is especially used when the user knows the number of times the statements need to
be executed in the code block of the loop. The three parts of for statement are initialization,
condition, increment/decrement.
The placing of a loop in the body of another loop is called nesting.
Java provides two keywords namely, break and continue that serve diverse purposes. However,
both are used with loops to change the flow of control.
Concepts
Try it Yourself
1. Consider the following code snippet:
if (aNumber >= 0)
if (aNumber == 0)
System.out.println(first string);
else System.out.println(second string);
System.out.println(third string);
What output will the code produce, if the value in the variable, aNumber is 3?
To make the code clear and understandable, put the braces ({}) in the code at appropriate
places.
2. Write a program to develop a menu for the calculator program. Accept the choice from the user and
display an appropriate message. Further, to continue with the menu, ask for confirmation in
Yes/No.
3. Write a program to display all the prime numbers between the two numbers.
4. Write a program to display the sum of all the digits for the accepted number.
For example, if number entered as 1345, then sum of all digits will be 1 + 3 + 4 + 5.
Concepts
6.1 Introduction
The class is a logical construct that defines the shape and nature of an object. As it is the prime unit of
execution for object-oriented programming in Java, so any concept in Java program must be encapsulated
within the class.
In Java, class is defined as a new data type. This data type is used to create objects of its type. Each object
created from the class contains its own copy of the attributes defined in the class. The attributes are
also referred to as fields and represents the state of an object. The initialization of objects is done using
constructors and the behavior of the objects is defined using methods.
Class name can be in mixed case, with the first letter of each internal word capitalized.
Class name cannot begin with a digit. However, they can begin with a dollar ($) symbol or an
underscore character.
The syntax to declare a class in Java is as follows:
Syntax:
class <class_name> {
// class body
}
Concepts
Class declaration is enclosed within code blocks. In other words, the body of the class is enclosed between
the area between the curly braces. In the class body, you can declare members, such as fields, methods,
and constructors.
class Customer {
// body of class
In the code, a class is declared that acts as a new data type. The name of the new data type is Customer.
This data type declaration is just a template for creating multiple objects with similar features and does
not occupy any memory.
Concepts
The expression on the right side, new Customer() allocates the memory at runtime. After the memory
is allocated for the object, it returns the reference or address of the allocated object, which is stored in
the variable, objCustomer.
Figure 6.2 shows the effect of the statement, Customer objCustomer; which just declares a reference
variable.
Consider a scenario where the Customer class represents the details of customers holding accounts
in a bank. In this scenario, a typical question that can be asked is What are the different data that are
required to identify a customer in a banking domain and represent it as a single object?.
Figure 6.4 shows a Customer object with its data requirement.
Figure 6.5 shows various instances of the class with their own copy of instance variables.
a class, but outside any method definitions. They can be accessed only through the objects using the dot
operator (.).
Code Snippet 3 demonstrates the declaration of instance variables within a class in the Java program.
Code Snippet 3:
In the code, lines 3 to 6 declares instance variables. Line 11 creates an object of type Customer and
stores its reference in the variable, objCustomer1. Lines 13 to 16 accesses the instance variables and
assigns them the values. Note, that to assign value to the instance variable, you qualify the variable name
with an instance name followed by a dot operator.
Finally, lines 18 to 21 display the values assigned to the instance variables for the object,
objCustomer1.
Figure 6.6 shows the allocation of Customer object in the memory. The reference of the object is stored
in the variable, objCustomer1 which is of type Customer.
The instance method can access instance variables declared within the class and manipulate the data in
the field.
Following conventions have to be followed while naming a method:
Should be a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns,
and so forth.
Figure 6.8 shows the instance methods declared in the class, Customer that are invoked by all the
instances of the class.
}
where,
access_modifier: Is an optional keyword specifying the access level of an instance method. It could be
private, protected, and public.
returntype: Specifies the data type of the value that is returned by the method.
method_name: Is the method name.
list of parameters: Are the values passed to the method.
Figure 6.9 shows the declaration of an instance method within the class.
Code Snippet 4 demonstrates the code that declares instance methods within the class, Customer.
Code Snippet 4:
/**
* Declares an instance method changeCustomerAddress is created to change
* the address of the customer object
*/
void changeCustomerAddress(String address) {
customerAddress = address;
}
/**
* Declares an instance method displayCustomerInformation is created to
* display the details of the customer object
*/
void displayCustomerInformation() {
System.out.println(Customer Identification Number: + customerID);
System.out.println(Customer Name: + customerName);
System.out.println(Customer Address: + customerAddress);
System.out.println(Customer Age: + customerAge);
}
}
Concepts
The class Customer is modified with the instance methods namely, changeCustomerAddress() and
displayCustomerInformation(). The changeCustomerAddress() method will accept a string
value through parameter address. It then assigns the value of address variable to the customerAddress
field. As methods are part of class declaration, they can access the other class members, such as instance
variables and methods of the class.
/*
* Invokes the instance method to display the details
* of objCustomer object
*/
objCustomer.displayCustomerInformation();
/*
* Invokes the instance method to
* change the address of the objCustomer object
*/
objCustomer.changeCustomerAddress(123 Fort, Main Street);
/*
* Invokes the instance method after changing the address field
* of objCustomer object
*/
objCustomer.displayCustomerInformation();
}
}
The code instantiates an object objCustomer of type Customer class and initializes its instance
variables. The method displayCustomerInformation() is invoked using the object objCustomer.
This method displays the values of the initialized instance variables on the console.
Then, the method changeCustomerAddress(123 Fort, Main Street) is invoked to change
the data of the customerAddress field. Finally, the method displayCustomerInformation() is
invoked again to display the details of the objCustomer object.
Concepts
6.5 Constructor
A class can contain multiple variables whose declaration and initialization becomes difficult to track if
they are done within different blocks. Likewise, there may be other startup operations that need to be
performed in an application like opening a file and so forth. Java programming language allows objects to
initialize themselves immediately upon their creation. This behavior is achieved by defining constructors
in the class.
A constructor is a method having the same name as that of the class. Constructors initialize the variables
of a class or perform startup operations only once when the object of the class is instantiated. They are
automatically executed whenever an instance of a class is created, before the new operator completes.
Also, constructor methods do not have return types, but accepts parameters.
Concepts
Note - Constructors have no return type. This is because the implicit return type of a constructor is the
class itself. It is also possible to have overloaded constructors in Java.
The syntax for declaring constructor in a class is as follows:
Syntax:
<classname>() {
// Initialization code
}
Code Snippet 6 demonstrates a class Rectangle with a constructor.
Code Snippet 6:
width = 10;
height = 10;
}
}
The code declares a method named Rectangle() which is a constructor. This method is invoked by
JVM to initialize the two instance variables, width and height, when the object of type Rectangle
is constructed. Also, the constructor does not have any parameters; hence, it is called as no-argument
constructor.
}
}
The code creates an object, objRec of type Rectangle. First, the memory allocation for the Rectangle
object is done and then the constructor is invoked. The constructor initializes the instance variables of
the newly created object, that is, width and height to 10.
/**
* Accesses the instance variables and displays
Concepts
System.out.println(Employee Details);
System.out.println(================);
System.out.println(Employee Name: + employeeName);
System.out.println(Employee Age: + employeeAge);
System.out.println(Employee Salary: + employeeSalary);
System.out.println(Employee MaritalStatus: + maritalStatus);
}
}
The code declares a class Employee with instance variables and an instance method
displayEmployeeDetails(). The method prints the value of the instance variables on the console.
Code Snippet 9 demonstrates a class containing the main() method. This class creates an instance of the
class Employee and invokes the methods of the Employee class.
Code Snippet 9:
As the Employee class does not have any constructor defined for itself, a default constructor is created
for the class at runtime.
When the statement new Employee() is executed, the object is allocated in memory and the
Concepts
instance variables are initialized to their default values by the constructor. Then, the method
displayEmployeeDetails() is executed which displays the values of the instance variables referenced
by the object, objEmp.
Table 6.1 lists the default values assigned to instance variables of the class depending on their data
types.
situations.
The parameterized constructor contains a list of parameters that initializes instance variables of an
object. The value for the parameters is passed during the object creation. This means each object will be
initialized with different set of values.
Code Snippet 10 demonstrates a code that declares parameterized constructor for the Rectangle
class.
Code Snippet 10:
int width;
int height;
/**
* A default constructor for Rectangle class
*/
Rectangle() {
System.out.println(Constructor Invoked...);
width = 10;
height = 10;
}
/**
* A parameterized constructor with two parameters
* @param wid will store the width of the rectangle
* @param heig will store the height of the rectangle
*/
Rectangle (int wid, int heig) {
System.out.println(Parameterized Constructor);
width = wid;
height = heig;
}
/**
Concepts
System.out.println(Width: + height);
}
}
The code declares a parameterized constructor, Rectangle(int wid, int heig). During execution,
the constructor will accept the values in two parameters and assigns them to width and height variable
respectively.
Code Snippet 11 demonstrates the code with main() method. This class creates objects of type Rectangle
and initializes them with parameterized constructor.
Code Snippet 11:
The code creates two objects which invokes the parameterized constructor. For example, the statement
Concepts
Concepts
System.out.println(\nRectangle1 Details);
System.out.println(===================);
System.out.println(\nRectangle2 Details);
System.out.println(===================);
objRec2.displayDimensions();
}
}
The code creates two object reference variables, objRec1 and objRec2. The objRec1 points to the
object that has been allocated memory and initialized to 10 and 20, whereas objRec2 does not point
to any object. For the statement, objRec2 = objRec1; reference stored in the objRec1 is copied
into objRec2, that is, the address in objRec1 is coped into objRec2. Thus, the references are copied
between the variables created on the stack without affecting the actual objects created on the heap.
Concepts
Figure 6.19 shows the assigning of reference for the statement, objRec2 = objRec1;.
6.7 Encapsulation
Consider a scenario in which you want to learn how to drive a car. As a learner, it is not necessary for you
to understand the details on how the engine works, how the petrol tank is built, how wheel implements
right-turn or left-turn functionality, and so on. As a driver, you are interested and concerned with how to
start and switch off the engine and how to provide fuel to the car. Also, you may be interested in knowing
how to use gears and apply brakes to accomplish the complete understanding of the car. Thus, to drive a
car, you are interested in the interface of the car, rather than how each part functions.
Similarly, in object-oriented programming, the concept of hiding implementation details of an object is
Concepts
Similarly, implementation details of what a class contains need not be visible to other classes and
objects that use it. Instead, only specific information can be made visible to the other components of the
application and the rest can be hidden. This is achieved through encapsulation, also called data hiding.
In other words, it can be said that in OOP languages, encapsulation covers the internal workings of a
Java object. The main purpose of data hiding within a class is to reduce the complexity in the software
development. By hiding the implementation details about what is required to implement the specific
operation in the class, the usage of operation becomes simple. In Java, the data hiding is achieved by
using access modifiers.
Data encapsulation hides the instance variables that represent the state of an object. Thus, the only
interaction or modification is performed through methods. For example, for modifying the accounts
holder name, the appropriate method such as changeHolderName()can be provided in the Account
class. This way the implementation of the class is hidden from the rest of the application.
public: The public access modifier provides the most permissive access level. The members
declared as public can be accessed from anywhere in the class as well as from other classes.
private: The private access modifier provides the least permissive access level. Private members
are accessible only from within the class in which they are declared.
protected: The protected access modifier allows the class members to be accessible from within
the class as well as from within the derived classes. The derived classes are sub class created while
implementing inheritance.
package (default): The package access modifier allows only the public members of a class to be
accessible to all the classes present within the same package. This is the default access level for all
the members of the class. If the modifier is not specified with any member declared in the class,
then it is treated with the package access level.
As a general rule in Java, the details and implementation of a class is hidden from the other classes
Concepts
or external objects in the application. This is done by making instance variables as private and
instance methods as public.
Code Snippet 13 demonstrates the use of the concept of encapsulation in the class Rectangle.
Code Snippet 13:
/**
* Declares a parameterized constructor with two parameters
* @param wid
* @param heig
*/
public Rectangle (int wid, int heig) {
System.out.println(Parameterized Constructor Invoked...);
width = wid;
height = heig;
}
/**
Concepts
System.out.println(Width: + width);
System.out.println(Width: + height);
}
}
The code changes the access specifier of the instance variables or fields, width and height of the
Rectangle class from default to private. This means that the class fields are not directly accessible
from outside the class. This is done to restrict the access to the data members of the class. Similarly, the
access modifiers for the methods are changed to public. Thus, the users can access the class members
through its methods without impacting the internal implementation of the class.
void displayDetails() {
System.out.println(Person Details);
System.out.println(==============);
System.out.println(Person Name: + name);
In the code, the instance variables name and age are initialized to values John and 12 respectively.
Initializing the variables within the class declaration does not require them to initialize in a constructor.
Code Snippet 15 shows the class with main() method that creates objects of type Person.
Code Snippet 15:
The code creates an object of type Person and invokes the method to display the details.
The output of the code is shown in figure 6.20.
Initialization Block
In this approach, an initialization block is specified within the class. The initialization block is
Concepts
/**
* Initialization block
*/
{
accountID = 100;
holderName = John Anderson;
accountType = Savings;
}
/**
* Displays the details of Account object
*/
public void displayAccountDetails() {
System.out.println(Account Details);
System.out.println(===============);
System.out.println(Account ID: + accountID + \nAccount Type: +
accountType);
}
}
In the code, the initialization blocks initializes the instance variables or fields of the class. The
initialization blocks are basically used to perform complex initialization sequences.
Concepts
Code Snippet 17 shows the code with main() method to initialize the Account object through
initialization block.
Code Snippet 17 :
Concepts
c. Declaration of the class need not be preceded with the keyword class
2. Which of the following method have the same name as class name?
3. You want to declare a class Student containing an instance variable rollNo. Further, you want to
create two instances of this class namely, objJohn and objMartin and assign values to their
respective instance variables and display them. Arrange the steps in sequence.
objJohn.rollNo = 1151;
a.
Student objMartin = new Student();
public static void main(String[] args) {
b.
Student objJohn = new Student();
System.out.println(objMartin.rollNo);
c.
}}
objMartin.rollNo = 1152;
d.
System.out.println(objJohn.rollNo);
Concepts
class Student {
e.
int rollNo;
(A) e, b, a, d, c (C) b, e, d, a, c
(B) c, a, b, e, d (D) d, c, e, a, b
4. In Java, ________ provides a way to create an object and initialize its fields, before the constructor
methods are invoked.
5. Which of the following option specifies a feature of OOP language that hides the instance variables
within the class?
Concepts
6.9.1 Answers
1. C
2. B
3. A
4. D
5. C
Concepts
Summary
The class is a logical construct that defines the shape and nature of an object.
Objects are the actual instances of the class and are created using the new operator. The new operator
instructs JVM to allocate the memory for the object.
The members of a class are fields and methods. Fields define the state and are referred to as instance
variables, whereas methods are used to implement the behavior of the objects and are referred to as
instance methods.
Each instance created from the class will have its own copy of the instance variables, whereas methods
are common for all instances of the class.
Constructors are methods that are used to initialize the fields or perform startup operations only once
when the object of the class is instantiated.
The heap area of memory deals with the dynamic memory allocations for objects, whereas the stack area
holds the object references.
Data encapsulation hides the instance variables that represents the state of an object through access
modifiers. The only interaction or modification on objects is performed through the methods.
Concepts
1.
Try it Yourself
1. Consider a situation where you have been asked to develop a paint application. The paint application
should be able to draw the different types of shapes, such as circle, square, parallelogram, rectangle,
and so on. Each of these shapes is a collection of many points. Thus, you decide to create a Point
class in the application. The features to be implemented in the Point class are as follows:
a. As a point is formed with two co-ordinates on the plane, include x and y as the fields in the
Point class.
b. Implement the methods, such as setX(), setY(), and displayPoints() in the Point
class to represent the behavior of the Point class.
c. Implement necessary constructors to initialize the objects of the Point class during their
creation.
d. Create two objects of Point type and compare their x and y co-ordinates. If co-ordinates
have same values, then display Points are Same, otherwise, display Points are
Different.
2. What will be the output when you compile and run the following code:
public class MyClass {
public static void main(String arguments[]) {
someMethod(arguments);
}
public void someMethod(String[] parameters) {
System.out.println(parameters);
}
}
Concepts
7.1 Introduction
Consider a situation where in a user wants to perform some mathematical operations on two numbers.
The numbers may be integers or floating-point numbers. One way to do this would be to declare several
different variables in the class and write as many expressions as the number and type of mathematical
operations required. In this case, all the operations will be performed at a time on the numbers during
program execution.
However, what if the user wants only a single operation to be executed at a time? In such a case, it is
necessary to have a feature that allows execution of only the required expressions and not the entire
program. Methods in Java are such a feature that allows grouping of statements and execution of a
specific set of statements instead of executing the entire program. Again, what if the user wants to
restrict access to certain methods? Java provides a set of access specifiers that can help the user to
accomplish this task.
7.2 Methods
A Java method can be defined as a set of statements grouped together for performing a specific task. For
example, a call to the main() method which is the point of entry of any Java program, will execute all
the statements written within the scope of the main() method. The syntax for declaring a method is as
follows:
Syntax:
modifier return_type method_name([list_of_parameters]) {
// Body of the method
}
where,
modifier: Specifies the visibility of the method. Visibility indicates which object can access the
method. The values can be public, private, or protected.
return_type: Specifies the data type of the value returned by the method.
method_name: Specifies the name of the method.
list_of_parameters: Specifies the comma-delimited list of values passed to the method.
Generally, a method declaration has the following six components, in order:
1. Modifiers such as public, private, and protected.
Concepts
2. A return type that indicates the data type of the value returned by the method. The return type is
set to void if the method does not return a value.
3. The method name that is specified based on certain rules. A method name:
cannot be a Java keyword
cannot have spaces
cannot begin with a digit
cannot begin with any symbol other than a $ or _
can be a verb in lowercase
can be a multi-word name that begins with a verb in lowercase, followed by adjectives or
nouns
can be a multi-word name with the first letter of the second word and each of the following
words capitalized
should be descriptive and meaningful
Some valid method names are add, _view, $calc, add_num, setFirstName, compareTo,
isValid, and so on.
4. The parameter list in parenthesis is separated with a comma delimiter. Each parameter is preceded
by its data type. If there are no parameters, an empty parenthesis is used.
5. An exception list that specifies the names of exceptions that can be thrown by the method. An
exception is an event encountered during the execution of the program, disrupting the flow of
program execution.
6. The method body which consists of a set of statements enclosed between curly braces {}. The
method body can have variables, method calls, and even classes.
The two components of a method declaration namely, the method name and the parameter types
comprise the method signature.
Code Snippet 1 defines a method named add() that accepts two parameters num1 and num2, each of
type integer. Also, the method has been declared with the public access specifier which means that it
can be accessed by all objects. The return type set to void indicates that the method does not return
anything.
The method body consists of three statements. The first statement int num3; is a declaration of
an integer variable named num3. The second statement num3 = num1 + num2; is an addition
Concepts
operation performed on parameters num1 and num2 using the arithmetic operator +. The result is
stored in a third variable num3 by using the assignment operator =. The last statement System.out.
println(Addition is + num3); is used to print the value of variable num3. The method signature
is add(int, int).
While creating a method, a user defines the structure and function of the method. In other words, a
developer specifies what the method will perform.
However, to use the method, it must be called or invoked. When a program calls a method, the control is
transferred to the called method. The called method executes and returns control to the caller. The call is
returned back after the return statement of a method is executed or when the closing brace is reached.
A method can be invoked in one of the following ways:
If the method returns a value, then, a call to the method results in return of some value from the
method to the caller. For example,
int result = obj.add(20, 30);
Assuming that the add() method returns an integer value, the method call is placed to the right
of the assignment operator. The returned value will be stored in a variable named result placed
on the left of the assignment operator. The return type of a method specifies the type of value that
the method returns. Thus, the data type of the variable result must be same as the return type
of the method add().
If the methods return type is set to void, then, a call to the method results in execution of the
statements within the method without returning any value to the caller. For example, the add()
method in Code Snippet 1 returns void and prints the output using the statement
System.out.println(Addition is + num3);
Hence, a call to the method would be obj.add(23,30) without anything returned to the caller.
In such cases, a call to the method will be a statement.
Consider the project Session7 created in the NetBeans IDE as shown in figure 7.2.
Concepts
The project consists of a package named session7 with the Calculator class that has the main()
method. Several methods for mathematical operations can be added to the class.
Code Snippet 2 demonstrates an example of creation and invocation of methods.
Code Snippet 2:
package session7;
public class Calculator {
int num3;
num3 = num1 + num2;
System.out.println(Result after addition is + num3);
}
int num3;
num3 = num1 - num2;
System.out.println(Result after subtraction is + num3);
}
int num3;
Concepts
The class Calculator consists of methods such as add(), sub(), mul(), and div() that are used
to perform the respective operations. Each method accepts two integers as parameters. The main()
method creates an object, objCalc of class Calculator. The object objCalc uses the dot . operator
to call or invoke the add() and mul() methods. When the program is executed in NetBeans IDE, first the
main() method is executed by the JVM. The runtime creates the object objCalc of class Calculator.
Next, the add() method is invoked with two values 3 and 4. The add() method is processed and the
print statement displays the result. Lastly, the mul() method is invoked with two parameters and prints
the result.
Note - The statement package session7; indicates that the class belongs to a package named
session7. A package is a folder used to group related classes. Also, the text within /** */ symbols
are the default javadoc comments generated by the runtime to describe the code.
Concepts
Note - All the methods defined in class Calculator are instance methods. Instance methods are
those methods that are invoked using an object of the class. Also, all the methods are public which
means that they are accessible to all objects across packages.
package session7;
public class PassByValue {
}
public static void main(String[] args) {
prints the value of num1 to verify if it has changed. However, the output shows that the value of num1 is
still 10 even after invoking setVal() method where the value had been incremented.
This is because, num1 was passed by value. That is, only a copy of the value of num1 was passed to
setVal() method and not the actual address of num1 in memory. So that, the value of num1 remains
unchanged even after invoking the method setVal().
package session7;
class Circle{
return 3.14;
}
}
3.14, one can also store the value in a variable and specify the name of the variable with the return
keyword. For example, the class Circle and its getPI() method can be modified as shown in Code
Snippet 5.
Code Snippet 5:
return PI;
}
}
In the modified class Circle, the value 3.14 is stored in a private double variable PI. Later, the
method getPI() returns the value stored in the variable PI instead of the constant value 3.14.
Note - The variable PI is declared private to restrict direct access to it by any object. Instead the
getPI() method is used to access it. Therefore, the getPI() method becomes the accessor method
for PI. Similarly, one can create a mutator method such as setPI() to modify the value of PI.
package session7;
public class Varargs {
int sum=0;
The class Varargs consists of a method called addNumber(intnum). The method accepts variable
number of arguments of type integer. The method uses the enhanced for loop to iterate through the
variable argument parameter num and adds each value with the variable sum. Finally, the method prints
the value of sum.
The main() method creates an object of the class and invokes the addNumber() method with multiple
arguments of type integer. The output displays 100 after adding up the numbers.
API documentation or API docs: These are the online or hard copy descriptions of the API that
are primarily intended for the programmers. The API specification consists of all assertions for a
proper implementation of the Java Platform to ensure that the write once, run anywhere feature
of Java is retained.
Documentation comments or doc comments: These are special comments in the Java source
code. They are written within the /** */ delimiters. These comments are processed by the
Javadoc tool for generating the API docs.
The four types of source files from which Javadoc tool can generate output are as follows:
Java source code files (.java) which consist of the field, class, constructor, method, and
interface comments.
Package comment files that consist of package comments.
Overview comment files that contain the comments about set of packages.
Miscellaneous files that are unprocessed such as images, class files, sample source codes,
HTML files, applets, and any other file that is referenced from the previous files.
A doc comment is written in HTML and it must precede a field, class, method, or constructor declaration.
The doc comment consists of two parts namely, a description and block tags. For example, consider the
class given in Code Snippet 7.
Code Snippet 7:
Code Snippet 7 consists of a class Circle, a variable PI, and a method calcArea() that accepts radius
as a parameter.
Now, a doc comment for calcArea() method can be written as depicted in Code Snippet 8.
Code Snippet 8:
/**
* Returns the area of a circle
*
* @param rad a variable indicating radius of a circle
* @return the area of the circle
* @see PI
*/
Here, the first statement is the method description whereas @param, @return, and @see are block tags
that refer to the parameters and return value of the method. A blank comment line must be provided
between the description line and block tags. The HTML generated from running the Javadoc tool is as
follows:
calcArea
public double calcArea(double rad)
Returns the area of a circle
Parameters:
rad a variable storing the radius of the circle
Returns:
the area of a circle
See Also:
PI
To use Javadoc tool to lookup methods of a class, perform the following steps:
1. Open the Calculator class created earlier.
2. Open Javadoc widow by clicking Window Other Javadoc as shown in figure 7.7.
Concepts
The window will show the built-in Java documentation of the println() method as shown in
figure 7.9.
The javadoc lists the various classes available in the selected package. To move to the next or
previous package, one can click the PrevPackage and NextPackage links on the page.
7. Click the Calculator class under the Class Summary tab.
Concepts
The window will show the javadoc created for the add() method as shown in figure 7.13.
Java provides a number of access specifiers or modifiers to set the level of access for a class and its
members such as fields, methods, and constructors within the class. This is also known as the visibility
of the class, field, and methods. When no access specifier is mentioned for a class member, the default
accessibility is package or default.
Access specifiers help to control the access of classes and class members.
Access specifiers help to prevent misuse of class details as well as hide the implementation details
that are not required by other classes.
The access specifiers also determine whether classes and the members of the classes can be
invoked by other classes or interfaces.
Accessibility affects inheritance and how members are inherited by the subclass.
Public
The public access specifier is the least restrictive of all access specifiers. A field, method, or class
declared public is visible to any class in a Java application in the same package or in another
package.
Private
The private access specifier is the most restrictive of all access specifiers. The private access
specifier cannot be used for classes and interfaces as well as fields and methods of an interface.
Fields and methods declared private cannot be accessed from outside the enclosing class.
A standard convention is to declare all fields private and provide public accessor or getter
methods to access them. Thus, when data is important, sensitive, and cannot be shared with
others, it is declared as private.
Protected
The protected access specifier is used with classes that share a parent-child relationship which
is referred to as inheritance. The protected keyword cannot be used for classes and interfaces as
well as fields and methods of an interface. Fields and methods declared protected in a parent or
Concepts
super class can be accessed only by its child or subclass in another packages. However, classes in
the same package can also access protected fields and methods, even if they are not a subclass of
the protected members class.
Default
The default access specifier is used when no access specifier is present. The default specifier gets
applied to any class, field, or method for which no access specifier has been mentioned. With
default specifier, the class, field, or method is accessible only to the classes of the same package.
The default specifier is not used for fields and methods within an interface.
Figure 7.14 shows the various access specifiers.
The third column states whether the subclasses of a class declared outside this package can access a
member. In such cases, public and protected members can be accessed. The fourth column states
whether all classes can access a data member.
While declaring members, a private access specifier cannot be used with abstract, but it can
be used with final or static.
A constructor when declared private will be accessible in the class where it was created.
A constructor when declared protected will be accessible within the class where it was created
and in the inheriting classes.
The most restrictive access level must be used that is appropriate for a particular member.
Mostly, a private access specifier is used at all times unless there is a valid reason for not using
it.
package session7;
public class Employee {
Concepts
/**
* Parameterized constructor
*
* @param ID an integer variable storing the employee ID
* @param name a String variable storing the employee name
* @return void
*/
public Employee(int ID, String name){
empID = ID;
empName = name;
}
/**
* Returns the value of SSN
*
* @return String
*/
public String getSSN(){ // Accessor for SSN
return SSN;
}
/**
* Sets the value of SSN
*
* @param ssn a String variable storing the social security number
* @return void
*/
public void setSSN(String ssn) { // Mutator for SSN
SSN = ssn;
}
/**
Concepts
empDesig = desig;
}
/**
* Displays employee details
*
* @return void
*/
public void display(){ // Public method
System.out.println(Employee ID is + empID);
System.out.println(Employee name is + empName);
System.out.println(Designation is + empDesig);
System.out.println(SSN is + SSN);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
In Code Snippet 9, the class Employee has been declared public. The class has two members with
default access specifier namely, empID and empName, a protected class member named empDesig,
and a private class member named SSN. The class has one parameterized constructor that is used to
set the values of member variables empID and empName. The class also has an accessor and a mutator
method for variable SSN and two other public methods.
The main() method creates an object of Employee class with values of empID and empName. Next, the
values of empDesig and SSN are specified by directly accessing the variables with the object objEmp1
even though empDesig is protected and SSN is private. This is because, objEmp1 is an object present
in the same class. So, objEmp1 has access to data members with any access specifier. The display()
method is used to display all the values as shown in the output.
Code Snippet 10 demonstrates the use of access specifiers in another class named EmployeeDetails
but in the same package as Employee class.
Code Snippet 10:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Within the main() method of EmployeeDetails class, an object of Employee is created to set the
values of empID and empName. Next, value of empDesig is specified by directly accessing the protected
variable empDesig. This is because, a protected variable can be accessed by another class of the same
package even if it is not a child class of Employee.
However, to set the value of SSN, the setSSN() method is used. This is because SSN is a private
member variable in Employee class and hence, cannot be directly accessed by other classes. Finally, the
display() method is used to print all the details as shown in the output.
Classes of other packages that are not child class of Employee can set the value of empID and empName
by using the constructor, of empDesig by using setDesignation() method, and of SSN by using
setSSN() method.
names are different. This is not sufficient to make a method overloaded. The methods must differ in
argument type and number and not simply in name of arguments.
Similarly, the add()method numbered 7 has a signature similar to the method numbered 1. Both the
method accepts two integers, a and b as parameters. However, the return type of method numbered 7
is int whereas that of method numbered 1 is void.
Again, this does not make the method overloaded as it does not differ in argument type and number.
Thus, the add() methods numbered 6 and 7 are not overloaded methods and will lead to compilation
error. Changing only the names of parameters or return type of method does not make it overloaded.
Also, a method cannot be considered as overloaded if only the access specifiers are different.
Code Snippet 11 demonstrates an example of method overloading.
Code Snippet 11:
package session7;
public class MathClass {
/**
* Method to add two integers
*
* @param num1 an integer variable storing the value of first number
* @param num2 an integer variable storing the value of second number
* @return void
*/
public void add(int num1, int num2) {
/**
* Overloaded method to add three integers
*
* @param num1 an integer variable storing the value of first number
* @param num2 an integer variable storing the value of second number
* @param num3 an integer variable storing the value of third number
* @return void
*/
public void add(int num1, int num2, int num3) {
/**
* Overloaded method to add a float and an integer
*
* @param num1 a float variable storing the value of first number
* @param num2 an integer variable storing the value of second number
Concepts
* @return void
*/
public void add(float num1, int num2) {
/**
* Overloaded method to add a float and an integer accepting the values
* in a different sequence
*
* @param num1 an integer variable storing the value of first number
* @param num2 a float variable storing the value of second number
* @return void
*/
public void add(int num1, float num2) {
/**
* Overloaded method to add two floating-point numbers
*
* @param num1 a float variable storing the value of first number
* @param num2 a float variable storing the value of second number
* @return void
*/
public void add(float num1, float num2) {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Instantiate the MathClass class
MathClass objMath = new MathClass();
Figure 7.18 shows a class named MathClass consisting of overloaded add() methods. The main()
method creates an object of MathClass and invokes the add() methods with different types and
number of arguments. The compiler executes the appropriate add() method based on the type and
number of arguments passed by the user. The output displays the result of addition of the different
values.
package session7;
public class Student {
/**
* No-argument constructor
*
*/
public Student(){
rollNo = 0;
name = ;
address = ;
marks = 0;
}
/**
* Overloaded constructor
*
* @param rNo an integer variable storing the roll number
* @param name a String variable storing student name
Concepts
*/
rollNo = rNo;
name = sname;
}
/**
* Overloaded constructor
*
* @param rNo an integer variable storing the roll number
* @param score a float variable storing the score
*/
public Student(int rNo, float score) {
rollNo = rNo;
marks = score;
}
/**
* Overloaded constructor
*
* @param sName a String variable storing student name
* @param addr a String variable storing the address
*/
public Student(String sName, String addr) {
name = sName;
address = addr;
}
/**
* Overloaded constructor
*
* @param rNo an integer variable storing the roll number
* @param sName a String variable storing student name
* @param score a float variable storing the score
*/
public Student(int rNo, String sname, float score) {
rollNo = rNo;
name = sname;
marks = score;
Concepts
/**
* Displays student details
*
* @return void
*/
public void displayDetails(){
System.out.println(Rollno :+ rollNo);
System.out.println(Student name:+ name);
System.out.println(Address + address);
System.out.println(Score + marks);
System.out.println(------------------------);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
The class Student consists of member variables named rollNo, name, address, and marks.
Student() is the default or no-argument constructor of the Student class. The other constructors are
overloaded constructors created by changing the number and type of parameters. The main() method
creates three objects objStud1, objStud2, and objStud3 of Student class. Each object passes
different arguments to the constructor. Later, each object invokes the displayDetails() method to
print the student details.
Concepts
Figure 7.19 shows the output generated by displayDetails() method for objects objStud1,
objStud2, and objStud3 of Student class based on the constructor invoked by these objects. Notice
the values 0 and null for the variables for which no argument was specified. These are the default
values for integer and String data types in java.
/**
* Returns the value of PI
*
* @return float
*/
public float getPI(){
return 3.14;
/**
* Calculates area of a circle
* @param rad an integer to store the radius
* @return void
*/
public void calcArea(int rad) {
The method calcArea() calculates the area of a circle and stores it in the variable, area. It retrieves
the value of PI by invoking the getPI() method. Here, the method call does not involve any object even
though getPI() is an instance method. This is because of the implicit use of this keyword.
For example, the method calcArea() can also be written as shown in Code Snippet 14.
Code Snippet 14:
/**
* Returns the value of PI
*
Concepts
* @return float
*/
public float getPI(){
return 3.14;
}
/**
* Calculates area of a circle
* @param rad an integer to store the radius
* @return void
*/
public void calcArea(int rad) {
/**
* No-argument constructor
*
*/
public Circle(){
PI = 3.14;
}
/**
* Overloaded constructor
*
* @param r a float variable to store the value of radius
*/
public Circle(float r) {
...
}
The keyword this can be used to resolve naming conflicts when the names of actual and formal
parameters of a method or a constructor are the same as depicted in Code Snippet 16.
/**
* no-argument constructor
*
*/
public Circle(){
PI = 3.14;
}
/**
* overloaded constructor
*
* @param rad a float variable to store the value of radius
*/
public Circle(float rad) { // line2
this();
this.rad = rad; // line3
}
...
}
Code Snippet 16 defines the constructor Circle with the parameter rad in line2 which is the formal
parameter. Also, the parameter declared in line1 has the same name rad which is the actual parameter to
which the users value will be assigned at runtime. Now, while assigning a value to rad in the constructor,
the user would have to write rad = rad. However, this would confuse the compiler as to which rad is the
actual and which one is the formal parameter. To resolve this conflict, this.rad is written on the left of
the assignment operator to indicate that it is the actual parameter to which value must be assigned. Concepts
(A) b, d (C) b, c
(B) a, b (D) a, d
3. Match the following access specifiers with the corresponding descriptions with respect to variables
and methods of a class.
(A) a-3, b-2, c-1, d-4 (C) a-3, b-1, c-4, d-2
Concepts
(B) a-2, b-4, c-3, d-1 (D) a-4, b-3, c-2, d-1
(A) a, d (C) b, c
(B) b, d (D) a, b
Vno=Vno; // line1
Vtype=Vtype; // line2
}
The code is giving the warning Assignment to Itself. What change must be made in line1
and line2 to resolve the issue?
Vno=3764; this.Vno=Vno;
(A) (C)
Vtype=Car; this.Vtype=Vtype;
Vno=this.Vno; Vno=0;
(B) (D)
Vtype=this.Vtype; Vtype=;
Concepts
int EmpID;
String EmpName, Designation;
public Employee(){
EmpID=0;
EmpName=;
Designation=;
}
Which of the following programming concept has been used in the code?
7.5.1 Answers
1. D
2. C
3. D
4. B
5. C
6. B
Concepts
Summary
A Java method is a set of statements grouped together for performing a specific operation.
Parameters are the list of variables specified in a method declaration, whereas arguments are the
actual values that are passed to the method when it is invoked.
The variable argument feature is used in Java when the number of a particular type of arguments
that will be passed to a method is not known until runtime.
Java provides a JDK tool named Javadoc that is used to generate API documentation from
documentation comments.
Access specifiers are used to restrict access to fields, methods, constructor, and classes of an
application.
Java comes with four access specifiers namely, public, private, protected, and default.
Using method overloading, multiple methods of a class can have the same name but with different
parameter lists.
Java provides the this keyword which can be used in an instance method or a constructor to
refer to the current object, that is, the object whose method or constructor is being invoked.
Concepts
Try it Yourself
1. Phoenix Systems is a well known computer hardware store located in L.A., California. The manager
of the store wishes to develop a software through which he can store and view data about the
hardware devices that he sells. The manager has hired a programmer to develop the software. The
programmer has written the following class to store and view details about the devices.
public class DeviceDetails {
int deviceNo;
String deviceName,deviceType;
double devicePrice;
public DeviceDetails(){
deviceNo=0;
deviceName=;
deviceType=;
devicePrice=0.0;
}
public DeviceDetails(int deviceNo, String deviceType){
deviceNo=deviceNo;
deviceType=deviceType;
}
public void displayDetails(){
System.out.println(Device number is + deviceNo);
System.out.println(Device name is + deviceName);
System.out.println(Device type is + deviceType);
Concepts
The program is giving compilation errors and not functioning as expected. Modify the program as
follows:
The user should be able to specify all details about a device at a time.
The user should be able to specify only deviceNo and devicePrice when needed.
The variables should not be accessible outside the class.
The program should display all details of a device properly even when some details are not
provided.
Generate javadoc for the class to view the details of methods of the class.
Concepts
This session explains the creation and use of arrays in Java. Further, this
session explains accessing values from an ArrayList using loops. The session
also describes command line arguments and the working of String and
StringBuilder classes. Lastly, the session describes Wrapper classes and
the concept of autoboxing and unboxing.
Describe an array
8.1 Introduction
Consider a situation where in a user wants to store the marks of ten students. For this purpose, the user
can create ten different variables of type integer and store the marks in them. What if the user wants to
store marks of hundreds or thousands of students? In such a case, one would need to create as many
variables. This can be a very difficult, tedious, and time consuming task. Here, it is required to have a
feature that will enable storing of all the marks in one location and access it with similar variable names.
Array, in Java, is a feature that allows storing multiple values of similar type in the same variable.
Arrays are the best way of operating on multiple data elements of the same type at the same
Concepts
time.
Memory is assigned to an array only at the time when the array is actually used. Thus, the memory
is not consumed by an array right from the time it is declared.
Single-dimensional arrays
Multi-dimensional arrays
an exception. An exception is an abnormal event that occurs during the program execution and disrupts
the normal flow of instructions. Array creation involves the following tasks:
Declaring an array
Instantiating an array
Initializing an array
Note - Array name should follow the same rules as naming a variable.
Declaring an Array:
Declaring an array is similar to declaring any other variable. Declaring an array notifies the compiler
that the variable will contain an array of the specified data type. It does not create an array. The
syntax for declaring a single-dimensional array is as follows:
Syntax:
datatype[] <array-name>;
where,
datatype: Indicates the type of elements that will be stored in the array.
[]: Indicates that the variable is an array.
array-name: Indicates the name by which the elements of the array will be accessed.
For example,
int[] marks;
Similarly, arrays of other types can also be declared as follows:
byte[] byteArray;
float[] floatsArray;
boolean[] booleanArray;
char[] charArray;
String[] stringArray;
Instantiating an Array:
Since array is an object, memory is allocated only when it is instantiated. The syntax for instantiating
an array is as follows:
Syntax:
datatype[] <array-name> = new datatype[size];
Concepts
where,
new: Allocates memory to the array.
size: Indicates the number of elements that can be stored in the array.
For example,
int[] marks = new int[4];
Similarly, arrays of other types can also be instantiated according to requirement.
Initializing an Array:
Since, array is an object that can store multiple values, array needs to be initialized with the values
to be stored in it. Array can be initialized in the following two ways:
During creation:
To initialize a single-dimensional array during creation, one must specify the values to be
stored while creating the array as follows:
Notice that while initializing an array during creation, the new keyword or size is not required.
This is because all the elements to be stored have been specified and accordingly the
memory gets automatically allocated based on the number of elements. This is also known
as declaration with initialization.
After creation:
A single-dimensional array can also be initialized after creation and instantiation. In this case,
individual elements of the array need to be initialized with appropriate values. For example,
Notice that in this case, the array must be instantiated and size must be specified. This is
because, the actual values are specified later and to store the values, memory must be
allocated during creation of the array.
Another way of creating an array is to split all the three stages as follows:
int marks[]; // declaration
marks = new int[4]; // instantiation
marks[0] = 65; // initialization
Concepts
package session8;
public class OneDimension {
//Declare a single-dimensional array named marks
int marks[]; // line 1
/**
* Instantiates and initializes a single-dimensional array
*
* @return void
*/
public void storeMarks() {
// Instantiate the array
*
* @return void
*/
System.out.println(marks[0]);
System.out.println(marks[1]);
System.out.println(marks[2]);
System.out.println(marks[3]);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
The class OneDimension consists of an array named marks[] declared in line 1. To instantiate and
initialize the array elements, the method storeMarks() is created. The array is instantiated using the
new keyword in line 2.
The elements of the array are assigned values by using the array name and the subscript of the element,
that is, marks[0]. Similarly, to display the array elements, the displayMarks() method is created and
the values stored in each element of marks[] array is displayed.
The object oneDimenObj of the class OneDimension is created in line 4. The object is used to invoke
the storeMarks() and displayMarks() methods.
Figure 8.3 shows the output of the code.
The array named marks consists of four rows and two columns. Similarly, arrays of other types can also
be instantiated according to the requirement.
During creation:
To initialize a multi-dimensional array during creation, one must specify the values to be stored
while creating the array as follows:
int[][] marks = {{23,65},
{42,47},
{60,75},
{75,50}};
Notice that while initializing an array during creation, the elements in rows are specified in a set of
curly brackets separated by a comma delimiter. Also, the individual rows are separated by a comma
separator.
This is a two-dimensional array that can be represented in a tabular form as shown in figure 8.4.
After creation:
A multi-dimensional array can also be initialized after creation and instantiation. In this case,
individual elements of the array need to be initialized with appropriate values. Each element is
accessed with a row and column subscript. For example,
int[][] marks = new int[4][2];
marks[0][0] = 23; // first row, first column
marks[0][1] = 65; // first row, second column
Concepts
marks[1][0] = 42;
marks[1][1] = 47;
marks[2][0] = 60;
marks[2][1] = 75;
marks[3][0] = 75;
marks[3][1] = 50;
Here, the element 23 is said to be at position (0,0), that is, first row and first column. Therefore, to
store or access the value 23, one must use the syntax marks[0][0]. Similarly, for other values, the
appropriate row-column combination must be used. Similar to row index, column index also starts
at zero. Therefore, in the given scenario, an attempt to write marks[0][2] would result in an
exception as the column size is 2 and column indices are 0 and 1.
Code Snippet 2 demonstrates an example of two-dimensional array.
Code Snippet 2:
package session8;
public class TwoDimension {
//Declare a two-dimensional array named marks
int marks[][]; //line 1
/**
* Stores marks in a two-dimensional array
*
* @return void
*/
public void storeMarks() {
// Instantiate the array
marks = new int[4][2]; // line 2
System.out.println(Storing Marks. Please wait...);
marks[1][1] = 47;
marks[2][0] = 60;
marks[2][1] = 75;
marks[3][0] = 75;
marks[3][1] = 50;
}
/**
* Displays marks from a two-dimensional array
*
* @return void
*/
public void displayMarks() {
System.out.println(Marks are:);
// Display the marks
System.out.println(Roll no.1: + marks[0][0]+ , + marks[0][1]);
System.out.println(Roll no.2: + marks[1][0]+ , + marks[1][1]);
System.out.println(Roll no.3: + marks[2][0]+ , + marks[2][1]);
System.out.println(Roll no.4: + marks[3][0]+ , + marks[3][1]);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Instantiate class TwoDimension
TwoDimension twoDimenObj = new TwoDimension(); // line 4
//Invoke the storeMarks() method
twoDimenObj.storeMarks();
//Invoke the displayMarks() method
twoDimenObj.displayMarks();
Concepts
}
}
The class TwoDimension consists of an array named marks[][] declared in line 1. To instantiate and
initialize the array elements, the method storeMarks() is created.
The array is instantiated using the new keyword in line 2. The elements of the array are assigned values by
using the array name and the row-column subscript of the element, that is, marks[0][0]. Similarly, to
display the array elements, the displayMarks() method is created and invoked and the values stored
in each element of marks[][]array is displayed.
The object twoDimenObj of the class TwoDimension is created in line 4. The object is used to invoke
the storeMarks() and displayMarks() methods.
Figure 8.5 shows the output of the code, that is, marks of four students are displayed from the array
marks[][].
...
public void displayMarks() {
System.out.println(Marks are:);
// Display the marks using for loop
for(int count = 0; count < marks.length; count++) {
Concepts
System.out.println(marks[count]);
}
}
...
In Code Snippet 3, a for loop has been used to iterate the array from zero to marks.length.
The property, length, of the array object is used to obtain the size of the array. Within the loop, each
element is displayed by using the element name and the variable count, that is, marks[count].
Code Snippet 4 depicts the revised displayMarks() method of the two-dimensional array
marks[][].
Code Snippet 4:
...
public void displayMarks(){
System.out.println(Marks are:);
// outer loop
for (int row = 0; row < marks.length; row++) {
System.out.println(Roll no. + (row+1));
// inner loop
for (int col = 0; col < marks[row].length; col++) {
System.out.println(marks[row][col]);
}
}
}
...
In Code Snippet 4, a nested for loop (outer and inner) has been used to iterate through the array marks.
The outer loop keeps track of the number of rows and inner loop keeps track of the number of columns
in each row. For each row, the inner loop iterates through all the columns using marks[row].length.
Within the inner loop, each element is displayed by using the element name and the row-column count,
that is, marks[row][column].
Figure 8.6 shows the output of the two-dimensional array marks[][], after using the for loop.
Concepts
...
public void displayMarks() {
System.out.println(Marks are:);
}
...
Here, the loop will print all the values of marks[] array till marks.length without having to explicitly
specify the initializing and terminating conditions for iterating through the loop.
Code Snippet 6 demonstrates the calculation of total marks of each student by using the for loop and
the enhanced for loop together with the two-dimensional array marks[][].
Code Snippet 6:
...
public void totalMarks() {
System.out.println(Total Marks are:);
// Display the marks using for loop and enhanced for loop
for(int value:marks[row]) {
sum = sum + value;
}
System.out.println(sum);
}
}
...
Here, the enhanced for loop is used to iterate through the columns of the row selected in the outer loop
using marks[row]. The code sum = sum + value will add up the values of all columns of the currently
selected row. The selected row is indicated by the subscript variable row. Concepts
Figure 8.7 shows the sum of the values of the two-dimensional array named marks[][] using for loop
and enhanced for loop together.
store, retrieve, and manipulate aggregate data. Typically, they represent data items that form a natural
group, such as a collection of cards, a collection of letters, or a set of names and phone numbers.
Java provides a set of collection interfaces to create different types of collections. The core Collection
interfaces that encapsulate different types of collections are shown in figure 8.8.
Note - A package is a collection of related classes. The java.util package consists of all the collection
interfaces and classes.
The ArrayList class is a frequently used collection that has the following characteristics:
It can be traversed by using for loop, enhanced for loop, or other iterators.
The Arraylist collection provides methods to manipulate the size of the array. ArrayList extends
AbstractList and implements the interfaces such as List, Cloneable, and Serializable. The
capacity of an ArrayList grows automatically. It stores all elements including null.
Table 8.2 lists the constructors of ArrayList class.
Constructor Description
ArrayList( ) Creates an empty array list.
ArrayList(Collection c) Creates an array list initialized with the elements of the
collection c.
ArrayList(int capacity) Creates an array list with a specified initial capacity. Capacity
is the size of the underlying array used to store the elements.
The capacity can grow automatically as elements are added
to an array list.
Table 8.2: Constructors of ArrayList Class
ArrayList consists of several methods for adding elements. These methods can be broadly divided into
following two categories:
Methods that append one or more elements to the end of the list.
Methods that insert one or more elements at a position within the list.
Table 8.3 lists the methods of ArrayList class.
Method Description
void add(int index, Inserts the specified element at the given index in
Object element) this list. If index>=size() or index<0, it throws
IndexOutOfBoundsException.
boolean add(Object o) Appends the specified element to the end of this list.
boolean Appends all elements in the specified collection to the
addAll(Collection c) end of this list. If the specified collection is null, it throws
NullPointerException.
boolean addAll(int Inserts all of the elements in the specified collection into this
index, Collection c) list, starting at the specified index. If the collection is null, it
throws NullPointerException.
void clear() Removes all of the elements from this list.
Object clone() Returns a copy of the ArrayList.
Concepts
boolean contains(Object Returns true if and only if the list contains the specified
o) element.
void ensureCapacity(int Increases the capacity of the ArrayList, if required, to
minCapacity) ensure that it can store at least as many number of elements
as indicated by the minimum capacity.
Method Description
Object get(int index) Returns the element at the specified index in this
list. If index>=size() or index<0, it throws
IndexOutOfBoundsException.
int indexOf(Object o) Returns the index of the first occurrence of the specified
element in the list. If the element is not found, it returns -1.
int lastIndexOf(Object Returns the index of the last occurrence of the specified
o) element in this list. If the element is not found, it returns -1.
Object remove(int index) Removes the element at the specified index in this
list. If index >= size() or index < 0, it throws
IndexOutOfBoundsException.
protected void Removes all the elements between fromIndex, inclusive
removeRange(int and toIndex, exclusive of the list.
fromIndex, int toIndex)
Object set(int index, Replaces the element at the specified index in this list with
Object element) the newly specified element. If index >= size() or
index < 0, it throws IndexOutOfBoundsException.
int size() Returns the number of elements in this list.
Object[] toArray() Returns an array containing all of the elements in the
list in the correct order. If the array is null, it throws
NullPointerException.
Object[] Returns an array containing all of the elements in the list in
toArray(Object[] a) the correct order. The type of the returned array is same as
that of the specified array.
void trimToSize() Trims the capacity of the ArrayList to the lists actual size.
Table 8.3: Methods of ArrayList Class
To traverse an ArrayList, one can use one of the following approaches:
A for loop
Iterator
ListIterator
Concepts
Iterator interface provides methods for traversing a set of data. It can be used with arrays as well as
the various classes of the Collection framework.
The Iterator interface provides the following methods for traversing a collection:
hasNext(): This method returns true if there are additional elements in the collection.
remove(): This method removes the element from the list while iterating through the collection.
There are no specific methods in the ArrayList class for sorting. However, one can use the sort()
method of the Collections class to sort an ArrayList. The syntax for using the sort() method is
as follows:
Syntax:
Collections.sort(<list-name>);
Code Snippet 7 demonstrates instantiation and initialization of an ArrayList.
Code Snippet 7:
package session8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class ArrayLists{
// Create an ArrayList instance
ArrayList marks = new ArrayList(); // line 1
/**
* Stores marks in ArrayList
*
Concepts
* @return void
*/
/**
* Displays marks from ArrayList
*
* @return void
*/
public void displayMarks() {
System.out.println(Marks are:);
// iterating the list using for loop
System.out.println(Iterating ArrayList using for loop:);
for (int i = 0; i < marks.size(); i++) {
System.out.println(marks.get(i));
}
System.out.println(-------------------------------------);
// Iterate the list using Iterator interface
Iterator imarks = marks.iterator(); // line 3
}
System.out.println(-------------------------------------);
The ArrayList named marks has been instantiated in line 1. The storeMarks() method is used to
add elements to the collection by using marks.add() method as shown in line 2.
Within the displayMarks() method, a for loop is used to iterate the ArrayList marks from 0 to
marks.size(). The get() method is used to retrieve the element at index i.
Similarly, the Iterator object imarks is instantiated in line 3 and attached with the marks ArrayList
using marks.iterator(). It is used to iterate through the collection. The Iterator interface provides
the hasNext() method to check if there are any more elements in the collection as shown in line 4. The
method, next() is used to traverse to the next element in the collection. The retrieved element is then
displayed to the user in line 5.
The static method, sort() of Collections class is used to sort the ArrayList marks in line 6 and
print the values on the screen. Within main() method, the object of ArrayLists class has been created
Concepts
in line 7 and the methods storeMarks() and displayMarks() have been invoked.
Figure 8.9 shows the output of the code.
Similarly, to store names of multiple persons, one can create a two-dimensional array. However, the
number of characters in an array must be fixed during creation. This is not possible since the names
of persons may be of variable sizes. Also, manipulating the character array would be tedious and time
consuming. Java provides the String data type to store multiple characters without creating an array.
8.3.1 Strings
Concepts
String literals such as Hello in Java are implemented as instances of the String class. Strings are
constant and immutable, that is, their values cannot be changed once they are created. String buffers
allow creation of mutable strings. A simple String instance can be created by enclosing a string literal
inside double quotes as shown in Code Snippet 10.
...
String name = Mary;
// This is equivalent to:
char name[] = {M, a, r, y};
...
An instance of a String class can also be created using the new keyword, as shown in
Code Snippet 11.
Code Snippet 11:
The code creates a new object of class String, and assigns its reference to the variable str.
Java also provides special support for concatenation of strings using the plus (+) operator and for
converting data of other types to strings as depicted in Code Snippet 12.
Code Snippet 12:
...
String str = Hello;
String str1 = World;
// The two strings can be concatenated by using the operator +
System.out.println(str + str1);
// This will print HelloWorld on the screen
...
One can convert a character array to a string as depicted in Code Snippet 13.
Code Snippet 13:
The java.lang.String class is a final class, that is, no class can extend it. The java.lang.String
Concepts
class differs from other classes, in that one can use += and + operators with String objects for
concatenation.
If the string is not likely to change later, one can use the String class. Thus, a String class can be used
for the following reasons:
The threads will only read them, which is normally a thread safe operation.
Note - A thread is a single unit of execution in a program. The JVM allows an application to execute
multiple threads of a process concurrently.
However, if the string is likely to change later and it will be shared between multiple threads, one can use
the StringBuffer class. The use of StringBuffer class ensures that the string is updated correctly.
However, the drawback is that the method execution is comparatively slower.
If the string is likely to change later but will not be shared between multiple threads, one can use the
StringBuilder class. The StringBuilder class can be used for the following reasons:
Methods of StringBuilder class execute as fast as, or faster, than those of the StringBuffer
class
length(String str)
The length() method is used to find the length of a string. For example,
String str = Hello;
System.out.println(str.length()); // output: 5
charAt(int index)
The charAt() method is used to retrieve the character value at a specific index. The index ranges
from zero to length() 1. The index of the first character starts at zero. For example,
System.out.println(str.charAt(2)); // output: l
concat(String str)
The concat() method is used to concatenate a string specified as argument to the end of another
string. If the length of the string is zero, the original String object is returned, otherwise a new
Concepts
compareTo(String str)
The compareTo() method is used to compare two String objects. The comparison returns an
integer value as the result. The comparison is based on the Unicode value of each character in the
strings. That is, the result will return a negative value, if the argument string is alphabetically greater
than the original string. The result will return a positive value, if argument string is alphabetically
lesser than the original string and the result will return a value of zero, if both the strings are equal.
For example,
System.out.println(str.compareTo(World)); // output: -15
The output is 15 because, the second string World begins with W which is alphabetically
greater than the first character H of the original string, str. The difference between the position
of H and W is 15. Since H is smaller than W, the result will be -15.
Note - Unicode is a standard that provides a unique number for every character irrespective of
the platform, program, or language. The Unicode Standard has been adopted for programming by
major industry leaders such as IBM, Apple, Microsoft, HP, Oracle, Sun, SAP, and several others.
indexOf(String str)
The indexOf() method returns the index of the first occurrence of the specified character or
string within a string.
If the character or string is not found, the method returns -1. For example,
System.out.println(str.indexOf(e)); // output: 1
lastIndexOf(String str)
The lastIndexOf() method returns the index of the last occurrence of a specified character
or string from within a string. The specified character or string is searched backwards that is the
search begins from the last character. For example,
System.out.println(str.lastIndexOf(l)); // output: 3
The substring begins at the specified position denoted by index or beginIndex and extends
to the character specified by index or endIndex - 1. Thus, the length of the substring is
endIndex beginIndex. Here, the beginIndex is included in the output whereas the
endIndex is excluded.
For example,
System.out.println(str.substring(2,5)); // output: llo
toString()
The toString() method is used to return a String object. It is used to convert values of other
data types into strings. For example,
Integer length = 5;
System.out.println(length.toString()); // output: 5
Notice that the output is still 5. However, now it is represented as a string instead of an integer.
Note - The class Integer used in the example is a Wrapper class for the primitive data type
int.
trim()
The trim() method returns a new string by trimming the leading and trailing whitespace from the
current string. For example,
String str1 = Hello ;
System.out.println(str1.trim()); // output: Hello
The trim() method will return Hello after removing the spaces.
Code Snippet 14 demonstrates the use of String class methods.
Code Snippet 14:
/**
* Displays strings using various String class methods
*
* @return void
*/
public void displayStrings(){
// using various String class methods
System.out.println(String length is:+ str.length());
System.out.println(Character at index 2 is:+ str.charAt(2));
System.out.println(Concatenated string is:+ str.concat(World));
System.out.println(String comparison is:+ str.compareTo(World));
System.out.println(Index of o is:+ str.indexOf(o));
System.out.println(Last index of l is:+ str.lastIndexOf(l));
System.out.println(Replaced string is:+ str.replace(e,a));
System.out.println(Substring is:+ str.substring(2, 5));
System.out.println(Integer to String is:+ strLength.toString()) ;
String str1= Hello ;
System.out.println(Untrimmed string is:+ str1);
System.out.println(Trimmed string is:+ str1.trim());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
The class Strings consists of a String variable str. The member variable has been initialized with
the value Hello and an Integer variable named strLength has been initialized with a value 5.
The displayStrings() method is used to display the values generated by using the various String
class methods. The class Strings is instantiated in line 1. The object, objString is used to invoke the
displayStrings() method.
Figure 8.10 shows the output of the Strings.java class.
StringBuilder class. However, developers prefer to use String class unless StringBuilder offers
an advantage of simpler code in some cases. For example, for concatenating a large number of strings,
using a StringBuilder object is more efficient.
The StringBuilder class also provides a length() method that returns the length of the character
sequence in the class.
However, unlike strings a StringBuilder object also has a property capacity that specifies the number
of character spaces that have been allocated. The capacity is returned by the capacity() method
and is always greater than or equal to the length. The capacity to hold data in the instance of the
StringBuilder class will automatically expand according to the user requirement to accommodate
the new strings when added to the string builder.
Thus, the StringBuilder class is used for manipulating the String object. Objects of StringBuilder
class are mutable and flexible. StringBuilder object allows insertion of characters and strings as well
as appending characters and strings at the end.
The constructors of the StringBuilder class are as follows:
StringBuilder(String str): Constructs an object that is initialized with the contents of the
specified string, str.
append()
The append() method is used to append values at the end of the StringBuilder object. This
method accepts different types of arguments, including char, int, float, double, boolean, and
so on, but the most common argument is String.
For each append() method, String.valueOf() method is invoked to convert the
parameter into a corresponding string representation value and then the new string is appended to the
StringBuilder object.
For example,
StringBuilder str = new StringBuilder(JAVA );
System.out.println(str.append(SE ); // output: JAVA SE
System.out.println(str.append(7); // output: JAVA SE 7
Concepts
insert()
The insert() method is used to insert one string into another. Similar to the append()method,
it calls the String.valueOf() method to obtain the string representation of the value. The new
string is inserted into the invoking StringBuilder object. The insert() method has several
versions as follows:
delete()
The delete() method deletes the specified number of characters from the invoking
StringBuilder object.
For example,
StringBuilder str = new StringBuilder(JAVA SE 7);
System.out.println(str.delete(4,7); // output: JAVA 7
reverse()
The reverse() method is used to reverse the characters within a StringBuilder object.
For example,
StringBuilder str = new StringBuilder(JAVA SE 7);
System.out.println(str.reverse()); // output: 7 ES AVAJ
Code Snippet 15 demonstrates the use of methods of the StringBuilder class.
Code Snippet 15:
package session8;
public class StringBuilders {
// Instantiate a StringBuilder object
StringBuilder str = new StringBuilder(JAVA );
/**
* Displays strings using various StringBuilder methods
Concepts
*
* @return void
*/
The class StringBuilders consists of a StringBuilder object named str and initializes it with the
value JAVA . The displayStrings() method is used to display the output generated after using
the various StringBuilder class methods. The class StringBuilders is instantiated in line 1. The
object objStrBuild is used to invoke the displayStrings() method.
Concepts
package session8;
public class StringArray {
// Instantiate a String array
String[] empID = new String[5];
/**
* Creates a String array
* @return void
*/
Concepts
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
The class StringArray consists of a String array object named empID having a size of 5. The
createArray() method is used to initialize the elements of the array using the for loop and the
printArray() method is used to print the values of the array. The class StringArray is instantiated in
line 1. The object objStrArray is used to invoke the createArray() and printArray() methods.
Figure 8.12 shows the output of the StringArray.java class.
The parameter of the main() method is a String array that represents the command line arguments.
The size of the array is set to the number of arguments specified at runtime. All command line arguments
are passed as strings.
Code Snippet 18 demonstrates an example of command line arguments.
Code Snippet 18:
package session8;
public class CommandLine {
/**
Concepts
The class CommandLine consists of the main() method. Within main() method, the if statement
checks whether the number of command line arguments specified is equal to 3. If so, it prints the values
present in the respective elements of the array such as args[0], args[1], and args[2]; otherwise it
prints the message specified in the else part.
To run the program with command line arguments at command prompt, do the following:
1. Open the command prompt.
2. Compile the Java program by writing the following statement:
javac CommandLine.java
3. Execute the program by writing the following statement:
java CommandLine Roger Smith Manager
To run the program with command line arguments using NetBeans IDE, perform the following steps:
1. Right-click the project name in the Projects tab and click Properties. The Project Properties dialog
box is displayed.
2. Click Run in the Categories pane to the left. The runtime properties are displayed in the right pane
as shown in figure 8.13.
Concepts
The wrapper classes are part of the java.lang package. The primitive types and the corresponding
wrapper types are listed in table 8.4.
Concepts
The two type of methods, that is, parseXxx() and valueOf(), take a String as an argument and if
the String argument is not properly formed, both the methods throw a NumberFormatException.
These methods can convert String objects of different bases if the underlying primitive type is any of
the four integer types.
However, the parseXxx() method returns a named primitive whereas the valueOf() method returns
a new wrapped object of the type that invoked the method.
Code Snippet 19 demonstrates the use of Integer wrapper class to convert the numbers passed by
user as strings at command line into integer types to perform the calculation based on the selected
operation.
Code Snippet 19:
package session8;
public class Wrappers {
/**
* Performs calculation based on user input
*
* @return void
*/
public void calcResult(int num1, int num2, String choice){
(num1*num2));
break;
}
}
The class Wrappers consists of the calcResult() method that accepts two numbers and an operator
as the parameter. The main() method is used to convert the String arguments to int type by using
the Integer wrapper class.
Next, the object, objWrap of Wrappers class is created to invoke the calcResult() method with
three arguments namely, num1, num2, and args[2] which is the operator specified by the user as the
third argument.
To run the class, specify the command line values as 35, 48, and - in the Arguments box as shown in
figure 8.17.
package session8;
public class AutoUnbox {
/**
* @param args the command line arguments
*/
Concepts
The class AutoUnbox consists of two variable declarations chBox and chUnbox. chBox is an object type
and chUnbox is a primitive type of character variable. Figure 8.19 shows the output of the code.
(A) a, c (C) b, d
(B) a, d (D) b, c
3. Match the following String method code snippets with the corresponding outputs with respect
to the statement, String str=Java.
a. System.out.println(str.compareTo(World)); 1. v
b. System.out.println(str.concat(World)); 2. -13
c. System.out.println(str.indexOf(e)); 3. JavaWorld
d. System.out.println(str.charAt(2)); 4. -1
Concepts
(A) a-3, b-4, c-1, d-2 (C) a-4, b-3, c-2, d-1
(B) a-2, b-4, c-3, d-1 (D) a-2, b-3, c-4, d-1
4. Which of the following option will declare and initialize a single-dimensional array?
int marks = {65, 47, 75, int[ ] marks = {65, 47,
(A) 50}; (C) 75, 50};
int[ ] marks = {65, 47, int[ ] marks =
(B) 75, 50}; (D) {65},{47},{75},{50};
5. Consider the following code snippet to add two numbers specified by user at command line:
public class Addition{
public static void main(String[] args) {
if(args.length==2) {
int sum = args[0]+args[1]; // line 1
System.out.println(Sum is:+sum);
}
else{
System.out.println(Specify two integers.);
}
}
}
The code is giving compilation error Incompatible types. What change must be made in
line 1 to resolve the error?
int sum = (int)(args[0])+ String sum = args[0]+
(A) (int)(args[1]); (C) args[1];
int sum = args[0]. int sum = Integer.
(B) toInteger()+ args[1]. (D) parseInt(args[0])+ Integer.
toInteger(); parseInt(args[1]);
Concepts
Match the code snippet at following lines with the corresponding Java feature.
Line Number Output
b. line 2 2. Autoboxing
d. line 4 4. Unboxing
(A) a-3, b-4, c-1, d-2 (C) a-4, b-3, c-2, d-1
(B) a-2, b-4, c-1, d-3 (D) a-2, b-3, c-4, d-1
Concepts
8.5.1 Answers
1. C
2. A
3. D
4. B
5. D
6. B
Concepts
Summary
An array is a special data store that can hold a fixed number of values of a single type in
contiguous memory locations.
A single-dimensional array has only one dimension and is visually represented as having a single
column with several rows of data.
A multi-dimensional array in Java is an array whose elements are also arrays.
A collection is an object that groups multiple elements into a single unit.
Strings are constant and immutable, that is, their values cannot be changed once they are created.
StringBuilder objects are similar to String objects, except that they are mutable.
Java provides a set of classes known as Wrapper classes for each of its primitive data type that
wrap the primitive type into an object of that class.
The automatic conversion of primitive types to object types is known as autoboxing and
conversion of object types to primitive types is known as unboxing.
Concepts
Try it Yourself
1. CompuTech is a well known computer training institute in Los Angeles, USA. The institute teaches
several computer courses such as Java, .NET, and so on. The institute also organizes coding
competitions for students of the institute. As a student of Java course, you have participated in the
Java coding competition and you have been assigned the following problem:
Create a Java program to accept employee details for employees of Sales department such as
Employee ID, Name, Designation, Salary, and Sales. Based on the employees sales, calculate the
commission according to the rules given in table 8.6:
Sales Commission
>=10000 30% of basic salary
>=8000 30% of basic salary
>=6000 20% of basic salary
>=4000 10% of basic salary
Table 8.6: Rules for Calculating Commission
Based on the commission, calculate the total salary by adding the commission amount to the basic
salary. Display the details of the employee as follows:
Employee ID:
Employee Name:
Designation:
Basic Salary:
Sales Done:
Commission:
Total Salary:
Concepts
This session explains the use of different field and method modifiers in
Java with the rules and best practices for using field modifiers. Further, this
session describes class variables, methods, and creation and advantages
of using packages. Lastly, the session explains the creation of .jar files for
deployment.
9.1 Introduction
Java is a tightly encapsulated language. This means, that no code can be written outside the class. Not
even the main() method. However, even within the class, code can become vulnerable to access from
external environment. For this purpose, Java provides a set of access specifiers such as public, private,
protected, and default that help to restrict access to class and class members. However, at times, it
is required to further restrict access to the members of a class to prevent modification by unauthorized
code. Java provides additional field and method modifiers for this purpose.
Also, in some cases, it may be required to have a common data member that can be shared by all objects
of a class as well as other classes. Java provides the concept of class variables and methods to solve
this purpose. Classes sharing common attributes and behavior can also be grouped together for better
understanding of the application. Java provides packages that can be used to group related classes. Also,
the entire set of packages can be combined into a single file called the .jar file for deployment on the
target system.
volatile
native
transient
final
local cache. In such a case, if the value of the variable is updated, it updates the copy in the local cache
and not the main variable present in the memory. The other thread using the same variable does not get
the updated value.
To avoid this problem, a variable is declared as volatile to indicate that it will not be stored in the local
cache.
Also, whenever a thread updates the values of the variable, it is updates the variable present in the main
memory. This helps other threads to access the updated value.
For example,
System.loadLibrary(libraryName);
To declare a native method, the method is preceded with the native modifier. Also, the implementation
is not provided for the method. For example,
class NativeModifier {
native void nativeMethod(); // declaration of a native method
/**
* static code block to load the library
*/
static {
Concepts
System.loadLibrary(NativeMethodDefinition);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
NativeModifier objNative = new NativeModifier(); // line1
objNative.nativeMethod(); // line2
}
}
Notice that a static code block is used to load the library. Here, the static keyword indicates that the
library is loaded as soon as the class is loaded. This ensures that the library is available when the call to
the native method is made. The native method can be used in the same way as a non-native method. For
example, to invoke the native method nativeMethod() one can write the code as shown in line1 and
line2 of Code Snippet 1.
Native methods allow access to existing library routines created outside the JVM. However, the use of
native methods introduces two major problems. They are as follows:
Impending security risk: The native method executes actual machine code, and therefore, it can
gain access to any part of the host system. That is, the native code is not restricted to the JVM
execution environment. This may lead to a virus infection on the target system.
Loss of portability: The native code is bundled in a DLL, so that it can be loaded on the machine
on which the Java program is executing. Each native method is dependent on the CPU and the OS.
This makes the DLL inherently non-portable. This means, that a Java application using native
methods will run only on a machine in which a compatible DLL has been installed.
the objects persistent state. The transient modifier is useful to prevent security sensitive data from
being copied to a source in which no security mechanism has been implemented. Also, transient
modifier reduces the amount of data being serialized, improves performance, and reduces costs.
The transient modifier can only be used with instance variables. It informs the JVM not to store
the variable when the object, in which it is declared, is serialized. Thus, when the object is stored in
persistent storage, the instance variable declared as transient is not persisted. Code Snippet 2 depicts
the creation of a transient variable.
Code Snippet 2:
class Circle {
transient float PI; // transient variable that will not persist
float area; // instance variable that will persist
}
The variable PI is declared final so that its value cannot be changed later.
A method declared final cannot be overridden or hidden in a Java subclass. The reason for using a final
method is to prevent subclasses from changing the meaning of the method and increase the efficiency
of code by allowing the compiler to turn method calls into inline Java code. A final method is commonly
used to generate a random constant in a mathematical application. Code Snippet 4 depicts the creation
of a final method.
Code Snippet 4:
The method getCommission() can be used to calculate commission based on monthly sales. The
implementation of the method cannot be modified by other classes as it is declared as final. A final
method cannot be declared abstract as it cannot be overridden.
Note - abstract keyword is used with a method and class. An abstract method cannot have a body
and an abstract class cannot be instantiated and must be inherited or subclassed.
A class declared final cannot be inherited or subclassed. Such a class becomes a standard and must be
used as it is. The variables and methods of a class declared final are also implicitly final. The reason for
declaring a class as final is to limit extensibility and to prevent the modification of the class definition.
Code Snippet 5 shows the creation of a final class.
Code Snippet 5:
The class Stock is declared final. All data members within this class are implicitly final and cannot be
modified by other classes.
Code Snippet 6 demonstrates an example of creation of a final class.
Code Snippet 6:
package session9;
public class Final {
// Declare and initialize a final variable
final float PI = 3.14F; // variable to store value of PI
/**
* Displays the value of PI
*
* @param pi a float variable storing the value of PI
* @return void
*/
public void display(float pi) {
PI = pi; // generates compilation error
System.out.println(The value of PI is:+PI);
Concepts
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Instantiate the Final class
final Final objFinal = new Final();
// Invoke the display() method
objFinal.display(22.7F);
}
}
The class Final consists of a final float variable PI set to 3.14. The method display() is used to
set a new value passed by the user to PI . However, this leads to compilation error cannot assign a
value to final variable PI. If the user chooses to run the program anyway, the following runtime
error is issued as shown in figure 9.1.
Native methods violate Javas platform independence characteristic. Therefore, they should not
be used frequently.
A static block is used to initialize static variables as soon as the class is launched. They are used
when a block of code needs to be executed during loading of the class by JVM. It is enclosed within {}
braces.
Generally, a constructor is used to initialize variables. It is the best approach as the constructor is invoked
implicitly when an object is created. However, a programmer sometime needs to create objects before
anything can be done in a program. This is because, an object is required to call an instance variable or
method.
However, instead of a constructor, a static block can be used to initialize static variables because
static block is executed even before the main() method is executed. That is, the execution of Java
code starts from static blocks and not from main() method. There can be more than one static
block in a program. They can be placed anywhere in the class. A static initialization block can reference
only those class variables that have been declared before it.
Code Snippet 7 demonstrates an example of static variables, static method, and static block.
Code Snippet 7:
package session9;
public class StaticMembers {
// Declare and initialize static variable
public static int staticCounter = 0;
// Declare and initialize instance variable
int instanceCounter = 0;
/**
* static block
*
*/
static{
System.out.println(I am a static block);
}
Concepts
/**
* Static method
*
* @return void
*/
public static void staticMethod(){
System.out.println(I am a static method);
}
/**
* Displays the value of static and instance counters
*
* @return void
*/
public void displayCount(){
//Increment the static and instance variable
staticCounter++;
instanceCounter++;
// Print the value of static and instance variable
System.out.println(Static counter is:+ staticCounter);
System.out.println(Instance counter is:+ instanceCounter);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(I am the main method);
Concepts
The class StaticMembers consists of two variables, a static variable and an instance variable. Also,
a static block and a static method have been created. The instance method displayCount() is
used to increment the value of the static and instance counters by 1 and then, display the resulting
value of both variables. In the main() method, the static method is invoked in line 1 using the class
name StaticMembers.staticMethod() instead of creating an object of the class. Next, three objects
of the class StaticMembers are created namely objStatic1, objStatic2, and objStatic3. Each
object is used to invoke the displayCount() method.
Figure 9.2 shows the output of the program.
Concepts
From figure 9.2 it is clear that the static block is executed even before the main() method. Also, the
value of static counter is incremented to 1, 2, 3, , and so on whereas the value of instance counter
remains 1 for all the objects. This is because a separate copy of the instance counter exists for each
object. Hence, every time a new object is created, the count is incremented from an initial value of 0 to
1 when the displayCount() method is invoked.
However, for the static variable, only one copy exists per class. Every object increments the same copy
of the variable, staticCounter. Therefore, when the first object increments the value of the variable
staticCounter, it is set to 1. Then, the second object increments it by 1 and the value is set to 2 and
so on.
Thus, by using a static counter, a user can keep track of the number of instances of a class.
9.4 Packages
Consider a situation where in a user has about fifty files of which some are related to sales, others are
related to accounts, and some are related to inventory. Also, the files belong to different years. All these
files are kept in one section of a cupboard. Now, when a particular file is required, the user has to search
the entire cupboard. This is very time consuming and difficult. For this purpose, the user creates separate
folders and divides the files according to the years and further groups them according to the content as
shown in figure 9.3.
Concepts
Similarly, in Java, one can organize the files using packages. A package is a namespace that groups related
classes and interfaces and organizes them as a unit. Conceptually, one can think of packages as being
similar to different folders created on a computer to store files. For example, one can keep source files in
one folder, images in another, and executables in yet another folder. Software written in Java is composed
of several classes. Therefore, it is advisable to keep the classes organized by placing related classes and
interfaces into packages.
Packages have the following features:
A package can have sub packages.
If a class or interface is bundled inside a package, it must be referenced using its fully qualified
name, which is the name of the Java class including its package name.
If multiple classes and interfaces are defined within a package in a single Java source file, then only
one of them can be public.
Package names are written in lowercase.
One can know where to find the required type that can provide the required functions.
The names of classes of one package would not conflict with the class names in other packages as
the package creates a new namespace. For example, myPackage1.Sample and myPackage2.
Sample.
One can allow classes within one package to have unrestricted access to one another while
restricting access to classes outside the package.
Packages can also store hidden classes that can be used within the package, but are not visible or
accessible outside the package.
Concepts
Packages can also have classes with data members that are visible to other classes, but not
accessible outside the package.
When a program from a package is called for the first time, the entire package gets loaded into
the memory. Due to this, subsequent calls to related subprograms of the same package do not
require any further disk Input/Output (I/O).
Predefined packages
User-defined packages
The predefined packages are part of the Java API. Predefined packages that are commonly used are as
follows:
java.io
java.util
java.awt
The user-defined packages are created by the developers. To create user-defined packages, perform the
following steps:
1. Select an appropriate name for the package by using the following naming conventions:
Package names are usually written in all lower case to avoid conflict with the names of
classes or interfaces.
Companies usually attach their reversed Internet domain name as a prefix to their package
names. For example, com.sample.mypkg for a package named mypkg created by a
programmer at sample.com .
Concepts
Naming conflicts occurring in the projects of a single company are handled according to the
naming conventions specific to that company. This is done usually by including the region
name or the project name after the company name. For example, com.sample.myregion.
mypkg.
Package names should not begin with java or javax as they are used for packages that are
part of Java API.
In certain cases, the Internet domain name may not be a valid package name. For example,
if the domain name contains special characters such as hyphen, if the package name consists
of a reserved Java keyword such as char, or if the package name begins with a digit or some
other character that is illegal to use as the beginning of a Java package name. In such a case,
it is advisable to use an underscore as shown in table 9.1.
3. Place the source files in the folder created for the package.
4. Add the package statement as the first line in all the source files under that package as depicted in
Code Snippet 8. Note that there can only be one package statement in a source file.
Code Snippet 8:
package session9;
class StaticMembers{
public static void main(String[] args)
{}
}
javac d . StaticMembers.java
where, -d stands for directory and . stands for current directory. The command will create a
sub-folder named session9 and store the compiled class file inside it.
7. From the parent folder of the source file, execute it using the fully qualified name as follows:
java session9.StaticMembers
Note - The CLASSPATH variable must be set to the source file directory that has the StaticDemo.java
file before executing the program. For example, set classpath=D:\session9 or CLASSPATH can
be specified while executing. For example, java cp D:\session9 session9.StaticDemo.
Java allows the user to import the classes from predefined as well as user-defined packages using an
import statement. For example, one can use the StaticMembers class created in Code Snippet 7 as
well as the built-in class ArrayList of the java.util package by importing them into another class
belonging to another package. However, the access specifiers associated with the class members will
determine if the class members can be accessed by a class of another package.
A member of a public class can be accessed outside the package by doing any of the following:
Referring to the member class by its fully qualified name, that is, package-name.class-name.
1. Open the project in which the package is to be created. In this case Session9 project has been
chosen.
2. Right-click Source Packages New Java Package to display the New Java Package dialog
box. For example, in figure 9.4, the project Session9 is opened and the Java Package option is
selected.
Concepts
3. Type userpkg in the Package Name box of the New Java Package dialog box that is displayed.
5. Right-click userpkg and select New Java Class to add a new class to the package.
6. Type UserClass as the Class Name box of the New Java Class dialog box and click Finish.
package userpkg;
// Import the predefined and user-defined packages
import java.util.ArrayList;
import session9.StaticMembers;
public class UserClass {
// Instantiate ArrayList class of java.util package
ArrayList myCart = new ArrayList(); // line 1
Concepts
/**
* Initializes an ArrayList
*
* @return void
*/
public void createList() {
// Add values to the list
myCart.add(Doll);
myCart.add(Bus);
myCart.add(Teddy);
The class UserClass is defined within the package, userpkg. The two import statements namely,
java.util.ArrayList and session9.StaticMembers are used to import the packages
java.util and session9 into the UserClass class. However, only ArrayList and StaticMembers
classes are imported from the respective packages. To import all classes of the packages, one must write
the statements import java.util.* and import session9.* respectively.
Next, the ArrayList is instantiated in line 1 and the createList() method is used to initialize and
display the list. In the main() method, the object of UserClass is created to invoke the createList()
method and the object of StaticMembers class is created to invoke the displayCount() method.
Figure 9.6 shows the output of the program.
Security: The .jar file can be digitally signed so that only those users who recognize your
signature can optionally grant the software security privileges that the software might not
otherwise have.
Decrease in Download Time: The source files bundled in a .jar file can be downloaded to a
browser in a single HTTP transaction without having to open a new connection for each file.
File Compression: The .jar format compresses the files for efficient storage.
Packaging for Extensions: The extension framework in Java allows adding additional
functionality to the Java core platform. The .jar file format defines the packaging for extensions.
Java 3D and Java Mail are examples of extensions developed by Sun Microsystems. The .jar file
format allows converting the software into extensions as well.
Package Sealing: Java provides an option to seal the packages stored in the .jar files so that the
Concepts
packages can enforce version consistency. When a package is sealed within a .jar file, it implies
that all classes defined in that package must be available in the same .jar file.
Package Versioning: A .jar file can also store additional information about the files, such as
vendor and version information.
Portability: The .jar files are packaged in a ZIP file format. This enables the user to use them for
tasks such as lossless data compression, decompression, archiving, and archive unpacking.
To perform basic tasks with .jar files, one can use the Java Archive Tool. This tool is provided with the
JDK. The Java Archive Tool is invoked by using the jar command. The basic syntax for creating a .jar
file is as follows:
Syntax:
jar cf jar-file-name input-file-name(s)
where,
c: indicates that the user wants to CREATE a .jar file.
f: indicates that the output should go to a file instead of stdout.
jar-file-name: represents the name of the resulting .jar file. Any name can be used for a .jar file.
The .jar extension is provided with the file name, though it is not required.
input-file-name(s): represents a list of one or more files to be included in the .jar separated by a
space. This argument can contain the wildcard symbol * as well. If any of the input files specified is a
directory, the contents of that directory are added to the .jar recursively.
The options c and f can be used in any order, but without any space in between. The jar command
generates a compressed .jar file and places it by default in the current directory. Also, it will generate
a default manifest file for the .jar file. The metadata in the .jar file such as entry names, contents of
the manifest, and comments must be encoded in UTF8.
Note - UTF 8 is an encoding standard that represent every character in the Unicode character set.
Some of the other options, apart from cf, available with the jar command are listed in table 9.2.
Option Description
Produces VERBOSE output on stdout while the .jar is begin built.
V The output displays the name of each of the files that are included
in the .jar file.
0 (zero) Indicates that the .jar file must not be compressed.
M Indicates that the default manifest file must not be created.
Allows inclusion of manifest information from an existing manifest
file.
m
jar cmf existing-manifest-name jar-file-name
input-file-name(s)
Concepts
When a .jar file is created, the time of creation is stored in the .jar file. Therefore, even if the contents
of the .jar file are not changed, if the .jar file is created multiple times, the resulting files will not be
exactly identical. For this reason, it is advisable to use versioning information in the manifest file instead
of creation time, to control versions of a .jar file.
For example, consider the following files of a simple BouncingBall game application as shown in figure
9.7.
2. Create a text file with the code depicted in Code Snippet 10.
Code Snippet 10:
package bounceball;
public class BouncingBall {
/**
* @param args the command line arguments
Concepts
*/
The command will create a subfolder with the same name bounceball and store the class file
BouncingBall.java in that directory as shown in figure 9.7.
Note - The PATH variable must be set before executing the command. For example, E:\bouncingball\
set path=C:\Program Files\Java\jdk1.7.0\bin. If the class file must be stored in some
other folder, use the -cp option to specify the CLASSPATH for the class files.
5. Create a text file with the Main-class attribute as shown in figure 9.8.
6. Save the file as Manifiest.txt in the source bounceball folder as shown in figure 9.7. The
Manifest.txt file will be referred by the Jar tool for the Main class during .jar creation. This will
inform the Jar tool about the starting point of the application.
Concepts
7. To package the application in a single .jar named BouncingBall.jar, write the following
command:
jar cvmf Manifest.txt bounceball.jar bounceball/BouncingBall.class sounds
images
Note - The name of the manifest and the .jar file must be in the same order as the options m and f.
This will create a bounceball.jar file in the source folder as shown in figure 9.9.
8. To execute the .jar file at command prompt, type the following command:
java -jar bounceball.jar
The command will execute the main() class of the .jar file and print the following output:
This is the bouncing ball game.
Figure 9.10 shows the entire series of steps for creation of .jar file with the verbose output and
the final output after .jar file execution.
Concepts
failure.au
ping.au
success.au
greenball.gif
redball.gif
table.gif
Task Command
jar cf jar-file-name input-file-
To create a .jar file name(s)
To view contents of a .jar file jar tf jar-file-name
To extract contents of a .jar file jar xf jar-file-name
To run the application packaged into the .jar file. java -jar jar-file-name
Manifest.txt file is required with Main-class
header attribute.
Table 9.3: Frequently Used jar Command Options
To create a .jar file of the application using NetBeans IDE, perform the following steps:
2. Create a new java class named BouncingBall.java within the bounceball package.
package bounceball;
public class BouncingBall {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(This is the bouncing ball game);
}
}
4. Set BouncingBall.java as the main class in the Run properties of the application.
5. Run the application by clicking the Run icon on the toolbar. The output will be shown in the Output
window.
6. To create the .jar file, right-click the Session9 application and select Clean and Build option as
shown in figure 9.11.
Concepts
7. The IDE will build the application and generate the .jar file. A message as shown in figure 9.12 will
be displayed to the user in the status bar, once .jar file generation is finished.
Note - If double-click does not work, right-click the .jar file and select Open With. Select the Java(TM)
Platform SE Binary as the default program for .jar files.
Concepts
2. Which of the following statements about the final modifier are true?
(A) b, c (C) a, c
(B) a, d (D) b, d
3. Match the following field and method modifiers with the corresponding description.
Modifier Description
a. volatile 1. Used with a variable, method, and class.
b. native 2. Applied only to fields.
(A) a-3, b-2, c-4, d-1 (C) a-2, b-4, c-1, d-3
(B) a-2, b-3, c-4, d-1 (D) a-3, b-4, c-1, d-2
Concepts
4. Which of the following option represents the correct command for generating a .jar file using an
existing manifest file and displaying a verbose output? (Assumption: jar file - MyJar.jar,
Manifest file - Manifest.txt, class file - MyClass.class, package - mypkg).
5. Consider the following code to check the number of users logged in to a system:
package myPkg;
public class UserLogin{
public int userNo=0; // line 1
public void displayUserCount(){
userNo++;
System.out.println(User number is:+ userNo);
}
public static void main(String[] args) {
UserLogin objUser1 = new UserLogin();
objUser1.displayUserCount();
UserLogin objUser2 = new UserLogin();
objUser2.displayUserCount();
}
}
The code is executing properly without any error. However, the value of variable, userNo is
displaying 1 for every new object that is created. What change must be made in line 1 to ensure
that the userNo is incremented when a new object is created? (Assumption: The program is not
using multiple threads.)
public transient int public volatile int
(A) userNo=0; (C) userNo=0;
Concepts
(B) public final int userNo=0; (D) public static int userNo=0;
6. Identify the correct command to execute the .jar file myJar.jar at the command prompt.
9.5.1 Answers
1. B
2. B
3. C
4. C
5. D
6. B
Concepts
Summary
Field and method modifiers are used to identify fields and methods that have controlled access to
users.
The volatile modifier allows the content of a variable to be synchronized across all running
threads.
A thread is an independent path of execution within a program.
The native modifier indicates that the implementation of the method is in a language other than
Java such as C or C++.
The transient modifier can only be used with instance variables. It informs the JVM not to store
the variable when the object, in which it is declared, is serialized.
The final modifier is used when modification of a class or data member is to be restricted.
Class variables are also known as static variables and there exists only one copy of that variable
for all objects.
A package is a namespace that groups related classes and interfaces and organizes them as a unit.
All the source files of a Java application are bundled into a single archive file called the Java
Archive (JAR).
Concepts
Try it Yourself
1. SmartDesigns is a well-known company of architects situated in Chicago, Illinois. Currently, the
management is hiring IT professionals to automate the tasks performed in the company such as
drawing, animation, and calculation of dimensions by developing a software application in Java. For
this purpose, the company has organized technical interviews for aspiring developers. As one of the
candidates, you have been assigned the following tasks:
Create a program to calculate area of shapes such as circle and square.
Specify an appropriate package name to store the source file and class file.
The value for shape must be taken from the user along with the value for radius or length
according to the shape.
If a user does not provide any value, appropriate message must be displayed to the user.
If a user specifies necessary values, calculate the area of the specified shape.
Display the output as follows:
User Number:
Shape:
Value of radius/length:
Calculated Area:
The user number must be incremented with every user that runs the program.
Package the files into a .jar file. (Either by using command prompt or by NetBeans IDE).
Execute the .jar file at command prompt.
Concepts
This session explains the concept of inheritance and the types of inheritance
in Java, creation of super class and subclass as well as the use of super
keyword. Further, the session describes the concepts of method overriding
and polymorphism, static and dynamic binding, and virtual method
invocation. Lastly, the session explains the use of abstract keyword.
Describe Polymorphism
10.1 Introduction
Consider a situation where in a student is developing an online Website showing the food habits of
the different animals on the earth. While designing and developing the online food Website, the
student realizes that there are many animals and birds that eat the same type of food and have similar
characteristics. The child groups of all the animals that eat plants are known as herbivores, those that eat
animals are known as carnivores, and those that eat both plants and animals are known as omnivores.
This kind of grouping or classification of things is called subclassing and the child groups are known
as subclasses. Similarly, Java provides the concept of inheritance for creating subclasses of a particular
class.
Also, animals such as chameleon change their color based on the environment. Human beings also play
different roles in their daily life such as father, son, husband, and so on. This means, that they behave
differently in different situations. Similarly, Java provides a feature called polymorphism in which objects
behave differently based on the context in which they are used.
10.2 Inheritance
In daily life, one often comes across objects that share a kind-of or is-a relationship with each other.
For example, Car is-a four-wheeler, a four-wheeler is-a vehicle, and a vehicle is-a machine. Similarly,
many other objects can be identified having such relationship. All such objects have properties that are
common. For example, all four wheelers have wipers and a rear view mirror. All vehicles have a vehicle
number, wheels, and engine irrespective of a four-wheeler or two-wheeler.
Figure 10.1 shows some examples of is-a relationship.
Concepts
Thus, the class Animal becomes the top-level class from which the other classes such as Herbivore,
Carnivore, and Omnivore inherit properties and behavior. And the classes Deer, Horse, Lion, and so on
inherit properties from the classes Herbivore, Carnivore, and so on.
This is called inheritance. Thus, inheritance in Java is a feature through which classes can be derived from
other classes and inherit fields and methods from those classes.
The concept of inheritance is simple but powerful in that, it allows creating a new class from an existing
class that already has some of the code required. The new class derived from the existing class can reuse
the fields and methods of the existing class without having to re-write or debug the code again.
A subclass inherits all the members such as fields, nested classes, and methods from its super class except
those with private access specifier. However, constructors of a class are not considered as members of a
class and are not inherited by subclasses. The child class can however invoke the constructor of the super
class from its own constructor.
Members having default accessibility in the super class are not inherited by subclasses of other packages.
These members can only be accessed by subclasses within the same package as the super class. The
subclass will have its own specific characteristics along with those inherited from the super class.
Single Inheritance: When a child class inherits from one and only one parent class, it is called
single inheritance. In figure 10.2, class B inherits from a single class A.
Multilevel Inheritance: When a child class derives from a parent that itself is a child of another
class, it is called multilevel inheritance. In figure 10.2, class C derives from class B which is derived
from class A.
Hierarchical Inheritance: When a parent class has more than one child classes at different levels,
it is called hierarchical inheritance. In figure 10.2, class C is derived from class B and classes B and
D is derived from class A.
Multiple Inheritance: When a child class derives from more than one parent class, it is called
multiple inheritance. Java does not support multiple inheritance. This means, a class in Java cannot
inherit from more than one parent class. However, Java provides a workaround to this feature in
the form of interfaces. Using interfaces, one can simulate inheritance by implementing more than
one interface in a class.
The inherited members, including fields and methods, can be directly used just like any other
fields.
One can declare a field with the same name in the subclass as the one in the super class. This will
lead to hiding of super class field which is not advisable.
One can declare new fields in the subclass that are not present in the super class. These members
will be specific to the subclass.
One can write a new instance method with the same signature in the subclass as the one in the
super class. This is called method overriding.
A new static method can be created in the subclass with the same signature as the one in the
super class. This will lead to hiding of the super class method.
One can declare new methods in the subclass that are not present in the super class.
A subclass constructor can be used to invoke the constructor of the super class, either implicitly or
Concepts
Syntax:
public class <class1-name> extends <class2-name>
{
}
where,
class1-name: Specifies the name of the child class.
class2-name: Specifies the name of the parent class.
Code Snippet 1 demonstrates the creation of super class Vehicle.
Code Snippet 1:
package session10;
public class Vehicle {
// Declare common attributes of a vehicle
protected String vehicleNo; // Variable to store vehicle number
protected String vehicleName; // Variable to store vehicle name
protected int wheels; // Variable to store number of wheels
/**
* Accelerates the vehicle
*
* @return void
*/
public void accelerate(int speed) {
System.out.println(Accelerating at:+ speed + kmph);
}
}
Concepts
The parent class Vehicle consists of common attributes of a vehicle such as vehicleNo, vehicleName,
and wheels. Also, it consists of a common behavior of a vehicle, that is, accelerate() that prints the
speed at which the vehicle is accelerating.
Code Snippet 2 demonstrates the creation of subclass FourWheeler.
Code Snippet 2:
package session10;
class FourWheeler extends Vehicle{
/**
* Parameterized constructor to initialize values based on user input
*
* @param vID a String variable storing vehicle ID
* @param vName a String variable storing vehicle name
* @param numWheels an integer variable storing number of wheels
* @param pSteer a String variable storing steering information
*/
public FourWheeler(String vId, String vName, int numWheels, boolean pSteer){
// Attributes inherited from parent class
vehicleNo = vId;
vehicleName = vName;
wheels = numWheels;
// Child class own attribute
powerSteer = pSteer;
}
/**
* Displays vehicle details
*
Concepts
* @return void
*/
if(powerSteer == true)
System.out.println(Power Steering:Yes);
else
System.out.println(Power Steering:No);
}
}
/**
* Define the TestVehicle.java class
*/
public class TestVehicle {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Create an object of child class and specify the values
FourWheeler objFour = new FourWheeler(LA-09 CS-1406, Volkswagen, 4, true);
objFour.showDetails(); // Invoke the child class method
objFour.accelerate(200); // Invoke the inherited method
}
}
Code Snippet 2 depicts the child class FourWheeler with its own attribute powerSteer. The values
for the inherited attributes and its own attribute are specified in the constructor. The showDetails()
method is used to display all the details.
Concepts
The class TestVehicle consists of the main() method. In the main() method, the object objFour
of child class is created and the parameterized constructor is invoked by passing appropriate arguments.
Next, the showDetails() method is invoked to print the details. Also, the child class object is used
to invoke the accelerate() method inherited from parent class and the value of speed is passed as
argument.
The overriding method must have the same name, type, and number of arguments as well as
return type as the super class method.
An overriding method cannot have a weaker access specifier than the access specifier of the super
class method.
The accelerate() method in Code Snippet 1 can be overridden in the subclass as shown in Code
Snippet 3. The modified code is demonstrated in Code Snippet 3.
Code Snippet 3:
package session10;
class FourWheeler extends Vehicle{
// Declare a field specific to child class
private boolean powerSteer; // Variable to store steering information
Concepts
/**
* Parameterized constructor to initialize values based on user input
*
* @param vID a String variable storing vehicle ID
/**
* Displays vehicle details
*
* @return void
*/
public void showDetails() {
System.out.println(Vehicle no:+ vehicleNo);
System.out.println(Vehicle Name:+ vehicleName);
System.out.println(Number of Wheels:+ wheels);
if(powerSteer==true){
System.out.println(Power Steering:Yes);
else
Concepts
System.out.println(Power Steering:No);
}
/**
* Overridden method
* Accelerates the vehicle
*
* @return void
*/
@Override
public void accelerate(int speed) {
System.out.println(Maximum acceleration:+ speed + kmph);
}
}
/**
* Define the TestVehicle.java class
*/
public class TestVehicle {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Create an object of child class and specify the values
FourWheeler objFour = new FourWheeler(LA-09 CS-1406, Volkswagen, 4, true);
objFour.showDetails(); // Invoke child class method
objFour.accelerate(200); // Invoke inherited method
}
}
The accelerate() method is overridden in the child class with the same signature and return type but
Concepts
with a modified message. Notice the use of @Override on top of the method. This is an annotation that
instructs the compiler that the method that follows is overridden from the parent class. If the compiler
detects that such a method does not exist in the super class, it will generate compilation error.
Note - Annotations provide additional information about a program. Annotations have no direct effect
on the functioning of the code they annotate.
constructor.
Code Snippet 4:
package session10;
class Vehicle {
protected String vehicleNo; // Variable to store vehicle number
protected String vehicleName; // Variable to store vehicle name
protected int wheels; // Variable to store number of wheels
/**
* Parameterized constructor to initialize values based on user input
*
* @param vId a String variable storing vehicle ID
* @param vName a String variable storing vehicle name
* @param numWheels an integer variable storing number of wheels
*/
public Vehicle(String vId, String vName, int numWheels){
vehicleNo=vId;
vehicleName=vName;
wheels=numWheels;
}
/**
* Accelerates the vehicle
*
* @return void
*/
public void accelerate(int speed){
System.out.println(Accelerating at:+ speed + kmph);
}
Concepts
Code Snippet 4 demonstrates the use of parameterized constructor in Vehicle class for initializing the
common attributes of a vehicle.
Code Snippet 5 depicts the modified subclass FourWheeler.java using the super keyword to invoke
super class constructor and methods.
Code Snippet 5:
package session10;
class FourWheeler extends Vehicle{
private boolean powerSteer; // Variable to store steering information
/**
* Parameterized constructor to initialize values based on user input
*
* @param vID a String variable storing vehicle ID
* @param vName a String variable storing vehicle name
* @param numWheels an integer variable storing number of wheels
* @param pSteer a String variable storing steering information
*/
public FourWheeler(String vId, String vName, int numWheels, boolean pSteer){
// Invoke the super class constructor
super(vId,vName,numWheels);
powerSteer=pSteer;
}
/**
* Displays vehicle details
*
* @return void
*/
public void showDetails(){
System.out.println(Vehicle no:+ vehicleNo);
System.out.println(Vehicle Name:+ vehicleName);
System.out.println(Number of Wheels:+ wheels);
Concepts
if(powerSteer==true){
System.out.println(Power Steering:Yes);
}
else{
System.out.println(Power Stearing:No);
}
/**
* Overridden method
* Displays the acceleration details of the vehicle
*
* @return void
*/
@Override
public void accelerate(int speed){
// Invoke the super class accelerate() method
super.accelerate(speed);
System.out.println(Maximum acceleration:+ speed + kmph);
}
}
/**
* Define the TestVehicle.java class
*/
public class TestVehicle {
/**
* @param args the command line arguments
*/
public static void main(String[] args){
FourWheeler objFour = new FourWheeler(LA-09 CS-1406, Volkswagen, 4, true);
objFour.showDetails();
objFour.accelerate(200);
Concepts
}
}
Code Snippet 5 depicts the use of super() to call the super class constructor from the child class
constructor. Similarly, the super.accelerate() statement is used to invoke the super class
accelerate() method from the child class.
10.3 Polymorphism
The word polymorph is a combination of two words namely, poly which means many and morph which
means forms. Thus, polymorph refers to an object that can have many different forms. This principle
can also be applied to subclasses of a class that can define their own specific behaviors as well as derive
some of the similar functionality of the super class. The concept of method overriding is an example of
polymorphism in object-oriented programming in which the same method behaves in a different manner
in super class and in subclass.
Similarly, Java does not allow polymorphic behavior of variables of a class. Therefore, access to all the
variables also follows static binding.
Some important differences between static and dynamic binding are listed in table 10.1.
package session10;
class Employee {
String empId; // Variable to store employee ID
String empName; // Variable to store employee name
int salary; // Variable to store salary
float commission; // Variable to store commission
/**
* Parameterized constructor to initialize the variables
*
* @param id a String variable storing employee id
* @param name a String variable storing employee name
* @param sal an integer variable storing salary
*
*/
public Employee(String id, String name, int sal) {
Concepts
empId=id;
empName=name;
salary=sal;
}
/**
* Calculates commission based on sales value
* @param sales a float variable storing sales value
*
* @return void
*/
public void calcCommission(float sales){
if(sales > 10000)
commission = salary * 20 / 100;
else
commission=0;
}
/**
* Overloaded method. Calculates commission based on overtime
* @param overtime an integer variable storing overtime hours
*
* @return void
*/
public void calcCommission(int overtime){
if(overtime > 8)
commission = salary/30;
else
commission = 0;
}
/**
* Displays employee details
*
Concepts
* @return void
*/
Code Snippet 6 depicts a class Employee with four member variables. The constructor is used to initialize
the member variables with the received values. The class consists of two calcCommission() methods.
The first method calculates commission based on the sales done by the employee and the other based
Concepts
on the number of hours the employee worked overtime. The displayDetails() method is used to
print the details of the employee.
Another class EmployeeDetails is created with the main() method. Inside the main() method, object
objEmp of class Employee is created and the parameterized constructor is invoked with appropriate
arguments. Next, the calcCommission() method is invoked with a float argument 20000F.
In the example, when the calcCommission() method is executed, the method with float argument
gets invoked because it was bounded during compile time based on the type of variable, that is, float.
Lastly, displayDetails() method is invoked to print the details of the employee.
Figure 10.6 shows the output of the code.
package session10;
class PartTimeEmployee extends Employee{
// Subclass specific variable
String shift; // Variable to store shift information
/**
* Parameterized constructor to initialize values based on user input
*
* @param id a String variable storing employee ID
Concepts
Code Snippet 7 displays the PartTimeEmployee class that is inherited from the Employee class created
earlier. The class has its own variable called shift which indicates the day or night shift for an employee.
The constructor of PartTimeEmployee class calls the super class constructor using the super keyword
to initialize the common attributes of an employee. Also, it initializes the shift variable.
The subclass overrides the displayDetails() method. Within the overridden method, the
calcCommission() method is invoked with an integer argument. This will calculate commission based
on overtime. Next, the super class displayDetails() method is invoked to display the basic details of
the employee as well as the shift details.
The EmployeeDetails class is modified to create another object objEmp1 of class Employee. However,
the object is assigned the reference of class PartTimeEmployee and the constructor is invoked with
four arguments. Next, the displayDetails() method is invoked to print the employee details.
Figure 10.8 shows the output of the code.
Concepts
This is dynamic binding, that is, the method call is bound to the object at runtime based on the reference
assigned to the object.
In Java, all methods behave in this manner, whereby a method overridden in the child class is invoked at
run time irrespective of the type of reference used in the source code at compile time. In other languages
such as C++, the same can be achieved by using the keyword virtual.
For example,
public abstract Calculator
{
public float getPI(){ // Define a concrete method
return 3.14F;
}
abstract void Calculate(); // Declare an abstract method
}
Consider the class hierarchy as shown in figure 10.9.
package session10;
abstract class Shape {
private final float PI = 3.14F; // Variable to store value of PPI
/**
* Returns the value of PI
*
* @return float
*/
public float getPI(){
return PI;
Concepts
/**
* Abstract method
* @param val a float variable storing the value specified by user
*
* @return float
*/
abstract void calculate(float val);
}
The class Shape is an abstract class with one concrete method getPI() and one abstract method
calculate().
To use the abstract class, one needs to create subclasses. Code Snippet 9 demonstrates two subclasses
Circle and Rectangle inheriting the Shape class.
Code Snippet 9:
package session10;
/**
* Define the child class Circle.java
*/
class Circle extends Shape{
float area; // Variable to store area of a circle
/**
* Implement the abstract method to calculate area of circle
*
* @param rad a float variable storing value of radius
* @return void
*/
@Override
void calculate(float rad){
Concepts
/**
* Define the child class Rectangle.java
*/
class Rectangle extends Shape{
float perimeter; // Variable to store perimeter value
float length=10; // Variable to store length
/**
* Implement the abstract method to calculate the perimeter
*
* @param width a float variable storing width
* @return void
*/
@Override
void calculate(float width){
perimeter = 2 * (length+width);
System.out.println(Perimeter of the Rectangle is:+ perimeter);
}
}
The class Circle implements the abstract method calculate() to calculate the area of a circle.
Similarly, the class Rectangle implements the abstract method calculate() to calculate the
perimeter of a rectangle.
Code Snippet 10 depicts the code for Calculator class that uses the subclasses based on user input.
Code Snippet 10:
package session10;
public class Calculator {
/**
* @param args the command line arguments
Concepts
*/
public static void main(String[] args)
{
Shape objShape; // Declare the Shape object
String shape; // Variable to store the type of shape
The class Calculator takes two arguments from the user at command line namely, the shape and
the value for the shape. Notice the Shape class object objShape. It was mentioned earlier that an
abstract class cannot be instantiated. That is, one cannot write Shape objShape = new Shape().
However, an abstract class can be assigned a reference of its subclasses.
The statement args.length checks the number of arguments supplied by the user. If the length is 2,
the value for shape is extracted from the first argument args[0] and stored in the shape variable. Next,
the switch statement evaluates the value of shape variable and accordingly assigns the reference of
the appropriate shape to the objShape object. For example, if shape is circle, it assigns new Circle()
as the reference. Then, using the object objShape, the calculate() method is invoked for the
referenced subclass.
Concepts
To execute the example in NetBeans IDE, type the arguments in the Arguments box of Run property as
shown in figure 10.10.
2. Which of the following statements about the static and dynamic binding are true?
(A) a, c (C) b, d
(B) b, c (D) a, d
(A) a-4, b-3, c-2, d-1 (C) a-2, b-4, c-1, d-3
Concepts
(B) a-2, b-3, c-4, d-1 (D) a-4, b-1, c-3, d-2
super(ID,price);
this.type = type;
}
Concepts
super.displayDetails();
System.out.println(Type: +type);
}
5. Consider the following code: (Assumption: Super class Vehicle and Subclass Car)
Car objCar = new Car();
Vehicle objVehicle = objCar;
10.5.1 Answers
1. C
2. B
3. C
4. C
5. D
6. B
Concepts
Summary
Inheritance is a feature in Java through which classes can be derived from other classes and inherit
fields and methods from classes it is inheriting.
The class that is derived from another class is called a subclass, derived class, child class, or
extended class. The class from which the subclass is derived is called a super class.
Creation of an instance method in a subclass having the same signature and return type as an
instance method of the super class is called method overriding.
When the compiler resolves the binding of methods and method calls at compile time, it is called
static binding or early binding. If the compiler resolves the method calls and the binding at
runtime, it is called dynamic binding or late binding.
An abstract method is one that is declared with the abstract keyword without an implementation,
that is, without any body.
An abstract class is one that consists of abstract methods and serves as a framework that provides
certain pre-defined behavior for other classes that can be modified later as per the requirement
of the inheriting class.
Concepts
Try it Yourself
1. ITQuest.com is a well-known online IT training company based in Los Angeles, USA. The company
organizes online code competitions every year. Thousands of IT whiz kids participate in the
competition to test their IT skills. The winner(s) is awarded with a 1 year scholarship and free training
in the subject of his choice in the IT institutes affiliated with the company. This year, the competition
is on Java and the following code has been posted online for the participants.
package session10;
public class TwoWheeler {
String vehicleId;
String type;
int wheels;
float price;
public TwoWheeler(String vId, String vType, int tyres, float rate)
{
vehicleId=vId;
type=vType;
wheels=tyres;
price=rate;
}
public void printDetails(){
boolean gear;
super(vId,vName,tyres,price);
gear=gear;
}
@Override
public void printDetails(){
if(gear==true)
System.out.println(Geared: Yes);
else
System.out.println(Geared: No);
}
}
}
Concepts
The code is not functioning properly. The user passes the following arguments at command line:
B001 Mountain-Bicycle 2 200 true
Concepts
This session explains the concept of interfaces and the purpose of using
interfaces as well as implementation of multiple interfaces. Further, the
session describes the concept of abstraction, nested class, member class,
and local class. Lastly, the session explains the use of anonymous class and
static nested class.
Describe Interface
Describe Abstraction
11.1 Introduction
Java does not support multiple inheritance. However, there are several cases when it becomes mandatory
for an object to inherit properties from multiple classes to avoid redundancy and complexity in code. For
this purpose, Java provides a workaround in the form of interfaces.
Also, Java provides the concept of nested classes to make certain types of programs easy to manage,
more secure, and less complex.
11.2 Interfaces
An interface in Java is a contract that specifies the standards to be followed by the types that implement
it. The classes that accept the contract must abide by it.
An interface and a class are similar in the following ways:
An interface is saved with a .java extension and the name of the file must match with the name of
the interface just as a Java class.
Interfaces are stored in packages and the bytecode file is stored in a directory structure that
matches the package name.
However, an interface and a class differ in several ways as follows:
The fields declared in an interface must be both static and final. Interface cannot have instance
fields.
<visibility>: Indicates the access rights to the interface. Visibility of an interface is always public.
<interface-name>: Indicates the name of the interface.
<other-interfaces>: List of interfaces that the current interface inherits from.
For example,
public interface Sample extends Interface1{
package session11;
public interface IVehicle {
// Declare and initialize constant
static final String STATEID=LA-09; // variable to store state ID
/**
Concepts
/**
* Abstract method to accelerate a vehicle
* @param speed an integer variable storing speed
* @return void
*/
public void accelerate(int speed);
/**
* Abstract method to apply a brake
* @return void
*/
public void brake();
/**
* Abstract method to stop a vehicle
* @return void
*/
public void stop();
}
Code Snippet 1 defines an interface IVehicle with a static constant String variable STATEID. Also,
it declares several abstract methods such as start(), accelerate(int), brake(), and stop().
To use the interface, a class is required to implement the interface. The instantiating class implementing
the interfaces must define all these methods.
The syntax to implement an interface is as follows:
Syntax:
class <class-name> implements <Interface1>,
Concepts
{
// class members
// overridden abstract methods of the interface(s)
}
Code Snippet 2 defines the class TwoWheeler that implements the IVehicle interface.
Code Snippet 2:
package session11;
class TwoWheeler implements IVehicle {
/**
* Parameterized constructor to initialize values based on user input
*
* @param ID a String variable storing vehicle ID
* @param type a String variable storing vehicle type
*/
public TwoWheeler(String ID, String type){
this.ID = ID;
this.type = type;
}
/**
* Overridden method, starts a vehicle
*
* @return void
*/
@Override
public void start() {
System.out.println(Starting the + type);
Concepts
/**
* Overridden method, accelerates a vehicle
* @param speed an integer storing the speed
* @return void
*/
@Override
public void accelerate(int speed) {
System.out.println(Accelerating at speed:+speed+ kmph);
}
/**
* Overridden method, applies brake to a vehicle
*
* @return void
*/
@Override
public void brake() {
System.out.println(Applying brakes);
}
/**
* Overridden method, stops a vehicle
*
* @return void
*/
@Override
public void stop() {
System.out.println(Stopping the + type);
Concepts
/**
* Displays vehicle details
*
* @return void
*/
public void displayDetails(){
System.out.println(Vehicle No.: + STATEID+ + ID);
System.out.println(Vehicle Type.: + type);
}
}
/**
* Define the class TestVehicle.java
*
*/
public class TestVehicle {
/**
* @param args the command line arguments
*/
public static void main(String[] args){
// Verify the number of command line arguments
if(args.length==3) {
// Instantiate the TwoWheeler class
TwoWheeler objBike = new TwoWheeler(args[0], args[1]);
// Invoke the class methods
objBike.displayDetails();
Concepts
objBike.start();
objBike.accelerate(Integer.parseInt(args[2]));
objBike.brake();
objBike.stop();
}
else {
System.out.println(Usage: java TwoWheeler <ID> <Type> <Speed>);
}
}
}
Code Snippet 2 defines the class TwoWheeler that implements the IVehicle interface. The class
consists of some instance variables and a constructor to initialize the variables. Notice, that the class
implements all the methods of the interface IVehicle. The displayDetails() method is used to
display the details of the specified vehicle.
The main() method is defined in another class TestVehicle. Within the main() method, the number
of command line arguments specified is verified and accordingly the object of class TwoWheeler is
created. Next, the object is used to invoke the various methods of the class.
Figure 11.2 shows the output of the code when the user passes CS-2723 Bike 80 as command line
arguments.
simulate multiple inheritance. To implement multiple interfaces, write the interface names after the
implements keyword separated by a comma. For example,
public class Sample implements Interface1, Interaface2{
}
package session11;
public interface IManufacturer {
/**
* Abstract method to add contact details
* @param detail a String variable storing manufacturer detail
* @return void
*/
public void addContact(String detail);
/**
* Abstract method to call the manufacturer
* @param phone a String variable storing phone number
* @return void
*/
public void callManufacturer(String phone);
/**
* Abstract method to make payment
* @param amount a float variable storing amount
* @return void
*/
public void makePayment(float amount);
}
Concepts
Code Snippet 4:
package session11;
class TwoWheeler implements IVehicle, IManufacturer {
/**
* Parameterized constructor to initialize values based on user input
*
* @param ID a String variable storing vehicle ID
* @param type a String variable storing vehicle type
*/
public TwoWheeler(String ID, String type){
this.ID = ID;
this.type = type;
}
/**
* Overridden method, starts a vehicle
*
* @return void
*/
@Override
public void start() {
System.out.println(Starting the + type);
Concepts
/**
* Overridden method, accelerates a vehicle
* @param speed an integer storing the speed
* @return void
*/
@Override
public void accelerate(int speed) {
System.out.println(Accelerating at speed:+speed+ kmph);
}
/**
* Overridden method, applies brake to a vehicle
*
* @return void
*/
@Override
public void brake() {
System.out.println(Applying brakes...);
}
/**
* Overridden method, stops a vehicle
*
* @return void
*/
@Override
public void stop() {
Concepts
/**
* Displays vehicle details
*
* @return void
*/
public void displayDetails()
{
System.out.println(Vehicle No.: + STATEID+ + ID);
System.out.println(Vehicle Type.: + type);
}
/**
* Overridden method, adds manufacturer details
* @param detail a String variable storing manufacturer detail
* @return void
*/
@Override
public void addContact(String detail) {
System.out.println(Manufacturer: +detail);
}
/**
* Overridden method, calls the manufacturer
* @param phone a String variable storing phone number
Concepts
* @return void
*/
@Override
public void callManufacturer(String phone) {
System.out.println(Calling Manufacturer @: +phone);
}
/**
* Overridden method, makes payment
* @param amount a String variable storing the amount
* @return void
*/
@Override
public void makePayment(float amount) {
System.out.println(Payable Amount: $+amount);
}
}
/**
* Define the class TestVehicle.java
*
*/
public class TestVehicle {
/**
* @param args the command line arguments
*/
public static void main(String[] args){
if(args.length==6) {
The class TwoWheeler now implements both the interfaces; IVehicle and IManufacturer. Also, it
implements all the methods of both the interfaces.
Figure 11.3 shows the output of the modified code. The user passes CS-2737 Bike 80 BN-Bikes
808-283-2828 300 as command line arguments.
Concepts
The basis of the design principle programming for interface than implementation is abstraction
and that of encapsulate whatever changes is encapsulation.
class Outer{
...
class Nested{
...
}
}
The class Outer is the external enclosing class and the class Nested is the class defined within the class
Outer.
Nested classes are classified as static and non-static. Nested classes that are declared static are simply
termed as static nested classes whereas non-static nested classes are termed as inner classes. This has
been demonstrated in Code Snippet 6.
Code Snippet 6:
class Outer{
...
static class StaticNested{
...
}
class Inner{
...
}
}
Notice that the class StaticNested is a nested class that has been declared as static whereas the
non-static nested class, Inner, is declared without the keyword static.
A nested class is a member of its enclosing class. Note that non-static nested classes or inner classes
can access the members of the enclosing class even when they are declared as private. On the other
hand, static nested classes cannot access any other member of the enclosing class. As a member of
the outer class, a nested class can have any access specifier such as public, private, protected, or
Concepts
Creates logical grouping of classes: If a class is of use to only one class, then it can be
embedded within that class and the two classes can be kept together. In other words, it helps in
grouping the related functionality together. Nesting of such helper classes helps to make the
package more efficient and streamlined.
Increases encapsulation: In case of two top level classes such as class A and B, when B wants
access to members of A that are private, class B can be nested within class A so that B can
access the members declared as private. Also, this will hide class B from the outside world. Thus,
it helps to access all the members of the top-level enclosing class even if they are declared as
private.
Increased readability and maintainability of code: Nesting of small classes within larger
top-level classes helps to place the code closer to where it will be used.
The different types of nested classes are as follows:
Local classes
Anonymous classes
inner class exist within an instance of the outer class. To instantiate an inner class, one must create an
instance of the outer class. Then, one can access the inner class object within the outer class object using
the statement defined in Code Snippet 7.
Code Snippet 7:
package session11;
class Server {
String port; // variable to store port number
/**
* Connects to specified server
*
* @param IP a String variable storing IP address of server
* @param port a String variable storing port number of server
* @return void
*/
public void connectServer(String IP, String port) {
System.out.println(Connecting to Server at:+ IP + : + port);
}
/**
* Define an inner class
*
*/
class IPAddress
{
/**
Concepts
String getIP() {
return 101.232.28.12;
}
}
}
/**
* Define the class TestConnection.java
*
*/
public class TestConnection {
/**
* @param args the command line arguments
*/
public static void main(String[] args){
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// Check the number of command line arguments
if(args.length==1) {
// Instantiate the outer class
Server objServer1 = new Server();
The class Server is an outer class that consists of a variable port that represents the port at which
the server will be connected. Also, the connectServer(String, String) method accepts the IP
address and port number as a parameter. The inner class IPAddress consists of the getIP() method
that returns the IP address of the server.
The main() method is defined in the class TestConnection. Within main()method, the number
of arguments is verified and accordingly the object of Server class is created. Next, the object
objServer1 is used to create the object, objIP, of inner class IPAddress. Lastly, the outer class object
is used to invoke the connectServer() method. The IP address is retrieved using objIP.getIP()
statement. Figure 11.5 shows the output of the code when user provides 8080 as the port number at
command line.
specifier. That is, it cannot use modifiers such as public, protected, private, or static. However,
it can access all members of the outer class as well as final variables declared within the scope in which
it is defined.
It can access any members, including private members, of the enclosing class.
It can access any local variables, method parameters, or exception parameters that are in the
scope of the local method definition, provided that these are declared as final.
Code Snippet 9 demonstrates an example of local inner class.
Code Snippet 9:
package session11;
class Employee {
/**
* Evaluates employee status
*
* @param empID a String variable storing employee ID
Concepts
/**
* Local inner class Rank
*
*/
class Rank{
/**
* Returns the rank of an employee
*
* @param empID a String variable that stores the employee ID
* @return char
*/
public char getRank(String empID){
/**
* Define the class TestEmployee.java
*
*/
public class TestEmployee {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
Concepts
{
if(args.length==2) {
The class Employee is the outer class with a method named evaluateStatus(String,int). The
method consists of a local final variable named age. The class Rank is a local inner class within the
method. The Rank class consists of one method getRank() that returns the rank of the specified
employee Id.
Next, if the age of the employee is greater than 40, the object of Rank class is created and the rank is
retrieved. If the rank is equal to A then, the employee is eligible for upgrade otherwise the employee is
not eligible.
The main() method is defined in the TestEmployee class. Within the main() method, an object
objEmp1 of class Employee is created and the method evaluateStatus() is invoked with appropriate
arguments.
Figure 11.7 shows the output of the code when user passes E001 as employee Id and 50 for age.
Anonymous class is a type of local class that cannot use the extends and implements keywords nor
can specify any access modifiers, such as public, private, protected, and static. It cannot define
a constructor, static fields, methods, or classes. Also, it cannot implement anonymous interfaces
because an interface cannot be implemented without a name.
Since, an anonymous class does not have a name, it cannot have a named constructor but it can have an
instance initializer. Rules for accessing an anonymous class are the same as that of local inner class.
Usually, anonymous class is an implementation of its super class or interface and contains the
implementation of the methods. Anonymous inner classes have a scope limited to the outer class. They
can access the internal or private members and methods of the outer class. Anonymous class is useful
for controlled access to the internal details of another class. Also, it is useful when a user wants only one
instance of a special class.
Figure 11.8 displays an anonymous class.
package session11;
class Authenticate {
/**
* Define an anonymous class
*
*/
Account objAcc = new Account() {
/**
* Displays balance
*
* @param accNo a String variable storing balance
* @return void
*/
@Override
public void displayBalance(String accNo) {
System.out.println(Retrieving balance. Please wait...);
/**
* Define the Account class
*
*/
class Account {
/**
* Displays balance
*
* @param accNo a String variable storing balance
* @return void
*/
public void displayBalance(String accNo) {
}
}
/**
* Define the TestAuthentication class
*
*/
public class TestAuthentication {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Instantiate the Authenticate class
Authenticate objUser = new Authenticate()
Concepts
The Authenticate
class consists of an anonymous object of type Account. The
displayBalance(String) method is used to retrieve and display the balance of the specified
account number.
The main() method is defined in the TestAuthentication class. Within main() method, an object
of class Authenticate is created. The number of command line arguments is verified. If the number of
arguments are correct, the username and password is verified and accordingly the object of anonymous
class is used to invoke the displayBalance() method with account number as the argument.
Figure 11.9 shows the output of the code when user passes admin, abc@123, and akdle26152, as
arguments.
Concepts
package session11;
import java.util.Calendar;
class AtmMachine {
/**
* Define the static nested class
*
*/
static class BankDetails
{
// Instantiate the Calendar class of java.util package
static Calendar objNow = Calendar.getInstance();
/**
* Displays the bank and transaction details
*
* @return void
Concepts
*/
/**
* Displays balance
* @param accNo a String variable that stores the account number
* @return void
*/
public void displayBalance(String accNo) {
// Assume that the server returns 200000
System.out.println(Balance of account number + accNo.toUpperCase() + is
$200000);
}
}
/**
* Define the TestATM class
*
*/
public class TestATM {
/**
Concepts
// Invoke the static nested class method using outer class object
AtmMachine.BankDetails.printDetails();
The class AtmMachine consists of a static nested class named BankDetails. The static nested
class creates an object of the Calendar class of java.util package. The Calendar class consists of
built-in methods to set or retrieve the system date and time. The printDetails() method is used to
print the bank details along with the current date and time using the getTime() method of Calendar
class.
The main() method is defined in the TestATM class. Within main() method, the number of command
line arguments is verified and accordingly an object of class AtmMachine is created. Next, the static
method printDetails() of the nested class BankDetails is invoked and accessed directly using the
class name of the outer class AtmMachine. Lastly, the object objAtm of outer class is used to invoke
displayBalance() method of the outer class with account number as the argument.
Figure 11.10 shows the output of the code when user passes akdle26152 as account number.
Concepts
Notice that the output of date and time shows the default format as specified in the implementation
of the getTime() method. The format can be modified according to the user requirement using the
SimpleDateFormat class of java.text package. SimpleDateFormat is a concrete class used
to format and parse dates in a locale-specific manner. SimpleDateFormat class allows specifying
user-defined patterns for date-time formatting. The modified BankDetails class using
SimpleDateFormat class is displayed in Code Snippet 12.
Code Snippet 12:
import java.text.SimpleDateFormat;
import java.util.Calendar;
class AtmMachine {
/**
* Define the static nested class
*
*/
/**
* Displays the bank and transaction details
*
* @return void
*/
public static void printDetails(){
System.out.println(State Bank of America);
System.out.println(Branch: New York);
System.out.println(Code: K3983LKSIE);
Concepts
The SimpleDateFormat class constructor takes the date pattern as a String. In Code Snippet 12,
the pattern dd/MM/yyyy HH:mm:ss uses several symbols that are pattern letters recognized by the
SimpleDateFormat class. Table 11.2 lists the pattern letters used in the code with their description.
(A) b, c (C) b, d
(B) a, d (D) a, c
3. Match the following description with the corresponding nested class type.
(A) a-3, b-4, c-1, d-2 (C) a-4, b-3, c-2, d-1
(B) a-2, b-4, c-1, d-3 (D) a-2, b-3, c-4, d-1
String ID;
String type;
@Override
public void addContact() {
System.out.println(Storing contact .....);
}
@Override
public void getRoyaltyAmt() {
System.out.println(Royalty amount is $2000);
}
if (args.length == 2)
{
} else {
System.out.println(Usage: java Book <ID> <Type>);
}
}
}
What will be the output of the code when user passes B001 as the command line argument?
<Interface2>, <Interface2>&
11.4.1 Answers
1. D
2. D
3. B
4. C
5. B
6. A
Concepts
Summary
An interface in Java is a contract that specifies the standards to be followed by the types that
implement it.
To implement multiple interfaces, write the interfaces after the implements keyword separated by
a comma.
Abstraction, in Java, is defined as the process of hiding the unnecessary details and revealing only
the necessary details of an object.
Java allows defining a class within another class. Such a class is called a nested class.
A member class is a non-static inner class. It is declared as a member of the outer or enclosing
class.
An inner class defined within a code block such as the body of a method, constructor, or an
initializer, is termed as a local inner class.
An inner class declared without a name within a code block such as the body of a method is called
an anonymous inner class.
A static nested class cannot directly refer to instance variables or methods of the outer class just
like static methods but only through an object reference.
Concepts
Try it Yourself
1. Imaginations Pvt. Ltd. is a famous graphics design and animation company located in New York,
USA. The company has started a new IT division wherein they recruit programmers to create
customized graphic software. Currently, the company is working on an animation software. The
project manager has assigned the various modules to different programmers according to their
skill.
Jack, one of the Java programmers, has been assigned the task to create a code for drawing and
animating shapes according to specifications given by user. Jack has written the following sample
code to accomplish the task.
public abstract class Shape {
@Override
public void calcArea(float rad)
{
System.out.println(Area of Circle is: + (3.14*rad*rad));
}
@Override
public void rotateObject(int degree) {
System.out.println(Rotating Circle by + degree + degrees);
}
@Override
public void flipObject(int direction) {
System.out.println(Flipping Circle + direction);
}
@Override
public void moveObject(int distance) {
System.out.println(Moving Circle by+ distance + cm);
}
}
}
Jack wishes to use the characteristics of both the Shape and Animate classes into the Circle
class. However, the code is generating compilation errors and not functioning properly.
Concepts
This session explains the concept of exception and the types of errors and
exceptions. Further, this session describes the Exception class and exception
handling. The session also explains the try-catch and finally blocks. Finally,
the session explains the execution flow of exceptions and guidelines to
exception handling.
Describe exceptions
12.1 Introduction
Java is a very robust and efficient programming language. Features such as classes, objects, inheritance,
and so on make Java a strong, versatile, and secure language. However, no matter how well a code
is written, it is prone to failure or behaves erroneously in certain conditions. These situations may be
expected or unexpected. In either case, the user would be nonplussed or confused with such unexpected
behavior of code.
To avoid such a situation, Java provides the concept of exception handling using which, a programmer
can display appropriate message to the user in case such unexpected behavior of code occurs.
12.2 Exceptions
An exception is an event or an abnormal condition in a program occurring during execution of a program
that leads to disruption of normal flow of program instructions. An exception can occur for different
reasons such as when the user enters invalid data, a file that needs to be opened cannot be found, a
network connection has been lost in the middle of communications, or the JVM has run out of memory.
When an error occurs inside a method, it creates an exception object and passes it to the runtime
system. This object holds information about the type of error and state of the program when the error
occurred.
This process of creating an exception object and passing it to the runtime system is termed as throwing
an exception. After an exception is thrown by a method, the runtime system tries to find some code block
to handle it. The possible code blocks where the exception can be handled are a series of methods that
were invoked in order to reach the method where the error has actually occurred. This list or series of
methods is called the call stack. In other words, the stack trace shows the sequence of method invocations
that led up to the exception.
Figure 12.1 shows the method call from main Method A Method B Method C. When an
exception occurs in method C, it throws the exception object to the runtime environment. The runtime
environment then searches the entire call stack for a method that consists of a code block that can
handle the exception. This block of code is called an exception handler.
The runtime environment first searches the method in which the error occurred. If a handler is not found,
it proceeds through the call stack in the reverse order in which the methods were invoked. When an
appropriate handler is found, the runtime environment passes the exception to the handler.
An appropriate exception handler is one that handles the same type of exception as the one thrown by
the method. In this case, the exception handler is said to catch the exception. If while searching the call
stack, the runtime environment fails to find an appropriate exception handler, the runtime environment
will consequently terminate the program.
An exception is thrown for the following reasons:
Separate Error-Handling Code from Normal Code: Exceptions help separating the details of
what must be done when something wrong happens from the main logic of a program. In
conventional programming, error detection, error reporting, and error handling code were written
in the same area which often led to confusing and cluttered code. Exceptions on the other hand
allow a user to write the main flow of the code while dealing with the exceptional cases
elsewhere.
Concepts
Propagate Errors Higher Up in the Call Stack: Exceptions allow propagation of error reporting
up in the call stack of methods. A method that is part of the call stack can evade any exceptions
that are thrown within it so that a method further up the call stack can catch it. Thus, only the
concerned methods have to worry about detecting specific types of errors.
Group the Similar Error Types: All exceptions that are thrown within a program are objects.
Thus, grouping of similar exceptions is an obvious outcome of the class hierarchy. For example, the
group of related exception classes defined in java.io package such as IOException and its
descendants. The IOException class is the most general exception that represents any type of
error occurring while performing Input/Output (I/O) operations. The subclasses of IOException
represent more specific errors. For example, the subclass FileNotFoundException handles the
exception when the user attempts to open a file that does not exist.
Checked Exceptions: These are exceptions that a well-written application must anticipate and
provide methods to recover from. For example, suppose an application prompts the user to
specify the name of a file to be opened and the user specifies the name of a nonexistent file. In
such a case, the java.io.FileNotFoundException is thrown. However, a well-written program
will have the code block to catch this exception and inform the user of the mistake by displaying
an appropriate message. In Java, all exceptions are checked exceptions, except those indicated by
Error, RuntimeException, and their subclasses.
suppose a user specified the file name of the file to be opened. However, due to some logical
error a null is passed to the application, then the application will throw a
NullPointerException. The application can choose to catch this exception and display
appropriate message to the user or eliminate the error that caused the exception to occur.
Runtime exceptions are indicated by RuntimeException class and its subclasses.
Concepts
Exception Description
InstantiationException Occurs upon an attempt to create instance of an
abstract class.
InterruptedException Occurs when a thread is interrupted.
NoSuchMethodException Occurs when JVM is unable to resolve which method
to be invoked.
Table 12.1: Checked Exceptions
Table 12.2 lists some of the commonly observed unchecked exceptions.
Exception Description
ArithmeticException Indicates an arithmetic error condition.
ArrayIndexOutOfBoundsException Occurs if an array index is less than zero
or greater than the actual size of the
array.
IllegalArgumentException Occurs if method receives an illegal
argument.
NegativeArraySizeException Occurs if array size is less than zero.
NullPointerException Occurs on access to a null object
member.
NumberFormatException Occurs if unable to convert the string to
a number.
StringIndexOutOfBoundsException Occurs if index is negative or greater
than the size of the string.
Table 12.2: Unchecked Exceptions
Most of the methods throw and catch objects that derive from the Exception class. An exception
indicates that a problem has occurred, but it is not a serious system problem. Majority of the programs
are capable of throwing and catching exceptions as opposed to errors.
The Java platform defines many subclasses of the Exception class. These subclasses indicate the
various types of exceptions that can occur. For example, an IllegalAccessException indicates that
a method that was called could not be found. Similarly, a NegativeArraySizeException indicates
that a program attempted to create an array with a negative size.
The RuntimeException subclass of Exception class is reserved for those exceptions that indicate
incorrect use of an API. For example, the NullPointerException occurs when a method tries to
access a member of an object through a null reference.
// statement 2
}
The statements within the try block may throw an exception. Now, when the exception occurs, it is
trapped by the try block and the runtime looks for a suitable handler to handle the exception. To handle
the exception, the user must specify a catch block within the method that raised the exception or
somewhere higher in the method call stack.
// handling exception
// error message
}
where,
exception-type: Indicates the type of exception that can be handled.
object-name: Object representing the type of exception.
The catch block handles exceptions derived from Throwable class.
Code Snippet 2 demonstrates an example of try with a single catch block.
Code Snippet 2:
package session12;
class Mathematics {
/**
* Divides two integers
* @param num1 an integer variable storing value of first number
* @param num2 an integer variable storing value of second number
* @return void
*/
Concepts
/**
* Define the TestMath.java class
*/
public class TestMath {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// Check the number of command line arguments
if(args.length==2) {
// Instantiate the Mathematics class
Mathematics objMath = new Mathematics();
// Invoke the divide(int,int) method
Concepts
objMath.divide(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
}
else {
System.out.println(Usage: java Mathematics <number1> <number2>);
}
}
}
The class Mathematics consists of one method named divide() that accepts two integers as
parameters and prints the value after division on the screen. However, it is clear that the statement
num1/num2 might raise an error if the user specifies zero for the denominator num2. Therefore, the
statement is enclosed within the try block. Division being an arithmetic operation, the user can create
an appropriate catch block with ArithmeticException class object.
Within the catch block, the ArithmeticException class object e is used to invoke the getMessage()
method that will print the detail about the error. The main() method is defined in the TestMath class.
Within the main() method, the object of Mathematics class is created to invoke the divide() method
with the parameters specified by the user at command line.
Figure 12.3 shows the output of the program when user specifies 12 as numerator and 0 as
denominator.
Figure 12.4 shows the execution of the code when try-catch block is not provided.
The throw clause requires an argument of Throwable instance and raises checked or unchecked
exceptions in a method. Code Snippet 3 demonstrates the modified class Mathematics now using
throw and throws keywords for handling exceptions.
Code Snippet 3:
package session12;
class Mathematics {
/**
* Divides two integers, throws ArithmeticException
* @param num1 an integer variable storing value of first number
* @param num2 an integer variable storing value of second number
* @return void
*/
public void divide(int num1, int num2) throws ArithmeticException
{
// Check the value of num2
if(num2==0) {
/**
* Define the TestMath.java class
*/
public class TestMath {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
else{
The method divide(int,int) now includes the throws clause that informs the calling method that
divide(int,int) may throw an ArithmeticException. Within divide(int,int), the code
checks for the value of num2. If it is equal to zero, it creates an instance of ArithmeticException
using the new keyword with the error message as an argument. The throw keyword throws the instance
to the caller.
Within the main() method, an instance, objMath is used to invoke the divide(int,int) method.
However, this time, the code is written within the try block since divide(int,int) may throw an
ArithmeticException that the main() method will have to handle within its catch block.
Figure 12.6 shows the output of the program when user specifies 12 as numerator and 0 as
denominator.
Concepts
Figure 12.7 shows the execution of the code when throw and throws clauses are used.
In this case, each catch block is an exception handler that handles a specific type of exception indicated
by its argument exception-type. The catch block consists of the code that must be executed if and when
the exception handler is invoked.
The runtime system invokes the handler in the call stack whose exception-type matches the type of the
exception thrown. Code Snippet 4 demonstrates the use of multiple catch blocks.
Code Snippet 4:
package session12;
public class Calculate {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
The class Calculate consists of the main() method. Within main() method, the try block performs
division of two values specified by the user. As seen earlier, the division may lead to a divide-by-zero error.
Therefore, a corresponding catch block that handles ArithmeticException has been created.
However, one can identify another type of exception also that might be raised, that is,
NumberFormatException. This may happen if the user specifies a string instead of a number that
cannot be converted to integer using Integer.parseInt() method. Therefore, another catch block
to handle the NumberFormatException has been specified.
Notice that the last catch block with Exception class handles any other exception that might occur in
the code. Since, Exception class is the parent of all exceptions, it must be used in the last catch block.
If Exception class is used with the first catch block, it will handle all the exceptions and the other
catch blocks, that is, ArithmeticException and NumberFormatException blocks will never be
invoked. In other words, when multiple catch blocks are used, catch blocks with exception subclasses
must be placed before the super classes, otherwise the super class exception will catch exceptions of the
same class as well as its subclasses. Consequently, catch blocks with exception subclasses will never be
reached.
Figure 12.8 shows the output of the code when user specifies 12 and 0 as arguments.
Concepts
Figure 12.9 shows the output of the code when user specifies 12 and zero as arguments.
The finally block is mainly used as a tool to prevent resource leaks. Tasks such as closing a file and
network connection, closing input-output streams, or recovering resources, must be done in a finally
block to ensure that a resource is recovered even if an exception occurs.
However, if due to some reason, the JVM exits while executing the try or catch block, then the finally
block may not execute. Similarly, if a thread executing the try or catch block gets interrupted or killed,
the finally block may not execute even though the application continues to execute. The syntax for
declaring try-catch blocks with a finally block is as follows:
Syntax:
try
{
// statements that may raise exception
// statement 1
// statement 2
}
catch(<exception-type> <object-name>)
{
// handling exception
// error message
}
finally
{
// clean-up code
// statement 1
// statement 2
}
Code Snippet 5 demonstrates the modified class Calculate using the finally block.
Code Snippet 5:
package session12;
Concepts
/**
* @param args the command line arguments
*/
try {
int num3 = Integer.parseInt(args[0])/ Integer.parseInt(args[1]);
System.out.println(Division is: +num3);
}
catch (ArithmeticException e) {
System.out.println(Error: + e.getMessage());
}
catch (NumberFormatException e) {
System.out.println(Error: Required Integer found String: +
e.getMessage());
}
catch (Exception e) {
System.out.println(Error: + e.getMessage());
}
finally {
// Write the clean-up code for closing files, streams, and network
//connections
System.out.println(Executing Cleanup Code. Please Wait...);
System.out.println(All resources closed.);
}
}
else {
System.out.println(Usage: java Calculate <number1> <number2>);
Concepts
}
}
}
Within the class Calculate, finally block is included after the last catch block. In this case, even
if an exception occurs in the code, the finally block statements will be executed. Figure 12.11 shows
the output of the code after using finally block when user passes 12 and zero as command line
arguments.
The try statement must be followed by at least one catch or a finally block.
Use the throw statement to throw an exception that a method does not handle by itself along
with the throws clause in the method declaration.
The Exception subclasses should be used when the caller of the method is expected to handle
the exception. The compiler will raise an error message if the caller does not handle the exception.
Provide appropriate message along with the default message when an exception occurs. All
necessary data must be passed to the constructor of the exception class which can be helpful to
understand and solve the problem.
Try to handle the exception as near to the source code as possible. If the caller can perform the
corrective action, the condition must be rectified there itself. Propagating the exception further
away from the source leads to difficulty in tracing the source of the exception.
Exceptions should not be used to indicate normal branching conditions that may alter the flow of
code invocation. For example, a method that is designed to return a zero, one, or an object can be
modified to return null instead of raising an exception when it does not return any of the
specified values. However, a disconnected database is a critical situation for which no alternative
can be provided. In such a case, exception must be raised.
Concepts
Repeated re-throwing of the same exception must be avoided as it may slow down programs that
are known for frequently raising exceptions.
Avoid writing an empty catch block as it will not inform anything to the user and it gives the
impression that the program failed for unknown reasons.
(A) a, d (C) b, c
(B) a, b (D) b, d
Concepts
Exception Description
(A) a-2, b-4, c-1, d-3 (C) a-2, b-3, c-4, d-1
(B) a-4, b-1, c-3, d-2 (D) a-3, b-4, c-1, d-2
What will be the output of the code when user passes B001, Thriller, and James-Hadley
as the command line arguments?
java.lang.
(A) Compilation Error (C) ArrayIndexOutOfBoundsException
5. Identify the method of Exception class that returns the result of getMessage() along with the
name of the exception class concatenated to it.
Concepts
12.5.1 Answers
1. B
2. B
3. D
4. C
5. D
6. A
Concepts
Summary
An exception is an event or an abnormal condition in a program occurring during execution of a
program that leads to disruption of the normal flow of the program instructions.
The process of creating an exception object and passing it to the runtime system is termed as
throwing an exception.
An appropriate exception handler is one that handles the same type of exception as the one
thrown by the method.
Checked exceptions are exceptions that a well-written application must anticipate and provide
methods to recover from.
Errors are exceptions that are external to the application and the application usually cannot
anticipate or recover from errors.
Runtime Exceptions are exceptions that are internal to the application from which the application
usually cannot anticipate or recover from.
Throwable class is the base class of all the exception classes and has two direct subclasses namely,
Exception and Error.
The try block is a block of code which might raise an exception and catch block is a block of code
used to handle a particular type of exception.
The user can associate multiple exception handlers with a try block by providing more than one
catch blocks directly after the try block.
Java provides the throw and throws keywords to explicitly raise an exception in the main()
method.
Java provides the finally block to ensure execution of cleanup code even when an exception
occurs.
Concepts
Try it Yourself
1. Data Informatics Ltd. is a well-known business outsourcing company located in New Jersey, USA.
The company hires workforce for data entry projects. Recently, the company has created its own
data entry software. However, the software is not functioning properly. The software does not check
the number of values the user is entering nor provides appropriate message to the user if some
functionality is not working and simply terminates the application.
The company has hired a developer to fix the issue. The developer has created the following sample
code to handle ArithmeticException and ArrayIndexOutOfBounds exceptions.
public class Tester {
int perGrace=grace*100/sum;
System.out.println(Sum is:+sum);
System.out.println(Percentage grace is:+perGrace);
}
catch(Exception ex) {
Concepts
System.out.println(Error in code);
}
catch(ArithmeticException ex) {
System.out.println(Division by zero);
}
catch(ArrayIndexOutOfBoundsException ex) {
System.out.println(Unreachable array index);
}
}
}
However, the code is not functioning properly and showing the error java.lang.
ArithmeticException has already been caught. Fix the code to handle the
ArrayIndexOutOfBoundsException when user passes 3, 4, and 5 as command line arguments
and display the following message:
Unreachable array index
Concepts