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

Fundamental Programming in Java - Trainer's Guide

java programming fundamentals

Uploaded by

Prince Alu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
403 views

Fundamental Programming in Java - Trainer's Guide

java programming fundamentals

Uploaded by

Prince Alu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 553

y

nl
O
se
Fundamental Programming
rU
in Java
te
en
C
h
ec
pt
rA
Fo
Fundamental Programming
in Java
Trainer’s Guide

y
nl
O
© 2016 Aptech Limited

se
All rights reserved.

rU
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
te
or transferred without the prior written permission of copyright owner Aptech Limited.
en

All trademarks acknowledged.

APTECH LIMITED
C

Contact E-mail: ov-support@onlinevarsity.com


h
ec
pt
rA

First Edition - 2016


Fo

y
nl

O
A little learning is a dangerous thing,

se
but a lot of ignorance is just as bad.
rU
te
en
C
h
ec
pt
rA
Fo
Preface
The book ‘Fundamental Programming in Java’ Trainer’s Guide aims to teach the basics of Java
programming language. The book teaches the various Java features and development of Java
applications based on object-oriented programming methodology. The book also teaches the
enhancements in the Java Standard Edition (Java SE) version 8.

The faculty/trainer should teach the concepts in the theory class using the slides. This Trainer’s
Guide will provide guidance on the flow of the session and also provide tips and additional

y
examples wherever necessary. The trainer can ask questions to make the session interactive and

nl
also to test the understanding of the students.

O
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

se
part of the ISO 9001 Certification for Aptech-IT Division, Education Support Services. As part of
Aptech’s quality drive, this team does intensive research and curriculum enrichment to keep it in
line with industry trends.

We will be glad to receive your suggestions.


rU
te
Design Team
en
C
h
ec
pt
rA
Fo
“ Practice is the best of

all instructors.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
Table of Contents

Sessions
1. Introduction to Java

2. Application Development in Java

y
3. Variables and Operators

nl
4. Decision-Making Constructs

O
5. Looping Constructs

se
6. Classes and Objects

7. Methods and Access Specifiers

8. Arrays and Strings rU


9. Modifiers and Packages
te
10. Inheritance and Polymorphism
en

11. Interfaces and Nested Classes


C

12. Exceptions

13. New Date and Time API


h
ec

14. Annotations and Base64 Encoding

15. Functional Programming in Java


pt

16. Stream API


rA

17. More on Functional Programming

18. Additional Features of Java 8


Fo


y
The future depends on what

nl
O
we do in the present.

se
rU
te
en
C
h
ec
pt
rA
Fo
Introduction to Java

Session 1 – Introduction to Java

1.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

1.1.1 Objectives
By the end of this session, the learners will be able to:

y
 Explain the structured programming paradigm

nl
 Explain the object-oriented programming paradigm
 Explain the features of Java as a OOP language

O
 Describe Java platform and its components
 List the different editions of Java

se
 Explain the evolution of Java Standard Edition (Java SE)
 Describe the steps for downloading and installing Java Development Kit (JDK)

1.1.2 Teaching Skills rU


To teach this session, you should be well-versed with object-oriented paradigm which is used as a
te
solution to develop applications that are modeled to real world entities called objects and classes.
Also, you should be aware with Java which is an Object-Oriented Programming Language (OOP) to
en

develop platform independent applications.

You should teach the concepts in the theory class using the images provided. For teaching in the
C

class, you are expected to use slides and LCD projectors.


h

Tips:
ec

It is recommended that you test the understanding of the students by asking questions in between
the class.
pt

In-Class Activities:
Follow the order given here during In-Class activities.
rA
Fo

©Aptech Limited
Introduction to Java

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
Tell the students that this session introduces them to Java as an OOP language as well as a platform
for executing Java applications. This session introduces them to the features of OOP language. They

rU
will understand the two most important entities of OOP namely class and object which form the
base for application designing in OOP languages. Further, the session explains them about the
different editions of Java and components of Java Development Kit. Finally, they will learn how to
install JDK and set its path on the system.
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

1.2 In-Class Explanations


Slide 3
Let us understand software applications in computers.

y
nl
O
Using slide 3, explain the use of software development as a solution in information technology.

se
The process of problem solving using computers is complex and needs a proper planning and logical
thinking. The solution adopted to solve a problem is provided as a sequence of instructions or

rU
specifications of activity which enables a user to achieve the desired result.

Software Applications
The solution for solving a problem in the field of information technology is achieved by developing
te
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.
en

Discuss with the students about the different types of high-level programming languages and their
features in developing software applications. During discussion, you can provide examples of
C

different languages used for application development for different purposes. For example, to
develop a Web site, you work with Web languages, such as HTML, JavaScript, PHP, or JSP. To
h

develop a Product-Order form to be executed on Windows platform, you can use Visual Basic as it
ec

provided rich user interface controls such as text boxes, command buttons, check boxes, and so on.
To develop compilers or driver software for the devices, C language is preferred.
pt

Similarly, Java is a fundamental object-oriented programming language used for developing


applications that can be executed on any platform.
rA
Fo

©Aptech Limited
Introduction to Java

In-Class Question:
After you finish explaining, the concept of software applications, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.

Mention some of the examples where C language can be used?

Answer:
 Operating systems
 Compilers

y
 Text editors

nl
 Network drivers
 Utility programs

O
Slide 4

se
Let us discuss on domain and its knowledge in application development.

rU
te
en
C
h
ec

Using slide 4, explain the knowledge of domain.

Domain plays an important role while developing software applications. It can be defined as the field
pt

of business or technology to which a problem belongs. For example, in ordering the food from a
restaurant, the knowledge of all the restaurants in nearby area forms the domain knowledge.
rA

Domain – Restaurant.
Domain knowledge - Type of food served.
Fo

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.

Similarly, explain another scenario for domain and its knowledge to the students. Tell them about
the different processes in bank related to accounts, customer, payments, and so on.

©Aptech Limited
Introduction to Java

The software application developed to handle the bank operations based on the domain needs will
be the solution.

Slide 5
Let us understand on different programming language paradigms.

y
nl
O
se
Using slide 5, explain the use of programming languages and their programming style or
methodology to develop an application.

rU
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. They enforce a
particular style or approach to be followed while application development referred to as a
te
programming paradigm.
en

Normally, there are two types of programming paradigms:


 Structured programming paradigm
 Object-oriented programming paradigm
C

Tell them earlier programming language such as C, Pascal, and COBOL followed structured
h

programming paradigm where application development is decomposed into hierarchy of sub-


programs.
ec

The modern programming languages such as Smalltalk, Java, .Net languages such as C# are based on
object-oriented paradigm or methodology. The object-oriented methodology enables application
pt

designers and developers to think in terms of objects. For example, in the banking domain, each
entity such as customer, account, or so on are the objects similar to real-world objects.
rA

Tips:
All object-oriented programming languages, such as C++ use the concepts of class and objects.
Fo

©Aptech Limited
Introduction to Java

Slides 6 and 7
Let us understand structured programming paradigm and its use.

y
nl
O
se
rU
te
en
C

Using slides 6 and 7, explain structured programming paradigm.


h
ec

A software application developed as a solution can break the problem into smaller tasks which can
be developed separately and then assembled to solve a particular problem. Example, suppose you
want to design a loan calculator for the banking domain which will help its customers to get the loan
pt

amount and its interest rate to be paid by him. Each task in developing the loan calculator can be
divided into modules or procedures or function, based on which structured language is used for
rA

developing the application.

Structured Programming
Fo

Structured programming paradigm aimed on improving the clarity, quality, and development time of
computer program by making extensive use of sub-routines and block structures. It mainly used to
solve complex problems, however, it had paid very less attention on how data is used between the
sub-routines. Efficiency of programs is measured on time and memory occupancy. The application
development is decomposed into a hierarchy of subprograms. The subprograms are referred to as
procedures, functions, or modules in different structured programming languages.

Each subprogram is defined to perform a specific task. Some of structured programming languages
are C, Pascal, and COBOL.

©Aptech Limited
Introduction to Java

Main disadvantage of structured programming languages are as follows:


 Data is shared globally between the subprograms.
 Efforts are spent on accomplishing the solution rather than focusing on problem
domain.
This often led to a software crisis, as the maintenance cost of complex applications became high and
availability of reliable software was reduced.

Slides 8 to 11
Let us understand object-oriented programming paradigm and its features.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

y
nl
O
se
rU
te
en
C
h
ec

Using slides 8 to 11, explain the object-oriented programming paradigm and its features.

Object-oriented programming paradigm represents the concept of objects that have data fields and
pt

associated procedures known as methods. It is an approach to design modular, reusable software


components. It integrates code and data by using the concept of object. Growing complexity of
rA

software required change in programming style. Some of the features that were aimed are as
follows:
 Development of reliable software at reduced cost.
Fo

 Reduction in the maintenance cost.


 Development of reusable software components.
 Completion of software development with the specified time interval.

These features resulted in the evolution of object-oriented programming paradigm.

The software applications developed using object-oriented programming paradigm is designed


around data, rather than focusing only on the functionalities.

©Aptech Limited
Introduction to Java

There are different types of activities involved in the object-oriented software development. They
are: object-oriented analysis, object-oriented design, and object-oriented programming.
• Object-oriented Analysis (OOA) phase determines the functionality of the system.
• Object-oriented Design (OOD) phases determine the process of planning a system in which
objects interact with each other to solve a software problem.
• Object-oriented Programming (OOP) deals with the actual implementation of the
application.

Unified Modeling Language (UML) helps to create visual models in the system, while performing the
analysis of the OOP project. The actual implementation of these visual models is done using an OOP
language.

y
Then, explain the features of OOP languages which are based on certain principles that are as

nl
follows:
 Object – Represents an entity which possesses certain features and behaviors.

O
 Class – Is a template that is used to create objects of that class.
 Abstraction – Is a design technique that focuses only on the essential features of an entity

se
for a specific problem domain.
 Encapsulation – It refers to the creation of self-contained module that binds processing
functions to the data. It is a mechanism that combines data and implementation details into
a single unit called class.
rU
 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.
te
 Polymorphism – Is the ability of an object to respond to same message in different ways.
en

In-Class Question:
After you finish explaining Object-oriented programming paradigm, you will ask the students an In-
Class question. This will help you in reviewing their understanding of the topic.
C
h
ec

What is known as abstraction?


Answer:
pt

An abstraction is a design technique that focuses only on the essential features of an entity based on
the problem domain. It helps the designer to focus only on the necessary features of the object
rA

relevant to its domain.


Fo

©Aptech Limited
Introduction to Java

Slides 12 to 15
Let us understand concept of an object.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

y
nl
Using slides 12 to 15, explain the concept of object and its anatomy.

O
An object represents a real-world entity. Any tangible or touchable entity in the real-world can be
described as an object. In object-oriented programming paradigm an object refers to a particular

se
instance of class where it can be combination of variables, functions, and data structures.

Each object has:

rU
• Characteristics – Defined as attributes, properties, or features describing the object.
• Actions – Defined as activities or operations performed by the object.
te
The concept of objects in the real-world can be extended to the programming world where software
‘objects’ can be defined. Software object has state and behavior.
en

• ‘State’ refers to object’s characteristics or attributes.


• ‘Behavior’ of the software object comprises its actions.
C

The advantages of using objects are as follows:


• They help to understand the real-world.
• They map attributes and actions of real-world entities with state and behavior of
h

software objects.
ec

• A program can carry out various tasks such as implementing GUI, sending, and
receiving information over network.
pt

In the real-world, several objects have common state and behavior. For Example: all car objects have
attributes, such as color, make, or model.
rA

In-Class Question:
After you finish explaining, the concept of software object, you will ask the students an In-Class
Fo

question. This will help you in reviewing their understanding of the topic.

Identify some of the real-world objects around you.

Answer:
Desk, Books, Pen, and so on.

©Aptech Limited
Introduction to Java

Slides 16 to 18
Let us understand designing a class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 16 to 18, explain the class design and its members.

©Aptech Limited
Introduction to Java

Several objects having common state and behavior and can be grouped under a single class. For
example, the class Car can be a general class with many features, whereas Toyota Car is an object of
the class which is specific in features.

Tell the students that a class is a template which defines the state and behavior for all objects
belonging to that class. A class comprises fields and methods which can be mapped to state and
behavior respectively. These fields and methods are collectively known as members of a class.

 Fields – Are variables that depict the state of objects. There is one field for each object of a
class.
 Methods – Are functions that depict the behavior of objects.

y
nl
Tell the students that the class is a conceptual model, is used for describing an entity and consists
of fields and methods. On the other hand, an object is a real thing, it is an actual entity, and it is an

O
instance of a class.

Tips:

se
A class is a general concept whereas an object is a specific embodiment of that class and has a
limited lifespan. A class provides the template for something more specific that the programmer
has to define.

Slide 19
Let us understand Java.
rU
te
en
C
h
ec
pt
rA

Using slide 19, explain the Java programming language.


Fo

Java is object-oriented programming language which is specifically designed to have implementation


dependencies as possible. It is one of the most popular OOP languages. It helps programmers to
develop wide range of applications that can run on various hardware and Operating System (OS). It
is also a platform that creates an environment for executing Java application.

Java caters the need of small-scale to large-scale business problems across the Internet. It is
compiled to byte code and most popular for the client-server Web applications.

©Aptech Limited
Introduction to Java

Java applications are built on variety of platforms that range from:


• Embedded devices to desktop applications
• Web applications to mobile phones
• Large business applications to supercomputers

Java platform is a name for bundle of programs that allow developing and running programs in Java
programming language.

Slides 20 to 22
Let us understand history of Java.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

y
nl
O
Using slides 20 to 22, describe the history of Java.

se
Java Origins: Embedded Systems
 1991

rU
Mention that in the period from 1991–1994, the basic objective behind the development of
the language, was to create software that could be embedded in consumer electronics. In C
and C++, different compilers were required for a particular CPU which was expensive. Thus,
te
efforts were made to develop a portable, platform independent language that could run on
different CPUs under different environments. Team included: James Gosling, Mike Sheridan,
and Patrick Naughton. Efforts were taken to produce portable and a platform independent
en

language that can run on any machine. Result was evolution of Java. Initially called ‘OAK’ and
later renamed to Java.
C

Java Wonder: Internet


 1995
h

Sun Microsystems releases the first implementation as Java. Internet and Web started
ec

emerging and was used worldwide. Sun Microsystems turned Java into an Internet
programming language. It emerged as a Web technology that added dynamic capabilities to
the Web pages. Later, Java became an ideal software for network computers.
pt

Java Moved: Middle-tier


rA

Later, that is in late 90’s, Sun introduced middle-tier capabilities to Java to ensure that it runs on
Web/Application servers. In 1999, Sun offered middle-tier solution for Java called Java 2 Enterprise
Edition, also known as J2EE.
Fo

 1997
Sun Microsystems defined Servlets API to generate dynamic HTML for Web pages and
Enterprise JavaBeans for developing business logics.

 2006
Sun Microsystems released three versions for free under General Public License (GPL). These
are: Java Platform, Standard Edition (Java SE), Java Platform, Enterprise Edition (Java EE),
and Java Platform Micro Edition (Java ME).

©Aptech Limited
Introduction to Java

Java Ahead: Acquisition


 2009
Sun Microsystems was acquired by Oracle Corporation. The project Coin was launched to
enhance Java programming language. Java EE 6 was released with simplified development
and deployment model.
 2010
The specification for Java 7 was approved by the Java Community Process (JCP). Java
software runs on everything from laptops to data centers and game consoles.

In-Class Question:
After you finish explaining history of Java, you will ask the students an In-Class question. This will

y
help you in reviewing their understanding of the topic.

nl
O
Why was servlets API defined by Sun Microsystems?

se
Answer:
It was defined to generate dynamic HTML for Web pages and Enterprise JavaBeans for developing
business logics.

Slides 23 to 27
rU
Let us understand the features of Java language.
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

y
nl
O
se
Using slides 23 to 27, explain the features of Java language.

become a popular programming language. rU


Explain the features of Java programming language. Tell them these features have helped Java to

Mention that Java besides providing a platform-independent environment is also a high level
te
programming language. Tell the students that Java is purely object-oriented language and has no
standalone constants, variables, or functions. All of these are accessed through classes and objects.
en

Explain to the students that 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
C

development in Java starts with a class designing.


h

Next, inform the students that Java is platform-independent which means the same Java code can
be executed on any platform. Java achieves platform-independence by using bytecode.
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

You can explain the execution of same bytecode with different implementations of JVM on various
platforms with the help of following figure (draw simplified version of the figure).

y
nl
O
se
Then, tell the students that it is designed for writing highly reliable or robust software. It requires

rU
explicit method declaration and checks for syntax error at the time of compilation, and also at the
time of interpretation. Java does not support pointers and pointer arithmetic.

Next, explain the security features of Java. Java provides a controlled environment for the execution
te
of the program. It never assumes that the code is safe for execution. Java is secured and provides
several layers of security control. In the first layer, the data and methods are accessed through
en

interfaces that the class provides. In the second layer, the compiler ensures that the code is safe and
follows the protocols set by Java before compiling the code. The third layer is safety and is provided
by the interpreter. The fourth layer loads the class and ensures that the class does not violate the
C

access restrictions, before loading it into the system.


h

Mention that Java is used for developing applications that are portable across multiple platforms,
ec

operating systems, and graphical user interfaces.

Next, explain to the students that since Java supports multi-threading, an application can perform
pt

multiple tasks. For example, in a Word application program, a user can type the content at the same
time, the Word application performs spell-check for the typed content. Thus, Word application can
rA

perform multiple tasks at the same time.

Multithreading allows a single program having different threads to be executed independently at the
Fo

same time. It is easy to work with threads in Java as it has built-in language support. Threads are also
known as light-weight processes. Each thread runs independently without disturbing the execution
of other threads.

Java is a dynamic language designed to adapt to an evolving environment. Tell them that Java
programs are compiled to an architecture neutral bytecode format to transport the code efficiently
to multiple hardware and software platforms. Bring to the notice of the students that Java
technology takes portability, a stage further, by explicitly specifying the size of its basic data types to
eliminate implementation dependence.

©Aptech Limited
Introduction to Java

Lastly, explain to the students that Java is high-performance. Compared to those high-level, fully-
interpreted scripting languages, Java is high-performance. The automatic garbage collector runs as a
low-priority background thread, ensuring a high probability.

In-Class Question:
After you finish explaining, the features of Java, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.

Which is the feature that allows a single program having different threads to be executed

y
independently at the same time?

nl
Answer:

O
Multithreading.

se
Slide 28
Let us understand Java platform.

rU
te
en
C
h
ec
pt
rA

Using slide 28, explain the Java platform.

Java is portable which means computer program written in Java must run on any hardware-based
Fo

platforms or operating systems. The platform is not specific to any one processor, but it is an
execution engine called virtual machine and compiler with a set of libraries. It is a software-only
platform that runs on top of other hardware-based platforms. It contains Java Runtime Environment
(JRE) with components namely:

 Java Virtual Machine (JVM)


 Java class library also referred to as Java Programming Interface (Java API)

©Aptech Limited
Introduction to Java

Slides 29 and 30
Let us understand Java Virtual Machine (JVM).

y
nl
O
se
rU
te
en
C
h
ec

Using slides 29 and 30, explain the working of JVM.


pt

Explain to the students that JVM is the heart of Java programming language. Mention to them that
rA

the Java environment consists of five elements namely, Java language, bytecode definitions,
Java/Sun libraries, JVM, and structure of .class files.
Fo

Tell the students that the portability feature of .class file helps the execution of the class files on any
computer or chip set having an implementation of the JVM. Mention that the virtual machine is
based on the idea of an imaginary computer which has a set of instructions. These instructions
define the operations of the imaginary computer.

JVM is a processed virtual machine that can execute Java byte code. It is an executable engine that
creates an environment for Java compiled code, that is, byte code. It is a code execution component
for Java platform. It is known as a virtual machine because it is an imitation of a Java processor on
the physical machine. JVM can be used to implement interpreters for dynamic languages. There are
different implementations of JVM available for different platforms, such as Windows, UNIX, and
Solaris.

©Aptech Limited
Introduction to Java

Bytecode:
It is an intermediate form closer to machine representation. It is an optimized set of instructions
executed by the Java runtime environment. Each byte code is comprised of one or two bytes that
represent instructions. This environment is known as JVM. The same byte code can be executed by
different implementations of JVM on various platforms.

Mention that it forms a layer of abstraction for the underlying hardware platform, operating system,
and compiled code. Also mention that different versions of JVMs are available for different operating
systems.

In-Class Question:

y
After you finish explaining Java Virtual Machine (JVM), you will ask the students an In-Class question.

nl
This will help you in reviewing their understanding of the topic.

O
se
Why Java Virtual Machine (JVM) is known as virtual machine?
Answer:

machine.

Tips:
rU
JVM is known as virtual machine because it is an imitation of a Java processor on the physical
te
JVM is included with a Java interpreter and Just In Time (JIT) compiler. JIT comes with virtual
en

machine and is used optionally. Sun Microsystems, suggest that, it is usually faster to select the JIT
compiler option, especially if the method executable is used repeatedly.
C

JIT’s main purpose is to convert the bytecode instruction set to machine code instructions targeted
for a particular microprocessor. These instructions are stored and used, whenever a call is made to a
h

particular method.
ec

Bring to the notice of the students that once the code has been recompiled by the JIT compiler, it
will usually run more quickly in the computer.
pt
rA
Fo

©Aptech Limited
Introduction to Java

Slide 31
Let us understand Java API.

y
nl
O
se
Using slide 31, explain the Java APIs.

rU
Java API is a set of classes included with the Java development environment. It is a large collection of
ready-made software components. These components are classes and interface grouped into
libraries referred to as packages in Java.
te
Some of the examples of Java API are as follows:
• The Swing library provides classes for User Interface (UI) components.
en

• The Input/Output (I/O) library provides the standard interface for reading and writing data into
files stored in the system.
• The network library to read and write the data on the sockets.
C

• The collection library to store the objects in the collection, such as linked list, set, or as a map.
h

Tips:
ec

There are three types of Java API:


 Official core Java API: It contains JDK and JRE.
 Optional official API: They can be downloaded separately.
pt

 Unofficial API: They are developed by third parties. For example, NetBeans platform.
rA

In-Class Question:
After you finish explaining Java APIs, you will ask the students an In-Class question. This will help you
in reviewing their understanding of the topic.
Fo

What are the components of Java API?


Answer:
An Application Programming Interface (API), in the context of Java, is a collection of prewritten
packages, classes, and interfaces with their respective methods, fields, and constructors. Similar to a
user interface, which facilitates interaction between humans and computers, an API serves as a
software program interface facilitating interaction.

©Aptech Limited
Introduction to Java

Slide 32
Let us understand editions of Java.

y
nl
O
se
Using slide 32, explain the editions of Java.

Java Standard Edition (Java SE) – It is a widely used platform for development and deployment of
rU
portable applications for desktop and server environment. It is a base platform and enables to
develop console and networking applications for desktop computers. It is a platform specification.
Java Enterprise Edition (Java EE) – It provides an API and run time environment for developing and
te
running enterprise software including network and Web services. It is built on top of Java SE
platform and provides a standard specification for developing and deploying distributed, scalable,
en

and multi-tier enterprise applications.


Java Mobile Edition (Java ME) - Is a robust platform for developing embedded Java applications for
consumer electronic devices, such as mobiles, Personal Digital Assistants (PDAs), and TV set-top
C

boxes.
h

Slides 33 and 34
Let us understand components of Java SE platform.
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

y
nl
O
Using slides 33 and 34, explain the components of Java SE platform.

se
There are two software components of Java SE platform:

JRE

rU
JRE provides JVM and Java libraries that are used to run a Java program. JRE is part of the Java
Development Kit (JDK), but can be downloaded separately. JRE was originally developed by Sun
Microsystems Inc., a wholly-owned subsidiary of Oracle Corporation. It is also known as Java
te
runtime.
en

JDK
It is known as Java Development Kit (JDK). It includes JRE and command line development tools such
as compilers and debuggers that are necessary for developing applications. It is a binary software
C

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

It contains a comprehensive set of tools, such as compilers and debuggers that are used to develop
ec

Java applications.

Description of some of these tools is as follows:


pt

 Development Tools – Include tools used for compiling, running, debugging, and
documenting a Java application.
rA

 API - Provides the core functionality of the Java programming language.


 Deployment Tools – Provides software for deploying the developed applications to end-
users.
Fo

 User Interface Toolkits - Enables the developer to create graphical interfaces in a Java
application.
 Integration libraries - Enable developers to access and manipulate database and remote
objects in an application.

©Aptech Limited
Introduction to Java

Slide 35
Let us understand evolution of Java.

y
nl
O
se
Using slide 35, explain the evolution of Java.

rU
The Java language has undergone several changes since JDK 1.0 and various additions of classes and
packages to the standard libraries.
te
Explain the features and improvements of different JDK versions as listed in the slide.

Slide 36
en

Let us understand Java SE 7.


C
h
ec
pt
rA
Fo

Using slide 36, explain the features of Java SE 7.

Java SE 7 is the new major release of Java with internal version number as 1.7. It includes JVM
support for dynamic languages.

The lists of new features that are incorporated in the language are as follows:
• Supports the use of String class in the switch decision-making construct.
• Integer types can be assigned with a binary number value.

©Aptech Limited
Introduction to Java

• Supports the use of underscore character (_) between the digits of a numeric value.
• An expandable try statement called try-with-resources statement used for automatic
resource management.
• Constructor of a generic class declaration can be replaced with an empty set of parameters
(<>).
• Enhancement in exception handling mechanism. In exception handling code, a single catch
can be used to handle one or more exceptions.
• Compiler warnings generated for varargs methods has been improved.

Tips:

y
Check the following link for examples on each of the features added in Java SE 7:
http://radar.oreilly.com/2011/09/java7-features.html.

nl
O
Slides 37 to 42
Let us understand downloading and installing of JDK on Windows system.

se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Introduction to Java

y
nl
Using slides 37 to 42, explain the steps to download and install JDK.

O
Explain the steps presented on slides 37 to 41 on downloading and installing JDK on the Windows

se
system.

Then, explain the created directory structure of JDK within the installed directory listed on slide 42.

Tips: rU
The following figure shows the JDK 1.7 files and directories:
te
en
C
h
ec
pt
rA
Fo

The explanation is as follows:

 /jdk1.7.0 - Root directory of the JDK software installation. Contains copyright, license,
and README files. Also contains src.zip, the archive of source code for the Java platform.

©Aptech Limited
Introduction to Java

 /jdk1.7.0/bin - Executables for all the development tools contained in the JDK.
The PATH environment variable should contain an entry for this directory. For more
information on the tools, see JDK Tools.
 /jdk1.7.0/lib - Files used by the development tools. Includes tools.jar, which
contains non-core classes for support of the tools and utilities in the JDK. Also
includes dt.jar, the DesignTime archive of BeanInfo files that tell interactive development
environments (IDE's) how to display the Java components and how to let the developer
customize them for an application.
 /jdk1.7.0/jre - Root directory of the Java runtime environment used by the JDK
development tools. The runtime environment is an implementation of the Java platform.
This is the directory referred to by the java.home system property.

y
 /jdk1.7.0/jre/bin - Executable files for tools and libraries used by the Java

nl
platform. The executable files are identical to files in /jdk1.7.0/bin. The java launcher
tool serves as an application launcher (and replaced the old jre tool that shipped with 1.1

O
versions of the JDK). This directory does not need to be in the PATH environment variable.
 /jdk1.7.0/jre/lib - Code libraries, property settings, and resource files used by the
Java runtime environment. For example:

se
 rt.jar -- the bootstrap classes (the RunTime classes that comprise the Java platform's
core API).

rU
charsets.jar -- character-conversion classes.
o Aside from the ext subdirectory (described here) there are several additional
resource subdirectories not described here.
 /jdk1.7.0/jre/lib/ext - Default installation directory for Extensions to the Java
te
platform. This is where the JavaHelp jar file goes when it is installed, for example.
 localedata.jar -- locale data for java.text and java.util.
en

 /jdk1.7.0/jre/lib/security - Contains files used for security management.


These include the security policy (java.policy) and -security properties
C

(java.security) files.
 /jdk1.7.0/jre/lib/sparc - Contains the .so (shared object) files used by the
Solaris version of the Java platform.
h

 /jdk1.7.0/jre/lib/sparc/client - Contains the .so file used by the Java


ec

HotSpot™ Client Virtual Machine, which is implemented with Java HotSpot™ technology.
This is the default VM.
 /jdk1.7.0/jre/lib/sparc/server - Contains the .so file used by the Java
pt

HotSpot™ Server Virtual Machine.


 /jdk1.7.0/jre/lib/applet - Jar files containing support classes for applets can be
rA

placed in the lib/applet/ directory. This reduces startup time for large applets by
allowing applet classes to be pre-loaded from the local file system by the applet class loader,
providing the same protections as if they had been downloaded over the net.
Fo

 /jdk1.7.0/jre/lib/fonts - Font files for use by platform.

©Aptech Limited
Introduction to Java

Slides 43 to 45
Let us understand configuring JDK.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 43 to 45, explain the steps to use PATH and CLASSPATH environment variables on
Windows platform.

To work with JDK and Java programs, certain settings need to be made to the environment variables.
Environment variables are pointers pointing to programs or other resources.

©Aptech Limited
Introduction to Java

The variables to be configured are as follows:


• PATH - Set to point to the location of Java executables (javac.exe and java. exe). The
PATH environment variables are a series of directories separated by semicolons (;).
• CLASSPATH - Specifies the location of the class files and libraries needed by the Java compiler
to compile applications. On Windows platform, you can check if the CLASSPATH is set on the
command line using echo %CLASSPATH%.

Then, explain the steps to set the PATH and CLASSPATH variables on Windows 7 as explained
on slides 44 and 45.

Tips:

y
nl
The CLASSPATH can also be specified using the -cp command line switch which allows
the CLASSPATH to be set individually for each application without affecting other applications. The

O
default value of the class path is ".", meaning that only the current directory is searched. Specifying
either the CLASSPATH variable or the -cp command line switch overrides this value.

se
To get more information on the CLASSPATH, read the technical documentation on this link:
http://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpa
th.html.

In-Class Question:
rU
After you finish explaining configuring JDK, you will ask the students an In-Class question. This will
te
help you in reviewing their understanding of the topic.
en

What is CLASSPATH?
C

Answer:
h

It specifies the location of the class files and libraries needed by the Java compiler to compile
ec

applications.
pt
rA
Fo

©Aptech Limited
Introduction to Java

Slides 46 and 47
Let us summarize the session.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 46 and 47, summarize the session. End the session with a brief summary of what has
been taught in the class.
Fo

1.3 Post Class Activities for Faculty


You should familiarize yourself with the topics of the next session which is based on developing Java
applications in NetBeans IDE.

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.

©Aptech Limited
Application Development in Java

Session 2 – Application Development in


Java

2.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.

y
Prepare a question or two which will help you to relate the current session objectives.

nl
2.1.1 Objectives

O
By the end of this session, the learners will be able to:
 Explain the structure of a Java class

se
 List and explain steps to write a Java program
 Identify the benefits of NetBeans IDE



rU
Describe the various elements of NetBeans IDE
Explain the steps to develop, compile, and execute Java program using NetBeans IDE
Explain the various components of JVM
te
 Describe comments in Java
en

2.1.2 Teaching Skills


To teach this session, you should be well-versed with basic structure of designing a class in Java. You
C

have to familiarize yourself with the NetBeans Integrated Development Environment (IDE) and its
components used for developing the Java applications in the course.
h

You should develop and execute a simple Java program in NetBeans IDE to be covered in the session.
ec

Also, comment the code, which will help you to explain the use of comments for Java
documentation.
pt

You should teach the concepts in the theory class using the images provided. For teaching in the
class, you are expected to use slides and LCD projectors.
rA

Tips:
Fo

It is recommended that you test the understanding of the students by asking questions in between
the class.

In-Class Activities:
Follow the order given here during In-Class activities.

©Aptech Limited
Application Development in Java

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
Tell the students that this session introduces the basic structure of Java class and NetBeans

se
integrated development environment (IDE) and its components. Explain the execution of Java
program using NetBeans IDE.

2.2 In-Class Explanations


Slides 3 and 4
rU
Let us understand about the environment used for Java development.
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
Using slides 3 and 4, explain the environment used for Java development.

se
Java helps the programmers to develop wide range of applications that can run on various hardware
and Operating System (OS). Java is a popular OOP language that supports developing applications for
different requirements and domain areas.
rU
Different types of Java applications can be developed using various editors of Java available in the
te
market. Some of the editors include: a simple text editor, such as Notepad, a full equipped
environment with Java development tools such as NetBeans, Eclipse, JCreator, Oracle JDeveloper,
en

and so on. These editors provide necessary tools, such as compiler, debugger, Java runtime
integrated in them to develop Java applications. Hence, they are called as Integrated Development
Environment (IDE).
C

Then, explain the type of applications that can be developed using Java as shown on slide 4.
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

Slides 5 to 9
Let us understand structure of a Java class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
se
rU
te
en
C

Using slides 5 to 9, explain the structure of Java class.


h

The Java program begins with a class design. Everything has to be included inside the class and this
ec

makes code easier to reuse. Java class is like a container which holds codes. The class represents a
template for the objects created or instantiated by the Java runtime environment. The definition of
the class is written in a file and is saved with a .Java extension. In order to compile Java application
pt

successfully, at least one class and one method are required in the project.
rA

Tips:
A class with a main() method is a tester class in which objects can be instantiated. The functional
testing of the methods can be done by invoking them on the object.
Fo

Different parts of the Java class are:


package
Package contains classes and methods. It defines a namespace that stores classes with similar
functionalities in them. The package keyword identifies the name of the package to which the class
belongs and the visibility of the class within the package and outside the package. The concept of
package is similar to folder in the OS. In Java, all classes belong to a package. If the package
statement is not specified, then the class belongs to the default package.
Example: All the user interface classes are grouped in the Java.awt or Java.swing packages.

©Aptech Limited
Application Development in Java

import
It allows specifying the classes from other packages that can be referenced without qualifying them
with their package. It identifies the classes and packages that are used in a Java class. It helps to
narrow down the search performed by the Java compiler by informing it about the classes and
packages.
It is mandatory to import the required classes, before they are used in the Java program. Some
exceptions wherein the use of import statement is not required are as follows:
 If classes are present in the Java.lang package.
 If classes are located in the same package. For example, if a package named accountpack
contains class Account and class Loan. Then, importing the classes is not required.
 If classes are declared and used along with their package name. For example,

y
Java.text.NumberFormat nf = new Java.text. NumberFormat();

nl
class

O
Class keyword identifies a Java class. It precedes the name of the class in the declaration. Public
keyword indicates the access modifier that decides the visibility of the class. Name of a class and file
name should match.

se
Variables
They are also referred to as instance fields or instance variables. They represent the state of objects.

Methods rU
Java programs mostly made up of methods. A main method is where main code of the program is
te
executed. Methods are functions that represent some action to be performed on an object. They are
also referred to as instance methods.
en

Constructors
Constructors are also methods or functions that are invoked during the creation of an object. It is
C

used to initialize the objects. It is a special method in a class which is used to construct an instance of
the class.
h

In-Class Question:
ec

After you finish explaining structure of Java class, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
pt
rA

What does the package contain?


Answer:
Fo

Package contains classes and interfaces.

©Aptech Limited
Application Development in Java

Slide 10
Let us understand developing a Java program on Windows.

y
nl
O
se
Using slide 10, explain the requirements for developing Java programs on Windows platform.

Java is write once, run anywhere language which means that the same Java class can be executed on
any platform containing the JVM.
rU
However, to develop a Java program, the basic requirements are as follows:
te
 The JDK 7 installed and configured on the system.
 A text editor, such as Notepad.
en

Then, explain the steps required to create, compile, and execute a Java program.
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

Slides 11 to 14
Let us understand to create a Java program in the notepad.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
Using slides 11 to 14, explain how to create a Java program in the notepad.

O
To program in Java, user needs a compiler which is a program to convert Java source code to

se
bytecode. Also a Java virtual machine is required which understands Java bytecode and translate
them into machine language. The basic unit of Java program is class. Class is a keyword and
HelloWorld is the name of the class. The entire class definition and its members must be written

rU
within the opening and closing curly braces {}.

The area between the braces is known as the class body and contains the code for that class.
te
• main()- method is the entry point for a Java-based console application. It invokes when Java
program starts from the command line.
en

• 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.
C

• 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. It is not a type in Java. It
represents the absence of a type.
h

• args - Is an array of type String and stores command line arguments. String is a class in Java
ec

and stores group of characters.


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. out is the
pt

output stream connected to the console. The println() is the built-in method of the output
stream that is used to display a string. Save the file as HelloWorld.Java. The file name is same
rA

as class name, as the compilation of a Java code results in a class. Hence, the class name and the file
name should be same.
Fo

In-Class Question:
After you finish explaining the Java program creation, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.

What is the use of void keyword?


Answer:
It is a keyword that represents the data type of the value returned by the main () method.

©Aptech Limited
Application Development in Java

Slides 15 to 18
Let us understand compile .java file.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
Using slides 15 to 18, explain the compilation process in Java.

se
Before the JVM can run a Java program, the program source code can be compiling into bytecode.
Java bytecode is a platform independent version of machine code. Once the Java source code
compiled successfully, user can invoke Java Virtual Machine to run the application byte-code. The

rU
HelloWorld.Java file is known as source code file. It is compiled by invoking tool named
Javac.exe, which compiles the source code into a .class file. The .class file contains the
bytecode which is interpreted by java.exe tool. java.exe interprets the bytecode and runs the
te
program.
en

Explains the lists of the options that can be used with the .Javac command shown on slide 17.

Then, explain the steps to compile the HelloWorld.Java program from the Windows platform
C

on slide 18.

Tips:
h

Check the following site for more information on the Javac command:
ec

http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/win3
2/Javac.html.
pt
rA
Fo

©Aptech Limited
Application Development in Java

Slides 19 to 22
Let us understand to build and execute Java program.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
se
Using slides 19 to 22, explain the process to build and execute the Java program.

rU
Java programs are run or interpret by another program called the Java VM. The JVM is at the heart
of the Java programming language. It is responsible for executing the .class file or bytecode file. The
.class file can be executed on any computer or device that has the JVM implemented on it. The class
te
loader component of JVM loads all the necessary classes from the runtime libraries required for
execution of the compiled bytecode. The bytecode verifier then checks the code to ensure that it
en

adheres to the JVM specification. The bytecode is executed by the interpreter.

To boost the speed of execution, in Java version 2.0, a Hot Spot Just-in-Time (JIT) compiler was
C

included at runtime. During execution, the JIT compiler compiles some of the code into native code
or platform-specific code to boosts the performance. The Java interpreter command, Java is used to
h

interpret and run the Java bytecode. Once the Java source code compiled successfully, user can
ec

invoke Java Virtual Machine to run the application byte-code.

Using slide 22, explain the lists of the options that can be used with the Java command.
pt

Tips:
rA

Check this site for more information on Java command options to execute the Java code:
http://docs.oracle.com/Javase/7/docs/technotes/tools/windows/Java.ht
ml.
Fo

©Aptech Limited
Application Development in Java

Slides 23 to 29
Let us understand NetBeans IDE.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
Using slides 23 to 29, explain the NetBeans IDE.

se
NetBeans is an open-source integrated development environment written purely in Java. It is a free
and robust IDE that helps developers to create cross-platform desktop, Web, and mobile

rU
applications using Java. It is an application platform framework for Java desktop applications and
others. The NetBeans platform allows application to be developed from a set of modular software
components called modules. It contains features such as code completion, code template, and fix
import for faster development.
te
Some of its benefits are as follows:
en

• Provides plug-in modules and supports rich client applications.


• Provides graphical user interface for building, compiling, debugging, and packaging of
C

applications.
• Provides simple and user-friendly IDE configuration.
h

Then, using slides 25 to 29, explain all the NetBeans IDE elements.
ec

Tips:
Some of the tips to work with the source editor in NetBeans IDE are as follows:
pt

 You can right-click into the Source Editor and write code. When you write code this way, editor
automatically highlights code in color as appropriate and as you type, it provides suggestions
rA

for code-completion.
 You can customize colors in the highlighting by going to Tools  Options  Fonts and Colors.
 Code completion finishes package names, classes, interfaces, and common methods. To
Fo

deactivate this feature, press Esc or you can deactivate it from Tools  Options  Editor 
General. Under Code Completion, deselecting the Auto Popup Completion Window checkbox.
 You can also save time by assigning abbreviations that the Source Editor expands for you. To
set, go to Tools  Options  Editor  Code Templates. Type the first few letters of an
abbreviation and press the spacebar. The Source Editor then expands the abbreviation.
 To turn the line numbering, right-click the left sidebar of the Source Editor's and select Show
Line Numbers.
 To add commonly-used code templates for your code, press Ctrl-I in the Source Editor to view
the Insert Code pop-up menu. Add properties to classes, create constructors, generate accessor
methods, and override methods from superclasses.

©Aptech Limited
Application Development in Java

Slides 30 to 34
Let us understand download and install NetBeans IDE.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
se
Using slides 30 to 34, explain the steps to download and install NetBeans IDE.

rU
The latest version of NetBeans IDE for different platforms, such as Windows, Linux, Solaris, and Mac
OS X is available for download at http://netbeans.org/downloads/index.html.
On the NetBeans IDE download Web page, you will find different installers. Each installer of
NetBeans IDE contains the basic IDE and its related tools. The different installers are namely, Java SE,
te
Java EE, C/C++, PHP, All.
en

Then using slides 32, 33, and 34, explain the steps to download the NetBeans IDE 7.1.2.

Slide 35
C

Let us understand writing a Java program using NetBeans IDE.


h
ec
pt
rA
Fo

Using slide 35, explain that the basic requirements to write a Java program using the NetBeans IDE is
as follows:
 The JDK 7 installed and configured on the system – It is a development environment for
developing applications, applets, and components.

©Aptech Limited
Application Development in Java

 The NetBeans IDE - It is an open-source integrated development environment written purely


in Java.

Slides 36 and 37
Let us understand to create a project in IDE.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 36 and 37, explain the steps to create project in NetBeans IDE.

In setting the project, the application created has two projects which are a Java class library
project in which a utility class is created whereas a Java application project with a main class that
implements a method from the library project utility class.

Explain the steps for creating a project in NetBeans IDE.

©Aptech Limited
Application Development in Java

Slide 38
Let us understand how to add code to the generated source files.

y
nl
O
se
Using slide 38, explain to add code to the generated source files.

rU
When creating projects using New project wizard, the Create main class checkbox is selected to
create the project with a skeleton. The necessary skeleton of the program has been created by the
te
IDE.

Using slide 38, explain how to add the statement, System.out.println(), in the
en

HelloMessageApp class. This statement will print the provided string on the console.
C

Tips:
The ‘out’ is a variable. There are two possibilities – it could be a static or an instance variable.
Because ‘out’ is being called with the ‘System’ class name itself, and not an instance of a class (an
h

object), then we know that ‘out’ must be a static variable, since only static variables can be called
ec

with just the class name itself.

So ‘out’ is a static member variable belonging to the System class. It belongs to the
pt

PrintStream class and provides the println() method.


rA
Fo

©Aptech Limited
Application Development in Java

Slides 39 and 40
Let us understand to build and execute Java program in NetBeans IDE.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 39 and 40, explain how to build and execute the Java program in NetBeans IDE.

Explain the steps to build and execute the code in NetBeans IDE. In Build process, the bytecode file is
Fo

generated.

©Aptech Limited
Application Development in Java

Slide 41
Let us understand comments in Java.

y
nl
O
se
Using slide 41, explain comments in Java.
rU
Comments allow inserting text that will not be compiled or interpreted. Comments in Java are
placed in a Java program source file. They are used to document the Java program and are not
te
by the compiler and are added as remarks to make the program more readable for the user. It is
useful to explain the adopted technical choice and to give the required explanations to
en

understand the code.

Comments in Java are of three types:


C

 Single-line comments
 Multi-line comments
 Javadoc comments
h
ec

Slides 42 and 43
Let us understand single-line comments.
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
Using slides 42 and 43, explain the single-line comment.

se
Java single-line comment starts with two forward slashes with no white spaces and lasts till the end
of line. A single-line comment is used to document the functionality of a single line of code. It is

rU
useful to provide short explanations for variables, functions, and expressions.

There are two ways of using single-line comments that are as follows:
 Beginning-of-line comment - This type of comment can be placed before the code (on a
te
different line).
 End-of-line comment - This type of comment is placed at the end of the code (on the same
en

line).
C

Then, explain the conventions for using single-line comments in Java code.

Slide 44
h

Let us understand multi-line comments.


ec
pt
rA
Fo

Using slide 44, explain the multi-line comments.

©Aptech Limited
Application Development in Java

Multi-line Comments is a comment that spans multiple lines. It starts with a forward slash and an
asterisk (/*) and ends with an asterisk and a forward slash (*/). Anything that appears between
these delimiters is considered to be a comment. It is useful when the comment text does not fit in
one line or can be used when the comment need to be inserted in the middle of the code.

In-Class Question:
After you finish explaining the multi-line comments, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.

y
nl
Why multi-line comments are useful?

O
Answer:
Multi-line comments are useful when the comment text does not fit in one line or can be used when
the comment need to be inserted in the middle of the code.

se
Slides 45 and 46
Let us understand Javadoc comments.
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Application Development in Java

y
nl
O
Using slides 45 and 46, explain Javadoc comments.

se
Javadoc comment is used to document public or protected classes, attributes, and methods. Also
to document the API which is developed as a part of source code and kept in source file. It starts

rU
with /** and ends with */. Everything between the delimiters is a comment. The Javadoc
command can be used for generating Javadoc comments. The Javadoc is a tool which comes as a
part of JDK. By using this comment, classes, fields, constructors, and methods are documented.
te
Slides 47
en

Let us summarize the session.


C
h
ec
pt
rA
Fo

In slide 47, you will summarize the session. End the session with a brief summary of what has been
taught in the session.

©Aptech Limited
Application Development in Java

2.3 Post Class Activities for Faculty


You should familiarize yourself with the topics of the next session that is based on how to deal with
variables and operators in Java.

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

Session 3 – Variables and Operators

3.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
3.1.1 Objectives

nl
By the end of this session, the learners will be able to:

O
 Explain variables and their purpose
 State the syntax of variable declaration

se
 Explain the rules and conventions for naming variables
 Explain data types



Describe escape sequence
Describe format specifiers
rU
Describe primitive and reference data types
te
 Identify and explain different type of operators
 Explain the concept of casting
en

 Explain implicit and explicit conversion

3.1.2 Teaching Skills


C

To teach this session, you should be well-versed with usage of variables, literals, data types, and
constants in Java. You should be familiar with different types of operators and their usage in writing
h

the expressions in the Java program.


ec

You should teach the concepts in the theory class using the images provided. For teaching in the
class, you are expected to use slides and LCD projectors.
pt
rA

Tips:
It is recommended that you test the understanding of the students by asking questions in between
the class.
Fo

In-Class Activities:
Follow the order given here during In-Class activities.

©Aptech Limited
Variables and Operators

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
rU
Tell them that Java is an object-oriented programming language used for developing various types of
te
applications that can be executed on any platform. Tell the student that this session will focus on the
usage of variables and different data types that are present in Java programming language.
en

They will also learn about the various operators and their implementation in Java programs. The
session also explains the different type of conversions used in Java to convert the value from one
C

data type onto another.


h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

3.2 In-Class Explanations

Slide 3
Let us understand the use of variables in Java.

y
nl
O
se
rU
te
en

Using slide 3, explain the concept of variables in Java.

The core of any programming language is the way it stores and manipulates the data. Thus, to work
C

with the data in a program, you need variables. They act as a container that holds data to be
processed by the Java program. Tell the students that in a Java program variables store data that
changes during the execution of the program. After declaring a variable, compiler reserves an area of
h

the memory to put appropriate data into it.


ec

The type of data that a variable can hold depends upon the data type assigned to the variable. In
Java every variable must have a data type, hence, the variable is associated with a data type that
pt

defines the type of data that will be stored in the variable.


rA

A variety of data types are built into the Java language to work with different types of data, such as
number, character, boolean, and so on. Every variable must be declared to use a data type. For
instance, a variable could be declared to use one of the eight primitive data types namely, byte,
Fo

short, int, long, float, double, char, or boolean. Every variable must be given an initial
value, before it can be used.

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.

©Aptech Limited
Variables and Operators

Slides 4 and 5
Let us understand the declaration of variables.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 4 and 5, explain the syntax and example to work with the variables.

The variable is a location in the computer’s memory, where the data is stored and from which the
value can be retrieved later. Tell the students that in a Java program variables store data that
changes during the execution of the program. They are the basic units of storage in a Java program.
Discuss some of the example for declaring variables in a class. For instance to store the employee
details in an application, you need to declare variables such as name, address, salary, and so on.

Explain to them the syntax for declaring variables. Variables must be declared before they can be
used in the program. 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.

©Aptech Limited
Variables and Operators

For example,
int rollNumber;
char gender;

Tell the students that these statements declare an integer variable called rollNumber, and a
character variable called gender. These statements instruct the JVM to allocate the required amount
of memory to each variable in order to hold the type of data specified for each.

Explain to them that the name can be used within the program to access the values stored in each of
the variables. Values can be assigned to variables by using the assignment operator (=) as follows:

y
rollNumber = 101;
gender = ‘M’;

nl
Also, tell the students that values can be assigned to a variable upon creation, as shown:

O
int rollNumber = 101;

se
Tips:
Multiple variables also can be declared and initialized at the same time as shown:

int a=5, b, c=10;


rU
The statement initializes a and c, but declares three variables.
te
In-Class Question:
en

After you finish explaining variables, you will ask the students an In-Class question. This will help you
in reviewing their understanding of the topic.
C
h

How to assign the value of one variable to another variable?


ec

Answer:
Using assignment operator (=).
pt

For example, int a =10; int b = a;


rA
Fo

©Aptech Limited
Variables and Operators

Slides 6 and 7
Let us understand rules for naming variables.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 6 and 7, explain the naming conventions for variables in Java.

Tell them that every programming language has its own set of rules and conventions for the kinds of
names that you're allowed to use, and the Java programming language is also not different. For
instance, variable names should be short and meaningful. Not adhering to the rules will result in
syntax errors.

Explain the naming conventions that should be followed while declaring variables in Java.

©Aptech Limited
Variables and Operators

Tell them that the rules and conventions for naming your variables are as follows:
 Variable names may consist of Unicode letters and digits, underscore (_), and dollar sign ($).
 A variable’s 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 ’_’.
 Variable names must not be a keyword or reserved word in Java.
 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

y
word should be capitalized (for example, employeeNumber and accountBalance).

nl
Tips:

O
If your variable stores a constant value, such as static final int NUM_GEARS = 6, the
convention changes slightly, capitalizing every letter and separating subsequent words with the
underscore character. By convention, the underscore character is never used elsewhere.

se
Slides 8 to 10

rU
Let us understand assigning value to a variable.
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 8 to 10, explain how to assign the values to a variable.

The values can be assigned to the variable in two ways, that is, at the time of variable declaration or
Fo

after the variable is declared. The value assigned to the variable is also called as literal. Literals are
constant values assigned to variables directly in the code without any computation.

At the time of declaring a variable


...
int rollNumber = 101;

In the code, variable rollNumber is an integer variable, so it has been initialized with a numeric
value 101.

©Aptech Limited
Variables and Operators

After the variable declaration


int rollNumber; // Variable is declared
. . .
rollNumber = 101; //variable is initialized
...
Here, the variable rollNumber is declared first and then, it has been initialized with the numeric
literal 101.

Slides 11 to 13
Let us understand different kinds of variables in Java.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
rU
Using slides 11 to 13, explain that Java programming language allows you to define different kind of
variables that are categorized as follows:

Instance variables
te
They are declared in class but outside methods, constructor or any block. The state of an object is
represented as fields or attributes or instance variables in the class definition.
en

They are created when an object is created with the use of ‘new’ keyword and destroyed when the
object is destroyed. Each object created from a class will have its own copy of instance variables.
C

Instance variables can be accessed directly by calling the variable name inside the class.
Static variables
These are also known as class variables and declared with the static keyword in a class. Only one
h

copy of static variable is maintained in the memory that is shared by all the objects belonging to that
ec

class. Static variables are created when the program starts and destroyed when the program stops.
They are stored in static memory.
pt

Local variables
The variables declared within the blocks or methods of a class are called local variables. A method
rA

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
Fo

variable makes it local. There is no default value for local variable, so local variables can be declared
and an initial value can be assigned before the first use.

©Aptech Limited
Variables and Operators

In-Class Question:
After you finish explaining the different types of variables, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.

Where are the instance variable declared and when are they created?
Answer:
Instance variables are declared within the class definition and they are created when an object of
the class is instantiated in the memory. The object is created with the use of ‘new’ keyword.

y
Slides 14 to 16

nl
Let us understand scope and lifetime of variables.

O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
Using slides 14 to 16, explain the scope and lifetime of the variables.

rU
In Java, variables can be declared within a class, method, or within any block. A scope determines
the visibility of variables to other part of the program. The scope of a variable defines the section of
the code in which the variable is visible.
te
The lifetime of a variable refers to how long the variable exists before it destroyed. Destroying
en

variables means deallocating the memory that was allotted to the variables when declaring it.

Class scope
C

The variables declared within the class can be instance variables or static variables. The instance
variables are owned by the objects of the class and their existence or scope depends upon the object
creation. In this, any method in the class definition can access these variables. The static variables
h

are shared between the objects and exist for the lifetime of a class.
ec

Tell them that if any variable is declared with the static modifier. This tells the compiler that
there is exactly one copy of this variable in existence, regardless of how many times the class has
pt

been instantiated.
rA

Method scope
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
Fo

when the method is invoked and destroyed when the method returns. After the variables are
destroyed, they are no longer in existence.

Methods parameters 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.

Then, explain the example provided on slide 16 to understand the scope of variables within the
method.

©Aptech Limited
Variables and Operators

Slide 17
Let us understand data types.

y
nl
O
se
rU
Using slide 17, explain to the students about the data types in Java.

Tell them that Java programming language is statically-typed. This means that all variables need to
te
be declared before they can be used.
en

Explain to the students that when you define a variable in Java, you must tell 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.
C

This information is required for the following reasons:


 It tells the compiler how much space to allocate in the memory depending on the data type
h

of the variable
ec

 It also determines the type of data that can be stored in the variable
 It determines the type of operations that can be performed on this data
pt

Mention to the students that Java is a strongly typed language. This means that every variable has a
rA

type, every expression has a type, and every type is strictly defined. It also means that all
assignments, whether explicit or via parameter passing in method calls, are checked for type
compatibility by the Java compiler. Any type mismatches are considered as errors and need to be
corrected before compilation is over.
Fo

There are two data types available in Java programming language:


 Primitive Data Types
 Reference/Object Data Types

©Aptech Limited
Variables and Operators

Slide 18
Let us understand primitive data types.

y
nl
O
se
rU
Using slide 18, explain the primitive data types in Java.

Every variable has a typed declared in the source code. Primitive type directly contains value. The
te
Java programming language provides eight primitive data types to store data in Java programs.
A primitive data types are predefined by language and named by a reserved keyword. A primitive
en

data type, also called built-in data type, stores a single value at a time, such as a number or a
character. Primitive value does not share state with other primitive value. The size of each data type
C

will be same on all machines while executing a Java program. The primitive data types are
predefined in the Java language and are identified as reserved words.
h

Slide 18 shows the primitive data types that are broadly grouped into four groups. They are integer,
ec

float, character, Boolean. Integer data type is further sub-divided into four types. They are byte,
short, int, long. Float data type is further sub-divided into two types. They are float and
double. Character data type is named by the keyword char, whereas boolean data type is named
pt

by the keyword boolean.


rA

In-Class Question:
After you finish explaining the data types, you will ask the students an In-Class question. This will
help you in reviewing their understanding of the topic.
Fo

Which primitive data type is useful for saving memory in large areas?

Answer:
byte and short

©Aptech Limited
Variables and Operators

Slides 19 and 20
Let us understand integer types and floating-point types.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 19 and 20, explain the integer and floating-point types.
Integer and floating–point values are the basic building blocks of arithmetic and computation.
Fo

Integer Types
The integer data types supported by Java are byte, short, int, and long. These data type can
store signed integer values. Signed integers are those integers, which are capable of representing
positive as well as negative numbers, such as -40. Java does not provide support for unsigned
integers. Byte data type is used to save space in large arrays since byte is four times smaller then
int. While short data type is also used to save memory, but it is two times smaller then int.

©Aptech Limited
Variables and Operators

Floating-point Types
The floating-point data types supported by Java are float and double. These are also called real
numbers, as they represent numbers with fractional precision. For example, calculation of a square
root or PI value is represented with a fractional part. Float data type is mainly used to save memory
in large arrays of floating-point numbers and should not be used for precise values such as currency.
Double data type is used as a default data type for decimal values.

Slides 21 to 24
Let us understand character and boolean types.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
rU
te
en
C
h
ec

Using slides 21 to 24, explain the character and boolean types.


pt

char is used to store any character, while boolean has only two possible values which is true or
false. char represents symbols in a character set such as letters and numbers. char stores 16-bit
rA

Unicode character and its value ranges from 0 (‘\u0000’) to 65,535 (‘\uffff’).

Unicode is a 16-bit character set, which contains all the characters commonly used in information
Fo

processing. It is an attempt to consolidate the alphabets of the world’s various languages into a
single and international character set.

Apart from primitive data types, Java programming language also supports strings. A string is a
sequence of characters. Java does not provide any primitive data type for storing strings, instead
provides a class String to create string variables. The String class is defined within the
java.lang package in Java SE API. Though, String is a class in Java, however, you can use it as data
type in the program. For example, String str = “A String Data”, it will remain constant
and you cannot change the value of the variable within the program.

©Aptech Limited
Variables and Operators

However, initializing string variable with new value creates a new String object. This behavior of
strings makes them as immutable objects.

Slide 25
Let us understand reference data types.

y
nl
O
se
rU
te
Using slide 25, explain the reference data type in Java.
en

Tell them that, in Java, a reference data type is a variable that can contain the reference or an
address of dynamically created object. These types of data type are not predefined such as primitive
data type.
C

Explain it to them that a variable of a reference data type holds the reference to the actual value or a
set of values represented by the variable. The reference data types are arrays, classes, and
h

interfaces. They are described as follows:


ec

Array
It is a collection of several items of the same data type. For example, names of students in a class
pt

can be stored in an array. It is used to store collection of data but here the collection of variable is of
same size.
rA

Class
It is encapsulation of instance variables and instance methods. It can be defined as a blue print that
Fo

describes the behavior that an object of its type supports.

Interface
It is a type of class in Java used to implement inheritance. It is a sequence of one or more character.

©Aptech Limited
Variables and Operators

Slides 26 to 29
Let us understand literals.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
rU
te
en
C
h
ec
pt

Using slides 26 to 29, explain literals in Java.


rA

Explain to the students the meaning of literal. Tell them that by literal we mean any number, text, or
other information that represents a value. In other words, it means that what you type is what you
Fo

get.

Explain to the students that a literal signifies a fixed value and is represented directly in the code
without requiring computation. For instance,
int val =50;
float num = 35.7f;
In the statement, the literal is an integer value that is 50. The literal is 50 because it directly
represents the integer value.

A literal is used wherever a value of its type is allowed.

©Aptech Limited
Variables and Operators

Tips:
A literal is the source code representation of a fixed value. Literal does not require computation.

integer literals are used to represent an int value, which in Java is a 32-bit integer value.

Any whole number value is an integer literal. Integers can be expressed as:
 Decimal values, expressed in base 10
 Octal values, expressed in base 8
 Hexadecimal values, expressed in base 16

Mention to the students that values of the integral types byte, short, int, and long can be

y
created from int literals. Explain to them that an integer literal is of type long if it ends with the

nl
letter L or l, otherwise it is of type int.

O
Tips:
Tell the students that as discussed integers can either be in decimal, hexadecimal, or octal format.
To indicate a decimal format, put the left most digit as nonzero. Similarly, put the characters as ox to

se
the left of at least one hexadecimal digit to indicate hexadecimal format. Also, we can indicate the
octal format by a zero digit followed by the digits 0 to 7.

rU
Floating-point numbers are same as real numbers in mathematics.
Explain to them that floating-point literals represent decimal values with a fractional component.
Floating-point literals have several parts such as:
te
 Whole number component, for example, 0, 1, 2, ..... , 9.
 Decimal point, for example, 4.90, 3.141, and so on.
en

 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.
C

Tell the students that Java has two kinds of floating-point numbers, float and double. The default
h

type when you write a floating-point literal is double. A float literal is represented by F or f
appended to the value, and a double literal is represented by D or d.
ec

Tell the students that boolean literals are simple and have only two logical values, true and false.
pt

These values do not convert into any numerical representation. A true boolean literal in Java is
neither equal to one nor does the false literal equals to zero. They can only be assigned to variables
rA

declared as boolean, or used in expressions with boolean operators.

Explain to the students about character literals. Tell them that character literal are represented as a
single printable character in a pair of single quote characters such as 'a', '#', and '3'. The ASCII
Fo

character set includes 128 characters including letters, numerals, punctuations, and so on. There are
few character literals which are not readily printable through a keyboard. Single characters that
cannot be directly entered are hyphen (-) and backslash (\).

Tell them that one specifies the Null literal in the source code as 'null'. To reduce the number of
references to an object, one can use null literal.

Explain to them that when an object is created, a certain amount of memory is allocated for that
object. The starting address of this memory is stored in an object, that is, a reference variable.

©Aptech Limited
Variables and Operators

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 as shown:
obj = null;

In this statement, you reduce the number of references to an object by assigning null to obj.
Now, as in this example, the object is no longer referenced so it will be available for the garbage
collection that is the compiler will destroy it and the free memory will be allocated to the other
object.

Explain to the students about string literals. Tell them that string literals consists of sequence of
characters enclosed in double quotes. The characters can be printable or non-printable. However,

y
backslash, double quote, and non-printable characters are represented using escape sequences.

nl
Tips:
In Java, a string is not a basic data type, rather it is an object. These strings are not stored in arrays as

O
in C language. Literals of types char and String may contain any Unicode (UTF-16) characters.
Always use 'single quotes' for char literals and ’double quotes’ for String literals.

se
In-Class Question:
After you finish explaining, the variables and literals in Java, you will ask the students the following
In-Class question:
rU
te
Can variable names begin with underscore character?
en

Answer:
Yes.
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

Slides 30 and 31
Let us understand underscore character in numeric literals.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 30 and 31, explain the use of underscore character in numeric literals.
Fo

Java SE 7 allows you to add underscore characters (_) between the digits of a numeric literal. This
feature helps to separate groups of digit in numeric literals which can improve the readability of the
code. The underscore character can be used only between the digits. In integral literals, underscore
characters can be provided for telephone numbers, identification numbers, or part numbers, and so
on. Similarly, for floating-point literals, underscores are used between large decimal values.

©Aptech Limited
Variables and Operators

Restrictions for using underscores in numeric literals are as follows:


 A number cannot begin or end with an underscore.
 In the floating-point literal, underscore cannot be placed adjacent to a decimal point.
 Underscore cannot be placed before a suffix, L or F.
 Underscore cannot be placed before or after the binary or hexadecimal identifiers, such as b
or x.

Slide 31 shows the list of valid and invalid placement of underscore character.

In-Class Question:
After you finish explaining the underscore character, you will ask the students an In-Class question.

y
This will help you in reviewing their understanding of the topic.

nl
O
Why underscore character is used in numeric literals?

se
Answer:
1. The underscore character can be used only between the digits.
2. It helps to separate groups of digit in numeric literals which can improve the readability of
the code.
rU
te
Slides 32 to 34
Let us understand escape sequences.
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
rU
te
en
C
h
ec
pt

Using slides 32 to 34, explain the use of escape sequence.


rA

Tell them that a character preceded by a backslash (\) is an escape sequence and has special
meaning to the compiler.
Fo

Mention that an escape sequence is a special sequence of characters that is used to represent
characters, which cannot be entered directly into a string. For example, to include tab spaces or a
new line character or to include characters which otherwise have a different connotation in a Java
program (such as \ or “), escape sequences are used.

An escape sequence begins with a backslash character (\), which indicates that the character (s) that
follows should be treated in a special way. The output displayed by Java can be formatted with the
help of escape sequence characters.

©Aptech Limited
Variables and Operators

Tips:
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.

Slides 35 to 39
Let us understand constants and enumerations.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
Using slides 35 to 39, explain the use of constants and enumerations in Java.

rU
Constants are a way to use meaningful names in place of a value that does not change. Constants in
Java are fixed values assigned to identifiers that are not modified throughout the execution of the
code. In Java, the declaration of constant variables is prefixed with the final keyword. Constant can
te
be used to provide meaningful names to make code more readable.
en

Then explain the syntax to initialize a constant variable in the code.

Java SE 5.0 introduced enumerations. An enumeration is defined as a list that contains constants.
C

The enumeration instance defined the methods by which user can enumerate the elements in a
collection of objects. Unlike C++, where enumeration was a list of named integer constants, in Java,
h

enumeration is a class type. This means it can contain instance variables, methods, and constructors.
The enumeration is created using the enum keyword.
ec

An enum type is a special data type that enables for a variable to be a set of predefined constants.
pt

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
rA

data types. The enumeration is mostly used with decision-making constructs, such as switch-
case statement.

Explain the code to define enumeration in the Java program using slides 38 and 39.
Fo

©Aptech Limited
Variables and Operators

Slide 40
Let us understand formatted output and input.

y
nl
O
se
rU
Using slide 40, explain formatted output and input methods used in Java.

Programming simple input/output is easy, which involves only few classes and methods. Whenever
an output is to be displayed on the screen, it needs to be formatted. Formatting can be done using
te
three ways that are as follows:
 print() and println()
en

 printf()
 format()
C

These methods behave in a similar manner. The format() method uses the
java.util.Formatter class to do the formatting work. It formats multiple arguments based on
h

a format string.
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

Slides 41 and 42
Let us understand print() and println() methods.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 41 and 42, explain print() and println() methods.

The println() methods print the string and moves the cursor to a new line. It can also be used
Fo

without parameters, to position the cursor on the next line. The print() method print the string,
but does not move the cursor to the new line. These methods convert all the data to strings and
display it as a single value. The methods uses the appropriate toString() method for conversion
of the values. These methods can also be used to print mixture combination of strings and numeric
values as strings on the standard output.

Explain the code snippet which demonstrates the use of print() and println() methods.

©Aptech Limited
Variables and Operators

Slides 43 and 44
Let us understand printf() method.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 43 and 44, explain the printf() method.


Fo

Tell them that whenever an output is to be displayed on the screen, it needs to be formatted. The
formatting can be done with the help of format specifiers in Java. Tell the students that the
printf() method introduced in J2SE 5.0 can be used to format the numerical output to the
console.

All format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the
kind of formatted output being generated.

©Aptech Limited
Variables and Operators

The format specifiers are as follows:

 d formats an integer value as a decimal value.


 f formats a floating point value as a decimal value.
 n outputs a platform-specific line terminator.
 outputs a value as an octal number.
 e outputs value as a decimal number in scientific notation.

Then, explain the code snippet for the printf() method. Tell the students that in the code
snippet, ‘%09.3f’ indicates that there will be total 9 digits including decimal point and three places
of decimals. If the number of digits is less than 9, then it will be padded with zeroes. If ‘0’ is omitted

y
from ‘%09.3f’, then it will be padded with spaces.

nl
Slides 45 to 47

O
Let us understand format() method.

se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 45 to 47, explain the format() method.

The format() method is used to format string in Java. This method formats multiple arguments
based on a format string. It works in same way as printf(), but it does not print the string, it
Fo

returns a formatted string. The format string consists of the normal string literal information
associated with format specifiers and argument list.

Explain the syntax of a format specifier presented on slide 45. Then, explain the code snippet
presented on slides 46 and 47 to demonstrates the format() method.

©Aptech Limited
Variables and Operators

Slides 48 to 50
Let us understand formatted Input.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
Using slides 48 to 50, explain the scanner() class.

Tell the students that the java.util.Scanner class is a simple text scanner which can parse

rU
primitive types and strings using regular expressions.

Tell the students that the Scanner class allows the user to read values of various types. To use the
te
Scanner class, pass the InputStream object to the constructor.
en

For example,

Scanner input = new Scanner(System.in);


C

Here, input is an object of Scanner class and System.in is an input stream object.

Explain to them the methods of the Scanner class. Tell them that Scanner breaks its input into
h

tokens using a delimiter pattern, which is by default matches whitespace. The nextByte(),
ec

nextInt(), nextLong(), nextFloat(), and nextDouble() methods returns the next


token as byte, int, long, float, and double value respectively.
pt

Then, demonstrate the Scanner class methods and how they can be used to accept values from
the user and finally, print the output.
rA

Tips:
Fo

1. A scanning operation may block resources waiting for input and a Scanner is not safe for
multithreaded, use without external synchronization.

2. A token is a series of characters that ends with delimiters. A delimiter can be a whitespace
(default delimiter for tokens in Scanner class), a tab character, a carriage return, or the
end of the file. Thus, if we read a line that has a series of numbers separated by whitespaces,
the scanner will take each number as a separate token.

©Aptech Limited
Variables and Operators

Slide 51
Let us understand operators.

y
nl
O
se
Using slide 51, explain the operators in Java.

rU
Tell them that operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.
te
Tell the students that all programming languages provide some mechanism for performing various
en

operations on the data stored in variables. Also mention that the simplest form of operations
involves arithmetic (such as adding, dividing, 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
C

operators.

For instance,
h

Z = X + Y
ec

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 operands. The
pt

combination of both the operator and the operands, Z = X + Y, is known as an Expression.


rA

Mention to the students about the different categories of operators such as:
 Arithmetic
 Relational
Fo

 Logical
 Assignment
 Bitwise
 Bit Shift

Tips:
In general-purpose programming, certain operators tend to appear more frequently than others. For
example, the assignment operator (=) is more common than the unsigned right shift operator (>>>).

©Aptech Limited
Variables and Operators

Slides 52 and 53
Let us understand assignment operators.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 52 and 53, explain the assignment operator.


Fo

Tell the students that one of the most common operators is the assignment operator (=).

Explain that it is the simple assignment operator (=) and is used for assigning the value on its right to
the operand on its left. Assigning values to more than one variable can be done at a time. In other
words, it allows you to create a chain of assignments.

©Aptech Limited
Variables and Operators

For instance,
int a=b=5;

In the statement, it assigns value 5 to a and b integer variables.

Tell the students that, in addition to the basic assignment operator, there are combined operators
that allow you to use a value in an expression, and then set its value to the result of that expression.

For instance,
X = 3;
X+=5;

y
The second statement stores the value 8 in the variable X, the meaning of the statement is that, X =

nl
X + 5.
Explain to the students about the different types of combined assignment operators such as +=, -=,

O
*=, /=, and %= as demonstrated in the code snippet.

se
Tips:
Simple assignment operator (=) can also be used on objects to assign object references.

Slide 54
Let us understand arithmetic operators. rU
te
en
C
h
ec
pt
rA
Fo

Using slide 54, explain the arithmetic operators in Java.

Tell them that arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra.

Tell them that arithmetic operators manipulate numeric data and perform common arithmetic
operations on the data. Operands of the arithmetic operators must be of numeric type. Mention
that boolean operands cannot be used, but character operands are allowed. The operators

©Aptech Limited
Variables and Operators

mentioned here are binary in nature, that is, these operate on two operands, such as X+Y. Here, + is
a binary operator operating on X and Y.

Explain the different arithmetic operators such as +, -, *, /, and % which perform addition,
subtraction, multiplication, division, and modulus operations respectively.

Then, explain the code snippet showing the use of arithmetic operators.

Tips:
The modulus operator returns the remainder after performing the division.

y
Slide 55
Let us understand unary operator.

nl
O
se
rU
te
en
C
h
ec

Using slide 55, explain the unary operator.

Tell the students that the unary operators require only one operand, they perform various
pt

operations such as incrementing/decrementing a value by one, negating an expression, or inverting


the value of a boolean.
rA

The various type of unary operators are +, -, ++, --, and ! represents unary plus, unary minus,
increment operator, decrement operator, and logical complement operator respectively.
Fo

Tell them that the ++ and -- operators can be applied before (prefix) or after (postfix) the
operand. The statements ++variable and variable++ both result in incrementing the variable
value by 1.
Mention that 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.

Explain to the student the code snippet demonstrating the use of prefix and postfix increment and
decrement operator.

©Aptech Limited
Variables and Operators

Tips:
Tell the students that, if you are just performing a simple increment/decrement, it doesn't really
matter which version (prefix or postfix) you choose. However, if you use this operator in part of a
larger expression, the one that you choose may make a significant difference.

Slides 56 and 57
Let us understand conditional operators.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using 56 and 57, explain the conditional operator.

The conditional operators test the relationship between two operands. An expression involving
conditional operators always evaluates to a boolean value (that is, either true or false). Here, the
expression is evaluated so that truth and falsehood can be determined.

Explain the various relational operators such as ==, !=, >, <, >=, and <=.

©Aptech Limited
Variables and Operators

Tips:
Remember that you must use ’==’, not ’=’, when testing, if two primitive values are equal.

Slides 58 and 59
Let us understand logical operators.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 58 and 59, explain the logical operators.

Logical operators (&& and ||) work on two boolean expressions. These operators exhibit short-
circuit behavior, which means that the second operand is evaluated only if required.

©Aptech Limited
Variables and Operators

Explain to them that the operator && will return true, only if both expressions are true. Similarly, the
conditional operator || will return true, if either one expression is true or both the expressions are
true.

Slides 60 and 61
Let us understand bitwise operators.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 60 and 61, explain the bitwise operators.

Tell the students that the Java programming language also provides operators that perform bitwise
and bit shift operations on integral types.

©Aptech Limited
Variables and Operators

Tell them that the bitwise operators work on binary representations of data. These operators are
used to change individual bits in an operand. Bitwise shift operators are used to move all the bits in
the operand left or right, a given number of times.

Mention to the students that the unary bitwise complement operator (~) inverts a bit pattern. In
other words, it can be applied to any of the integral types, converting every ’0’ to ’1’ and every ’1’ to
’0’". For example, a byte contains 8 bits, applying this operator to a value whose bit pattern is
’00000000’ would change its pattern to ’11111111’.

Also tell them about the signed left shift operator (<<). This operator shifts a bit pattern to the left,
and the signed right shift operator (>>) shifts a bit pattern to the right. The bit pattern is given by

y
the left-hand operand, and the number of positions to be shifted is provided by the right-hand

nl
operand. The unsigned right shift operator (>>>) shifts a zero into the leftmost position, while the
leftmost position after (>>) depends on sign extension.

O
The bitwise & operator performs a bitwise AND operation. It converts two bits and generates a result
of 1 if both bits are 1, otherwise, it returns 0.

se
The bitwise ^ operator performs a bitwise exclusive OR operation. It compares two bits and
generates a result of 1 if either or both bits are 1, otherwise, it returns 0.

rU
The bitwise | operator performs a bitwise inclusive OR operation. It compares two bits and
generates a result of 1 if the bits are complementary, otherwise, it returns 0.
te
Then explain the code snippet to explain the concept of bitwise and bit shift operators. Explain the
en

output as specified in comments.

In-Class Question:
C

After you finish explaining Bitwise operators, you will ask the students an In-Class question. This will
help you in reviewing their understanding of the topic.
h
ec

What are bitwise operators?


pt

Answer:
These operators are used to change individual bits in an operand. It provides a way to manipulate
rA

individual bits into integral primitive data type.


Fo

©Aptech Limited
Variables and Operators

Slides 62 and 63
Let us understand ternary operator.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using 62 and 63, explain the ternary operator.


Fo

The ternary operator (?:) is a shorthand operator for an if-else statement. It is used to control the
flow of execution in Java. It works with three operands producing a value depending on the truth or
falsehood of a Boolean assertion. It makes your code compact and more readable.

Then, explain the syntax for ternary operator and the corresponding code snippet.

©Aptech Limited
Variables and Operators

Slides 64 and 65
Let us understand operator precedence.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using 64 and 65, explain the ternary operator.

Tell the students that operators with higher precedence are evaluated before operators with
relatively lower precedence. Also tell them that when operators of equal precedence appear in the
same expression, a rule must govern which is evaluated first.

Mention that expressions that are written generally consist of several operators. The rules of
precedence decide the order in which each operator is evaluated in any given expression.

©Aptech Limited
Variables and Operators

Explain to them using the following table:

Operators Precedence
parenthesis ()
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
&

y
bitwise AND
bitwise exclusive OR ^

nl
bitwise inclusive OR |
logical AND &&

O
logical OR ||
ternary ? :
= += -= *= /= %= &= ^= |= <<= >>= >>>=

se
assignment

Tell the students that the parentheses are used to change the order, in which an expression is

rU
evaluated. Any part of an expression enclosed in parentheses is evaluated first.

Explain to the students, the concept of operator precedence using the code snippet. Tell them that
the evaluation will be as shown:
te
1. (2*3+4/2) > 3 && 3<5 || 10<9
en

2. First, the arithmetic operators are evaluated.

3. ((2*3)+(4/2)) > 3 && 3<5 || 10<9


C

4. Division and Multiplication are evaluated before addition and subtraction.


h

5. (6+2) >3 && 3<5 || 10<9


ec

6. (8>3) && [3<5] || [10<9]


7. Next to be evaluated are the relational operators, all of which have the same precedence.
pt

These are therefore, evaluated from left to right.

8. (True && True) || False


rA

9. The last to be evaluated are the logical operators. && takes precedence over ||.

10. True || False


Fo

11. True

Tips:
When operators of same precedence appear in an expression, then a rule is followed. All binary
operators except for the assignment operators are evaluated from left to right, assignment
operators are evaluated right to left.

©Aptech Limited
Variables and Operators

Slides 66 and 67
Let us understand operator associativity.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 66 and 67, explain the operator associativity.

Tell them that when two operators with the same precedence appear in an expression, the
expression is evaluated, according to its associativity. For example, in Java, the - operator has left-
associativity and x - y - z is interpreted as, (x - y) - z, and = has right-associativity and x
= y = z is interpreted as, x = (y = z).

©Aptech Limited
Variables and Operators

Explain to the students about the associativity using the following table.
Operator Description Level Associativity
[] access array element 1 left to right
. access object member
() invoke a method
++ post-increment
-- post-decrement
++ pre-increment 2 right to left
-- pre-decrement
+ unary plus
- unary minus
!

y
logical NOT
~

nl
bitwise NOT
() cast 3 right to left
new

O
object creation
* multiplicative 4 left to right
/

se
%
+ - additive 5 left to right
+ string concatenation
<< >>
>>>
< <=
shift

relational
rU 6

7
left to right

left to right
> >=
te
type comparison
instanceof
== equality 8 left to right
en

!=
& bitwise AND 9 left to right
^
C

bitwise XOR 10 left to right


| bitwise OR 11 left to right
&& conditional AND 12 left to right
h

|| conditional OR 13 left to right


ec

?: conditional 14 right to left


= += assignment 15 right to left
-=
pt

*= /=
%=
rA

&= ^=
|=
<<= >>=
>>>=
Fo

Explain to the students about this concept using the expression as shown:

2+10+4-5*(7-1)

1. According to the rules of operator precedence, the ‘*’ has higher precedence than any other
operator in the equation. Since 7-1 is enclosed in parenthesis, it is evaluated first.
2+10+4-5*6

©Aptech Limited
Variables and Operators

2. Next, ‘*’ is the operator with the highest precedence. Since there are no more parentheses,
it is evaluated according to the rules.
2+10+4-30
3. As ‘+’ and ‘-‘ have the same precedence, the left associativity works out.
12+4-30
4. Finally, the expression is evaluated from left to right.
16 – 30
Finally, the result is -14.

In-Class Question:
After you finish explaining the operators, operator precedence, and operator associativity, you will

y
ask the students an In-Class question. This will help you in reviewing their understanding of the

nl
topic.

O
se
Which operator is used to compare two values, = or ==,?

Answer:

rU
The == operator is used for comparison and = is used for assignment.
te
en

Which operator would you use to invert the value of a boolean?


C

Answer:
h

The == logical complement operator ’!’.


ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

Slide 68
Let us understand casting.

y
nl
O
se
rU
Using slide 68, explain the concept of casting.
te
Tell them that in any application, there may be situations, where one data type may need to be
en

converted into another data type. The type casting feature in Java helps in such conversion. Type
conversion or typecasting refers to changing an entity of one data type into another. This is done to
take advantage of certain features of type hierarchies. For instance, values from a more limited set,
C

such as integers, can be stored in a more compact format. It can be converted later, to a different
format enabling operations not previously possible, such as division with several decimal places
worth of accuracy. In object-oriented programming languages, type conversion allows programs to
h

treat objects of one type as one of their ancestor types to simplify interacting with them.
ec

Mention that if a conversion results in the loss of precision, as in an int value converted to a short,
then the compiler issues an error message unless an explicit cast is made.
pt

Tell them that the two types of casting are as follows:


rA

 Implicit casting
 Explicit casting
Fo

©Aptech Limited
Variables and Operators

Slides 69 to 71
Let us understand implicit type casting.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Variables and Operators

y
nl
O
se
Using slides 69 to 71, explain the implicit casting.

rU
Tell them that when one type of data is assigned to a variable of another type, then automatic type
conversion takes place, also referred to as implicit type casting, provided it meets the conditions
specified:
 The two types should be compatible.
te
 The destination type should be larger than the source.
en

Explain to them that the primitive numeric data types that can be implicitly cast are as follows:
 byte (8-bits) to short, int, long, float, double
 short(16-bits) to int, long, float, double
C

 int (32-bits) to long, float, double


 long(64-bits) to float, double
h
ec

This is also known as the type promotion rule.

Tips:
pt

Type promotion rules are as follows:


 All byte and short values are promoted to int type.
rA

 If one operand is long, then the whole expression is promoted to long.


 If one operand is float, then the whole expression is promoted to float.
 If one operand is double, then the whole expression is promoted to double.
Fo

©Aptech Limited
Variables and Operators

Slides 72 and 73
Let us understand explicit casting.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 72 and 73, explain the explicit type conversion.

Explain to the students that a data type with lower precision, such as short, can be converted to a
type of higher precision, such as int, without using explicit casting. However, to convert a higher
precision data type to a lower precision data type, such as float to int data type, an explicit cast
is required. Otherwise, the compiler will display an error message.

©Aptech Limited
Variables and Operators

Explain this concept with the help of the code snippet. Tell them that the float value in a variable 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.

Slides 74
Let us summarize the session.

y
nl
O
se
rU
te
en

In slide 74, you will summarize the session. End the session with a brief summary of what has been
C

taught in the session.


h

3.3 Post Class Activities for Faculty


ec

You should familiarize yourself with the topics of the next session which is how to implement
decision-making constructs in the Java program.
pt

Tips:
rA

You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.
Fo

©Aptech Limited
Decision-Making Constructs

Session 4 – Decision-Making Constructs

4.1 Pre-Class Activities


Familiarize yourself with the topics of this session in-depth. You should revisit topics of the previous
session for a brief review.

Here, you can ask students the key topics they can recall from previous session. Prepare a question
or two which will be a key point to relate the current session objectives.

y
4.1.1 Objectives

nl
By the end of this session, the learners will be able to:

O
 Identify the need for decision-making statements
 List the different types of decision-making statements
 Explain the if statement

se
 Explain the various forms of if statement
 Explain the switch-case statement

 rU
Explain the use of strings and enumeration in the switch-case statement
Compare the if-else and switch-case statement

4.1.2 Teaching Skills


te
To teach this session, you should be well-versed with different types of decision-making statements
en

in Java programming language, comparison of data, and sequence of execution of statements. You
should teach the concepts in the theory class using the images provided. For teaching in the class,
you are expected to use slides and LCD projectors.
C

Tips:
h

It is recommended that you test the understanding of the students by asking questions in between
ec

the class.

In-Class Activities:
pt

Follow the order given here during In-Class activities.


rA
Fo

©Aptech Limited
Decision-Making Constructs

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
Tell the students that the ability to compare values and alter the course of a program, based on the

rU
result of the comparison. This ability of comparison gives a computer the power to solve problems.

There are two aspects to making decisions, the first is the comparison of data and the second is the
te
sequence of execution. This session focuses more on decision-making statements.
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

4.2 In-Class Explanations


Slide 3
Let us understand the introduction of control flow statements.

y
nl
O
se
rU
Using slide 3, explain the purpose of decision making statements.
te
Tell the students that the statements inside your source code files are generally executed from top
en

to bottom, in the order that they appear. Control flow statements, however, break up the flow of
execution by employing decision making, looping, and branching, enabling your program to
conditionally execute particular blocks of code.
C

Mention that a Java program is a set of statements, which are executed sequentially in the order in
h

which they appear. However, in some cases, the order of execution of statements may change based
on the evaluation of certain conditions. The Java programming language possesses decision-making
ec

capabilities.
pt

Then, explain the three categories of control flow statements supported by Java programming
language.
rA
Fo

©Aptech Limited
Decision-Making Constructs

Slide 4
Let us understand decision-making statements.

y
nl
O
se
Using slide 4, explain the types of decision-making statements in Java.
rU
Decision-making statements enable the user to change the flow of execution of a Java program and
evaluate a condition. Then, based on the result of evaluation, a statement or a sequence of
te
statements is executed. It is an expression that produces true or false results. Boolean operators can
be used in conditional statements.
en

Different types of decision-making statements supported by Java are, if Statement and Switch-
case statement. The if statement executes a block of code only if the specified expression is true.
C

If the value is false, then the if block is skipped and execution continues with the rest of the
program. The switch-case statement is a multi-way branch with several choices.
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

Slides 5 to 9
Let us understand ‘if’ statement.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
Using slides 5 to 9, explain the if statement in Java.

rU
Explain about the simple if statement. Tell that the simple if statement helps in decision-making
based on the evaluation of a given condition to true or false. Explain that if the condition is true,
then the statements in the if block get executed. On the other hand, if the condition evaluates to
te
false, the control is transferred to the statement directly outside the if block.
en

Explain the syntax of the if statement.

Mention that the opening and closing braces are optional, provided that the if clause contains only
C

one statement. Explain to them that deciding when to omit the braces is a matter of personal
choice. Omitting them can make the code more brittle. If a second statement is later added to the
h

if clause, a common mistake would be forgetting to add the newly required braces. The compiler
cannot catch this sort of error and thus, you will get the wrong output or results.
ec

Tips:
pt

The if statement braces contain the statements that are to be executed only if the condition
evaluates to true.
rA

Explain to the student the concept of simple if statement using the code snippet.
Tell them that the program tests the value of result and accordingly calculates the value of
second and prints it. If the result is greater than 1000, then the variable second gets
Fo

increased by 100 and is printed. If not, the value of second is not increased and the original value
is printed. The output of the code will be 800 for the second value.

©Aptech Limited
Decision-Making Constructs

Slides 10 to 12
Let us understand ‘if-else’ statement.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
Using slides 10 to 12, explain the if-else statement in Java.

rU
Tell them that the if-else statement provides a secondary path of execution, when an if
clause evaluates to false.
te
Mention to the students that generally, it is not only important to specify an action to be performed
when the condition is true, but also to specify what action is to be performed if the condition is false.
en

To do this, the if-else statement can be used.

Explain to the students the syntax of the if-else statements.


C

Mention that the program checks whether a number is even or odd. If the remainder is 0, the
message, ‘Number is even’ is printed. Else, the message, ‘Number is odd’ is printed.
h

The output of the program is the message ’Number is odd’.


ec

Tips:
Mention to the students that the if statement can be followed by an optional if...else
pt

statement, which is very useful to test various conditions using single if...else statement.
rA
Fo

©Aptech Limited
Decision-Making Constructs

Slides 13 to 16
Let us understand nested-if statement.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt

Using slides 13 to 16, explain the nested-if statement.


rA

Explain to the students that the if-else statement tests the result of a condition, that is, a
boolean expression, and performs appropriate actions based on the result. The if statement can
Fo

also be used inside another if. This is known as nested-if. Thus, a nested-if is the if statement
that is the target of another if or else.

©Aptech Limited
Decision-Making Constructs

The important points to remember in nested-if statements are as follows:


 The else statement should always refer to the nearest if statement.
 It should be within the same block.

Explain to the students the syntax of the nested-if statements.

Then, explain the code snippet, a variable num is declared which stores an integer value accepted
from the user. Then, using nested-if statements, it checks whether num is divisible by 3 and 5 or
only by 3, and then prints an appropriate message. Bring to the notice of the students that the final
else is associated with if(num % 3 == 0). Tell them that the inner else refers to
if(num % 5 == 0), because it is closest to the inner if within the same block.

y
nl
Slides 17 to 21

O
Let us understand ‘if-else-if’ ladder.

se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt

Using slides 17 to 21, explain the if-else-if ladder.


rA

Tell them that the multiple if construct is also known as the if-else-if ladder. The conditions
are evaluated sequentially starting from the top of the ladder and moving downwards. When a true
condition is found, the statement associated with the true condition is executed.
Fo

Explain them the syntax of multiple if statements.

Explain to the students that when they are using if , else if , else statements, there are few
points to be kept in mind. They are as follows:
 The if can have zero or one else's and it must come after any else if's.
 The if can have zero to many else if's and they must come before the else.
 Once the else if succeeds, none of the remaining else if's or else's will be tested.

©Aptech Limited
Decision-Making Constructs

Tell the students that in the code snippet, the value of totalmarks can satisfy the expression in
the statement, totalMarks >= 40. However, once a condition is satisfied, the appropriate
statements are executed (Grade = B) and the remaining conditions are not evaluated.
The output will be, Grade = B.

Slides 22 to 32
Let us understand ‘switch-case’ Statement.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
Using slides 22 to 32, explain the switch-case statement.

se
The switch-case statement allows a variable to be tested for equality against a list of values.

rU
Each value is called a case, and the variable being switched on is checked for each case. The
switch-case statement is alternative for too many if statements representing multiple
selection constructs. It contains a variable as an expression whose value is compared against
te
different values. Its results are better performance. It can have a number of possible execution paths
depending on the value of expression provided with the switch statement. It can evaluate different
primitive data types, such as byte, short, int, and char.
en

Tell them that the switch-case statement is used, when a variable needs to be compared
C

against different values.

Explain to them about the syntax of the switch-case statements. Mention that the important
h

keywords in switch-case statement are as follows:


ec

 switch
 case
 default
pt

 break
rA

Tips:
Unlike if-then and if-then-else statements, the switch statement can have a number
of possible execution paths. A switch works with the byte, short, char, and int primitive data
Fo

types.

Explain to the students the keywords switch and case. Tell the students that the body of a
switch statement is known as a switch block. Explain to them that the switch keyword is
followed by an integer expression enclosed in parentheses. The expression must be of type int,
char, byte, or short. Mention that each case value must be a unique literal. Thus, it must be a
constant and not a variable.

©Aptech Limited
Decision-Making Constructs

The switch statement executes the case corresponding to the value of the expression. Also
mention that the case keyword is followed by an integer constant and a colon. Each case value is a
unique literal. The case statement might be followed by code sequences that are executed, when
the switch expression and the case value match.

Then, explain to the students about the default and break clause. Mention to the student
that a switch statement can have an optional default case, which must appear at the end of the
switch.

The default case can be used for performing a task, when none of the case statements are
true. No break is needed in the default case. In other words, explain that if no case value matches

y
the switch expression value, execution continues at the default clause. This is the equivalent to

nl
the else clause for the switch statement.

O
Mention to the student the importance of break statement. Tell them that when a break
statement is reached, the switch terminates, and the flow of control jumps to the next line
following the switch statement. Therefore, the break statement is used inside the switch-case

se
statement to terminate the execution of the statement sequence. The control is then transferred to
the first statement, after the end of the switch. The break statement is optional. If there is no
break, execution flows sequentially into the next case statement. Sometimes, multiple cases can be
rU
present without break statements between them.

Tips:
te
Each break statement terminates the enclosing switch statement. Control flow continues with the
first statement following the switch block. The break statements are necessary because without
en

them, statements in switch blocks fall through.

All statements after matching case label are executed in sequence, regardless of the expression of
C

subsequent case labels, until a break statement is encountered.


h

Then, explain the code snippet on slides 28 and 29 which demonstrate the use of switch-case
statement. Explain to the students that in the code snippet, case 3 will be executed because value of
ec

choice is 3. So, the message, Multiplication is displayed and in the next statement, when
break is encountered the program exits.
pt

Then, explain another code snippet that uses multiple case statements with single break
rA

statement.
Fo

©Aptech Limited
Decision-Making Constructs

Slides 33 to 36
Let us understand string-based ‘switch-case’ statement.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 33 to 36, explain the string-based switch statement in Java SE 7.


Fo

Allowing the use of strings in switch-case statement enables the program to incorporate a
readable code. A string is not a primitive data type, but an object in Java. Thus, to use strings for
comparison, a String object is passed as an expression in the switch-case statement.

It is preferable to use string with switch as Java compiler generates most efficient byte code from
switch statements that use String objects.

©Aptech Limited
Decision-Making Constructs

Slides 33 to 35 shows the code snippet that demonstrates the use of strings in the switch-case
statement.

Following points are to be considered while using strings with the switch-case statement:
Null Values
A runtime exception is generated when a String variable is assigned a null value and is passed as an
expression to the switch statement.

Case-sensitive values
The comparison of string objects in switch statements is case-sensitive. The value of String variable
that is matched with the case literals is case sensitive. Example: a String value “Monday” when

y
matched with the case labeled “MONDAY”:, then it will not be treated as a matched value.

nl
In-Class Question:

O
After you finish explaining the string based switch case statements, you will ask the students an In-
Class question. This will help you in reviewing their understanding of the topic.

se
Answer:
rU
When a runtime exception is generated?
te
It is generated when a string variable is assigned a null value and is passed as an expression to the
switch statement.
en

Slides 37 to 39
C

Let us understand enumeration-based ‘switch-case’ statement.


h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 37 to 39, explain the enumeration-based switch-case statement.


Fo

The switch-case statement supports the use of an enumeration value in the expression. It is one
of the greatest new feature introduce from the version 5. Using Java enum in switch-case is
straight forward. Just use enum reference variable in switch and enum constants and interfaces in
case statement. The constraint with an enum expression is that all case constants must belong to
the same enum variable used with the switch statement.

©Aptech Limited
Decision-Making Constructs

Then, explain the code snippet that demonstrates the use of enumerations in the switch-case
statement.

Slides 40 to 43
Let us understand nested ‘switch-case’ statement.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Decision-Making Constructs

y
nl
O
se
rU
te
en
C
h
ec

Using slides 40 to 43, explain the nested-switch statement.


pt

A switch-case statement can be used as a part of another switch-case statement. This is


referred to as nested switch-case statements and it is exactly same idea as nested if-else
rA

statement. Since, the switch-case statement defines its own blocks; no conflicts arise between
the case constants present in the inner switch and those present in the outer switch because each
switch statement defines its own block.
Fo

Nested-switch statement can be use in many applications as it require less work than nested-if
statements and do not have compatibility issues.

Slides 40 to 42 shows the code snippet that demonstrates the use of nested switch-case
statements. 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

©Aptech Limited
Decision-Making Constructs

switch-case statement is executed. The inner switch statement compares the value of
hour variable with case constants “am” or “pm”.

The three important features of switch-case statements are as follows:


 The switch-case statement differs from the if statement, as it can only test for equality.
 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.

In-Class Question:
After you finish explaining the Nested switch case statements, you will ask the students an In-Class

y
question. This will help you in reviewing their understanding of the topic.

nl
O
What is Nested switch case statement?

se
Answer:
A switch-case statement can be used as a part of another switch-case statement which is
rU
referred to as nested switch-case statements.

Slide 44
te
Let us understand comparison between if and switch-case statement.
en
C
h
ec
pt
rA
Fo

Using slide 44, explain the difference between if and switch statement.

Tell them that the if-else-if and the switch-case decision-making statements have
similar use in a program, but there are distinct differences between them.

©Aptech Limited
Decision-Making Constructs

They are as follows:

if-else-if
 Each if has its own logical expression to be evaluated as true or false.
 The variables in the expression may evaluate to a value of any type.
 Only one of the blocks of code is executed.

switch
 Each case refers back to the original value of the expression in the switch statement.
 The expression must evaluate to a byte, short, char or int.
 If the break statement is omitted, the execution will continue into the next block.

y
nl
In-Class Question:
After you finish explaining, the decision-making statements in Java, you will ask the students an In-

O
Class question. This will help you in reviewing their understanding of the topic.

se
Which decision-making statement allows for any number of possible execution paths?

Answer: rU
The switch statement allows for any number of possible execution paths.
te
en

Slide 45
Let us summarize the session.
C
h
ec
pt
rA
Fo

In slide 45, you will summarize the session. End the session with a brief summary of what has been
taught in the session.

©Aptech Limited
Decision-Making Constructs

4.3 Post Class Activities for Faculty


You should familiarize yourself with the topics of the next session which is based on iterative
construct in Java.

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

Session 5 – Looping Constructs


5.1 Pre-Class Activities
Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
5.1.1 Objectives

nl
O
By the end of this session, the learners will be able to:
 List the different types of loops

se
Explain the while statement and the associated rules
 Identify the purpose of the do-while statement
 State the need of for statement



Describe nested loops
Compare the different types of loops
State the purpose of jump statements
rU
te
 Describe break statement
 Describe continue statement
en

5.1.2 Teaching Skills


C

To teach this session, you should be well-versed with different types of looping statements available
in Java programming language and the various jump statements which is called branching
h

statements.
ec

You should teach the concepts in the theory class using the images provided. For teaching in the
class, you are expected to use slides and LCD projectors.
pt

Tips:
rA

It is recommended that you test the understanding of the students by asking questions in between
the class.
Fo

In-Class Activities:
Follow the order given here during In-Class activities.

©Aptech Limited
Looping Constructs

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
Tell the students that this session introduces the different types of looping statements available in

rU
Java programming language and the various jump statements which is called branching statements.
Also it introduces the nested loops and compares the different types of loops.
te
5.2 In-Class Explanations
en

Slide 3
Let us understand the concepts of loops.
C
h
ec
pt
rA
Fo

Using slide 3 explain, introduction of loops.

Tell the students that a computer program is 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.

©Aptech Limited
Looping Constructs

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 addition
of 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.

y
Slide 4

nl
Let us understand looping statements.

O
se
rU
te
en
C
h

Using slide 4, explain Looping Statements.


ec

Loops enable programmers to develop concise programs, which otherwise would require thousands
of program statements. Loops consist of statement or a block of statements that are repeatedly
pt

executed. Statements in the loops are executed until a condition evaluates to true or false.
rA

Mention to the students the different types of the loop statements supported by Java programming
language are as follows:


Fo

while
• do-while
• for
• for-each

Tips:
All programming languages follow these three basic types of loop statements. The syntax changes
according to the programming language.

©Aptech Limited
Looping Constructs

In-Class Question:
After you finish explaining looping statements, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.

What does loop consists of?

Answer:
Loops consist of statement or a block of statements that are repeatedly executed, until a condition
evaluates to true or false.

y
Slides 5 to 9

nl
Let us understand the ‘while’ statement.

O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 5 to 9, explain the ‘while’ statement.

Mention to the students that the while statement in Java is used to execute a statement or a
block of statements, while a particular condition is true. Bring to the notice of the students that the
condition is checked, before the statements are executed. The condition for the while statement
can be any expression which returns a boolean value.

©Aptech Limited
Looping Constructs

Explain to them the syntax of the while loop.

Tell them that when executing, if the expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.

Tips:
The key point of the while loop is that the loop might not ever run.

Tell them that as shown in the code snippet, a variable of type integer, num, is declared to store the
number. The variable num is initialized to 1 and used in the while loop to start multiplication
from 1.

y
The condition num <= 5 ensures that the while loop executes as long as the value in num is

nl
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. The first statement within the body of the loop, calculates the value of

O
product by multiplying num with 10. The next statement prints this value and the last statement
within the body of the loop changes the value of num by incrementing it by 1.

se
Tips:
The key point of while loop is that when the expression is tested and the result is false, the loop
body will skipped and the first statement after the while loop will be executed.

Slides 10 and 11
rU
te
Let us understand null statement in loops.
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
Using slides 10 and 11, explain the null statement in loops.

se
There are situations when it is required to write a loop without any action statement to delay a
process. Such a loop is referred to as null statement loop.

Null statement loop:


rU
 There are no statements in the body of the loop.
 The loop is terminated with a semicolon.
te
Explain the code snippet that demonstrates a code that prints the midpoint of two numbers with an
en

empty while loop mentioned in the slides.

Tell them that a null statement is used to provide a null operation in situations where the grammar
C

of the language requires a statement, but a program requires no work to be done.

Tips:
h

The most common use of null statement is in the loop operations in which all the loop activity is
ec

performed by the test portion of the loop. It is useful where a label is needed just before a brace
that terminates compound statement.
pt

In-Class Question:
After you finish explaining null statement, you will ask the students an In-Class question. This will
rA

help you in reviewing their understanding of the topic.


Fo

How null statement loop can be identified?

Answer:
 There are no statements in the body of the loop.
 The loop is terminated with a semicolon.

©Aptech Limited
Looping Constructs

Slide 12
Let us understand rules for using ‘while’ loop.

y
nl
O
se
Using slide 12, explain rules for using ‘while’ loop.

rU
Tell them that the rules to be followed while implementing the while statements are as follows:
 The values 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
te
performed once, before the execution of the loop.


en

The body of the loop must have an expression that changes the value of the variable that is a
part of the loop’s expression. A variable is said to be incremented if its value increases in the
body of the loop, and is said to be decremented if its value decreases.
C

Slide 13
Let us understand infinite loop.
h
ec
pt
rA
Fo

Using slide 13, explain infinite loop.

An infinite loop is one which never terminates. It runs infinitely when the conditional expression or
the increment/decrement expression of the loop is missing.

©Aptech Limited
Looping Constructs

Any type of loop can be infinite loop. The loop never terminates as the expression always returns a
true value.

Explain the code snippet shows the implementation of an infinite loop using the while statement
mentioned in slide 13. The condition is simply a boolean value true, which leads to an infinite loop.

Additionally, explain the code showing an infinite while loop.


int count = 0;
while(count < 100) {
System.out.println(“This goes on forever, HELP!!!”);
count = count + 10; \\Incrementing the value of count by 10.
System.out.println(“Count = “ + count);

y
count= count - 10; \\Decrementing the value of count by 10.

nl
System.out.println(“Count = “ + count);
}

O
Explain to them that in the code, the value of count is always 0, which is less than 100. So, the
expression always returns a true value. Hence, the loop never ends.

se
A break statement can be used to terminate such programs. Thus, it will just go into the loop once
and terminate, displaying the output as:
This goes on forever, HELP!!!
Count = 10
Count = 0
rU
te
Slides 14 to 17
en

Let us understand ‘do-while’ statement.


C
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 14 to 17, explain the ‘do-while’ statement.

Tell the students that the Java programming language also provides a do-while statement.
Mention that the do-while statement checks the condition at the end of the loop rather than at
the beginning, to ensure that the loop is executed at least once. The condition of the do-while
statement usually comprises of an expression that evaluates to a boolean value.
Explain the syntax of do-while statement from slide.

©Aptech Limited
Looping Constructs

Tips:
The do-while evaluates its expression at the bottom of the loop instead of the top.

The flow of execution for the do-while loop:


• For each iteration, the do-while loop first executes the body of the loop and then, the
conditional expression is evaluated.
• When the conditional expression evaluates to true, the body of the loop executes.
• When the conditional expression evaluates to false, the loop terminates.
• The statement following the loop is executed.

For example, here’s a loop that counts 1 to 10.

y
int number = 1;

nl
do
{

O
System.out.print(number + " ");
number ++;

se
} while (number <= 10);

In ‘do-while’ loop, boolean expression appears at the end of the loop, so the statements in the

rU
loop execute once before the boolean is tested.

Tell them that in the code snippet, two integer variables, num and sum are declared and initialized
te
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 then,
en

the next statement in the loop changes the value of num by incrementing it by 1.

Next, the condition, num <= 10, included in the while statement is evaluated. If the condition is
C

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

The output will be, Sum = 55.


ec

Slides 18 to 22
Let us understand ‘for’ statement.
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
Using slides 18 to 22, explain the ‘for’ statement.

Tell them that a for loop is a repetition control structure that allows you to efficiently write a loop

se
that needs to execute a specific number of times.

rU
In other words, the for loops are especially used when the user knows how many times the
statements need to be executed in the code block. It is similar to the while statement in its
function. The statements within the body of the loop are executed as long as the condition is true.
Here too, the condition is checked before the statements are executed.
te
Explain to the students the syntax as follows:
en

 Initialization: Initializes the variables that will be used in the condition.


 Condition: Comprises the condition that is tested, before the statements in the loop are
C

executed.
 Increment/decrement: Comprises the statement that changes the value of the variable(s) to
ensure that the condition specified in the section is reached. Typically, increment and decre-
h

ment operators, such as ++, --, and shortcut operators, such as += or -= are used in
ec

this section. Note that there is no semicolon at the end of the increment/decrement
expressions.
pt

Tips:
A for loop is useful when you know how many times a task is to be repeated.
rA

Working of the for loop


Fo

Tell them that the three declaration parts are separated by semicolons. When the loop starts, the
initialization portion of the loop is executed. Generally, this is an expression that sets the value of
the loop control variable and acts as a counter that controls the loop. The initialization expression is
executed only once.

Next, point out that the boolean expression is evaluated. It usually tests the loop control variable
against a targeted value. If the expression is true, then the body of the loop is executed and if the
expression is false, then the loop terminates.

Lastly, tell them that the iteration portion of the loop is executed. This expression will usually
increment or decrement the loop control variable.

©Aptech Limited
Looping Constructs

In slide 21, you will explain the for statement using the code snippet. Tell them that 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 loop
exits when the condition becomes false, that is, when the value of num becomes equal to 6.
Finally, point out to the students that the increment statement, num++ in the
increment/decrement section of the for statement, increments the value of num by 1. The
increment/decrement expression is evaluated after the first round of iteration.

The output will be as shown:


1 * 10 = 10
2 * 10 = 20

y
3 * 10 = 30
4 * 10 = 40

nl
5 * 10 = 50

O
In-Class Question:
After you finish explaining for statement, you will ask the students an In-Class question. This will help

se
you in reviewing their understanding of the topic.

rU
How long the statements are executed in for loop?
te
Answer:
The statements within the body of the loop are executed as long as the condition is true.
en

Slides 23 and 24
Let us understand scope of control variable in ‘for’ statement.
C
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
Using slides 23 and 24, explain scope of control variable in ‘for’ statement.

se
Control Variables
• Are used within the for loops and may not be used further in the program.
• It is possible to restrict the scope of variables by declaring them at the time of initialization.

rU
A variable declared in for statement can only be used in that statement and in the body of the loop.
The scope of variable extends from its declaration to the end of the block of the for statement, so it
te
can be used in termination and increment expressions as well.

Explain the code snippet that declares the counter variable inside the for statement mentioned in
en

slides 23 and 24.


C

Slides 25 to 27
Let us understand use of comma operator in ‘for’ statement.
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
se
rU
te
en
C

Using slides 25 to 27, explain use of comma operator in ‘for’ statement.


h

Expressions:
ec

• The for statement can be extended by including more than one initialization or increment
expressions.
pt

• Expressions are separated by using the ‘comma’ (,) operator.


• Expressions are evaluated from left to right.
• The order of the evaluation is important, if the value of the second expression depends on
rA

the newly calculated value.

Explain the code snippet that demonstrates the use of for loop to print the addition table for two
Fo

variables using the ‘comma’ operator mentioned in the slides.

Explain to them that 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 0 and j is assigned the value of max, that is, 10. Thus, two parameters
are initialized using a ‘comma’ operator.

Bring to the notice of the student that 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.

©Aptech Limited
Looping Constructs

Finally, explain that 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.

Tips:
Any or all expressions in the for loop may be left blank. If all the three expressions are left blank,
an infinite loop will be created.

Slides 28 and 29
Let us understand variation in ‘for’ loop.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 28 and 29, explain variation in ‘for’ loop.

The most common variation involves the conditional expressions which can be:
 Tested with the targeted values, but, it can also be used for testing boolean expressions.
Alternatively, the initialization or the iteration section in the for loop may be left empty, that is,
they need not be present in the for loop.

Explain the code snippet that demonstrates the use of for loop without the initialization expression
mentioned in the slides.

©Aptech Limited
Looping Constructs

Slide 30
Let us understand infinite ‘for’ loop.

y
nl
O
se
Using slide 30, explain the Infinite ‘for’ Loop.

rU
If all the three expressions are left empty, then it will lead to an infinite loop. The infinite for loop
will run continuously because there is no terminating condition. Infinite loops make the program run
indefinitely for a long time resulting in the consumption of all resources and stopping the system.
te
An infinite loop is a sequence of instructions which loops endlessly.
en

Slides 31 and 32
Let us understand enhanced ‘for’ loop.
C
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
Using slides 31 and 32, explain the enhanced ‘for’ loop.

It is designed to retrieve or traverse through a collection of objects, such as an array. It is also used

se
to iterate over the elements of the collection objects, such as ArrayList, LinkedList,
HashSet, and so on defined in the collection framework. It continues till all the elements from a
collection are retrieved.
rU
Then, explain the syntax for using the enhanced for loop. Assuming that in the syntax, var is
defined to be an array of String objects, then each element is assigned to the var variable as it
te
loops through the array.
en

Tips:
The enhanced for loop was introduced in Java 5 as a simpler way to iterate through all the elements
C

of a collection. Enhanced for loops are simple, but inflexible. They can be used when you wish to
step through the elements of the array in first-to-last order, and you do not need to know the index
of the current element. In all other cases, the "standard" for loop should be preferred.
h
ec

Then, explain how to retrieve the elements of an array using standard for as well as for-each loop
discussed on slide 32.
pt

The code can be completed to execute both the loops as shown:


rA

 The usual way to step through all the elements of an array in order is with a standard for
loop will be as follows:
Fo

for (int i = 0; i < myArray.length; i++) {


System.out.println(myArray[i]);
}

 The enhanced for loop is a simpler way of retrieving elements from the array as follows:
for (int myValue : myArray) {
System.out.println(myValue);
}

©Aptech Limited
Looping Constructs

Slides 33 to 35
Let us understand nested-for loop.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 33 to 35, explain the nested loop.

The placing of a loop statement inside the body of another loop statement is called nesting of loops.
While nesting two loops, outer loop takes control of the inner loop. There can be any number of

©Aptech Limited
Looping Constructs

combinations between the three types of loops. The most commonly nested loops are formed by for
statements which can be nested within another for loop forming nested-for loop.

Explain the code snippet that demonstrates the use of a nested-for loop for displaying a pattern
mentioned in the slides. Explain them in the nested loops, the outer loop changes only after the
inner loop is completely finished.

Slide 36
Let us understand comparison of loops.

y
nl
O
se
rU
te
Using slide 36, explain comparison of loops.
en

Explain to them that the type of loop, that is chosen while writing a program, depends on the good
C

programming practice.

Mention that a loop written using the while statement can also be rewritten using the for
h

statement and vice versa. The do-while statement can be rewritten using the while or the
ec

for statement. However, this is not advisable because the do-while statement is executed at
least once. When the number of times the statements within the loop should be executed is known,
the for statement is used.
pt

Point out the differences between while/for and do-while loops:


rA

while/for
 Loop is pre-tested. The condition is checked before the statements within the loop, are
executed.
Fo

 The loop does not get executed if the condition is not satisfied at the beginning.

do-while
 Loop is post-tested. The condition is checked after the statements within the loop, are
executed.
 The loop gets executed at least once even if the condition is not satisfied at the beginning.

©Aptech Limited
Looping Constructs

In-Class Question:
After you finish explaining the loops in Java, you will ask the students an In-Class question. This will
help you in reviewing their understanding of the topic.

How do you write an infinite loop using the for statement?

Answer:
for ( ; ; ) {
}

y
nl
Which of the loop statement is similar to the while statement, but evaluates its

O
expression at the bottom of the loop?

Answer:

se
The do-while statement is similar to the while statement, but evaluates its expression at the
bottom of the loop.

Slide 37
Let us understand jump statements.
rU
te
en
C
h
ec
pt
rA

Using slide 37, explain the jump statements.


Fo

Tell the students that at times, the exact number of times the loop has to be executed is known only
during runtime. In such a case, the condition to terminate the loop can be enclosed within the body
of the loop. At some times, based on a condition, the remaining statements present in the body of
the loop need to be skipped.

Java supports jump statements that unconditionally transfer control to locations within a program
known as target of jump statements.
Java provides two keywords, break and continue that serve diverse purposes. However, both
are used with loops to change the flow of control based on conditions.

©Aptech Limited
Looping Constructs

Slides 38 to 40
Let us understand ‘break’ statement.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 38 to 40, explain the ‘break’ Statement.

Tell them that the break keyword is used to stop the entire loop. The break keyword must be
used inside any loop or a switch statement.

©Aptech Limited
Looping Constructs

Explain that the break statement in Java is used in two ways. First, it can be used to terminate a
case in the switch statement. Second, it forces immediate termination of a loop, bypassing the
loop’s normal conditional test.

When the break statement is encountered inside a loop, the loop is immediately terminated and
the program control is passed to the statement following the loop.

Explain the use of break as shown in the code snippet that demonstrates the use of break
statement in the slides.

Slides 41 and 42

y
Let us understand the ‘continue’ statement.

nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 41 and 42, explain the ‘continue’ statement.

Tell them that the continue keyword can be used in any of the loop control structures. It causes
the loop to immediately jump to the next iteration of the loop.

Mention the following points:


 In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.

©Aptech Limited
Looping Constructs

 In a while loop or do/while loop, flow of control immediately jumps to the boolean
expression.

Explain the code snippet. Tell them that 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, then the if statement evaluates to false, square and cube of cnt is calculated
and displayed.

Slides 43 to 47

y
Let us understand the labeled statements.

nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Looping Constructs

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 43 to 47, explain the labeled statements.

Tell them that a labeled statement is used only in case of nested loops.

©Aptech Limited
Looping Constructs

Labeled break Statement


It is used to indicate the nested loop that is to be continued with the next iteration or the nested
loop to break from. A break keyword, when used with a label, exits out of the labeled loop.

Tell them that in the code snippet, the loop is supposed to be executed five times. The first two
times it displays the sentence, ‘This is the outer loop’. In the third pass, the value of i is equal to 2,
thus it enters the if statement and prints the message, ‘Hello’.

Next, the break statement is encountered and the control passes to the label, outer:. Thus, the
loop is terminated and the last statement is printed.

y
Mention that the output of the code will be:
This is the outer loop.

nl
This is the outer loop.
Hello

O
Good-Bye

se
Labeled continue Statement
Similar to labeled break statement, where user can specify a label to enclose a loop that continues
with the next iteration of the loop.

rU
Explain the code snippet demonstrates the use of labeled continue statement mentioned in slides
46 and 47.
te
In-Class Question:
en

After you finish explaining, the jump statements in Java, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
C

Use of which jump statement will allow the programmer to transfer the control to the
statement outside the loop?
h
ec

Answer:
Break
pt
rA
Fo

©Aptech Limited
Looping Constructs

Slide 48
Let us summarize the session.

y
nl
O
se
In slide 48, you will summarize the session. End the session with a brief summary of what has been
taught in the session.

5.3 Post Class Activities for Faculty


rU
You should familiarize yourself with the topics of the next session which is based on classes and
te
objects in Java.
en

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
C

online tutors on the Online Varsity site to ask queries related to the sessions.
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

Session 6 – Classes and Objects

6.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
6.1.1 Objectives

nl
By the end of this session, the learners will be able to:

O
 Explain the process of creation of classes in Java
 Explain the instantiation of objects in Java
 Explain the purpose of instance variables and instance methods

se
 Explain constructors in Java
 Explain the memory management in Java
 Explain object initializers

6.1.2 Teaching Skills


rU
te
To teach this session, you should be well-versed with creation of classes in Java and the constructors
in Java. Also familiarize yourself with the purpose of instance variables, instance methods, and
en

object initializers in Java.

You should teach the concepts in the theory class using the images provided. For teaching in the
C

class, you are expected to use slides and LCD projectors.


h

Tips:
ec

It is recommended that you test the understanding of the students by asking questions in between
the class.
pt

In-Class Activities:
Follow the order given here during In-Class activities.
rA
Fo

©Aptech Limited
Classes and Objects

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
Tell them that Java is an object-oriented programming language used for developing various types of

rU
applications that can be executed on any platform. Explain to the student that this session will
familiarize them with the concept of classes and objects. This session explains them the instance
variables, instance methods, constructor methods, methods defined in the class. It also gives a brief
te
explanation of object initializers.
en

6.2 In-Class Explanations


C

Slide 3
Let us understand the concept of class in Java.
h
ec
pt
rA
Fo

Using slide 3, explain the concept of class in Java.

Class is the prime unit of execution for object-oriented programming in Java. The class is a logical
construct that defines the shape and nature of an object. Each object created from the class contains
its own copy of the attributes defined in the class.

©Aptech Limited
Classes and Objects

Everything in Java is contained in the classes. It is a collection of data members and functions where
data members are variable that are declared inside a class and member functions are the functions
or methods defined inside the class.

Next, you explain to them the rules for declaring a class. Tell them that:
 A class declaration should contain the keyword class and the name of the class that is
being declared.
 Class name should be a noun.
 Class name can be in mixed case, with the first letter of each internal word capitalized.
 Class name should be simple, descriptive, and meaningful.
 Class names cannot be Java keywords.

y
 Class names cannot begin with a digit. However, they can begin with a dollar ($) symbol or

nl
an underscore character (_).

O
Slides 4 and 5
Let us understand declaring a class.

se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 4 and 5, explain how to declare a class in Java.

Explain to them the syntax for declaring a class.

Mention to the students that this is a class declaration. The class body that is the area between the
braces. It contains all the code that provides for the life cycle of the objects created from the class.

©Aptech Limited
Classes and Objects

In other words, it contains the constructors for initializing new objects, declarations for the fields
that provide the state of the class and its objects, and methods to implement the behavior of the
class and its objects.

After explaining the syntax for declaring a class, explain to them the code snippet. Specify that the
code declares a class named Customer and within the braces, you need to define the variables and
methods of the class.

Tips:
The Javadoc comments for a class are as shown:
/**
* class description

y
*

nl
* @version 1.0
* @authorName Robert Robbsen

O
*/
@version adds ’Version’ subheading, for classes and interfaces, with version-text to the
generated docs when the -version option is used with Javadoc utility. This tag holds the current

se
version number of the software.

rU
@authorName adds author entry with name-text specified to the generated docs.

Slides 6 and 7
Let us understand declaring and creating an object.
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
Using slides 6 and 7, explain declaring and creating an object of the class in Java.

Mention that an object is created using the new keyword. On encountering the new keyword, the

se
JVM allocates memory for the object, invokes the constructor of the class, and returns a reference of
that allocated memory. The reference is assigned to the object.

rU
Next, explain the syntax for creating an object as shown:
Explain the code snippet. Tell them that it creates an object for the class Customer named,
objCustomer.
te
Tips:
en

Explain the following steps for creating an object from a class:


 Declaration: A variable declaration with a variable name with an object type.
 Instantiation: The new keyword is used to create the object.
C

 Initialization: The new keyword is followed by a call to a constructor. This call initializes the
new object.
h
ec

Slides 8 to 10
Let us understand creation of an object.
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C

Using slides 8 to 10, explain declaring and creating an object.


h

Discuss with the students that an object can be declared without using the new operator as shown:
ec

<class_name> <object_name>;
pt

However, in this case, the object object_name will not point to any memory location and memory
will not be allocated. Using an object, created without using the new operator, in the program will
rA

result in compile time error. Before using such an object, the object should be initialized using the
new operator.

Explain the figure which shows the effect of the statement, Customer objCustomer; which declares
Fo

a reference variable as mentioned in slide 9.

By default, the value null is stored in the object’s reference variable which means reference variable
does not point to an actual object.

Dynamic memory allocation of an object:


The object should be initialized using the new operator which dynamically allocates memory for an
object.

The new operator instantiates a class by allocating memory to the object and returning a reference
to that memory. The new operator returns a reference to an object it created.

©Aptech Limited
Classes and Objects

The reference returned by a new operator does not have to be assigned to a variable. It can also be
used directly in an expression.

Explain the figure that shows the creation of object in the memory and storing of its reference in the
variable, objCustomer as mentioned in slide 10.

Slide 11
Let us understand members of a class.

y
nl
O
se
rU
te
Using slide 11, explain members of a class.
en

The members of a class are fields and methods.


C

Fields - It defines the state of an object created from the class. It is referred to as instance
variables.
 Methods - Methods implement the behavior of the objects. It is referred to as instance
h

methods.
ec

Slides 12 to 18
Let us understand instance variables.
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 12 to 18, explain instance variables.

Consider a scenario, wherein a car dealer wants to keep track of the price of various cars in stock. So,
to store the prices of various cars, you need variables. Accordingly, you need several local variables
to store prices. However, an alternative is to create a class and declare a variable named, price in it.
This enables every instance created from this class to have its own copy of price variable referred to
as instance variable.

©Aptech Limited
Classes and Objects

Tell them that the figure from the slide demonstrates the instances of class with their own copy of
instance variable.

Tips:
The benefit of using instance variables over local variables is that, you declare only one instance
variable and use it for all instances of the class. The name of instance variable is shared across all
instances, but each instance has its own copy of instance variable.

First, bring to the notice of the students that there are several kinds of variables:
 Member variables in a class—these are called fields or instance variables.
 Variables in a method or block of code—these are called local variables.

y
 Variables in method declarations—these are called parameters.

nl
Tell them that instance variables are declared in the same way as local variables. The declaration

O
comprises the data type and a variable name. An instance variable also has an access specifier
associated with it. Tell them that an access modifier lets you control what other classes have access
to a member field. Instance variables are declared inside a class, but outside any method definitions.

se
They can be accessed only through an instance using the dot notation. Instance variables are
accessed by objects using the dot operator (.).

rU
Explain the syntax for declaring an instance variable within a class.
 access_modifier is an optional keyword specifying the access level of an instance
variable. It could be private, protected, and public.
te
 data_type specifies the data type of the variable. It can be of primitive types such as int,
float, boolean, and so on. Also it can be of reference types, such as strings, arrays, or objects.
en

 instanceVariableName specifies the name of the variable.

Tips:
C

It is common to make fields private. This means that they can only be directly accessed from the
class.
h

Explain the code snippet that demonstrates the declaration of instance variables within a class in the
ec

Java program as mentioned in slides 16 and 17.


pt

Finally, explain the pictorial representation of the object instantiated from the class along with the
generated output.
rA

In-Class Question:
After you finish explaining the Memory Management in Java, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
Fo

Where instance variables are declared?

Answer:
They are declared inside a class, but outside any method definitions.

©Aptech Limited
Classes and Objects

After you finish explaining, the concept of instance variables in Java, you will ask the students an In-
Class question. This will help you in reviewing their understanding of the topic.

How do you access instance variables?

Answer:
Instance variables are accessed using objects.

y
Slides 19 to 24
Let us understand instance methods.

nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
Using slides 19 to 24, explain Instance Methods.

They are functions declared in a class. They implement the behavior of an object. They are used to

se
perform operations on the instance variables. They can be accessed by instantiating an object of the
class in which it is defined and then, invoking the method. Instance method can access instance
variables and instance methods directly.
rU
For example, the class Car can have a method a Brake() that represents the ‘Apply Brake’ action.
To perform the action, the method Brake() will have to be invoked by an object of class Car.
te
Explain to them that following conventions have to be followed while naming a method:
en

 Cannot be a Java keyword.


 Cannot contain spaces.
 Cannot begin with a digit.
C

 Can begin with a letter, underscore, or a ’$’ symbol.


 Should be a verb in lowercase.
h

 Should be descriptive and meaningful.


ec

 Should be a multi-word name that begins with a verb in lowercase, followed by adjectives,
nouns, and so forth.
pt

Explain the syntax of defining the instance method in the class. More generally, method declarations
have six components, in order:
rA

1. Modifiers — such as public, private, and others you will learn about later.
2. The return type — the data type of the value returned by the method, or void, if the
method does not return a value.
Fo

3. The method name — the rules for field names apply to method names as well, but the
convention is a little different.
4. The parameter list in parenthesis — a comma-delimited list of input parameters, preceded
by their data types, enclosed by parentheses (). If there are no parameters, you must use
empty parentheses.
5. An exception list — the list of the exception which the method can throw from its body.
6. The method body, enclosed between braces — the method's code, including the declaration
of local variables, goes here.

©Aptech Limited
Classes and Objects

Each instance of the class has its own instance variables, but the instance methods are shared by all
the instances of the class during execution. As methods are part of class declaration, they can access
the other class member, such as instance variables and method of the class.

Explain the code snippet that demonstrates the code that declares instance methods within the
class, Customer as mentioned in slides 23 and 24.

Tips:
Instance methods should be placed in the class such that there is no needless duplication of it and it
is accessed in all the subclasses of the class in which it is defined.

y
Slides 25 to 28
Let us understand invoking methods.

nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C
h

Using slides 25 to 28, explain invoking methods.


ec

To invoke a method, the object name is followed by the dot operator (.) and the method name. A
method is always invoked from another method. The method which invokes a method is referred to
pt

as the calling method. The invoked method is referred to as the called method. After execution of all
the statements within the code block of the invoked method, the control returns back to the calling
rA

method.

Explain the code snippet that demonstrates a class with main () method which creates the
Fo

instance of the class Customer and invokes the methods defined in the class as mentioned in slides
26 to 28.

When a program invokes a method, the program control gets transferred to the called methods.
When the method is invoked, all the statements that are part of the method would be executed.
When the JVM invokes a class method, it selects the method to invoke based on the type of object
reference which is always known as compile time.

©Aptech Limited
Classes and Objects

Tips:
The Javadoc comments that are used for methods in Java are as follows:
 Method description: Javadoc comments on description of the method.
 @param tag: is followed by the name (not data type) and description of the parameter.
 @return tag: is used to specify the return type of methods. It is not used with methods
having a void return type.

Statements in the current method after the return statement are skipped, and the control returns to
the statement that invoked the method. With methods that are declared void, use the form of
return statement that does not return any value.
return;

y
nl
Sometimes, a void method has to return explicitly depending on a condition. In this situation, this
form of return statement can be used.

O
Slides 29 to 31
Let us understand constructor.

se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
Using slides 29 to 31, explain constructor methods in a Java class.

Bring to the notice of the students the importance of constructors. Tell them that when discussing

se
about classes, one of the most important sub topic would be constructors. Every class has a
constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default
constructor for that class.
rU
Next, provide the definition of constructor. Constructors are methods in a class that create objects
or instances of a class. Besides this, the constructors are used for initializing variables and invoking
te
any methods that may be required for initialization.
en

The constructor is invoked when an object is created. They do not have return types, but do have
parameters. A no-argument, default constructor is provided by the complier for any class that does
C

not have an explicit constructor.

Tips:
h

A class can have more than one constructor.


ec

The main rule for constructors is that they should have the same name as the class.

Explain the syntax for declaring a constructor.


pt

Java provides a default constructor which takes no argument and performs no special actions or
rA

initializations. The only action taken by the implicit default constructor is to call the superclass
constructor using super ().
Fo

Slide 31 shows the code snippet that demonstrates a class Rectangle with a constructor.

©Aptech Limited
Classes and Objects

Slides 32 to 34
Let us understand invoking constructor.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 32 to 34, explain how to invoke constructor method.

©Aptech Limited
Classes and Objects

The constructor is invoked immediately during the object creation which means:
 Once the new operator is encountered, memory is allocated for the object.
 Constructor method is invoked by the JVM to initialize the object.

The standard way to create objects in Java using new keyword which allocates the memory for the
new object, its instance variable is initialized, and constructor body is executed.

Explain the code snippet that demonstrates the code to invoke the constructor for the class
Rectangle as mentioned in slides 33 and 34.

Slides 35 to 39

y
Let us understand default constructor in the class.

nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 35 to 39, explain constructors in the class.

Consider a situation, where the constructor method is not defined for a class. In such a scenario, an
implicit constructor is invoked by the JVM for initializing the objects. This implicit constructor is also
known as default constructor.

©Aptech Limited
Classes and Objects

Default Constructor:
 Created for the classes where explicit constructors are not defined.
 Initializes the instance variables of the newly created object to their default values.

Explain the table which lists the default values assigned to instance variables of the class depending
on their data types mentioned in slide 36.

Explain the code snippet that demonstrates a class containing the main() method that creates an
instance of the class Employee and invokes its methods as mentioned in slides 37 to 39.

In Java, default constructors refer to a null constructor that is automatically generated by the

y
compiler if no constructors have been defined for the class. This means, they are empty and contain

nl
nothing.

O
In-Class Question:
After you finish explaining, the concept of constructors in Java, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.

se
rU
Is it a must to declare a default constructor for a class?
te
Answer:
No. If we do not explicitly write a constructor for a class, then the Java compiler builds a default
en

constructor for that class. The default constructor generated by the JVM is also called as vanilla
constructor.
C

Slides 40 to 44
Let us understand parameterized constructor.
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
Using slides 40 to 44, explain parameterized constructor.

The parameterized constructor contains a list of parameters that initializes instance variables of an

se
object. The value for the parameters is passed during the object creation. This means each object
will be initialized with different set of values.

rU
Explain the code snippet that demonstrates the code that declares parameterized constructor for
the Rectangle class mentioned in slides 40 to 41.
te
Explain the code snippet that demonstrates the code with main() method that creates objects of
type Rectangle and initializes them with parameterized constructor as mentioned in slides 42 and
en

43.
C

Each object contains its own copy of instance variables that are initialized through constructor which
is displayed in slide 44.
h

Tell them that in parameterized constructor, the number of parameters can be greater or equal to
ec

one. When an object is declared in a parameterized constructor, the initial values have to be passed
as argument to constructor function.
pt
rA
Fo

©Aptech Limited
Classes and Objects

Slides 45 and 46
Let us understand memory management in Java.

y
nl
O
se
rU
te
en
C
h
ec

Using slides 45 and 46, explain memory management in Java.


pt

Memory management is one of the prominent features of Java platform. Memory management is
the process of allocating new objects and removing unused objects to make space for those new
rA

object allocations.

Tell them that the memory comprises two areas namely, stack and heap.
Stack
Fo

 It is an area in the memory which stores object references and method information.
 It stores parameters of a method and local variables.

Heap
 It is area of memory deals with dynamic memory allocations.
 In Java, objects are allocated physical memory space on the heap at runtime, that is,
whenever JVM executes the new operator.

The heap memory grows as and when the physical allocation is done for objects. Hence, JVM
provides a garbage collection routine which frees the memory by destroying objects that are no
longer required in Java program. This way the memory in the heap is re-used for objects allocation.

©Aptech Limited
Classes and Objects

The figure shows the memory allocation for objects in stack and heap for Rectangle object in slide
46.

In-Class Question:
After you finish explaining the memory management in Java, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.

What is the use of garbage collection routine?

y
Answer:

nl
It frees the memory by destroying objects that are no longer required in Java program. Hence, the
memory in the heap is re-used for objects allocation.

O
Slides 47 to 50

se
Let us understand assigning object references.

rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C

Using slides 47 to 50, explain assigning object references.


h

Explain them how the value of two variables in copied using assignment operators for primitive data
ec

types. Explain the figure presented on slide 47 as follows:


pt

 int a = 10; int b = a; copies the value from variable a and stores it in the variable b.
rA

Similarly, the values between the two objects can be copied. However, the object variable also
known as reference variable contains the address of the object created in the heap. Thus, copying
the values in the objects, copies the reference or address.
Fo

Point on copying reference in objects is as follows:

 Both the reference variables must be of same type, that is, both the references must belong to
the same class.
 Thus, the references are copied between the variables created on the stack without affecting the
actual objects created on the heap.

Explain the code snippet that demonstrates assigning the reference of one object into another
object reference variable mentioned in slides 48 and 49.

The figure shows assigning of reference for the statement, objRec2 = objRec1; in slide 50.

©Aptech Limited
Classes and Objects

As values between primitive data types can be copied, similarly the value stored in object reference
type can be copied into another reference variable. As Java is strongly-typed language, both
reference variables can be of same type. In other words, both the references must belong to the
same class.

Reference variable can be used to store the address of the variable. Assigning reference will not
create distinct copies of objects.

Slide 51
Let us understand encapsulation in Java.

y
nl
O
se
rU
te
en
C
h

Using slide 51, explain encapsulation in Java.


ec

In OOP languages, the concept of hiding implementation details of an object is achieved by applying
the concept of encapsulation. It is a mechanism which binds code and data together in a class.
pt

The main purpose of encapsulation is to achieve data hiding within a class which means:
rA

 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
Fo

application and the rest can be hidden.

By hiding the implementation details about what is required to implement the specific operation in
the class, the usage of operation becomes simple.

Encapsulation is also called data hiding. It is said that in OOP languages, encapsulation covers the
internal workings of Java object. The main purpose of data hiding within a class is to reduce the
complexity in the software development.

Data encapsulation hides the instance variables that represent the state of an object. Thus, the only
interaction and modification is performed through methods.

©Aptech Limited
Classes and Objects

Slides 52 to 54
Let us understand access modifiers.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 52 to 54, explain access modifiers in Java.

©Aptech Limited
Classes and Objects

In Java, the data hiding is achieved by using access modifiers. Access modifiers are the keywords in
OOP languages that set the accessibility of classes, methods, and other members. They are specific
part of programming language that facilitates the encapsulation of components.

Features of access modifiers are:


 Determine how members of a class, such as instance variable and methods are accessible
from outside the class.
 Decide the scope or visibility of the members.
 Are of four types:
 public
o Members declared as public can be accessed from anywhere in the class as well

y
as from other classes.
 private

nl
o Members are accessible only from within the class in which they are declared.

O
 protected
o Members to be accessible from within the class as well as from within the
derived classes.

se
 package (default)
o It 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.
rU
As a general rule in Java, the details and implementation of a class is hidden from the other classes
te
or external objects in the application. This is done by making instance variables as private and
instance methods as public.
en

Explain the code snippet that demonstrates the use of the concept of encapsulation in the class
Rectangle as mentioned in slides 53 and 54.
C

In-Class Question:
h

After you finish explaining the access modifiers, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
ec
pt

What will happen by making instance variables as private and instance methods as
rA

public?

Answer:
Fo

The details and implementation of a class is hidden from the other classes or external objects in the
application.

Tips:
Ensure that errors cannot happen if other programmers use your class. This can be helped by access
levels. Like avoid public fields except for constants as public fields tend to link you to a particular
implementation and limit your flexibility in changing the code.

©Aptech Limited
Classes and Objects

Slides 55 to 60
Let us understand object initializers.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 55 to 60, explain object initializers.

They provide a way to create an object and initialize its fields. They complement the use of
constructors to initialize objects.

Tell them that object field initializers also known as instance variable initializers are declared inside
a class. An instance variable initializer contains an equal sign and an expression.

©Aptech Limited
Classes and Objects

Explain to them the syntax of object field initializer as shown:


class <classname>{
// Object field initialization with value/expression
<data_type> field1=<value>/<expression>
}

Explain the code snippet that demonstrates a Java program that declares a class, Person and
initializes its fields as mentioned in slides 55 and 56.

Next, you explain to them object block initializer. Object block initializers also known as instance
initialization block are declared within the class, but outside the constructor and method
definitions. An instance initializer begins with a brace bracket, followed by one or more statements

y
and ends with a brace bracket.

nl
Explain the code snippet which shows the code with main() method to initialize the Account

O
object through initialization block as mentioned in slides 59 and 60.

In-Class Question:

se
After you finish explaining the object initializers, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.

rU
te
When the initialization block is executed?
en

Answer:
It is executed before the execution of constructors, during an object initialization.
C

Tips:
It is not necessary to declare fields at the beginning of class declaration. But it is necessary that they
h

be declared and initialized before they are used.


ec
pt
rA
Fo

©Aptech Limited
Classes and Objects

Slide 61
Let us summarize the session.

y
nl
O
se
In slide 61, you will summarize the session. End the session with a brief summary of what has been
taught in the session.

6.3 Post Class Activities for Faculty


rU
You should familiarize yourself with the topics of the next session which is based on methods and
te
access specifiers.
en

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
C

additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

Session 7 – Methods and Access Specifiers

7.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
7.1.1 Objectives

nl
By the end of this session, the learners will be able to:

O
• Describe methods
• Explain the process of creation and invocation of methods
• Explain passing and returning values from methods

se
• Explain variable argument methods
• Describe the use of Javadoc to lookup methods




rU
Describe access specifiers and the types of access specifiers
Explain the use of access specifiers with methods
Explain the concept of method overloading
Explain the use of this keyword
te
7.1.2 Teaching Skills
en

To teach this session, you should be well-versed with creation and invocation of methods, passing
and returning values to and from methods and also the use of Javadoc to lookup methods. Also,
C

familiarize yourself with the concept of access specifiers for restricting access to the class members.

You should teach the concepts in the theory class using the images provided. For teaching in the
h

class, you are expected to use slides and LCD projectors.


ec

Tips:
pt

It is recommended that you test the understanding of the students by asking questions in between
the class.
rA

In-Class Activities:
Follow the order given here during In-Class activities.
Fo

©Aptech Limited
Methods and Access Specifiers

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
Tell the students that this session introduces the creation and invocation of methods, passing, and

rU
returning values to and from methods and also the use of Javadoc to lookup methods.

The session will explain the concept of access specifiers for restricting access to the class members
te
and the concept of method and constructor overloading.
en

7.2 In-Class Explanation


Slide 3
C

Let us understand the role of access specifiers in accessing methods.


h
ec
pt
rA
Fo

Using slide 3, explain the role of access specifiers in accessing methods.

Methods in Java allows grouping of statements and execution of a specific set of statements, instead
of executing the entire program.

Tell them what if the user wants to restrict access to certain methods in the class?

©Aptech Limited
Methods and Access Specifiers

Java provides a set of access specifiers that can help the user to accomplish this task. As already
learnt in the previous session, Java provides a set of access specifiers that can help the user to
restrict access to certain methods.

Slides 4 to 6
Let us understand methods in Java class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
Using slides 4 to 6, explain methods in Java class.

Tell them about the main() method which is the point of entry of any Java program will execute all

se
the statements written within the scope of the main() method.

rU
Then discuss the syntax of writing methods in Java. Any method such as main() method or
instance method will have three parts,


te
modifier: Specifies the visibility of the method. Visibility indicates which object can access
the method. The values can be public, private, or protected.

en

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
C

method.

Tell them that the two components of a method declaration namely, the method name and the
h

parameter types comprise the method signature.


ec

Then, discuss with them the rules for writing methods in Java and discuss some examples on valid
method names allowed in Java such as add, _view, $calc, add_num, setFirstName,
pt

compareTo, isValid, and so on.


rA

Then, discuss about the declaration of parameters and exceptions in the method signature.

Parameters in method signature


Fo

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.
Example: void addContactDetails(int cust_id, String cust_name, int
cust_age){ }

Exceptions in method signature


An exception list 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.
Example: void addContactDetails(int cust_id, String cust_name, int
cust_age) throws CustomerException { }

©Aptech Limited
Methods and Access Specifiers

The method declaration shows the writing of exceptions with the method signature, which indicates
that the method can throw an error while adding customer details.

Slides 7 to 13
Let us understand creating and invoking methods.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
Using slides 7 to 13, explain creating and invoking methods.

se
Tell them that to perform different types of mathematical operations such as addition, subtraction,
multiplication, and so on in a calculator class, a user can create individual methods as shown in the
figure mentioned in slide 7.

rU
Then explain how to create a method that adds two numbers, the user can write a method as
depicted in the code snippet mentioned in slide 8. Tell them that a method named add() that
te
accepts two parameters num1 and num2, each of type integer is defined. Also, the method has
been defined with the public access specifier which means that it can be accessed by all
en

objects. The return type set to void indicates that the method does not return anything.

To use a method, it must be called or invoked. A method can be invoked in one of the following
C

ways:

• If the method returns a value, then, a call to the method results in return of some value from
h

the method to the caller. For example, int result = obj.add(20, 30);
ec

• If the method’s 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, a call to the method would be obj.add(23,30) without anything returned
pt

to the caller.
rA

Explain the project Session7 with the class Calculator created in the NetBeans IDE as shown in
the figure on slide 10. Then, explain the code snippet demonstrates an example of creation and
invocation of methods within the created class in the NetBeans IDE as mentioned in slides 11 to 13.
Fo

Explain the creation of the methods within the class. 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.

©Aptech Limited
Methods and Access Specifiers

Slide 14
Let us understand passing and returning values from methods.

y
nl
O
se
Using slide 14, explain passing and returning values from methods.

rU
Passing of parameters to a method can be through passing a value or passing a reference.

Passing of parameters to a method involves Parameters list that is specified with the method
declaration and the actual argument values that are passed to the method when it is invoked.
te
When a method is invoked, the type and order of arguments that are passed must match the type
en

and order of parameters declared in the method. A method can accept primitive data types such as
int, float, double, and so on as well as reference data types such as arrays and objects as a
C

parameter.

Arguments can be passed as value or reference to the invoked method.


h
ec

Slides 15 and 16
Let us understand passing arguments by value.
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
Using slides 15 and 16, explain passing arguments by value.

se
When arguments are passed by value it is known as call-by-value and it means that:

 A copy of the argument is passed from the calling method to the called method.


calling method. rU
Changes made to the argument passed in the called method will not modify the value in the

Variables of primitive data types such as int and float are passed by value.
te
Explain the code snippet that demonstrates an example of passing arguments by value mentioned in
en

slides 15 and 16.

Tips:
C

The Java programming language does not allow to pass methods into methods, but you can pass
objects into methods and then invoke the object’s method.
h

Slides 17 to 19
ec

Let us understand passing arguments by reference.


pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C

Using slides 17 to 19, explain passing arguments by reference.


h
ec

When arguments are passed by reference it means that:

 The actual memory location of the argument is passed to the called method and the object
pt

or a copy of the object is not passed.


 The called method can change the value of the argument passed to it.
rA

 Variables of reference types such as objects are passed to the methods by reference.
 There are two references of the same object namely, argument reference variable and
parameter reference variable.
Fo

Explain the code snippet that demonstrates an example of passing arguments by reference
mentioned in slides 17 to 19.

©Aptech Limited
Methods and Access Specifiers

Slides 20 and 21
Let us understand returning values from methods.

y
nl
O
se
rU
te
en
C
h
ec

Using slides 20 and 21, explain returning values from methods.


pt

A method will return a value to the invoking method only when all the statements in the invoking
method are complete, or when it encounters a return statement, or when an exception is thrown.
rA

The return statement is written within the body of the method to return a value.

A void method will not have a return type specified in its method body. A compiler error is
generated when a void method returns a value. You can store the value in a variable and specify
Fo

the name of the variable with the return keyword.

Explain the class Circle and its getPI() method can be modified as shown in code snippet
mentioned in slide 21.

The type of data returned by a method must be compatible with the return type specified by the
method. For example, if the return type of some method is Boolean, you could not return an integer.
The variable receiving a value returned by the method must be compatible with the return type
specified for the method. Parameters should be passed in sequence and they must be accepted by
method in the same sequence.

©Aptech Limited
Methods and Access Specifiers

In-Class Question:
After you finish explaining the returning values from methods, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.

What happens when a void method returns a value?


Answer:
A compiler error is generated.

y
Slides 22 to 24
Let us understand declaring variable argument methods.

nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
Using slides 22 to 24, explain declaring variable argument methods.

se
Java provides a feature called varargs to pass variable number of arguments to a method.
varargs is used when the number of a particular type of argument that will be passed to a method
is not known until runtime. It serves as a shortcut to creating an array manually.

rU
To use varargs, the type of the last parameter is followed by ellipsis (...), then, a space,
followed by the name of the parameter. This method can be called with any number of values for
te
that parameter, including none.

Then, explain the syntax of a variable argument method as shown in the slide 22.
en

Explain the code snippet that demonstrates an example of a variable argument method as
C

mentioned in slides 23 and 24.

Varargs is helper syntax and it enables the use of variable number of arguments in a method call.
h

While invoking the varargs method, you can use any number of arguments and separated by
ec

comma. You can have only one varargs in a method and it must always be the last declared
argument in the signature.
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

Slides 25 to 35
Let us understand using Javadoc to lookup methods of a class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C

Using slides 25 to 35, explain how to use Javadoc to lookup methods of a class.
h

Java provides a JDK tool named Javadoc that is used to generate API documentation as an HTML
ec

page from declaration and documentation comments. These comments are descriptions of the code
written in a program.
pt

Then, explain the types of documentations that can be created using Javadoc namely API docs and
rA

doc comments.

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
Fo

interface comments.
 Package comment files that consist of package comments.
 Overview comment files that contain comments about set of packages.
 Miscellaneous files that are unprocessed such as images, class files, sample source codes,
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, explain the class given in the code snippet mentioned in slides 26 and 27.

©Aptech Limited
Methods and Access Specifiers

Explain the HTML generated from running the Javadoc tool is mentioned in slide 28.

Then, explain the steps to use Javadoc tool to lookup methods of a class listed from slides 29 to 35.

The Javadoc tool parses the declaration and documentation comments in a set of Java source files
and produces a corresponding set of HTML pages describing the public and protected classes, nested
classes, interfaces, constructors, and methods.

Tips:
The Javadoc tool must be able to find all referenced classes like extensions or user classes because
Javadoc tool builds its internal structure for the documentation and it loads all the referenced

y
classes.

nl
Slide 36
let us understand overview of access specifiers.

O
se
rU
te
en
C
h

Using slide 36, explain overview of access specifiers.


ec

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
pt

visibility of the class, field, and methods. When no access specifier is mentioned for a class member,
the default accessibility is package or default.
rA

Using access specifiers provides the following advantages:


Fo

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.
 A package is always accessible by default.

©Aptech Limited
Methods and Access Specifiers

Slides 37 to 39
Let us understand types of access specifiers

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 37 to 39, explain types of access specifiers.

Java comes with four access specifiers namely, public, private, protected, and default.

©Aptech Limited
Methods and Access Specifiers

Explain the access specifiers listed on slide 37 and also its related figure on slide 38. Explain the table
that shows the access level for different access specifiers mentioned on slide 39.

Java allows you to control access to classes, methods, and fields with the help of access specifiers.
This helps in encapsulation which concerns with hiding of data in a class and making this class
available only through methods. In this way, the chance of making mistakes in changing values is
minimized. Default access is more restricted than protected and protected members are accessible
in subclass.

In-Class Question:
After you finish explaining the types of access specifiers, you will ask the students an In-Class

y
question. This will help you in reviewing their understanding of the topic.

nl
O
What are the four Java access specifiers?

se
Answer:
 public
 private
 protected
 default
rU
te
Slide 40
Let us understand rules for access control.
en
C
h
ec
pt
rA
Fo

Using slide 40, explain the rules for access control.

©Aptech Limited
Methods and Access Specifiers

Slides 41 to 46
Let us understand using access specifiers with variables and methods.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 41 to 46, explain using access specifiers with variables and methods.

The access specifiers discussed can be used with variables and methods of a class to restrict access
from other classes.

Explain the code snippet that demonstrates an example of using access specifiers with variables and
methods mentioned in slides 41 to 46.

©Aptech Limited
Methods and Access Specifiers

Access specifiers are used to control the visibility of members like classes, variables, and methods.

Accessibility of instance variables can be controlled with the access specifiers. When a variable is
declared as public, it can be modified from all classes. If the variable is declared as private, access is
restricted to class itself.

Access specifiers for methods works in same way as that of variables. Methods too can be defined
using all the four access protection.

Slide 47
Let us understand method overloading.

y
nl
O
se
rU
te
en

Using slide 47, explain how to overload methods.


C

Discuss the calculator scenario used for performing mathematical operations such as addition,
subtraction, multiplication, and division. To add two numbers, the user normally selects the integer
h

numbers. What if a user wants to add numbers of different types such as two floating-point numbers
ec

or one integer and other floating-point number?

It would be more convenient to have a way to create different variations of the same add() method
pt

to add different types of values. However, if calculator has to provide multiple buttons for each type
of addition functionalities, then working with calculator will be cumbersome.
rA

The Java programming language provides the feature of method overloading to distinguish between
methods with different method signatures. Using method overloading, multiple methods of a class
Fo

can have the same name, but with different parameter lists.

When the class has two or more methods of same name but different parameters, it is known as
method overloading.

Method overloading can be implemented in the following three ways:


• Changing the number of parameters
• Changing the sequence of parameters
• Changing the type of parameters

If you have to perform only one operation, having same name of the methods increases the
readability of the code.

©Aptech Limited
Methods and Access Specifiers

Tips:
In Java, method overloading is not possible by changing the return type of the method.

Slide 48
Let us understand overloading with different parameter list.

y
nl
O
se
rU
Using slide 48, explain overloading with different parameter list.

Methods can be overloaded by changing the number or sequence of parameters of a method.


te
Explain the figure that shows an example of overloaded add() methods mentioned in slide 48.
en

When an overloaded method is called, Java look for a match between the arguments to call the
method and the method’s parameter. Sometimes, when the match is not found, Java automatic type
C

conversion plays a vital role.

Slides 49 to 53
h

Let us understand overloading with different data types.


ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
Using slides 49 to 53, explain overloading with different data types.

se
Methods can be overloaded by changing the data type of parameters of a method. Earlier figure
shows an example of add() method overloaded by changing the type of parameters. Each of the
add() methods numbered 1, 2, 3, and 5 accepts two parameters. However, they differ in the type of
parameters that they accept.
rU
Then, explain the method numbered 6 and its similarities with method numbered 5. Discuss that the
overloaded methods must differ in argument type and number and not simply in name of
te
arguments. Similarly, the add() method numbered 7 has a signature similar to the method
numbered 1.
en

Explain the code snippet demonstrates an example of method overloading mentioned in slides 50 to
C

53.

Slides 54 to 59
h

Let us understand constructor overloading.


ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C

Using slides 54 to 59, explain constructor overloading.


h

Constructor is a special method of a class that has the same name as the class name. A constructor is
ec

used to initialize the variables of a class. Similar to a method, a constructor can also be overloaded to
initialize different types and number of parameters. When the class is instantiated, the compiler
pt

invokes the constructor based on the number, type, and sequence of arguments passed to it.
rA

Explain the code snippet demonstrates an example of constructor overloading mentioned in slides
54 to 59.

Constructor overloading is not much different than method overloading. Just like in method
Fo

overloading you have multiple methods with same name but different signature, in constructor
overloading you have multiple constructors with different signatures. The only difference is that the
constructor does not have return type in Java.

One constructor can only be called from inside of another constructor and if called it must be first
statement of that constructor. It means that Overloaded constructor must be called from other
constructor only. The biggest advantage of overloaded constructor is flexibility which allows you to
create object in different way.

©Aptech Limited
Methods and Access Specifiers

Slides 60 to 65
Let us understand using ‘this’ keyword.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 60 to 65, explain ‘this’ Keyword.

Java provides the keyword this 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 called.

©Aptech Limited
Methods and Access Specifiers

Any member of the current object can be referred from within an instance method or a constructor
by using the this keyword. The keyword is not explicitly used in instance methods, while referring
to variables and methods of a class.

For example, consider the method calcArea() of the following code snippet mentioned in slides 60
and 61.

For example, explain the method calcArea() can also be written in the code snippet mentioned in
slides 62 and 63.

Explain the explicit constructor invocation as shown in the code snippet mentioned in slides 63 and

y
64.

nl
Explain 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 the code snippet

O
mentioned in slides 64 and 65.

se
In Java, this is a reference variable that refers to the current object which means the object whose
method or constructor being called. this() can be used to invoke current class constructor and
implicitly invoke current class method. The this() constructor call should be used to reuse the
constructor in the constructor.

In-Class Question:
rU
te
After you finish explaining the ‘this’ Keyword, you will ask the students an In-Class question. This will
help you in reviewing their understanding of the topic.
en
C

What is the use of this keyword?


h

Answer:
ec

Any member of the current object can be referred from within an instance method or a constructor.
pt
rA
Fo

©Aptech Limited
Methods and Access Specifiers

Slide 66
Let us summarize the session.

y
nl
O
se
In slide 66, you will summarize the session. End the session with a brief summary of what has been
taught in the session.

7.3 Post Class Activities for Faculty


rU
te
You should familiarize yourself with the topics of the next session which is teaching arrays and
strings in Java.
en

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
C

additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

Session 8 – Arrays and Strings

8.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
8.1.1 Objectives

nl
By the end of this session, the learners will be able to:

O
• Describe an array
• Explain declaration, initialization, and instantiation of a single-dimensional array
• Explain declaration, initialization, and instantiation of a multi-dimensional array

se
• Explain the use of loops to process an array
• Describe ArrayList and accessing values from an ArrayList



Explain command line arguments rU
Describe String and StringBuilder classes

Describe Wrapper classes, autoboxing, and unboxing


te
8.1.2 Teaching Skills
To teach this session, you should be well-versed with creation and use of arrays in Java and accessing
en

values from ArrayList using loops. Also, familiarize yourself with command-line argument and
working with String and StringBuilder classes.
C

You should teach the concepts in the theory class using the images provided. For teaching in the
class, you are expected to use slides and LCD projectors.
h
ec

Tips:
It is recommended that you test the understanding of the students by asking questions in between
pt

the class.

In-Class Activities:
rA

Follow the order given here during In-Class activities.


Fo

©Aptech Limited
Arrays and Strings

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
rU
Tell the students that this session introduces the creation and use of arrays in Java and accessing
values from ArrayList using loops. Explain to the student that an array is a type of storage where
same type of data can be stored or maintained in consecutive memory locations. This session
te
focuses more on single-dimensional and two-dimensional arrays. The session also covers the various
classes that are used to manipulate strings. String is a class that provides various methods to
en

manipulate characters. Tell them session also describes wrapper classes, boxing, and un-boxing.

8.2 In-Class Explanation


C

Slide 3
Let us understand how to store multiple values in a variable.
h
ec
pt
rA
Fo

Using slide 3, explain how to store multiple values in a variable.

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.

©Aptech Limited
Arrays and Strings

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.

Slides 4 to 6
Let us understand introduction to arrays.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
Using slides 4 to 6, explain introduction to arrays.

An array is a special data store that can hold a fixed number of values of a single type in contiguous

se
memory locations. It is implemented as objects. The size of an array depends on the number of
values it can store and is specified when the array is created. After creation of an array, its size or
length becomes fixed.
rU
Explain the figure which shows an array of numbers mentioned in slide 4. Explain that each value in
the array is called an element of the array. The numbers 0 to 9 indicate the index or subscript of the
te
elements in the array. The length or size of the array is 10. The first index begins with zero. Since the
index begins with zero, the index of the last element is always length - 1. The last, that is, tenth
en

element in the given array has an index value of 9. Each element of the array can be accessed using
the subscript or index. Array can be created from primitive data types such as int, float,
C

boolean as well as from reference type such as object. The array elements are accessed using a
single name but with different subscripts. The values of an array are stored at contiguous locations
in memory. This induces less overhead on the system while searching for values.
h
ec

The use of arrays has the following benefits:

 Arrays are the best way of operating on multiple data elements of the same type at the
pt

same time.
 Arrays make optimum use of memory resources as compared to variables.
rA

 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.
Fo

Arrays in Java are of the following two types namely, Single-dimensional arrays and Multi-
dimensional arrays.

An array is a container object that holds a fixed number of values of a single type. The length of an
array is established when the array is created. After creation, its length is fixed. Each item in an array
is called an element, and each element is accessed by numerical index.

Arrays are always fixed length abstracted data structure which cannot be altered when required. It
helps the programmer to organize the same type of data into easily manageable format.

©Aptech Limited
Arrays and Strings

Tips:
An array is a container object that holds a fixed number of values of a single type. The length of an
array is established when the array is created. After creation, its length is fixed.

Slides 7 to 14
Let us understand declaring, instantiating, and initializing single-dimensional array.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C

Using slides 7 to 14, explain declaring, instantiating, and initializing single-dimensional array.
h

A single-dimensional array has only one dimension and is visually represented as having a single
ec

column with several rows of data. Each element is accessed using the array name and the index at
which the element is located.
pt

Explain the figure which shows the array named marks and its elements with their values and indices
mentioned in slide 7.
rA

An exception is an abnormal event that occurs during the program execution and disrupts the
normal flow of instructions.
Fo

Array creation involves the following tasks:

Declaring an Array
Declaring an array notifies the compiler that the variable will contain an array of the specified data
type. It does not create an array.

Explain the syntax for declaring a single-dimensional array. Explain the following terms used in the
syntax:
 datatype: specifies any valid data type in Java
 []: denotes that the variable is an array

©Aptech Limited
Arrays and Strings

 arrayName: denotes the array variable name that will be used for referring to the array
 new: allocates memory for objects
 size: denotes the number of elements that can be stored in an array

Tips:
An array having four columns is not called a four-dimensional array; it is still a two-dimensional
array. The number of subscripts needed to access elements depends upon the dimensions of an
array.

Tell them that arrays of other types can also be declared.

y
Array variable is declared in same way as any variable is declared. It has a type and a valid Java

nl
identifier. The type means the type of elements contain in an array. Also, it is essential to assign
memory to an array when you declare it. Memory is assigned to set the size of declared array.

O
Instantiating an Array
Since array is an object, memory is allocated only when it is instantiated. Explain the syntax for

se
instantiating the array using the new operator. The new operator is used for allocation of memory
to the array object.

Initializing an Array
rU
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:
te
 During creation:
en

To initialize a single-dimensional array during creation, one must specify the values to be
stored while creating the array as follows: int[ ] marks = {65, 47, 75, 50};
C

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
h

the memory gets automatically allocated based on the number of elements.


ec

 After creation:

A single-dimensional array can also be initialized after creation and instantiation.


pt

In this case, individual elements of the array need to be initialized with appropriate values.
For example,
rA

int[] marks = new int[4];


marks[0] = 65;
marks[1] = 47;
Fo

marks[2] = 75;
marks[3] = 50;

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.

Explain the code snippet demonstrates an example of single-dimensional array mentioned in slides
12 to 14.

©Aptech Limited
Arrays and Strings

In-Class Question:
After you finish explaining the declaring, instantiating, and initializing single-dimensional array, you
will ask the students an In-Class question. This will help you in reviewing their understanding of the
topic.

Why there is a need to initialize array?

Answer:

y
Array is an object that can store multiple values hence, array needs to be initialized with the values
to be stored in it.

nl
Slides 15 to 21

O
Let us understand declaring, instantiating, and initializing multi-dimensional array.

se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C

Using slides 15 to 21, explain declaring, instantiating, and initializing multi-dimensional array.
h
ec

A multi-dimensional array in Java is an array whose elements are also arrays. This allows the rows to
vary in length. When the elements of array are themselves arrays, it is multi-dimensional arrays.
pt

Explain the syntax for declaring and instantiating a multi-dimensional array. Explain some of the
terms in the syntax:
rA

 datatype: Indicates the type of elements that will be stored in the array.
 rowsize and colsize: Indicates the number of rows and columns that the array will contain.
Fo

 new: Keyword used to allocate memory to the array elements.

Then, explain the example, int[][] marks = new int[4][2]; that declares and array
named marks consists of four rows and two columns.

Then, explain how to initialize the multi-dimensional array in the following two ways:

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

©Aptech Limited
Arrays and Strings

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.

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.

When you create multi-dimensional array using the new keyword, you always get a rectangular

y
array: one in which all the array values for a given dimension have the same size.

nl
Explain the code snippet demonstrates an example of two-dimensional array mentioned in slides 18
to 21.

O
Tips:

se
A quick way to initialize a two-dimensional array is to use nested-for loops.

Slides 22 to 27
rU
Let us understand using loops to process and initialize an array.
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
Using slides 22 to 27, explain using loops to process and initialize an array.

A user can use loops to process and initialize an array. Explain the code snippet depicts the revised

se
displayMarks() method of the single-dimensional array named marks[] mentioned in slide 22.

rU
Explain the code snippet depicts the revised displayMarks() method of the two-dimensional array
marks[][] mentioned in slides 23 and 24.

One can also use the enhanced for loop to iterate through an array.
te
Explain the code snippet depicts the modified displayMarks() method of single-dimensional array
en

marks[] using the enhanced for loop mentioned in slide 25.


C

Explain the code snippet 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[][] mentioned in
slides 26 and 27.
h
ec

Array can be processed using different types of loop. The main technique used to process array is for
loop. A for loop is a way for processing each element of the array in a sequential manner.
Array can also be processed using while loops. While loop iterate through the loop body until
pt

termination condition evaluates to a false value. While loops are very useful when the data is not
sequentially accessible with some sort of index.
rA
Fo

©Aptech Limited
Arrays and Strings

Slides 28 to 35
Let us understand initializing an arraylist.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C

Using slides 28 to 35, explain initializing an arraylist.


h
ec

One major disadvantage of an array is that its size is fixed during creation. The size cannot be
modified later. To resolve this issue, it is required to have a construct to which memory can be
allocated based on requirement. Also, addition and deletion of values can be performed easily. Java
pt

provides the concept of collections. A collection is a single object that groups multiple elements into
a single unit.
rA

Explain the figure of the core collection interfaces that encapsulate different types of collections
mentioned on slide 28.
Fo

Then, explain the ArrayList class that can be increased or decreased in size as needed. It
provides several useful methods to manipulate the collection and can be traversed by using for loop,
enhanced for loop, or other iterators.

Explain the table lists the constructors of ArrayList class in slide 30.

©Aptech Limited
Arrays and Strings

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.

Explain the table lists the methods of ArrayList class on slides 31 to 33. To traverse an
ArrayList, one can use one of the following approaches:

 A for loop
 An enhanced for loop

y
 Iterator

nl
 ListIterator

O
Then, explain Iterator interface provides methods for traversing a set of data. It can be used with
arrays as well as various classes of the Collection framework.

se
Explain the code snippet demonstrates instantiation and initialization of an ArrayList mentioned in
slide 35.

rU
Array lists are created with an initial size. When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array may be shrunk. They can dynamically increase or
decrease in size. The disadvantage of Array lists is that it holds only object type and not primitive
te
type like int.
en

Tips:
If you want to reduce the size of the array that underlies an ArrayList object, so that it is
precisely as large as the number of items that it is currently holding, call trimToSize() method.
C

In-Class Question:
h

After you finish explaining the initializing an ArrayList, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
ec
pt

Which methods provide by Iterator interface for traversing a collection?


rA

Answer:
 next()
Fo

 hasNext()
 remove()

©Aptech Limited
Arrays and Strings

Slides 36 to 40
Let us understand accessing values in an ArrayList.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C

Using slides 36 to 40, explain accessing values in an ArrayList.


h
ec

An ArrayList can be iterated by using the for loop or by using the Iterator interface.

Explain the code snippet demonstrates the use of ArrayList named marks to add and display
pt

marks of students mentioned in slides 36 to 40.


rA

Iterator enables you to cycle through the collections, obtaining, or removing elements.
Before you access a values through an iterator, you must obtain it. Each of the collection classes
provides an iterator() method that returns an iterator to the start of the collection. By using
Fo

this iterator object, you can access each element, one at a time.

©Aptech Limited
Arrays and Strings

Slide 41
Let us understand introduction to strings.

y
nl
O
se
Using slide 41, explain introduction to Strings. Consider a scenario, where in a user wants to store
the name of a person. One can create a character array as shown in the following code snippet:

char[] name = {‘J’,’u’,’l’,’i’,’a’} rU


Similarly, to store names of multiple persons, one can create a two-dimensional array. However, the
te
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.
en

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

Java strings are a series of characters gathered together. It stores text and a sequence of characters.
h

Each character in a string is a 16-bit Unicode character, to provide rich set of characters.
ec

Slides 42 to 44
Let us understand the features of strings.
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C

Using slides 42 to 44, explain the features of strings.


h

String literals such as “Hello” in Java are implemented as instances of the String class. Strings are
ec

constant and immutable, that is, their values cannot be changed once they are created. Thus, string
buffers can be used, as they allow creation of mutable strings.
pt

A simple String instance can be created by enclosing a string literal inside double quotes as shown
in the code snippet in slide 42. Java also provides special support for concatenation of strings using
rA

the plus (+) operator and for converting data of other types to strings as depicted in the code
snippet in slide 43.
Fo

The java.lang.String class is a final class, that is, no class can extend it. This 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. The threads will only read
them, which is normally a thread safe operation.

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.

©Aptech Limited
Arrays and Strings

If the string is likely to change later, but will not be shared between multiple threads, one can use
the StringBuilder class.

In Java, strings are objects and not a primitive type. Even string constants are string objects. As you
know, String is immutable and modifying the contents of one string can cause adverse effects on
other string.

JDK provides two classes to support mutable strings, StringBuffer and StringBuilder.
Both are just like any other ordinary object which are stored in the heap and not shared and
therefore can be modified without causing any effects to other objects.

y
Tips:
StringBuffer is an ordinary object. You need to use a constructor to create a StringBuffer

nl
and ‘+’ operator cannot be apply to object including StringBuffer.

O
Slides 45 to 51
Let us understand working with String class.

se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C

Using slides 45 to 51, explain working with String class.


h

Explain some of the frequently used methods of String class mentioned on slides 45 to 48.
ec

Explain the code snippet demonstrates the use of String class methods mentioned in slides 49 to
pt

51.
rA

The class String includes methods for examining individual characters of the sequence, for
comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string.
String class provides methods for dealing with characters and char values.
Fo

©Aptech Limited
Arrays and Strings

Slides 52 and 53
Let us understand working with StringBuilder class.

y
nl
O
se
rU
te
en
C
h
ec

Using slides 52 and 53, explain working with StringBuilder class.


pt

Explain the features of StringBuilder class listed on slide 52. The constructors of the
StringBuilder class are as follows:
rA

• StringBuilder() - Default constructor that provides space for 16 characters.


It creates an empty StringBuilder.
Fo

• StringBuilder(int capacity) - Constructs an object without any characters in it.


However, it reserves space for the number of characters specified in the argument,
capacity.

• StringBuilder (String str) - Constructs an object that is initialized with the


contents of the specified string, str.

StringBuilder objects are like String objects, except they can be modified. This class
provides an API compatible with StringBuffer, but no guarantee of synchronization. This class is
faster under most of the implementations.

©Aptech Limited
Arrays and Strings

The principal operations on a StringBuilder class are insert() and append() methods
which are overloaded so as to accept data of any type.

Slides 54 to 58
Let us understand methods of StringBuilder class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C

Using slides 54 to 58, explain methods of StringBuilder class.


h

Explain the StringBuilder class provides several methods for appending, inserting, deleting,
ec

and reversing strings as follows mentioned on slides 54 to 56.


pt

Explain the code snippet demonstrates the use of methods of the StringBuilder class mentioned in
slides 57 and 58.
rA

Tips:
You can use any String method on a StringBuilder object by first converting the string builder
to a string with the toString() method of StringBuilder class. Then convert the string back
Fo

into a string builder using StringBuilder(String str) constructor.

©Aptech Limited
Arrays and Strings

Slides 59 to 61
Let us understand string arrays.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 59 to 61, explain string arrays.

©Aptech Limited
Arrays and Strings

Sometimes there is a need to store a collection of strings. String arrays can be created in Java in the
same manner as arrays of primitive data types. For example, String[] empNames = new
String[10]; the statement will allocate memory to store references of 10 strings.

However, no memory is allocated to store the characters that make up the individual strings. Loops
can be used to initialize as well as display the values of a string array.

Explain the code snippet demonstrates the creation of a string array mentioned on slides 59 to 61.

String array is just like creating and using any other Java object array. It is nothing more than a
sequence of strings. The total number of strings must be fixed but each string can be of any length.

y
String arrays are relatively straightforward, and Java provides a moderate amount of built-in
functionality to make them easy to work with.

nl
O
The two basic aspects of string array are, initialization and iteration. Inline initialization is well suited
where number of strings is relatively small and you happen to know at compile-time which strings
should be in the array.

se
The iteration can be basic and advanced. The basic iteration is well suited where you need to write
to an element of an array and to analyze its existing contents. Advanced iteration is well suited
where you do not need to write to an array.

In-Class Question:
rU
te
After you finish explaining the string arrays, you will ask the students an In-Class question. This will
help you in reviewing their understanding of the topic.
en
C

What is the role of loops in string array?


h

Answer:
ec

They can be used to initialize and display the values of a string array.
pt
rA
Fo

©Aptech Limited
Arrays and Strings

Slides 62 to 68
Let us understand command line arguments.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
Using slides 62 to 68, explain command line arguments.

A user can pass any number of arguments to a Java application at runtime from the OS command

se
line. The main() method declares a parameter named args[] which is a String array that accepts
arguments from the command line. These arguments are placed on the command line and follow
the class name when it is executed.
rU
When the application is launched, the runtime system passes the command line arguments to the
application’s main() method using a String array, args[]. The array of strings can be given any other
te
name. The args[] array accepts the arguments and stores them at appropriate locations in the array.
en

The length of the array is determined from the number of arguments passed at runtime. The
arguments are separated by a space. The basic purpose of command line arguments is to specify the
configuration information for the application. The main() method is the entry point of a Java
C

program, where objects are created and methods are invoked.


h

The static main() method accepts a String array as an argument as depicted in the following code
snippet:
ec

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


pt

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
rA

arguments are passed as strings.

Explain the code snippet demonstrates an example of command line arguments mentioned in slide
64.
Fo

Explain the steps to run the program with command line arguments at command prompt mentioned
in slide 65.

Explain the steps to run the program with command line arguments using NetBeans IDE mentioned
in slides 66 to 68.

A Java application can accept any number of arguments from the command line. This allows the user
to specify configuration information when the application is launched.

©Aptech Limited
Arrays and Strings

The user enters command-line arguments when invoking the application and specifies them after
the name of the class to be run. Many Java applications started from the command line which take
arguments to control their behavior.

Slides 69 to 79
Let us understand wrapper classes.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

y
nl
O
se
rU
te
en
C

Using slides 69 to 79, explain wrapper classes.


h

Java provides a set of classes known as wrapper classes for each of its primitive data type that
ec

‘wraps’ the primitive type into an object of that class. In other words, the wrapper classes allow
accessing primitive data types as objects.
pt

The wrapper classes for the primitive data types are: Byte, Character, Integer, Long, Short, Float,
rA

Double, and Boolean. The wrapper classes are part of the java.lang package.

The primitive types and the corresponding wrapper types are listed in the table in slide 69.
Fo

What is the need for wrapper classes?

The use of primitive types as objects can simplify tasks at times. For example, most of the collections
store objects and not primitive data types. Many of the activities reserved for objects will not be
available to primitive data types.

Also, many utility methods are provided by the wrapper classes that help to manipulate data.
Wrapper classes convert primitive data types to objects, so that they can be stored in any type of
collection and also passed as parameters to methods. Wrapper classes can convert numeric strings
to numeric values.

©Aptech Limited
Arrays and Strings

valueOf()
 The valueOf() method is available with all the wrapper classes to convert a type into another
type.
 The valueOf() method of the Character class accepts only char as an argument.
 The valueOf() method of any other wrapper class accepts either the corresponding primitive
type or String as an argument.

typeValue()
The typeValue() method can also be used to return the value of an object as its primitive type.

Explain some of the wrapper classes and their methods are listed in the table in slides 71 and 72.

y
nl
Explain the difference between creation of a primitive type and a wrapper type mentioned in slide
73.

O
The six methods of type parseXxx() available for each numeric wrapper type are in close relation
to the valueOf() methods of all the numeric wrapper classes including Boolean. The two type of

se
methods, that is, parseXxx() and valueOf(), take a String as an argument. If the String
argument is not properly formed, both the methods throw a NumberFormatException.

rU
These methods can convert String objects of different bases if the underlying primitive type is any of
the four integer types. The parseXxx() method returns a named primitive whereas the
valueOf() method returns a new wrapped object of the type that invoked the method.
te
Explain the code snippet demonstrates the use of Integer wrapper class to convert the numbers
en

passed by user as strings at command line into integer types to perform the calculation based on the
selected operation mentioned in slides 75 to 79.
C

A wrapper class encloses around a data type and gives it an object appearance. Whenever, the data
type is required as an object, this object can be used.
h

Wrapper classes include methods to unwrap the object and give back the data type.
ec

The two main uses with Wrapper classes are:


 To convert simple data types into objects, that is, to give object form to a data type.
pt

 To convert strings into data types known as parsing operations, here methods of type parse ()
rA

are used.

In-Class Question:
After you finish explaining the wrapper classes, you will ask the students an In-Class question. This
Fo

will help you in reviewing their understanding of the topic.

Use of wrapper classes utility methods?

Answer:
They help to manipulate data.

©Aptech Limited
Arrays and Strings

Slides 80 to 82
Let us understand autoboxing and unboxing.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 80 to 82, explain autoboxing and unboxing.

©Aptech Limited
Arrays and Strings

Autoboxing

The automatic conversion of primitive data types such as int, float, and so on to their corresponding
object types such as Integer, Float, and so on during assignments and invocation of methods and
constructors is known as autoboxing.

For example,
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(10); // autoboxing
Integer y = 20; // autoboxing

Converting a primitive value into an object of the corresponding wrapper class is called autoboxing.

y
The Java class applies autoboxing when a primitive value is passed as a parameter to a method that

nl
expects an object of the corresponding wrapper class or assigned to a variable for the corresponding
wrapper class.

O
Unboxing

se
The automatic conversion of object types to primitive data types is known as unboxing.
For example,
int z = y; // unboxing
rU
Autoboxing and unboxing helps a developer to write a cleaner code. Using autoboxing and unboxing,
te
one can make use of the methods of wrapper classes as and when required.

Explain the code snippet demonstrates an example of autoboxing and unboxing mentioned in slides
en

81 and 82.
C

Converting an object of a wrapper type to its corresponding primitive value is called unboxing. The
Java compiler applies unboxing when an object of a wrapper class is passed as a parameter to a
method that expects a value of the corresponding primitive type or assigned to a variable of the
h

corresponding primitive type.


ec
pt
rA
Fo

©Aptech Limited
Arrays and Strings

Slide 83
Let us summarize the session.

y
nl
O
se
In slide 83, you will summarize the session. End the session with a brief summary of what has been
taught in the session.

8.3 Post Class Activities for Faculty


rU
te
You should familiarize yourself with the topics of the next session which is based on modifiers and
packages.
en

Tips:
C

You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.
h
ec
pt
rA
Fo

©Aptech Limited
Modifier and Packages

Session 9 – Modifiers and Packages

9.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
9.1.1 Objectives

nl
By the end of this session, the learners will be able to:

O
• Describe field and method modifiers
• Explain the different types of modifiers
• Explain the rules and best practices for using field modifiers

se
• Describe class variables
• Explain the creation of static variables and methods



Describe package and its advantages
rU
Explain the creation of user-defined package
Explain the creation of .jar files for deployment
te
9.1.2 Teaching Skills
To teach this session, you should be well-versed with different fields and method modifiers in Java
en

with the rules for using field modifiers. Also, familiarize yourself with creation of packages and .jar
files.
C

You should teach the concepts in the theory class using the images provided. For teaching in the
class, you are expected to use slides and LCD projectors.
h
ec

Tips:
It is recommended that you test the understanding of the students by asking questions in between
pt

the class.

In-Class Activities:
rA

Follow the order given here during In-Class activities.


Fo

©Aptech Limited
Modifier and Packages

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

 Describe field and method modifiers


 Explain the different types of modifiers
 Explain the rules and best practices for using field modifiers
 Describe class variables
 Explain the creation of static variables and methods

y
 Describe package and its advantages
Explain the creation of user-defined package

nl

 Explain the creation of .jar files for deployment

O
se
© Aptech Ltd. Modifiers and Packages/Session 9 2

rU
Tell the students that this session introduces different fields and method modifiers in Java with the
rules for using field modifiers. Also, the session will explain in detail about the packages, creation of
packages, and creation of JAR files.
te
en

9.2 In-Class Explanation

Slide 3
C

Let us understand the package and package specifier in Java.


h
ec
pt
rA
Fo

Using slide 3, explain package and package specifier in Java.

Java is a tightly encapsulated language. Java provides a set of access specifiers such as public,
private, protected, and default that help to restrict access to class and class members.

©Aptech Limited
Modifier and Packages

Explain them that Java provides additional field and method modifiers to further restrict access to
the members of a class to prevent modification by unauthorized code.

Java provides the concept of class variables and methods to create a common data member that can
be shared by all objects of a class as well as other classes. Java provides packages that can be used to
group related classes that share common attributes and behavior. The entire set of packages can be
combined into a single file called the .jar file for deployment on the target system.

Slide 4
Let us understand field and method modifiers.

y
nl
Field and method modifiers are keywords used to identify fields and methods that
provide controlled access to users.

O
Some of these can be used in conjunction with access specifiers such as public
and protected.

 The different field modifiers that can be used are as follows:

se
volatile

native

transient

final
rU
te
© Aptech Ltd. Modifiers and Packages/Session 9 4
en

Using slide 4, explain field and method modifiers.


C

Field and method modifiers are keywords used to identify fields and methods that provide
controlled access to users. Some of these can be used in conjunction with access specifiers such as
h

public and protected.


ec

Explain them the different field modifiers that can be used in Java. Tell them that volatile
modifier can be used to inform the compiler that it should not attempt to perform optimization on
pt

the field which could cause unpredicted results when the fields are accessed by multiple threads.
rA

Native methods are specified in the class as method prototype with the keyword native, no
method body is defined in the Java class.

The final variable is constant, its value cannot be changed after initialization. It can be applied to
Fo

local, instance, and static variables including parameters that are declared as final.

Transient fields are declared with keyword Transient in their class declaration if their value
should not be saved when object of class written to persistent storage.

©Aptech Limited
Modifier and Packages

Slides 5 and 6
Let us understand ‘volatile’ modifier.

The volatile modifier allows the content of a variable to be synchronized across


all running threads.

A thread is an independent path of execution of code within a program. Many threads can
run concurrently within a program.

The volatile modifier is applied only to fields.

y
Constructors, methods, classes, and interfaces cannot use this modifier.

nl
The volatile modifier is not frequently used.

O
While working with a multithreaded program, the volatile keyword is used.

se
© Aptech Ltd. Modifiers and Packages/Session 9 5

rU
When multiple threads of a program are using the same variable, in general, each
thread has its own copy of that variable in the local cache.
te
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.
en

The other thread using the same variable does not get the updated value.

 To avoid this problem, a variable is declared as volatileto indicate that it will not
be stored in the local cache.
C

 Whenever a thread updates the values of the variable, it updates the variable present
in the main memory.
 This helps other threads to access the updated value.
h

 For example,
private volatile int testValue; // volatile variable
ec

© Aptech Ltd. Modifiers and Packages/Session 9 6


pt

Using slides 5 and 6, explain volatile modifier.


rA

The volatile modifier allows the content of a variable to be synchronized across all running
threads. A thread is an independent path of execution of code within a program.
Fo

The features of volatile modifier are as follows:


• The volatile modifier is applied only to fields.
• Constructors, methods, classes, and interfaces cannot use this modifier.

When multiple threads of a program are using the same variable, in general, each thread has its own
copy of that variable in the 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.

©Aptech Limited
Modifier and Packages

To avoid this problem, a variable is declared as volatile to indicate that it will not be stored in
the local cache. Whenever a thread updates the values of the variable, it updates the variable
present in the main memory. This helps other threads to access the updated value.

For example, private volatile int testValue; // volatile variable

Declaring a volatile Java variable means the value of the variable will never cache thread-locally that
means all read and write will go to main memory and access to the variable acts as synchronized on
itself. Every thread accessing a volatile field will read its current value before continuing, instead
of using a cached value. A primitive variable may be declared as volatile.

y
Slides 7 to 9

nl
Let us understand ‘native’ modifier.

O
The native modifier is used only with methods.

se
It indicates that the implementation of the method is in a language other than Java
such as C or C++.

Constructors, fields, classes, and interfaces cannot use this modifier.

rU
The methods declared using the native modifier are called native methods.

The Java source file typically contains only the declaration of the native method and
not its implementation.
te
The implementation of the method exists in a library outside the JVM.

 Before invoking a native method, the library that contains the method implementation
must be loaded by making the following system call:
en

System.loadLibrary(“libraryName”);
 To declare a native method, the method is preceded with the native modifier.
 The implementation is not provided for the method. For example,
C

public native void nativeMethod();


© Aptech Ltd. Modifiers and Packages/Session 9 7
h
ec

 After declaring a native method, a complex series of steps are used to link it with the
Java code.
 Following code snippet demonstrates an example of loading a library named
NativeMethodDefinitioncontaining a native method named
pt

nativeMethod():
class NativeModifier {
native void nativeMethod(); // declaration of a native method
rA

/**
* static code block to load the library
*/
static {
System.loadLibrary(“NativeMethodDefinition”);
}
Fo

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
NativeModifier objNative = new NativeModifier(); // line1
objNative.nativeMethod(); // line2
}
}
© Aptech Ltd. Modifiers and Packages/Session 9 8

©Aptech Limited
Modifier and Packages

 Notice that a static code block is used to load the library.


 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.
 Native methods allow access to existing library routines created outside the JVM.
 However, the use of native methods introduces two major problems.

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

y
which the Java program is executing.
• Each native method is dependent on the CPU and the OS.

nl
• 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.

O
© Aptech Ltd. Modifiers and Packages/Session 9 9

Using slides 7 to 9, explain ‘native’ modifier.

se
The native modifier is used only with methods. It indicates that the implementation of the method is
in a language other than Java such as C or C++. Constructors, fields, classes, and interfaces cannot
use this modifier.
rU
The methods declared using the native modifier are called native methods. The Java source file
te
typically contains only the declaration of the native method and not its implementation. The
implementation of the method exists in a library outside the JVM.
en

Before invoking a native method, the library that contains the method implementation must be
loaded by making the following system call:
C

System.loadLibrary(“libraryName”);
h

To declare a native method, the method is preceded with the native modifier. The implementation is
ec

not provided for the method. For example, public native void nativeMethod();

After declaring a native method, a complex series of steps are used to link it with the Java code.
pt

Explain the code snippet demonstrates an example of loading a library named


rA

NativeMethodDefinition containing a native method named nativeMethod() mentioned


in slide 8.
Fo

Notice that a static code block is used to load the library.

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. Native methods allow access to existing library
routines created outside the JVM.

However, the use of native methods introduces two major problems, discuss with them referring
slide 9.

©Aptech Limited
Modifier and Packages

Slides 10 and 11
Let us understand ‘transient’ modifier.

When a Java application is executed, the objects are loaded in the Random Access
Memory (RAM).
Objects can also be stored in a persistent storage outside the JVM so that it can be
used later.

This determines the scope and life span of an object.

The process of storing an object in a persistent storage is called serialization.

y
For any object to be serialized, the class must implement the Serializable
interface.

nl
If transient modifier is used with a variable, it will not be stored and will not
become part of the object’s persistent state.

O
The transient modifier is useful to prevent security sensitive data from being
copied to a source in which no security mechanism has been implemented.
The transient modifier reduces the amount of data being serialized, improves
performance, and reduces costs.

se
© Aptech Ltd. Modifiers and Packages/Session 9 10


rU
The transientmodifier 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.
te
 Thus, when the object is stored in persistent storage, the instance variable declared as
transient is not persisted.
 Following code snippet depicts the creation of a transient variable:
en

class Circle {

transient float PI; // transient variable that will not persist


float area; // instance variable that will persist
C

}
h
ec

© Aptech Ltd. Modifiers and Packages/Session 9 11


pt

Using slides 10 and 11, explain transient modifier.


rA

When a Java application is executed, the objects are loaded in the Random Access Memory (RAM).
Objects can also be stored in a persistent storage outside the JVM so that it can be used later. This
determines the scope and life span of an object. The process of storing an object in a persistent
Fo

storage is called serialization.

For any object to be serialized, the class must implement the Serializable interface. If transient
modifier is used with a variable, it will not be stored and will not become part of the object’s
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. The transient modifier reduces the amount
of data being serialized, improves performance, and reduces costs.

©Aptech Limited
Modifier and Packages

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.

Explain the code snippet that depicts the creation of a transient variable mentioned in slide 11.

An instance variable is marked transient to indicate the JVM to skip the particular variable when
serializing the object containing it. This modifier is included in the statement that creates the
variable, preceding the class, and data type of the variable.

In-Class Question:

y
After you finish explaining the transient modifier, you will ask the students an In-Class question. This

nl
will help you in reviewing their understanding of the topic.

O
se
What is the use of transient modifier?

Answer:

rU
It is useful to prevent security sensitive data from being copied to a source in which no security
mechanism has been implemented.
te
Slides 12 to 16
Let us understand ‘final’ modifier.
en
C

The final modifier is used when modification of a class or data member is to be


restricted.

The final modifier can be used with a variable, method, and class.
h

Final Variable
ec

A variable declared as final is a constant whose value cannot be modified.


pt

A final variable is assigned a value at the time of declaration.

A compile time error is raised if a final variable is reassigned a value in a program


after its declaration.
rA

 Following code snippet shows the creation of a final variable:


final float PI = 3.14;

 The variable PI is declared final so that its value cannot be changed later.
Fo

© Aptech Ltd. Modifiers and Packages/Session 9 12

©Aptech Limited
Modifier and Packages

Final Method

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.
A final method is commonly used to generate a random constant in a
mathematical application.
 Following code snippet depicts the creation of a final method:
final float getCommission(float sales){
System.out.println(“A final method. . .”);
}

 The method getCommission() can be used to calculate commission based on

y
monthly sales.
The implementation of the method cannot be modified by other classes as it is

nl

declared as final.
 A final method cannot be declared abstract as it cannot be overridden.

O
© Aptech Ltd. Modifiers and Packages/Session 9 13

se
Final Class

rU
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.
te
 The reason for declaring a class as final is to limit extensibility and to prevent the
modification of the class definition.
en

 Following code snippet shows the creation of a final class:


public final class Stock {
...
}
C

 The class Stock is declared final.


 All data members within this class are implicitly final and cannot be modified by
other classes.
h

© Aptech Ltd. Modifiers and Packages/Session 9 14


ec

Following code snippet demonstrates an example of creation of a final class:


pt

package session9;
public class Final {
rA

// Declare and initialize a final variable


final float PI = 3.14F; // variable to store value of PI

/**
* Displays the value of PI
*
Fo

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

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
© Aptech Ltd. Modifiers and Packages/Session 9 15

©Aptech Limited
Modifier and Packages

// 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 .
 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 the following figure:

y
nl
 To remove the error, the method signature should be changed and the statement,
PI = pi; should be removed.

O
© Aptech Ltd. Modifiers and Packages/Session 9 16

Using slides 12 to 16, explain final modifier.

se
The final modifier is used when modification of a class or data member is to be restricted. The
final modifier can be used with a variable, method, and class.

Final Variable rU
te
A variable declared as final is a constant whose value cannot be modified. A final variable is
assigned a value at the time of declaration. A compile time error is raised if a final variable is
en

reassigned a value in a program after its declaration.

Following code snippet shows the creation of a final variable: final float PI = 3.14;
C

Explain them that the variable PI is declared final so that its value cannot be changed later.
h

A final variable can only be initialized once, either through an initialize or an assignment statement.
It does not need to be initialized at the point of declaration. This is called blank final variable.
ec

Final Method
pt

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. A final method is
rA

commonly used to generate a random constant in a mathematical application.

Explain the code snippet that depicts the creation of a final method mentioned in slide 13.
Fo

Final Class

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.

Explain the code snippet that shows the creation of a final class mentioned in slide 14.

©Aptech Limited
Modifier and Packages

Explain the code snippet demonstrates an example of creation of a final class mentioned in slides 15
and 16.

As the final class cannot be subclassed, this provides security and efficiency benefits. Java local
classes can only reference local variables and parameters that are declared as final. A visible
advantage of declaring Java variable as static final is, the compiled java class results in faster
performance.

Tips:
If the variable is the reference, this means that the variable cannot be re-bound to reference
another object.

y
Slide 17

nl
Let us understand rules and best practices for using field modifiers.

O
se
 Some of the rules for using field modifiers are as follows:

Final fields cannot be volatile.

rU
Native methods in Java cannot have a body.

Declaring a transient field as static or final should be avoided as far as


possible.
te
Native methods violate Java’s platform independence characteristic. Therefore,
they should not be used frequently.
en

A transient variable may not be declared as final or static.


C

© Aptech Ltd. Modifiers and Packages/Session 9 17


h

Using slide 17, explain rules and best practices for using field modifiers.
ec

Explain the rules listed on the slide 17 for using field modifiers.
pt
rA
Fo

©Aptech Limited
Modifier and Packages

Slide 18
Let us understand class variables.

Consider a situation, where in a user wants to create a counter that keeps track
of the number of objects accessing a particular method.

In such a scenario, a variable is required that can be shared among all the
objects of a class and any changes made to the variable are updated only in one
common copy.

y
nl
Java provides the implementation of such a concept of class variables by using
the static keyword.

O
se
© Aptech Ltd. Modifiers and Packages/Session 9 18

Using slide 18, explain class variables.


rU
Consider a situation, where in a user wants to create a counter that keeps track of the number of
te
objects accessing a particular method. In such a scenario, a variable is required that can be shared
among all the objects of a class and any changes made to the variable are updated only in one
en

common copy.

Java provides the implementation of such a concept of class variables by using the static
C

keyword.

When a number of objects are created from the same class, they each have their own distinct copies
h

of instance variables. Sometimes, you want to have variables that are common to all objects. This is
ec

accomplished with the static modifier. Fields that have static modifier in their declaration are called
static fields or class variables.
pt

Every instance of class shares a class variable, which is in one fixed location in memory. Any object
can change the value of a class variable, but class variable can also be manipulated without creating
rA

an instance of the class.


Fo

©Aptech Limited
Modifier and Packages

Slide 19
Let us understand declaring class variables.

Class variables are also known as static variables.

Note that the static variables are not constants.

Such variables are associated with the class rather than with any object.

All instances of the class share the same value of the class variable.

The value of a static variable can be modified using class methods or instance methods.

y
Unlike instance variable, there exists only one copy of a class variable for all objects in one

nl
fixed location in memory.

A static variable declared as final becomes a constant whose value cannot be modified.

O
 For example,
static int PI=3.14; // static variable-can be modified
static final int PI=3.14; // static constant-cannot be

se
modified
© Aptech Ltd. Modifiers and Packages/Session 9 19

Using slide 19, explain declaring class variables.

rU
Class variables are also known as static variables. Note that the static variables are not constants.
Such variables are associated with the class rather than with any object. All instances of the class
te
share the same value of the class variable.
en

The value of a static variable can be modified using class methods or instance methods. Unlike
instance variable, there exists only one copy of a class variable for all objects in one fixed location in
memory. A static variable declared as final becomes a constant whose value cannot be modified.
C

The class body contains all the code that provides for the life cycle of the object created from the
class: constructors for initializing new object, declaration for the fields that provide the state of the
h

class and its objects and methods to implement the behavior of the class and its objects.
ec
pt
rA
Fo

©Aptech Limited
Modifier and Packages

Slides 20 to 25
Let us understand creating static variables, static methods, and static blocks.

One can also create static methods and static initializer blocks along with
static variables.
Static variables and methods can be manipulated without creating an instance
of the class.
This is because there is only one copy of a static data member that is shared by
all objects.

A static method can only access static variables and not instance variables.

 Methods declared as static have the following restrictions:

y
Can invoke only

nl
static methods

O
Can access only Cannot use this or
static data super keywords

se
© Aptech Ltd. Modifiers and Packages/Session 9 20

rU
Generally, a constructor is used to initialize variables.
te
However, a static block can also be used to initialize static variables because
static block is executed even before the main() method is executed.
en

It is used when a block of code needs to be executed during loading of the class by
JVM.

Execution of Java code starts from static blocks and not from main() method.
C

It is enclosed within {} braces.

There can be more than one static block in a program. They can be placed
anywhere in the class.
h

A static initialization block can reference only those class variables that have
ec

been declared before it.

© Aptech Ltd. Modifiers and Packages/Session 9 21


pt
rA

 Following code snippet demonstrates an example of static variables, static


method, and static block:
package session9;
public class StaticMembers {
Fo

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

/**
* Static method
*
* @return void

© Aptech Ltd. Modifiers and Packages/Session 9 22

©Aptech Limited
Modifier and Packages

*/
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++;

y
// Print the value of static and instance variable
System.out.println(“Static counter is:”+ staticCounter);

nl
System.out.println(“Instance counter is:”+ instanceCounter);
}

O
© Aptech Ltd. Modifiers and Packages/Session 9 23

se
/**
* @param args the command line arguments
*/

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

System.out.println(“I am the main method”);


// Invoke the static method using the class name
StaticMembers.staticMethod();
te
// Create first instance of the class
StaticMembers objStatic1 = new StaticMembers();
objStatic1.displayCount();
en

// Create second instance of the class


StaticMembers objStatic2 = new StaticMembers();
objStatic2.displayCount();
C

// Create third instance of the class


StaticMembers objStatic3 = new StaticMembers();
objStatic3.displayCount();
}
}
h

© Aptech Ltd. Modifiers and Packages/Session 9 24


ec
pt

 Following figure shows the output of the program:


rA
Fo

 From the figure 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.
 However, for the static variable, only one copy exists per class.
 Every object increments the same copy of the variable, staticCounter.
 Thus, by using a static counter, a user can keep track of the number of instances of
a class.
© Aptech Ltd. Modifiers and Packages/Session 9 25

Using slides 20 to 25, explain creating static variables, static methods, and static blocks.

©Aptech Limited
Modifier and Packages

One can also create static methods and static initializer blocks along with static variables.
Static variables and methods can be manipulated without creating an instance of the class. This is
because there is only one copy of a static data member that is shared by all objects. A static method
can only access static variables and not instance variables.

Methods declared as static have the following restrictions:


 Can access only static data
 Can invoke only static methods
 Cannot use this or super keywords

Generally, a constructor is used to initialize variables. However, a static block can also be used to

y
initialize static variables because static block is executed even before the main() method is

nl
executed. It is used when a block of code needs to be executed during loading of the class by JVM.

O
Execution of Java code starts from static blocks and not from main() method. It is enclosed within
{} braces. 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

se
before it.

Explain the code snippet that demonstrates an example of static variables, static method, and static
block mentioned in slides 22 to 25.
rU
Static variables are initialized only once, at the start of the execution. A static variable can be
te
accessed directly by the class name and does not need any object.
en

Static method belongs to the class and not to the object. Static method can access only static data
and can call only other static methods. Static method cannot refer to ‘this’ keyword.
C

Tips:
Static variables will be initialized first, before the initialization of static variables.
h

Slides 26 and 27
ec

Let us understand packages.


pt
rA

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

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.
 This is depicted in the following figure:

© Aptech Ltd. Modifiers and Packages/Session 9 26

©Aptech Limited
Modifier and Packages

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

 For example, one can keep source files in one folder, images in another, and
executables in yet another folder. Packages have the following features:
A package can have sub packages.

A package cannot have two members with the same name.

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.

y
Package names are written in lowercase.

nl
Standard packages in the Java language begin with java or javax.

O
© Aptech Ltd. Modifiers and Packages/Session 9 27

Using slides 26 and 27, explain packages.

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

rU
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.
te
For this purpose, the user creates separate folders and divides the files according to the years and
further groups them according to the content. Similarly, in Java, one can organize the files using
en

packages.

A package is a namespace that groups related classes and interfaces and organizes them as a unit.
C

For example, one can keep source files in one folder, images in another, and executable in yet
another folder. Then, explain the features of the packages listed on slide 27.
h
ec

A Java package is a mechanism for organizing Java classes into namespace. Java packages can be
stored in compressed files called JAR files. It allows classes to download faster as a group rather than
one at a time. Package provides a unique namespace for the types it contain. Classes in the package
pt

can access each other package-access members.


rA

Programmers also used packages to organize classes belonging to the same category or providing
similar functionality.
Fo

In-Class Question:
After you finish explaining the packages, you will ask the students an In-Class question. This will help
you in reviewing their understanding of the topic.

How the class or interface is referenced inside a package?

Answer:
It can be referenced using the name of the Java class including its package name.

©Aptech Limited
Modifier and Packages

Slide 28
Let us understand advantages of using packages.

One can easily determine that these classes are related.

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

y
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

nl
accessible outside the package.

Packages can also have classes with data members that are visible to other classes, but not
accessible outside the package.

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

se
© Aptech Ltd. Modifiers and Packages/Session 9 28

Using slide 28, explain advantages of using packages.

rU
Explain them the reasons to group classes and interfaces in Java.
te
Slides 29 to 39
Let us understand type of packages.
en
C

 The Java platform comes with a huge class library which is a set of packages.
 These classes can be used in applications by including the packages in a class.
 This library is known as the Application Programming Interface (API).
h

 Every Java application or applet has access to the core package in the API, the
java.lang package.
ec

 For example,

The String class stores the state and behavior related to character strings.
pt

The File class allows the developer to create, delete, compare, inspect, or
modify a file on the file system.
rA

The Socket class allows the developer to create and use network sockets.

The various Graphical User Interface (GUI) control classes such as Button,
Fo

Checkbox, and so on provide ready to use GUI controls.


© Aptech Ltd. Modifiers and Packages/Session 9 29

©Aptech Limited
Modifier and Packages

y
nl
O
se
 To create user-defined packages, perform the following steps:

1 conventions:


rU
• Select an appropriate name for the package by using the following naming

Package names are usually written in all lower case to avoid conflict
with the names of classes or interfaces.
te
 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
en

created by a programmer at sample.com.


 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.
C

 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.
h

© Aptech Ltd. Modifiers and Packages/Session 9 31


ec
pt

 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
rA

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 the following table:

Domain Name Suggested Package Name


Fo

sample-name.sample.org org.sample.sample_name

sample.int int_.sample
007name.sample.com com.sample._007name

• Create a folder with the same name as the package.


2

• Place the source files in the folder created for the package.
3

© Aptech Ltd. Modifiers and Packages/Session 9 32

©Aptech Limited
Modifier and Packages

• Add the package statement as the first line in all the source files under that package as
4 depicted in the following code snippet:

package session9;
class StaticMembers{
public static void main(String[] args)
{}
}

 Note that there can only be one package statement in a source file.
• Save the source file StaticMembers.java in the package session9.
5
• Compile the code as follows:
6
javac StaticMembers.java
OR

y
 Compile the code with -d option as follows:
javac –d . StaticMembers.java

nl
 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.

O
© Aptech Ltd. Modifiers and Packages/Session 9 33

se
• From the parent folder of the source file, execute it using the fully qualified name as
7 follows:


rU
java session9.StaticMembers
Java allows the user to import the classes from predefined as well as user-defined
packages using an import statement.
However, the access specifiers associated with the class members will determine if the
class members can be accessed by a class of another package.
te
 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,
en

package-name.class-name.

Importing the package member, that is,


import package-name.class-name.
C

Importing the entire package, that is,


import package-name.*.
h

© Aptech Ltd. Modifiers and Packages/Session 9 34


ec
pt

 To create a new package using NetBeans IDE, perform the following steps:
• Open the project in which the package is to be created.
1 • In this case Session9 project has been chosen.
rA

• Right-click Source Packages → New → Java Package to display the New Java Package
2 dialog box.
 For example, in the following figure, the project Session9 is opened
and the Java Package option is selected:
Fo

© Aptech Ltd. Modifiers and Packages/Session 9 35

©Aptech Limited
Modifier and Packages

• Type userpkg in the Package Name box of the New Java Package dialog box that is
3 displayed.

• Click Finish. The userpkg package is created as shown in the following figure:
4

y
• Right-click userpkg and select New → Java Class to add a new class to the package.
5

nl
• Type UserClass as the Class Name box of the New Java Class dialog box and click
6 Finish.

O
© Aptech Ltd. Modifiers and Packages/Session 9 36

se
• Type the code in the class as depicted in the following code snippet:
7
package userpkg;

rU
// Import the predefined and user-defined packages
import java.util.ArrayList;
import session9.StaticMembers;

public class UserClass {


te
// Instantiate ArrayList class of java.util package
ArrayList myCart = new ArrayList(); // line 1
en

/**
* Initializes an ArrayList
*
* @return void
*/
C

public void createList() {

// Add values to the list


myCart.add(“Doll”);
h

© Aptech Ltd. Modifiers and Packages/Session 9 37


ec
pt

myCart.add(“Bus”);
myCart.add(“Teddy”);
// Print the list
System.out.println(“Cart contents are:”+ myCart);
rA

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Fo

// Instantiate the UserClass class


UserClass objUser = new UserClass();
objUser.createList(); // Invoke the createList() method

// Instantiate the StaticMembers class


StaticMembers objStatic = new StaticMembers();
objStatic.displayCount(); // Invoke the displayCount() method
}
}

© Aptech Ltd. Modifiers and Packages/Session 9 38

©Aptech Limited
Modifier and Packages

 The two import statements namely, java.util.ArrayListand


session9.StaticMembersare used to import the packages java.util and
session9into the UserClass class.
 Following figure shows the output of the program:

 The output shows the execution of the static block of StaticMembers class also.
 This is because the static block is executed as soon as the class is launched.

y
nl
O
© Aptech Ltd. Modifiers and Packages/Session 9 39

Using slides 29 to 39, explain type of packages.

se
Tell them that every Java application or applet has access to the core package in the API, the
java.lang package.
rU
For example, the String class stores the state and behavior related to character strings. The File
class allows the developer to create, delete, compare, inspect, or modify a file on the file system.
te
The Socket class allows the developer to create and use network sockets. The various Graphical
User Interface (GUI) control classes such as Button, Checkbox, and so on provide ready to use GUI
en

controls.

Tell them that Java packages are of two types namely, predefined packages and user-defined
C

packages.
h

The predefined packages are part of the Java API. Some of the predefined packages that are
commonly used are java.io, java.util , java.awt , and so on.
ec

The predefined packages are the type of Java packages that contain wide range of classes and
methods to perform different functionalities. They are also termed as Java API packages.
pt

User-defined packages are Java package type created by user. The user can grouped user defined
classes into user defined packages.
rA

Explain the steps to create user-defined packages mentioned in slides 31 to 34.


Fo

Explain the steps to create a new package using NetBeans IDE mentioned in slides 35 to 39.

Tips:
Package creates a new namespace hence, there will not be any name conflicts with names in other
packages.

©Aptech Limited
Modifier and Packages

Slides 40 to 55
Let us understand creating .jar files for deployment.

 All the source files of a Java application are bundled into a single archive file called the
Java Archive (JAR).
 The .jar file contains the class files and additional resources associated with the
application.
 The .jar file format provides several advantages as follows:

• The .jar file can be digitally signed so that only those users who
Security recognize your signature can optionally grant the software security
privileges that the software might not otherwise have.

y
• The source files bundled in a .jar file can be downloaded to a
Decrease in

nl
browser in a single HTTP transaction without having to open a new
Download Time connection for each file.

O
File
• The .jar format compresses the files for efficient storage.
Compression

se
© Aptech Ltd. Modifiers and Packages/Session 9 40

Packaging for
Extensions
rU
• The extension framework in Java allows adding additional functionality to
the Java core platform.
• The .jar file format defines the packaging for extensions. For example,
te
Java 3D and Java Mail extensions developed by Sun Microsystems.

• Java provides an option to seal the packages stored in the .jar files so
Package that the packages can enforce version consistency.
en

Sealing • 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 • A .jar file can also store additional information about the files, such as
C

Versioning vendor and version information.

• The .jar files are packaged in a ZIP file format.


Portability
h

• This enables the user to use them for tasks such as lossless data
compression, decompression, archiving, and archive unpacking.
ec

© Aptech Ltd. Modifiers and Packages/Session 9 41


pt
rA



To
Toperform
performbasic
basictasks with.jar
taskswith .jarfiles,
files,one
onecan canuse
usethe
theJava
JavaArchive
ArchiveTool.
Tool.


This
Thistool
toolisisprovided
providedwith
withthe theJDK.
JDK.


The
TheJava
JavaArchive
ArchiveTool
Toolisisinvoked
invokedby
byusing
usingthe thejar
jarcommand.
command.
The
Thebasic
basicsyntax
syntaxfor creatingaa.jar
forcreating .jarfilefileisisas
asfollows:
Fo


 follows:
Syntax
Syntax
jar
jar cf
cf jar-file-name
jar-file-name input-file-name(s)
input-file-name(s)
where,
where,
c:
c:indicates
indicatesthatthatthe
theuser
userwants
wantsto CREATEaa.jar
toCREATE .jarfile.
file.
f:
f:indicates
indicatesthatthatthe
theoutput
outputshould
shouldgo goto
toaafile
fileinstead
insteadofofstdout.
stdout.
jar-file-name:
jar-file-name:represents representsthe thename
nameof ofthe resulting.jar
theresulting .jarfile.
file.Any
Anyname
namecan
can
be
beused
usedforforaa.jar
.jarfile. The.jar
file.The .jarextension
extensionisisprovided
providedwith
withthe
thefile
filename,
name,
though it is not required.
though it is not required.
input-file-name(s):
input-file-name(s):represents representsaalist
listof
ofone
oneorormore
morefiles
filesto
tobe beincluded
includedinin
the.jar
the .jarseparated
separatedby byaaspace.
space.This
Thisargument
argumentcan cancontain
containthe
thewildcard
wildcardsymbol
symbol‘*’‘*’
as
aswell.
well.IfIfany
anyofofthe
theinput
inputfiles
filesspecified
specifiedisisaadirectory,
directory,the
thecontents
contentsof ofthat
that
directory are added to the .jar recursively.
directory are added to the .jar recursively.

©©Aptech
AptechLtd.
Ltd. Modifiers
Modifiersand
andPackages/Session
Packages/Session99 42
42

©Aptech Limited
Modifier and Packages

 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.
 Some of the other options, apart from cf, available with the jar command are listed
in the following table:

y
nl
O
© Aptech Ltd. Modifiers and Packages/Session 9 43

se
 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


rU
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.
Consider the following files of a simple BouncingBallgame application as shown in
the following figure:
te
en

 The figure shows the BouncingBall application with the source file
C

BouncingBall.java, class file BouncingBall.class, sounds directory,


imagesdirectory, and Manifest.txt file.
 sounds and images are subdirectories that contain the sound files and animated
.gif images used in the application.
h

© Aptech Ltd. Modifiers and Packages/Session 9 44


ec

To create a .jar of the application using command line, perform the following steps:
pt

• Create the directory structure as shown in the earlier figure.


1
rA

• Create a text file with the code depicted in the following code snippet:
2
package bounceball;
public class BouncingBall {
Fo

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(“This is the bouncing ball game”);
}
}

• Save the file as BouncingBall.java in the source package bounceball.


3

© Aptech Ltd. Modifiers and Packages/Session 9 45

©Aptech Limited
Modifier and Packages

• Compile the .java file at command prompt by writing the following command:
4
javac -d . BouncingBall.java
 The command will create a subfolder with the same name bounceball
and store the class file BouncingBall.java in that directory.
• Create a text file with the Main-class attribute as shown in the following figure:
5

y
nl
O
© Aptech Ltd. Modifiers and Packages/Session 9 46

se
• Save the file as Manifiest.txt in the source bounceball folder.
6

7


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

• To package the application in a single .jar named BouncingBall.jar, write the


following command:
te
jar cvmf Manifest.txt bounceball.jar
bounceball/BouncingBall.class sounds images
 This will create a bounceball.jar file in the source folder as shown
en

in the following figure:


C
h

© Aptech Ltd. Modifiers and Packages/Session 9 47


ec
pt

 The command options cvmf indicate that the user wants to create a .jar file with
verbose output using the existing manifest file, Manifest.txt.
 The name of the output file is specified as bounceball.jar instead of stdout.
rA

 Further, the name of the class file is provided with its location as
bounceball/BouncingBall.classfollowed by the directory names sounds
and images so that the respective files under these directories are also included in
the .jar file.
Fo

• To execute the .jar file at command prompt, type the following command:
8
java -jar bounceball.jar

 The command will execute the main() method of the class of the
.jar file and print the following output:
This is the bouncing ball game.

© Aptech Ltd. Modifiers and Packages/Session 9 48

©Aptech Limited
Modifier and Packages

 Following figure shows the entire series of steps for creation of .jar file with the
verbose output and the final output after .jar file execution:

y
nl
O
© Aptech Ltd. Modifiers and Packages/Session 9 49

se
Since sounds and images are directories, the Jar tool will recursively place the
contents in the .jar file.

rU
The resulting .jar file BouncingBall.jar will be placed in the current
directory.
The use of the option ‘v’ will shows the verbose output of all the files that are
included in the .jar file.
In the example, the files and directories in the archive retained their relative path
te
names and directory structure.
One can use the -c option to create a .jar file in which the relative paths of the
archived files will not be preserved.
en

 For example, suppose one wants to put sound files and images used by the
BouncingBall program into a .jar file, and that all the files should be on the
top level, with no directory hierarchy.
C

 One can accomplish this by executing the following command from the parent
directory of the sounds and images directories:
jar cf SoundImages.jar -c sounds . -c images .
h

© Aptech Ltd. Modifiers and Packages/Session 9 50


ec
pt

 Here, ‘-c sounds’ directs the Jar tool to the sounds directory and the ‘.’ following
‘-c sounds’ directs the Jar tool to archive all the contents of that directory.

Similarly, ‘-c images .’ performs the same task with the images directory.
rA

 The resulting .jar file would consist of all the sound and image files of the sounds
and images folder as follows:
META-INF/MANIFEST.MF
Fo

beep.au
failure.au
ping.au
success.au
greenball.gif
redball.gif
table.gif

 However, if the following command is used without the -c option:


jar cf SoundImages.jar sounds images
© Aptech Ltd. Modifiers and Packages/Session 9 51

©Aptech Limited
Modifier and Packages

y
nl
O
se
 To create a .jar file of the application using NetBeans IDE, perform the following
steps:
• Create a new package bounceball in the Session9 application.
1

3
rU
• Create a new java class named BouncingBall.java within the bounceball package.

• Type the code depicted in the following code snippet in the BouncingBall class:
te
package bounceball;
public class BouncingBall {
/**
* @param args the command line arguments
en

*/
public static void main(String[] args)
{
System.out.println(“This is the bouncing ball game”);
}
C

• Set BouncingBall.java as the main class in the Run properties of the application.
4
h

© Aptech Ltd. Modifiers and Packages/Session 9 53


ec
pt

• Run the application by clicking the Run icon on the toolbar.


5 • The output will be shown in the Output window.
• To create the .jar file, right-click the Session9 application and select Clean and Build
6 option as shown in the following figure:
rA
Fo

 The IDE will build the application and generate the .jar file.
 A message as shown in the following figure will be displayed to the user in the status
bar, once .jar file generation is finished:

© Aptech Ltd. Modifiers and Packages/Session 9 54

©Aptech Limited
Modifier and Packages

 The Clean and Build command creates a new dist folder into the application folder and
places the .jar file into it as shown in the following figure:

 User can load this .jar file in any device that has a JVM and execute it by
double-clicking the file or run it at command prompt by writing the following
command:
java –jar Session9.jar

y
nl
O
© Aptech Ltd. Modifiers and Packages/Session 9 55

Using slides 40 to 55, explain creating .jar files for deployment.

se
All the source files of a Java application are bundled into a single archive file called the Java Archive
(JAR). The .jar file contains the class files and additional resources associated with the application.
rU
Explain the .jar file format provides several advantages mentioned in slides 40 and 41.
te
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.
en

Then, explain the basic syntax for creating a .jar file. Tell them that 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
C

and places it by default in the current directory. Also, it will generate a default manifest file for the
.jar file.
h

The metadata in the .jar file such as entry names, contents of the manifest, and comments must
ec

be encoded in UTF8.
pt

Explain some of the other options available with the jar command are listed in the slide 43.

When a .jar file is created, the time of creation is stored in the .jar file. Therefore, even if the
rA

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

Consider the following files of a simple BouncingBall game application as shown in the slide 44.

Explain the steps to create a .jar of the application using command line mentioned in slides 45 to 49.

Tell them that since sounds and images are directories, the Jar tool will recursively place the
contents in the .jar file. The resulting .jar file BouncingBall.jar will be placed in the current directory.
The use of the option ‘v’ will show the verbose output of all the files that are included in the .jar file.

©Aptech Limited
Modifier and Packages

In the example, the files and directories in the archive retained their relative path names and
directory structure. One can use the -c option to create a .jar file in which the relative paths of the
archived files will not be preserved.

Explain the example, suppose one wants to put sound files and images used by the BouncingBall
program into a .jar file, and that all the files should be on the top level, with no directory hierarchy
mentioned in slides 50 to 52.

Explain the steps to create a .jar file of the application using NetBeans IDE mentioned in slides 53 to
55.

y
JAR file packaged with the ZIP file format, so you can use them for task such as data compression,
archiving, decompression, and archive unpacking. These tasks are among the most common uses of

nl
JAR files.

O
Explain the benefits of JAR file format:
 Security- You can digitally sign the content of JAR file.

se
 Compression- the JAR format allows compressing your file for efficient storage.
 Package Versioning- A JAR files can hold data about the files it contains such as version
information.

rU
 Portability- The mechanism for handling JAR files is a standard part of Java platform core
API.
te
In-Class Question:
After you finish explaining the creating .jar files for deployment, you will ask the students an In-class
en

question. This will help you in reviewing their understanding of the topic.
C

Why the resulting files will not be identical?


h
ec

Answer:
Because when a .jar file is created, the time of creation is stored in the .jar file.
pt
rA
Fo

©Aptech Limited
Modifier and Packages

Slide 56
Let us summarize the session.

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

y
 The final modifier is used when modification of a class or data member is to be
restricted.

nl
 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

O
them as a unit.
 All the source files of a Java application are bundled into a single archive file called the
Java Archive (JAR).

se
© Aptech Ltd. Modifiers and Packages/Session 9 56

rU
In slide 56, you will summarize the session. End the session with a brief summary of what has been
taught in the session.
te
9.3 Post Class Activities for Faculty
en

You should familiarize yourself with the topics of the next session which is based on inheritance and
polymorphism.
C

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
h

online tutors on the Online Varsity site to ask queries related to the sessions.
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

Session 10 – Inheritance and Polymorphism

10.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
10.1.1 Objectives

nl
By the end of this session, the learners will be able to:

O
 Describe inheritance
 Explain the types of inheritance

se
 Explain super class and subclass
 Explain the use of super keyword



Explain method overriding
Describe Polymorphism rU
Differentiate type of reference and type of objects
te
 Explain static and dynamic binding
 Explain virtual method invocation
en

 Explain the use of abstract keyword

10.1.2 Teaching Skills


C

To teach this session, you should be well-versed with concept of inheritance and its types, the
subclass and superclass. You should be familiar with the method overriding and polymorphism,
h

static, and dynamic binding and virtual method invocation.


ec

You should teach the concepts in the theory class using the images provided. For teaching in the
class, you are expected to use slides and LCD projectors.
pt
rA

Tips:
It is recommended that you test the understanding of the students by asking questions in between
the class.
Fo

In-Class Activities:
Follow the order given here during In-Class activities.

©Aptech Limited
Inheritance and Polymorphism

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
Tell the students that this session introduces the basic concept of inheritance and its types. The

rU
session explains the concept of subclass and superclass in inheritance. Also the session will introduce
them with the concept of polymorphism and method overriding. The session explains the concept of
static and dynamic binding in polymorphism. Finally, the session will explain them about virtual
te
method invocation and abstract classes.
en

10.2 In-Class Explanations


Slides 3 to 5
C

Let us understand the concept of inheritance.


h
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C

Using slides 3 to 5, explain the concept of inheritance.


h

Discuss with the students the example on animals falling in similar categories. For example, the
ec

animals that eat plants can be categorized as herbivores, those that eat animals as carnivores, and
those that eat both plants and animals as omnivores. Now, discuss that in each category, the animals
pt

and birds normally eat the same type of food and have similar characteristics.
rA

Based on the discussed example, explain that Java also provides the concept of inheritance where
the classes can extend and reuse the features of existing class and implement the behavior.
Fo

Similarly, you can discuss one more example of inheritance seen in human beings. Inform them that
in a family, traits of parents are often inherited by their children. In addition to having unique traits
and behavior of their own, children inherit those of their parents.

Introduce them to the concept of polymorphism in Java. Tell them that polymorphism in Java allows
an objects can take many forms, which means it can behave differently based on the context in
which it has been used.

Explain them the kind of relationship that exists in 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.

©Aptech Limited
Inheritance and Polymorphism

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.

Explain the figure that shows some examples of is-a relationship mentioned in slides 4 and 5.

Tell them that inheritance is based on is-a relationship where a class that is derived from another
class is called a subclass (also a derived class, extended class, or child class). The class from which the
subclass is derived is called a superclass (also a base class or a parent class).

Explain them that in Java every class will have one and only one direct superclass. The following
figure depicts the superclass and subclass relationship:

y
nl
O
se
rU
For example, in the absence of any other explicit superclass, every class is implicitly a subclass of
object.
te
In-Class Question:
en

After you finish explaining concept of inheritance, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
C
h

What is the advantage of using inheritance in Java applications?


ec

Answer:
pt

Inheritance encourages the code reusability and allows the developers to extend the functionalities
of the existing classes in the application.
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

Slides 6 and 7
Let us understand features and types of inheritance.

y
nl
O
se
rU
te
en
C
h
ec

Using slides 6 and 7, explain the features and types of inheritance.

Discuss with them the advantages of inheritance. Tell them that it saves work and encourages code
pt

reuse and customization, because the specialized class inherits all the properties and methods of the
general class, only new properties and methods need to be implemented. In other words, a user can
rA

simply derive the new class from the existing class without having to write or debug the new code.
The subclass will have its own specific characteristics along with those inherited from the super
class.
Fo

A subclass inherits all the members such as fields, nested classes, and methods from its super class
except those with private access specifier.

Constructors
Constructors of a superclass are not inherited by subclasses. Thus, the child class can invoke the
constructor of the super class from its own constructor. Also, the members having default modifier
in the super class are not inherited by subclasses of other packages.

©Aptech Limited
Inheritance and Polymorphism

Then, explain the different types of inheritance supported by an object-oriented language. The
following figure shows the different types of inheritance:

y
nl
O
se
Single Inheritance - A child class inherits from one and only one parent class.

rU
Multilevel Inheritance - A child class derives from a parent that itself is a child of another class. Here,
one class extends only one. The lower most subclass can make use of all of its super classes
members.
te
Multiple Inheritance - A child class derives from more than one parent class. It means one class
extending more than one base class.
en

Hierarchical Inheritance - A parent class has more than one child classes at different levels.
C

It means one class derived from many subclasses.

In-Class Question:
h

After you finish explaining features and terminologies, you will ask the students an In-Class question.
ec

This will help you in reviewing their understanding of the topic.


pt
rA

Which type of inheritance have more than one parent classes?


Answer:
Multiple
Fo

Tips:
Java language does not support multiple inheritance.

©Aptech Limited
Inheritance and Polymorphism

Slides 8 to 13
Let us understand working with super class and subclass in inheritance.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 8 to 13, explain working with super class and subclass in inheritance.

Explain the features of a subclass that one can use for the inherited members as listed in slide 8.

Then, explain the syntax of the subclass where <class1-name> is the name of the subclass and
<class2-name> is the name of the superclass.

©Aptech Limited
Inheritance and Polymorphism

Explain the code snippet that demonstrates the creation of super class Vehicle mentioned in slides 9
and 10. 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.
Explain the code snippet that demonstrates the creation of subclass FourWheeler mentioned in
slides 11 to 13. The code 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. 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

y
appropriate arguments. Next, the showDetails() method is invoked to print the details.

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

O
Slides 14 to 18
Let us understand overriding methods.

se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 14 to 18, explain overriding methods.

Java allows creation of an instance method in a subclass having the same signature and return type
as an instance method of the super class. This is called method overriding. Method overriding allows
a class to inherit behavior from a super class and then, to modify the behavior as needed.

©Aptech Limited
Inheritance and Polymorphism

The purpose of overriding is to define new or different behavior for the objects of the subclass. For
instance, taking a real-world example, a 1970’s model of a Toyota car also had a basic action of
driving and a latest model of a Toyota car also has the same basic action but with greater and better
performance. So, though the basic action still remains the same, how the models implement the
action is different in each case.

Discuss with the students the rules that one should remember when overriding methods. They are
as follows:
 The overriding method must match in name, type, number of arguments, and return type
with the overridden method.
 An overridden method cannot have a weaker access specifier than the access specifier of the

y
method it overrides. For example, a protected method in a superclass can be overridden
by a public method having same signature, but a public method in a superclass

nl
cannot be overridden by a protected method in the subclass.

O
Tips:
The ability of a subclass to override a method allows a class to inherit from a superclass whose

se
behavior is ’close enough’ and then to modify behavior as needed. The overriding method has the
same name, number and type of parameters, and return type as the method that it overrides. An
overriding method can also return a subtype of the type returned by the overridden method.

rU
Explain the accelerate() method that can be overridden in the subclass as in the code snippet
mentioned in slides 14 to 18.
te
The accelerate() method is overridden in the child class with the same signature and
en

return type but 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
C

will generate compilation error.


h

Slides 19 to 24
Let us understand accessing super class constructor and methods.
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C

Using slides 19 to 24, explain accessing super class constructor and methods.
h
ec

In the code explained on the earlier slides, the subclass constructor is used to initialize the values of
the common attributes inherited from the super class Vehicle. This is not the correct approach
because all the subclasses of the Vehicle class will have to initialize the values of common attributes
pt

every time in their constructors.


rA

Java allows the subclass to invoke the super class constructor and methods using the keyword
super. Also, when the accelerate() method is overridden in the subclass, the statement(s) written
in the accelerate() method of the super class, Vehicle, are not printed.
Fo

The basic purpose of super keyword is to enable access to those members of the superclass that
are presently hidden by members in the subclass. To invoke the super class method, use the syntax:
super.method-name()and to invoke super class constructor, use the syntax: super().

Explain the code snippet demonstrates the modified super class Vehicle.java using a parameterized
constructor mentioned in slides 20 and 21.

Explain the code snippet depicts the modified subclass FourWheeler.java using the super keyword
to invoke super class constructor and methods mentioned in slides 21 to 24.

©Aptech Limited
Inheritance and Polymorphism

In the code, 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.

In-Class Question:
After you finish explaining accessing super class constructor and methods, you will ask the students
an In-Class question. This will help you in reviewing their understanding of the topic.

y
How to work with the super() keyword?

nl
Answer:
To invoke the super class method, use the syntax: super.method-name()and to invoke super

O
class constructor, use the syntax: super().

Slide 25

se
Let us understand the concept of polymorphism.

rU
te
en
C
h
ec

Using slide 25, explain the concept of polymorphism.


pt

The word polymorph is a combination of two words namely, ‘poly’ which means ‘many’ and ‘morph’
rA

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

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.

The most common use of polymorphism in OOP occurs when a parent class reference is used to
refer to a child class object. It is the ability to create a variable, a function, or an object that has more
than one form.

Tips:
Any Java object that can pass more than one is-a test is considered to be polymorphic.

©Aptech Limited
Inheritance and Polymorphism

Slides 26 to 33
Let us understand static and dynamic binding.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C

Using slides 26 to 33, explain understanding static and dynamic binding.


h

When the compiler resolves the binding of methods and method calls at compile time, it is
ec

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. All static method calls are resolved at
pt

compile time and therefore, static binding is done for all static method calls. The instance
method calls are always resolved at runtime.
rA

Explain some important differences between static and dynamic binding are listed in table in
slide 26.
Fo

Then, explain the code snippet demonstrates an example of static binding mentioned in slides 26 to
30. The code snippet 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 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.

©Aptech Limited
Inheritance and Polymorphism

Explain the code snippet demonstrates an example of dynamic binding mentioned in slides 31 to 33.
The code snippet 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.

y
The EmployeeDetails class is modified to create another object objEmp1 of class

nl
Employee. However, the object is assigned the reference of class PartTimeEmployee and
the constructor is invoked with four arguments. Next, the displayDetails() method is

O
invoked to print the employee details.

se
In-Class Question:
After you finish explaining static and dynamic binding, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
rU
te
Which type of binding method bounds the invocation of method call to the object at
en

runtime?

Answer:
C

Dynamic

Slides 34 and 35
h

Let us understand to differentiate type of reference and type of object.


ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
Using slides 34 and 35, explain to differentiate type of reference and type of object.

Upcasting

se
Java allows casting an instance of a subclass to its parent class. This is known as upcasting. For
example, PartTimeEmployee objPT = new PartTimeEmployee();
Employee objEmp = objPT; // upcasting
rU
While upcasting a child object, the child object objPT is directly assigned to the parent class object
te
objEmp. However, the parent object cannot access the members that are specific to the child class
and not available in the parent class.
en

In upcasting, if two types are compatible and destination type is larger than source type, then Java
will perform the conversion automatically. For example, int type is always large enough to hold all
C

valid byte values, so no explicit cast statement is required.


h

Downcasting
ec

Java also allows casting the parent reference back to the child type. This is because parent
references an object of type child.
pt

Casting a parent object to child type is called downcasting because an object is being casted to a
class lower down in the inheritance hierarchy. However, downcasting requires explicit type casting
rA

by specifying the child class name in brackets.

For example,
Fo

PartTimeEmployee objPT1 = (PartTimeEmployee) objEmp;


// downcasting

Upcasting and downcasting are important parts of Java which allow us to build complex programs
using simple syntax. Upcasting can be done automatically, but downcasting must be manually done
by the programmer.

©Aptech Limited
Inheritance and Polymorphism

Slide 36
Let us understand invocation of virtual method.

y
nl
O
se
Using slide 36, explain invocation of virtual method.

rU
In the earlier code, during execution of the statement Employee objEmp1= new
PartTimeEmployee(…), the runtime type of the Employee object is determined. The compiler does
not generate error because the Employee class has a displayDetails() method.
te
At runtime, the method executed is referenced from the PartTimeEmployee object. This aspect of
polymorphism is called virtual method invocation. In other languages such as C++, the same can be
en

achieved by using the keyword virtual. In object-oriented programming, a virtual method is a


method whose behavior can be overridden within an inheriting class by a function with the same
signature to provide polymorphic behavior. The method which cannot be inherited for polymorphic
C

behavior is not a virtual method.


h

Static method is not a virtual method in Java as they are bound to the class itself, so calling static
method from class name or object does not provide polymorphic behavior to the static method.
ec

Explain the difference between the compiler and the runtime behavior listed in the slide.
pt

Tips:
rA

Every non-static method in Java is by default virtual method except final and private methods.
Fo

©Aptech Limited
Inheritance and Polymorphism

Slides 37 to 45
Let us understand using the ‘abstract’ keyword.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Inheritance and Polymorphism

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 37 to 45, explain Using the ‘abstract’ Keyword.

Java provides the abstract keyword to create a super class that serves as a generalized form that will
be inherited by all of its subclasses. The methods of the super class serve as a contract or a standard
that the subclass can implement in its own way.

©Aptech Limited
Inheritance and Polymorphism

Abstract method

An abstract method is one that is declared with the abstract keyword and is without an
implementation, that is, without any body. The abstract method does not contain any ‘{}’ brackets
and ends with a semicolon. An abstract method is only a contract that the subclass will provide
its implementation.

Explain the syntax for declaring an abstract method in the class.

Tell them that declaring a method as abstract has two outcomes:


 The class must also be declared abstract. If a class contains an abstract method, the class

y
must be abstract as well.
 Any child class must either override the abstract method or declare itself abstract.

nl
O
Abstract class

An abstract class is one that consists of abstract methods. Abstract class serves as a framework that

se
provides certain behavior for other classes. The subclass provides the requirement-specific behavior
of the existing framework.

rU
Abstract classes cannot be instantiated and they must be subclassed to use the class members. The
subclass provides implementations for the abstract methods in its parent class.
te
The syntax for declaring an abstract class is as follows:
en

The following code shows the implementation of abstract class:


public abstract Calculator
{
C

public float getPI(){ // Define a concrete method


return 3.14F;
}
h

abstract void Calculate(); // Declare an abstract method


}
ec

Explain the code snippet demonstrates creation of abstract class and abstract method mentioned in
pt

slide 40.
rA

Explain the code snippet demonstrates two subclasses Circle and Rectangle inheriting the abstract
class Shape mentioned in slides 41 and 42. The class Circle implements the abstract
method calculate() to calculate the area of a circle. Similarly, the class Rectangle
Fo

implements the abstract method calculate() to calculate the perimeter of a rectangle.

Explain the code snippet depicts the code for Calculator class that uses the subclasses based
on user input mentioned 43 and 45. 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.

©Aptech Limited
Inheritance and Polymorphism

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.
To execute the example at command line, write the following command:
java Calculator Rectangle 12

y
Slide 46
Let us summarize the session.

nl
O
se
rU
te
en
C

In slide 46, you will summarize the session. End the session with a brief summary of what has been
h

taught in the session.


ec

10.3 Post Class Activities for Faculty


pt

You should familiarize yourself with the topics of the next session which is based on interfaces and
nested classes.
rA

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
Fo

online tutors on the Online Varsity site to ask queries related to the sessions.

©Aptech Limited
Interfaces and Nested Classes

Session 11 – Interfaces and Nested Classes

11.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
11.1.1 Objectives

nl
By the end of this session, the learners will be able to:

O
 Describe Interface
 Explain the purpose of interfaces
 Explain implementation of multiple interfaces

se
 Describe Abstraction
 Explain Nested class



Explain Member class
Explain Local class
Explain Anonymous class
rU
te
 Describe Static nested class

11.1.2 Teaching Skills


en

To teach this session, you should be well-versed with concept and use of interface and
implementation of multiple interfaces. You should be familiar with the abstraction, multiple class,
C

nested class, and local class.

You should teach the concepts in the theory class using the images provided. For teaching in the
h

class, you are expected to use slides and LCD projectors.


ec

Tips:
pt

It is recommended that you test the understanding of the students by asking questions in between
the class.
rA

In-Class Activities:
Fo

Follow the order given here during In-Class activities.

©Aptech Limited
Interfaces and Nested Classes

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
Tell the students that this session explains the concept of interfaces in Java. The session explains

rU
how to declare the interfaces and implement them in Java class. The session also explains the
concept of multiple interfaces. The session explains the concept of abstraction, multiple class,
nested class, and local class. The session also explains the concept of anonymous class and static
te
nested class in Java.
en

11.2 In-Class Explanations


Slide 3
C

Let us understand the concept of interfaces and nested classes.


h
ec
pt
rA
Fo

Using slide 3, explain the concept of interfaces and nested classes.

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.

©Aptech Limited
Interfaces and Nested Classes

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.

Slides 4 and 5
Let us understand the concept of interfaces in Java.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slides 4 and 5, explain the concept of Interfaces in Java.

Tell the students that there are a number of situations in software engineering when it is important
for disparate groups of programmers to agree to a ’contract’ that specifies how their software
Fo

interacts. Each group should be able to write their code without any knowledge of how the other
group's code is written. Generally speaking, interfaces are such contracts.

Consider a new employee who joins an organization to work with them usually signs a contract
which states that he/she will abide by the rules laid down by the organization and comply with their
guidelines. In the programming world too, a contract can be defined for classes, such that once they
accept the contract they will abide by it. Such a contract is an interface.

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.

©Aptech Limited
Interfaces and Nested Classes

Then, explain the differences between an interface and a class in Java as presented in the figure in
slide 5.

Writing an interface is similar to writing a class, however the difference is that the class describes the
attributes and behaviors of an object. An interface contains the method declarations that a class can
implement by signing the interface.

Slides 6 to 16
Let us understand purpose of interfaces.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 6 to 16, explain purpose of interfaces.

©Aptech Limited
Interfaces and Nested Classes

The two main benefits that are derived from using interfaces:

 An interface provides a means of setting a standard. It defines a contract that promotes


reuse. If an object implements an interface then that object is promising to conform to a
standard.
 An interface also provides a level of abstraction that makes programs easier to understand.
Interfaces allow developers to start talking about the general way that code behaves
without having to get in to a lot of detailed specifics.

In Java, an interface is a collection of related methods without any body. These methods form
the contract that the implementing class must agree with. When a class implements an

y
interface, it becomes more formal about the behavior it promises to provide. This contract is

nl
enforced at build time by the compiler. If a class implements an interface, all the methods
declared by that interface must appear in the implementing class for the class to compile

O
successfully.

Declaring an interface

se
Explain the syntax for declaring an interface. Tell them that an interface in Java is defined as a

whereas the methods are abstract. rU


reference type and is similar to a class except that it has only final and static variables,

The following code snippet shows the declaration of the interface:


te
public interface Sample extends Interface1{
static final int someInteger;
en

public void someMethod();


}
C

Tell them that the method declaration does not have any braces and is terminated with a semicolon.
Also, the body of the interface contains only abstract methods and no concrete method. Since all
methods in an interface are implicitly abstract, the abstract keyword is not explicitly specified
h

with the method signature.


ec

Tell them the convention followed by Java for the interface names. It is written in CamelCase, that is,
first letter of each word is capitalized. Also, the name of the interface describes an operation that a
pt

class can perform.


rA

For example,
interface Enumerable
interface Comparable
Fo

Some programmers prefix the letter ‘I’ with the interface name to distinguish interfaces from
classes. For example, interface IEnumerable and interface Icomparable.

Consider the hierarchy of vehicles where IVehicle is the interface that declares the methods which
the implementing classes such as TwoWheeler, FourWheeler, and so on can define.

Explain the figure to create a new interface in NetBeans IDE, right-click the package name and select
New → Java Interface as mentioned in slide 9.

©Aptech Limited
Interfaces and Nested Classes

A dialog box appears where the user must provide a name for the interface and then, click OK. This
will create an interface with the specified name.

Explain the code snippet that defines the interface, IVehicle as mentioned in slides 10 and 11.

Implementing the Interface

To declare a class that implements an interface, you include an implements clause in the class
declaration. Your class can implement more than one interface, so the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.

y
Explain the syntax to implement an interface in the Java class:

nl
class <class-name> implements <Interface1>,…
{

O
// class members
// overridden abstract methods of the interface(s)
}

se
Explain the code snippet defines the class TwoWheeler that implements the IVehicle interface
mentioned in slides 12 to 16. The code snippet defines the class TwoWheeler that implements
rU
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
te
vehicle.
en

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
C

TwoWheeler is created. Next, the object is used to invoke the various methods of the class.
h

In-Class Question:
ec

After you finish explaining purpose of interfaces, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
pt
rA

How the interface names are written in Java?


Answer:
The first letter of each word in the interface name is capitalized.
Fo

Tips:
1. Interfaces are unaffected by changes to specific classes or the class hierarchy as a whole,
because they are declared independently of classes.

2. Java also supports the creation of empty interfaces. Empty interface does not have declared
methods. Empty interfaces can be used as types and to mark classes without requiring any
particular method implementations. For seeing an example of a useful empty interface, see
java.io.Serializable.

©Aptech Limited
Interfaces and Nested Classes

Slides 17 to 25
Let us understand implementing multiple interfaces.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 17 to 25, explain implementing multiple interfaces.

Java does not support multiple inheritance of classes but allows implementing multiple interfaces to
simulate multiple inheritance. To implement multiple interfaces, write the interface names after the
implements keyword separated by a comma.

©Aptech Limited
Interfaces and Nested Classes

For example,
public class Sample implements Interface1, Interaface2{
. . .
}

Explain the code snippet that defines the interface IManufacturer mentioned in slides 17 and 18.
Tell them that the interface IManufacturer declares three abstract methods namely,
addContact(String), callManufacturer(String), and makePayment(float)
that must be defined by the implementing classes.

Then tell them that the class class, TwoWheeler is modified for implementing both the IVehicle and

y
IManufacturer interfaces is displayed in the code snippet mentioned in slides 18 to 25. The class
TwoWheeler now implements all the methods of both the interfaces; IVehicle and

nl
IManufacturer. Otherwise, the class has to be declared as abstract.

O
Slides 26 to 28
Let us understand the concept of abstraction.

se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
Using slides 26 to 28, explain the concept of abstraction.

Abstraction is defined as the process of hiding the unnecessary details and revealing only the

se
essential features of an object to the user. Abstraction is a concept that is used by classes that
consist of attributes and methods that perform operations on these attributes.

rU
Abstraction can also be achieved through composition. For example, a class Vehicle is composed of
an engine, tyres, ignition key, and many other components.
te
To use an abstract class or interface one needs to extend or implement abstract methods with
concrete behavior.
en

Explain the differences between an abstract class and an interface are listed in the table mentioned
in slide 27. Tell them that an abstract class is just a superclass which enables other classes to inherit
C

from it so that each subclass can share a common design.


h
ec

Tips:
Programmers like to use abstract classes to reduce dependency on a range of specific subclass types.
To include abstract method in a class, you also have to declare the class as abstract.
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

Slides 29 and 30
Let us understand the concept of nested class.

y
nl
O
se
rU
te
en
C
h
ec

Using slides 29 and 30, explain the concept of nested class.


pt

Java allows defining a class within another class. Such a class is called a nested class.
rA

Tell them that the 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 the following code snippet mentioned in
Fo

slide 30.

Non-static nested classes have access to other members of the enclosing class, even if they are
declared private. Static nested classes do not have access to other members of the enclosing class.

Tips:
A static nested class interacts with the instance members of its outer class just like any other
top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in
another top-level class for packaging convenience.

©Aptech Limited
Interfaces and Nested Classes

Slide 31
Let us understand benefits of using nested class.

y
nl
O
se
Using slide 31, explain benefits of using nested class.

rU
Explain that nested classes can be used for the following reasons:
 Allows logical grouping of classes

If a class works as a helper class to another class, then it is logical to embed the second class
te
within the first and keep them together.
 Increases encapsulation
en

If class A needs access to private members of class B, then class A can be declared as nested
C

class of class B. As a result, class A can access all the private members of Class B and at the
same time class A will be hidden from the outside world.
 More maintainable code
h
ec

Nesting small classes within top-level classes places the code closer to where it is used. This
makes it easier to maintain the code.
pt

Tips:
A nested class is a member of its enclosing class.
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

Slide 32
Let us understand types of nested classes.

y
nl
O
se
Using slide 32, explain types of nested classes.

• Member classes or
rU
The different types of nested classes are as follows:

non-static nested classes


te
• Local classes
• Anonymous classes
en

• Static Nested classes


C

Slides 33 to 37
Let us understand member classes.
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
Using slides 33 to 37, explain member classes.

Tell them that as with instance methods and variables, an inner class is associated with an instance

se
of its enclosing class and has direct access to that object's methods and fields. Also, because an inner
class is associated with an instance, it cannot define any static members itself.

rU
A member class is a non-static inner class and is declared as a member of an outer or an enclosing
class. It cannot have static modifiers because it is associated with instances. It can access all fields
and methods of the outer class, but the reverse is not true. An outer class cannot access a member
te
of an inner class, even if it is declared as public because members of an inner class are declared
within the scope of inner class. A member class can be declared as public, protected,
en

private, abstract, final, or static.


C

One can access the inner class object within the outer class object using the statement defined in the
code snippet mentioned in slide 34.
h

Explain the code snippet that describes an example of non-static inner class mentioned in slides 34
ec

to 37.

Member class are declared outside a function hence it is a member and not declared static. A public
pt

member class behaves similar to a nested top-level class with the difference being that member
classes have access to the specific instance of the enclosing class.
rA

In-Class Question:
After you finish explaining member classes, you will ask the students an In-Class question. This will
Fo

help you in reviewing their understanding of the topic.

What is the condition to instantiate an inner class?

Answer:
To instantiate an inner class, one must create an instance of the outer class.

©Aptech Limited
Interfaces and Nested Classes

Slides 38 to 43
Let us understand local class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 38 to 43, explain local class.

©Aptech Limited
Interfaces and Nested Classes

The following figure shows the local class:

y
nl
Tell them that this is a special kind of inner class. Local classes are classes that are defined in a block,

O
which is a group of zero or more statements between balanced braces. You typically find local
classes defined in the body of a method.

se
A local class is declared within a method, constructor, or an initializer. In other words, a local class is
declared within a block of code and is visible only within that particular block. It cannot have a

rU
static modifier. It has the ability to refer to local variables in the scope that defines them.
Modifiers, such as public, protected, private, or static cannot be used in local classes.
te
Next, tell them that local classes have the following features:
 Local classes are associated with an instance of containing class, and can access any members,
en

including private members, of the containing class.


 Local classes 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.
C

Explain the code snippet that demonstrates an example of local inner class mentioned in slides 39 to
43.
h
ec

Tips:
1. You can define a local class not only in a method body, but also in a for loop, or an if
clause.
pt

2. Local classes are like local variables, specific to a block of code and their scope is only within
the block of their declaration. The modifiers cannot be used with them as local classes are
rA

not members.
3. You cannot declare static initializers or member interfaces in a local class.
Fo

©Aptech Limited
Interfaces and Nested Classes

Slides 44 to 49
Let us understand anonymous class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 44 to 49, explain anonymous class.

Tell them that anonymous classes enable you to make your code more concise. They enable you to
declare and instantiate a class at the same time. They are like local classes except that they do not
have a name. Use them if you need to use a local class only once.

©Aptech Limited
Interfaces and Nested Classes

An anonymous class does not have a name. It is a type of local class. It also does not allow the use of
extends, implements clauses, and access modifiers, such as public, private,
protected, and static. Since, it does not have a name, it cannot define a constructor. If
constructor declaration is needed, then a local class can be used. An anonymous class cannot define
any static fields, methods, or classes.

Anonymous interfaces are not possible to implement because an interface cannot be implemented
without a name.
Explain the code snippet that describes an example of anonymous class mentioned in slides 46 to 49.
The class Authenticate consists of an anonymous object of type Account. The
displayBalance(String) method is used to retrieve and display the balance of the

y
specified account number.

nl
The main() method is defined in the TestAuthentication class. Within main()

O
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

se
verified and accordingly the object of anonymous class is used to invoke the
displayBalance() method with account number as the argument.

Tips:
rU
1. While local classes are class declarations, anonymous classes are an expression, which
means that you define the class in another expression. The syntax of an anonymous class
te
expression is like the invocation of a constructor, except that there is a class definition
contained in a block of code.
en

2. Anonymous classes have no name. No constructor can be provided for them. Anonymous
inner class is used when an object creation, one time single method invocation to be done
C

and releasing the object at once. They can specify arguments to the constructor of the super
class, but cannot have a constructor.
h
ec

3. Some of the features of anonymous class are as follows:

 An anonymous class has access to the members of its enclosing class.


pt

 An anonymous class cannot access local variables in its enclosing scope that are not
declared as final or effectively final.
rA

 Like a nested class, a declaration of a type (such as a variable) in an anonymous class


shadows any other declarations in the enclosing scope that have the same name.
 Anonymous classes also have the same restrictions as local classes with respect to their
Fo

members.
 You cannot declare static initializers or member interfaces in an anonymous class.
 An anonymous class can have static members provided that they are constant variables.
 Note that you can declare the following in anonymous classes:
o Fields
o Extra methods (even if they do not implement any methods of the supertype)
o Instance initializers
o Local classes

4. However, you cannot declare constructors in an anonymous class.

©Aptech Limited
Interfaces and Nested Classes

Slides 50 to 56
Let us understand static nested class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Interfaces and Nested Classes

y
nl
O
Using slides 50 to 56, explain static nested class.

A static nested class is associated with the outer class just like variables and methods. A static nested

se
class cannot directly refer to instance variables or methods of the outer class just like static methods
but can access only through an object reference.

rU
A static nested class, by behavior, is a top-level class that has been nested in another top-level class
for packaging convenience. Static nested classes are accessed using the fully qualified class name,
that is, OuterClass.StaticNestedClass.
te
Static nested classes can have public, private, protected, package, final, and
en

abstract access specifiers. Private and protected static nested classes are used to
implement the internal features of a class or a class hierarchy. On the other hand, public static
nested classes are often used to group classes together or give access to private static variables and
C

methods to a group of classes.


h

Explain the code snippet demonstrates the use of static nested class mentioned in slides 50
ec

to 53. 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
pt

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
rA

time using the getTime() method of Calendar class.

The main() method is defined in the TestATM class. Within main() method, the number
Fo

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.

The modified BankDetails class using SimpleDateFormat class is displayed in the code snippet
mentioned in slides 54 to 56.

©Aptech Limited
Interfaces and Nested Classes

Tips:
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have
access to other members of the enclosing class, even if they are declared private. A static nested
class interacts with the instance members of its outer class (and other classes) just like any other
top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in
another top-level class for packaging convenience.

In-Class Question:
After you finish explaining Static Nested Class, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.

y
nl
O
How the static nested class can be accessed?

Answer:

se
Static nested classes are accessed using the fully qualified class name.

Slide 57
Let us summarize the session.
rU
te
en
C
h
ec
pt
rA

In slide 57, you will summarize the session. End the session with a brief summary of what has been
taught in the session.
Fo

11.3 Post Class Activities for Faculty


You should familiarize yourself with the topics of the next session which is based on error handling in
Java.

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.

©Aptech Limited
Exceptions

Session 12 – Exceptions

12.1 Pre-Class Activities


Before you commence the session, you should familiarize yourself with the topics of this session in-
depth.

Here, you can discuss the key points with the students that were covered in the previous session.
Prepare a question or two which will help you to relate the current session objectives.

y
nl
12.1.1 Objectives
By the end of this session, the learners will be able to:

O
 Describe exceptions
 Explain types of errors and exceptions

se
 Describe the Exception class
 Describe exception handling




Explain try-catch block
Explain finally block
Explain execution flow of exceptions
rU
Explain guidelines to exception handling
te
12.1.2 Teaching Skills
en

To teach this session, you should be well-versed with concept of exception handling in Java. You
C

should be aware with the types of error that occur during the program execution. You must be
aware with the exception classes hierarchy supported by Java, exception handling mechanism such
as try-catch and finally blocks.
h
ec

You should teach the concepts in the theory class using the images provided. For teaching in the
class, you are expected to use slides and LCD projectors.
pt

Tips:
rA

It is recommended that you test the understanding of the students by asking questions in between
the class.

In-Class Activities:
Fo

Follow the order given here during In-Class activities.

©Aptech Limited
Exceptions

Overview of the Session:


Give the students the overview of the current session in the form of session objectives. Show the
students slide 2 of the presentation.

y
nl
O
se
rU
Tell the students that this session explains them the concept of error handling in Java. The session
explains the type of errors that can occur at runtime. The session also introduce them with the
Exception class and its hierarchy in Java. The session also explain the mechanism to handle
exceptions using try-catch and finally blocks.
te
Tell them that this session focuses on defining, creating, and handling of exceptions in Java
en

programs.

They will also learn the execution flow of exceptions and guidelines to exception handling.
C

12.2 In-Class Explanations


h

Slide 3
ec

Let us understand the causes of getting errors in application.


pt
rA
Fo

Using slide 3, explain the causes of getting errors in application.

©Aptech Limited
Exceptions

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. This results
in raising of expected or unexpected errors in the application. In either case, the user would be
nonplussed or confused with such unexpected behavior of code. Tell them that the errors raised by
the environment during application execution are known as exceptions.

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.

y
Tips:

nl
In programs, exceptions can occur due to any of the following reasons:

O
 Programming errors
These exceptions arise due to errors present in APIs, such as NullPointerException.
The program using these APIs cannot do anything about these errors.

se
 Client code errors
The client code attempts operations, such as reading content from a file without opening it.

rU
This will raise an exception. The exception will provide information about the cause of the
error and is handled by the client code.
 Errors beyond the control of a program
There are certain exceptions that are not expected to be caught by the client code, such as
te
memory error or network connection failure error. These are errors which have been raised
by the run-time environment.
en

Slides 4 to 7
C

Let us understand exceptions.


h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 4 to 7, explain Exceptions.

Tell the students that an exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. When an error occurs within a method, the method creates
an object and hands it off to the runtime system. The object, called an exception object, contains
information about the error, including its type and the state of the program when the error
occurred. The runtime system in Java is JVM which provides a default exception handler for handling

©Aptech Limited
Exceptions

the runtime exceptions raised in an exception. Creating an exception object and handing it to the
runtime system is called throwing an exception.

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
 the JVM has run out of memory

y
The 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

nl
some code block to handle it.
The possible code blocks where the exception can be handled are a series of methods that were

O
invoked in order to reach the method where the error has actually occurred.

se
This list or series of methods is called the call stack. The stack trace shows the sequence of method
invocations that led up to the exception. Explain the figure shows an example of method call stack
mentioned in slides 5 and 6. If while searching the call stack, the runtime environment fails to find an

rU
appropriate exception handler, the runtime environment will consequently terminate the program.

An abnormality in execution detected by the JVM, such as:


te
 Violation of normal semantics of Java while evaluating an expression such as an integer
en

divided by zero.
 Error occurring while linking, loading, or initializing part of the program that will throw an
instance of a subclass of LinkageError.
C

 The JVM is prevented from executing the code due to an internal error or resource limitation
that will throw an instance of a subclass of VirtualMachineError.
h

Then explain the use of exceptions to handle errors that offer some advantages as follows:
ec

 Separate Error-Handling Code from Normal Code


 Propagate Errors Higher Up in the Call Stack
pt

 Group the Similar Error Types


rA

Tips:
The components of the runtime system involved in handling the exception are as follows:
 Call stack:
Fo

When a method throws an exception, the runtime system tries to find an appropriate
method to handle it starting from the method that caused the exception. In this process, the
system invokes a set of methods. The list of invoked methods that is called by the runtime
system to reach to the method where the exception occurred is known as the call stack.

 Exception handler:
The runtime system searches the call stack for a method that contains a piece of code that is
able to handle the exception. This piece of code is called an exception handler.

©Aptech Limited
Exceptions

 Catching an exception:
When an appropriate exception handler matching an exception object is found, then it is
known as catching an exception.

Slides 8 to 12
Let us understand types of errors and exceptions.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
se
rU
te
en
C
h

Using slides 8 to 12, explain types of errors and exceptions.


ec

Java provides the following two types of exceptions:


pt

Checked Exceptions

Checked exceptions are generated in situations that occur during the normal execution of a
rA

program. Some common examples of checked exceptions are: requesting for missing files, invalid
user input, and network failures. These exceptions should be handled to avoid compile-time errors.
If an exception occurs during the execution of a method, the method can handle the exception itself
Fo

or throw the exception back to the calling method to denote that a problem has occurred. The
calling method can again handle the exception itself or throw it to its calling method. This process
can continue until the exception reaches the top of a thread and the thread is terminated. This is
known as the Call-Stack mechanism. The main advantage of this practice is that a developer has the
flexibility of putting the error handling code wherever to choose.

These types of exceptions are derived from the Exception class. The program either handles the
checked exception or moves the exception further up the stack. It is checked during compilation.

©Aptech Limited
Exceptions

Unchecked Exceptions

Unchecked exceptions are generated in situations that are considered non-recoverable for a
program. Common examples of these situations are attempting to access an element beyond the
maximum length of an array. An application is not required to check for these kinds of exceptions.
Runtime exceptions are also examples of unchecked exceptions. They generally arise from logical
bugs. Unchecked exceptions that arise on account of environmental problems or errors are
impossible to recover from and are known as Errors. Exhausting a program’s allocated memory is a
common example of an error.

These exceptions are derived from the RuntimeException class, which in turn is derived from

y
the Exception class. The program need not handle unchecked exception. It is generated during

nl
the execution of the program.

O
The unchecked exceptions are of two types:
Error: These are exceptions that are external to the application. The application usually cannot

se
anticipate or recover from errors. For example, suppose the user specified correct file name for the
file to be opened and the file exists on the system. However, the runtime fails to read the file due to
some hardware or system malfunction. Such a condition of unsuccessful read throws the
java.io.IOError exception.
rU
Runtime Exception: These exceptions are internal to the application and usually the application
cannot anticipate or recover from such exceptions. These exceptions usually indicate programming
te
errors, such as logical errors or improper use of an API. For example, 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
en

application, then the application will throw a NullPointerException. A runtime exception is


an exception that occurs probably and can be avoid by the programmers. As opposed to checked
C

exceptions, runtime exceptions are ignored at the time of compilation.

Exception hierarchy
h
ec

Explain the Throwable class hierarchy shown in the figure mentioned in slide 11. Throwable
class is the base class of all the exception classes. Throwable class has two direct subclasses
namely, Exception, and Error.
pt

Explain the mentioned table that lists some of the checked exceptions mentioned in slide 12. Explain
rA

the mentioned table that lists some of the commonly observed unchecked exceptions mentioned in
slide 12.
Fo

In-Class Question:
After you finish explaining types of errors and exceptions, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.

What type of exceptions are those which are beyond the control of the user or the
programmer and are external to the application?

Answer:
Error.

©Aptech Limited
Exceptions

Tips:
JVM does not force you to handle unchecked exceptions as they are mostly generated at runtime
due to programmatic errors.

Slides 13 to 15
Let us understand Exception class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

Using slides 13 to 15, explain Exception class.

The class Exception and its subclasses indicate conditions that an application might attempt to
handle. The Exception class and all its subclasses except RuntimeException and its
subclasses, are checked exceptions.

The checked exceptions must be declared in a method or constructor’s throws clause if the method
or constructor is liable to throw the exception during its execution and propagate it further in the
call stack.

Explain the code snippet displays the structure of the Exception class mentioned in slide 13.

y
nl
Explain the table that lists the constructors of Exception class mentioned in slide 14.

O
The Exception class provides several methods to get the details of an exception. Explain the table
lists some of the methods of Exception class mentioned in slide 15.

se
In Java, exceptions are object. Java defines several exception classes inside the standard package
java.lang. The most general of these exceptions are subclasses of the standard type

rU
RuntimeException. Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available.
te
Slides 16 and 17
Let us understand handling exceptions in Java.
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
Using slides 16 and 17, explain handling exceptions in java.

se
Any exception that a method is liable to throw is considered to be as much a part of that method’s
programming interface as its parameters and return value. The code that calls a method must be
aware about the exceptions that a method may throw. This helps the caller to decide how to handle
them if and when they occur.
rU
A common situation where a user can throw a RuntimeException is when the user calls a
te
method incorrectly. For example, a method can check beforehand if one of its arguments is
incorrectly specified as null. In that case, the method may throw a NullPointerException,
en

which is an unchecked exception.

Thus, if a client is capable of reasonably recovering from an exception, make it a checked exception.
C

If a client cannot do anything to recover from the exception, make it an unchecked exception.
h

Tips:
An exception is handled by saving the current state of execution and switching the execution to a
ec

specific subroutine is known as exception handler.


pt

In-Class Question:
After you finish explaining handling exceptions in java, you will ask the students an In-Class question.
rA

This will help you in reviewing their understanding of the topic.


Fo

When a runtime exception is thrown?

Answer:
When a user calls a method incorrectly.

©Aptech Limited
Exceptions

Slides 18 to 22
Let us understand try-catch block.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
se
rU
te
en
C
h

Using slides 18 to 22, explain try-catch block.


ec

The first step in creating an exception handler is to identify the code that may throw an exception
and enclose it within the try block.
pt

Explain the syntax for declaring a try block in Java. 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
rA

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
Fo

exception or somewhere higher in the method call stack.

Explain the syntax for declaring a try-catch block in Java. The catch block handles exceptions
derived from Throwable class.

Explain the code snippet demonstrates an example of try with a single catch block mentioned in
slides 20 to 22. 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.

©Aptech Limited
Exceptions

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.

Tips:

y
A try and its catch statement form a unit. To handle a runtime error, simply enclose the code that
you want to monitor inside a try block. Immediately following the try block, includes a catch

nl
clause that specifies the exception type that you wish to catch.

O
The scope of the catch clause is restricted to those statements specified by the immediately
preceding try statement. The statements that are protected by try must be surrounded by curly

se
braces. The goal of catch clauses should be to resolve the exceptional condition and then continue
on as if the error had never happened.

Slides 23 and 24
rU
Let us understand execution flow of exceptions.
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
Using slides 23 and 24, explain execution flow of exceptions.

se
In the code, divide-by-zero exception occurs on execution of the statement num1/num2.If try-catch
block is not provided, any code after this statement is not executed as an exception object is

stack trace, and the program is terminated.rU


automatically created. Since, no try-catch block is present, JVM handles the exception, prints the

Explain the figure shows the execution of the code when try-catch block is not provided mentioned
te
in slide 23.
en

When the try-catch block is provided, the divide-by-zero exception occurring in the code is handled
by the try-catch block and an exception message is displayed. Also, the rest of the code gets
executed normally.
C

Explain the figure that shows the execution of the code when try-catch block is provided mentioned
h

in slide 24.
ec

When the code present in the try block body does not throw any exceptions then, first the body of
try block executes and then the code after catch block. Here, catch blocks never runs because no
pt

exceptions occur. However, when the exception occurs in try block the control is immediately
transferred to the catch block.
rA
Fo

©Aptech Limited
Exceptions

Slides 25 to 29
Let us understand ‘throw’ and ‘throws’ keywords.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
se
rU
te
en
C

Using slides 25 to 29, explain ‘throw’ and ‘throws’ Keywords.


h
ec

Tell the students that if a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a method's signature. Also,
mention that one can throw an exception, either a newly instantiated one or an exception that you
pt

just caught, by using the throw keyword.


rA

The throws keyword indicates that a method might throw the declared exception during its
execution. On the other hand, the throw keyword is used to manually throw an exception after
performing some validation in a program. After the throw keyword is encountered, the flow of
Fo

execution is altered and the subsequent statements are not executed. The exception generated by
the throw statement is then propagated to the previous calling method on the call stack.
The throw statement requires a single argument: a Throwable object that is an instance of the
Throwable class.

Sometimes, a method can throw more than one exception. A comma-separated list of all exceptions
thrown by a method is given with the method declaration. The throws keyword is used by the
method to raise any checked or unchecked exception that it does not handle and enables the caller
of the method to guard themselves against exception.

©Aptech Limited
Exceptions

More than one exception can be listed with the throws clause and are separated by a comma.
Except for Error or RuntimeException and their subclasses, the throws clause is necessary
for all exceptions.

Explain the code snippet demonstrates the modified class Mathematics now using throw and throws
keywords for handling exceptions mentioned in slides 25 to 28.

The control returns back to the caller, that is, the main() method where it is finally handled. The
catch block was executed and the result of getMessage() is displayed to the user. Notice, that
the remaining statement of the divide(int,int) method is not executed in this case.

y
Explain the figure shows the execution of the code when throw and throws clauses are used

nl
mentioned in slide 29.

O
Tips:
Never catch Throwable class. Because Java errors are also subclasses of the Throwable. Errors

se
are irreversible conditions that cannot be handled by JVM alone.

Slides 30 to 33
Let us understand multiple ‘catch’ blocks.
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
se
rU
te
en
C
h

Using slides 30 to 33, explain multiple ‘catch’ blocks.


ec

The user can associate multiple exception handlers with a try block by providing more than one
catch blocks directly after the try block.
pt

Explain the syntax for declaring a try block with multiple catch blocks. In this case, each catch
block is an exception handler that handles a specific type of exception indicated by its argument
rA

exception-type. The runtime system invokes the handler in the call stack whose exception-type
matches the type of the exception thrown.
Fo

Explain the code snippet demonstrates the use of multiple catch blocks mentioned in slides 31 and
32.

Then, explain the figure that shows the execution of the code when multiple catch blocks are used
as mentioned in slide 33.

©Aptech Limited
Exceptions

Slides 34 to 38
Let us understand ‘finally’ block.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
se
rU
te
en
C

Using slides 34 to 38, explain ‘finally’ block.


h
ec

Java provides the finally block to ensure execution of certain statements even when an
exception occurs. The finally block is always executed irrespective of whether or not an
exception occurs in the try block. The runtime system always executes the statements within the
pt

finally block regardless of what happens within the try block. So it's the perfect place to perform
cleanup.
rA

Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code. A finally block appears at the end of the catch
Fo

blocks.

Tips:
The finally block is a key tool for preventing resource leaks. When closing a file or otherwise
recovering resources, place the code in a finally block to ensure that resource is always
recovered. 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.

Explain the syntax for declaring try-catch blocks with a finally block mentioned in slide 35.

©Aptech Limited
Exceptions

Explain the code snippet demonstrates the modified class Calculate using the finally block
mentioned in slide 36 and 37. 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.

Explain the figure shows the execution of code when finally block is used as mentioned in slide 38.

In-Class Question:
After you finish explaining finally block, you will ask the students an In-Class question. This will help
you in reviewing their understanding of the topic.

y
nl
What will happen when thread executing the try or catch block gets interrupted?

O
Answer:
The finally block may not execute even though the application continues to execute.

se
Tips:
For each try block there can be zero or more catch blocks, but only one finally block.

Slides 39 to 41 rU
Let us understand guidelines for handling exceptions.
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
Exceptions

y
nl
O
se
rU
te
en
C
h

Using slides 39 to 41, explain guidelines for handling exceptions.


ec

• 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
pt

along with the throws clause in the method declaration.


• The finally block must be used to write clean up code.
• The Exception subclasses should be used when the caller of the method is expected to
rA

handle the exception.


• The compiler will raise an error message if the caller does not handle the exception.
• Subclasses of RuntimeException class can be used to indicate programming errors such
Fo

as IllegalArgumentException, UnsupportedOperationException, and so


on.
• Avoid using the java.lang.Exception or java.lang.Throwable class to catch
exceptions that cannot be handled. Since, Error and Exception class can catch all
exception of its subclasses including RuntimeException, the runtime behavior of such a
code often becomes vague when global exception classes are caught. For example, one
would not want to catch the OutOfMemoryError. How can one possible handle such an
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.

©Aptech Limited
Exceptions

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

y
the impression that the program failed for unknown reasons.

nl
Slides 42 and 43

O
Let us summarize the session.

se
rU
te
en
C
h
ec
pt
rA
Fo

In slides 42 and 43, you will summarize the session. End the session with a brief summary of what
has been taught in the session.

©Aptech Limited
Exceptions

12.3 Post Class Activities for Faculty


The session ends the Fundamentals of Java course. Ask the students some questions related from all
the topics which will help you to know the learnings taken by the students. You can solve the queries
related to the sessions taught in the course.

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to gain
additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

©Aptech Limited
New Date and Time API

Session 13 – New Date and Time API


13.1 Pre-Class Activities

Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.

13.1.1 Objectives

y
nl
By the end of this session, learners will be able to:

O
➢ Explain new classes of the Date and Time API in Java 8
➢ Explain Enum and Clock types
➢ Describe the role of time-zones in Java 8

se
➢ Explain support for backward compatibility in the new API

13.1.2 Teaching Skills


rU
To teach this session, you should be well versed with the new Date and Time API introduced
te
in Java 8.
en

You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
C

Tips:
It is recommended that you test the understanding of the students by asking questions in
h

between the class.


ec

In-Class Activities
pt

Follow the order given here during In-Class activities.


rA

Overview of the Session


Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.
Fo

© Aptech Limited
New Date and Time API

Slide 2

y
nl
O
se
Show the slide 2 and give the students a brief overview of the current session in the form of
rU
session objectives. Tell the students that they will be introduced to the new Date-Time API in
Java 8. Tell them that the session will cover enum and clock types and describe the role of
time-zones in Java 8. Finally, the session will explain how the new API supports backward
te
compatibility.
en

13.2 In-Class Explanations

Slide 3
C

Let us understand about the new Date-Time API in Java 8.


h
ec
pt
rA
Fo

Explain about the new Date-Time API in Java 8.

© Aptech Limited
New Date and Time API

Introduce the new Date-Time API by saying that earlier versions of Java had drawbacks related
to date and time such as java.util.Date class is not thread-safe and can lead to potential
concurrency issues. The object of the Date class stores both time and date leading to
confusion on the name of the class. Also, it does not store time zone information.

Additional Information:

Refer the following links for more information:

http://www.javaworld.com/article/2078757/java-se/java-se-java-101-the-next-generation-it-

y
s-time-for-a-change.html

nl
http://stackoverflow.com/questions/24631909/differences-between-java-8-date-time-api-
java-time-and-joda-time

O
Slide 4

se
Let us look at the overview of the classes in the new Date-Time API.

rU
te
en
C
h
ec
pt

Explain that:
rA

java.time package contains the classes and types of the new Java 8 Date-Time API. All the
classes are immutable and thread-safe and are based on ISO calendar system.
Fo

Additional Information:

Refer the following link for more information:

https://dzone.com/articles/deeper-look-java-8-date-and

© Aptech Limited
New Date and Time API

Slides 5 to 7

Let us understand the Clock class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
New Date and Time API

Explain about the Clock class in the Date-Time API.

Explain that:
Current date-time depends on the time-zone. For globalized applications, it is important to
create date-time with proper time-zone. java.time package consists of two classes:
Zoned class and Local class. Zoned class of java.time package deals with various
time-zones. You can use the Local class of java.time package without any time-zone
specification.

Explain about the code on slide 6 that shows example of using Clock.

y
nl
Explain that:
Clock.systemUTC() method returns a clock for the current instant converting date and

O
time using the Greenwich/UTC time zone.

se
Clock.systemDefaultZone() method returns the current instant of clock. It
converts date and time using the default time-zone.

rU
Explain about the code on slide 7 that shows how to verify a given date against the Clock
object.
te
Explain that:
The code is based on dependency injection framework for Clock object.
en

LocalDate class has two methods: isBefore() and isAfter() to compare dates. In
C

the given code, isBefore() method returns true if the given date comes before the date
on which the method is called.
h

To check whether today's date is either the start or end date, you can write
ec

if(!todayDate.isBefore(startDate)&&!todayDate.isAfter(endDate)
)
pt

Additional Information:
rA

Refer the following links for more information:


Fo

http://farenda.com/java/java-time-clock-fixed/
http://stackoverflow.com/questions/308683/how-can-i-get-the-current-date-and-time-in-
utc-or-gmt-in-java

© Aptech Limited
New Date and Time API

Slides 8 and 9

Let us learn about the Duration class.

y
nl
O
se
rU
te
en
C
h
ec
pt

Explain using slides 8 and 9 that:


rA

A Duration object represents the time interval between two instant objects. A
Duration object is immutable therefore, once it is created, its values cannot be changed.
Fo

Following code shows how to find the duration between two instants:
Instant one = Instant.now();

Instant two = Instant.now();

Duration dur = Duration.between(one, two)

Duration object consists of two parts, nanoseconds part and seconds part. You can access
nanoseconds and seconds part of duration using the getNano() and getseconds()
method respectively.

© Aptech Limited
New Date and Time API

Explain about the code that shows the usage of plusDays() and minusDays()
methods.

Explain that:

The syntax for plusDays() method is:

public Duration plusDays(long daysToAdd)

The code will return 3 days from the current date and 3 days before the current date. To get

y
10 days from current date, you can state:

nl
LocalDate today = LocalDate.now();

O
System.out.println("10 days after today will be
"+today.plusDays(10));

se
Give some more examples to illustrate the methods.

Slide 10

Let us look at the Instant class.


rU
te
en
C
h
ec
pt
rA
Fo

Using this slide, explain about Instant class and how to generate an instant. Explain the
code that shows an Instant object representing the exact moment of now, using
Instant.now() method. Then, explain the code that displays the use of Instant in
nanoseconds and milliseconds.

Explain that:

Instant class denotes a specific moment in time. A value of the Instant class calculates
time starting from the first second of January 1, 1970 in the format 1970-01-01T00:00:00Z. If
you run the code on 14th October, 2016 you will get the output as 2016-10-14T10:11:26.838Z.

© Aptech Limited
New Date and Time API

Slides 11 to 15

Let us look at the LocalDate class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
New Date and Time API

y
nl
O
se
rU
te
en
C
h
ec

Using slide 11, explain about LocalDate class and the method to create a LocalDate and
obtain a LocalDate.
pt

Explain that:
rA

LocalDate class represents date in the format yyyy-mm-dd. Its now() method helps to get
the current date. For example, use the given code to get the current date:
Fo

LocalDate curr = LocalDate.now();


System.out.println("Today is"+ curr);
}
}

List the methods as given on slide 12 that are used to access date information of a
LocalDate object and explain about LocalDate.

© Aptech Limited
New Date and Time API

Explain that:
LocalDate class is used to represent only date without the time. This class uses the clock
of the default time-zone to show the date. You can obtain a particular date using the static
method, now(). You can also create a date from another date using the LocalDate.of()
method.

Explain the code on slide 13 that illustrates the date information of a LocalDate.

Explain that:
When you use int in the LocalDate object, you must remember that month, week, and

y
so on are zero based. That is, the month January is 0 and December is 11. Similarly, Sunday is

nl
0 and Saturday is 6.

O
Explain the different methods available in LocalDate class for date calculations given on
slide 14.

se
Explain that:
You can obtain the date information using the different methods available in LocalDate
rU
class. plus() methods adds days, weeks, months, and years and minus() methods
subtracts days, weeks, months, and years.
te
Explain the code on slide 15 that shows how a LocalDate calculation method works.
en

Explain that:
In the code, a new instance of LocalDate is created using of() method. Then, a new
C

LocalDate instance shows a date four years later from the specified date. Finally, a new
LocalDate instance is created to denote the date four years before the specified date.
h
ec
pt
rA
Fo

© Aptech Limited
New Date and Time API

Slides 16 and 17

Let us understand the LocalDateTime class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slide 16, explain about LocalDateTime class.

Explain that:
Fo

LocalDateTime class is a combination of LocalDate and LocalTime classes of


Date-Time API.

Code shows creating a LocalDateTime object based on a specific year, month, and day.
Various parameters passed to of() are year, month, day (of month), hours, minutes, seconds,
and nanoseconds respectively.

Using slide 17, explain the code that shows how LocalDateTime calculation methods
work.

© Aptech Limited
New Date and Time API

Explain that:
In the code, a new instance of LocalDateTime is created signifying the current moment.
Then, the code creates a LocalDateTime object that denotes a date and time four years
later. Finally, the code builds a LocalDateTime object that denotes a date and time four
years prior.

In the code, a new instance of LocalDate is created using of() method. Then, a new
LocalDate instance shows a date four years later from the specified date. Finally, a new
LocalDate instance is created to denote the date four years before the specified date.

y
Slides 18 and 19

nl
Let us explore the LocalTime class.

O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slide 18, explain about the LocalTime class and the method to create a
LocalTime class. Explain the code that shows the now() method and then explain the
code that shows how to use of() method.

© Aptech Limited
New Date and Time API

Explain that:
LocalTime class in Date-Time API signifies exact time of day without any time-zone data.
The foremost approach to generate LocalTime instance is to create a LocalTime
instance that denotes the exact time of now. Another approach to produce a LocalTime
object is to create it from specific hours, minutes, seconds, and nanoseconds.

Additional Information:

Refer the following link for more information:

y
http://tutorials.jenkov.com/java-date-time/localtime.html

nl
Using slide 19, explain about the LocalTime calculations and explain the code that

O
explains LocalTime calculations.

se
Explain that:
LocalTime class consists of a set of methods that can perform local time calculations. For
example, plusMinutes() method adds minutes and minusMinutes() subtracts
rU
minutes from a given value in a calculation. LocalDateTime object consists of the plus or
minus methods.
te
Slide 20
en

Let us understand the MonthDay class.


C
h
ec
pt
rA
Fo

Explain about the MonthDay class and then explain the code that depicts how MonthDay
class can be used for checking the recurring date-time events.

Explain that:
MonthDay class represents month as well as day-of-month. You can use this class to derive
a birthday or anniversary day from a month and day object.

© Aptech Limited
New Date and Time API

Additional Information:

Refer the following link for more information:

http://docs.oracle.com/javase/8/docs/api/java/time/MonthDay.html

Slide 21

Let us look at the OffsetDateTime class.

y
nl
O
se
rU
te
en

Using this slide, explain about the OffsetDateTime class.


C

Explain that:
OffsetDateTime is an immutable illustration of date and time with an offset. This class
h

stores all date and time fields, to an accuracy of nanoseconds, as well as the offset from
ec

UTC/Greenwich.
pt

Explain the code that displays an example stating California is GMT or UTC–07:00 and to get
a similar time-zone, static method ZoneOffset.of() can be used.
rA

Explain that:
After fetching the offset value, OffSetDateTime can be shaped by passing a
Fo

LocalDateTime and an offset to it.

Additional Information:

Refer to the link https://blog.tompawlak.org/java-8-conversion-new-date-time-api to explain


how to use toInstant() method with ZoneOffset information.

© Aptech Limited
New Date and Time API

Slide 22

Let us look at the OffsetTime class.

y
nl
O
se
rU
Using this slide, explain about the OffsetTime class and the code that shows the complete
program to fetch the seconds using the OffsetTime class.
te
Explain that:
en

OffsetTime class is an immutable Date-Time object. This class denotes a time with an
offset from UTC/Greenwich time. Generally, the output is shown in the format hour-minute-
C

second-offset. The output of the code will be Minutes: 49.

Additional Information:
h
ec

Refer the following link to view more code samples of OffsetTime class:
pt

http://www.programcreek.com/java-api-examples/index.php?api=java.time.OffsetTime
rA
Fo

© Aptech Limited
New Date and Time API

Slides 23 to 25

Let us learn about the Period class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
New Date and Time API

Using slide 23, explain about the Period class.

Explain that:
Period class allows you to show an amount of time in the format days, months, and years.
The difference between Duration and Period is duration adds an accurate number of
seconds. We know that duration of one day is always exactly 24 hours. However, a Period
adds a conceptual day. Period tries to balance with the local time.

Using slide 24, explain the code that displays an example to calculate the span of time from
today until a birthday, assuming the birthday is on May 22 nd. The code shows the usage of

y
Period class. Note that the line java.time.termporal.ChronoUnit shows that the

nl
code uses ChronoUnit enumeration.

O
Using slide 25, explain the output of the code. Note that the number of days will differ based
on the current date that is, the calculated days will be current date minus May 22, 1983.

se
Slide 26
Let us learn about the Year class.
rU
te
en
C
h
ec
pt
rA

Explain the Year class and the code that displays the calculations using Year class.
Fo

A Year object is an immutable Date-Time object. It is used to denote a year. This class
does not store or represent a specific month, day, time, or time-zone.

The Year.isLeap() method checks whether the specified year is leap or not. It returns
true if the year represented is a leap year.

© Aptech Limited
New Date and Time API

Additional Information:

Refer the following links to get more information on Year class:

https://docs.oracle.com/javase/8/docs/api/java/time/Year.html
http://www.concretepage.com/java/jdk-8/java-8-time-api-example-period-year-yearmonth-
zoneddatetime

Slides 27 and 28

y
Let us explore the YearMonth class.

nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Explain the YearMonth class with the help of slides 27 and 28.

YearMonth class combines and displays year and month. You can use this class to calculate
the number of days in the current month. lengthOfMonth() method returns the number

© Aptech Limited
New Date and Time API

of days in the current YearMonth object. YearMonth class can also be used to check the
number of days in the month of February that is, 28 or 29 days.

Using slide 28, explain the code that shows the YearMonth calculations.

Explain that:
The method YearMonth.now() displays the current year and month.
getMonthValue() method displays only the month suppressing the year and
getYear() method displays only the year suppressing the month. isLeapYear()
method returns true if the given year is a leap year.

y
nl
Additional Information:

O
Refer the following link for more information:

se
http://www.concretepage.com/java/jdk-8/java-8-time-api-example-period-year-yearmonth-
zoneddatetime

Slides 29 and 30
Let us see the ZonedDateTime class.
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
New Date and Time API

y
nl
O
se
Using slide 29, explain about the ZonedDateTime class.

Explain that:
rU
ZonedDateTime class represents date and time with zone information. This class stores the
date and time fields to the precision of nanosecond values along with time-zone information.
te
Explain the code given on slide 30 that depicts the usage of methods to get year, month, day,
hour, minute, seconds, and zone offset.
en

Explain that:
C

ZonedDateTime.now() method displays the current date and time with zone
information. Parse() method converts the string to Date. ZonedDateTime class manages
the conversion from the local time-line to the instant time-line. The difference between the
h

two time-lines is the offset from UTC/Greenwich, represented by a ZoneOffset.


ec

Additional Information:
pt

Refer the following link for more information:


rA

http://www.concretepage.com/java/jdk-8/java-8-time-api-example-period-year-yearmonth-
zoneddatetime
Fo

© Aptech Limited
New Date and Time API

Slides 31 and 32

Let us understand ZoneId and ZoneOffset.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Explain the ZoneID class using slides 31 and 32.

Explain that:
Fo

ZoneId contains the zone rules that defines the time zone of a location. You can use the class
when you have to obtain the date and time of specific time zone. ZoneOffset represents
the period of time that denotes the difference between Greenwich time and a time-zone.

Using slide 32, explain the ZoneOffset class and explain the code that shows the usage of
the ZoneOffset class.

Explain that:
A time-zone offset is the quantity of time that a time-zone differs from Greenwich/UTC. The
time zone ID is unique. An offset ID begins with UTC, GMT, + or -, is a single letter.

© Aptech Limited
New Date and Time API

For example, 'Z', '+03:00', '-06:00', 'UTC+04' and 'GMT-2' are all valid offset IDs. However, +ABC
and ‘D’ are invalid ID’s even if they meet the criteria.

Additional Information:

You can use the following link to compare time of different zones:
http://www.java2s.com/Tutorials/Java/java.time/ZoneId/index.htm

Slide 33

y
Let us see the benefits of using enums.

nl
O
se
rU
te
en
C

Using this slide, explain about Enums in Java. An enumeration or enum helps to denote the
h

fixed number of well-known values in Java. It can contain constants, methods. For example,
ec

to define days of week, one can use:

public enum week{


pt

Sunday,
Monday,
rA

Tuesday,
Wednesday,
Thursday,
Fo

Friday,
Saturday}

Additional Information:

Refer the following links for more information on Enums:

https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html
http://tutorials.jenkov.com/java/enums.html

© Aptech Limited
New Date and Time API

Slides 34 and 35

Let us understand ChronoUnit.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Explain the code that shows the usage of ChronoUnit enumeration.

Explain that:
Fo

The Date-Time API in Java SE 8 supports several new and useful enumerations such as
ChronoUnit enumeration to represent the day, month. These units are especially helpful
while designing multiple calendar systems.

Continue explaining the code on slide 35 that shows the usage of ChronoUnit enumeration.

Explain that:
LocalDate.now() method helps to obtain the current date. today.plus(2,
ChronoUnit.WEEKS) method gives the date 2 weeks from the current date.
today.plus(2, ChronoUnit.MONTHS) method calculates the date 2 months from
current date, today.plus(2, ChronoUnit.YEARS) method calculates 2 years from

© Aptech Limited
New Date and Time API

current date and finally, today.plus(2, ChronoUnit.DECADES) method calculates


2 decades from current date.

Additional Information:

Refer the following links to get more information:


https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html
https://www.tutorialspoint.com/java8/java8_chronounits.htm

Slides 36 to 38

y
nl
Let us explore temporal adjusters.

O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
New Date and Time API

y
nl
O
se
Explain about TemporalAdjuster class using slides 36 to 38.

Explain that:
rU
You can use TemporalAdjuster to modify a temporal object, especially date and time.
You must input the temporal value and it outputs the adjusted value.
te
Using slides 37 and 38, explain the code that shows how to find the first day of a month using
a specified date.
en

Explain that:
C

To invoke temporal adjuster, use ‘with’ method of the temporal object to be adjusted.

LocalDate.now() method returns the current date.


h
ec

sampledateA.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY))
method returns the next Wednesday from current date.
pt

firstInYear.with(TemporalAdjusters.
nextOrSame(DayOfWeek.SUNDAY)).with(TemporalAdjusters.next(DayO
rA

fWeek.SUNDAY)) method returns the second Sunday of the month. Note the usage of with
method with the temporal object.
Fo

Additional Information:

Refer the following links for more information:


https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjusters.html
http://javapapers.com/java/java-8-date-and-time-temporal-adjuster/

© Aptech Limited
New Date and Time API

Slides 39 to 41

Let us understand backward compatibility support in Java 8 for legacy classes.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Explain about backward compatibility with older versions using slides 39 to 41.

© Aptech Limited
New Date and Time API

Explain that:
Java 8 helps to convert the date and time class represented by java.util.Date class to
java.time.LocalDate or LocalDateTime or LocalTime using the
toInstant() method. This method converts a date object to an instant.

Using slides 40 and 41, explain the code to get a LocalDateTime or ZonedDateTime
object.

Explain that:

y
The code uses ofInstant(Instant, ZoneId) method to get a LocalDateTime or

nl
ZonedDateTime object. The new Date() method is used to get the current date. The
method sampleCurDay.toInstant() is used to get the instant of current date.

O
LocalDateTime.ofInstant(samplenow, samplecurZone) method is used to

se
display the current local date and the method
ZonedDateTime.ofInstant(samplenow, samplecurZone) is used to display the
desired current zoned date.

Slide 42
rU
te
Let us examine how to parse and format dates.
en
C
h
ec
pt
rA
Fo

Explain about parsing and formatting dates.

Explain that:
java.text.SimpleDateFormat class helps to parse dates from strings (text to date)
and format dates to string (date to text).

Explain the code that shows how the SimpleDateFormat class works on
java.util.Date instances.

© Aptech Limited
New Date and Time API

Explain that:
yyyy/MM/dd shows the date in the form of year/month/day. The year will be shown in full
form. For example, 2016 of the year will be used. In the code, the dateString instance
passed to the format() method is a java.util.Date instance.

When you execute the code, the samplDate variable points to a Date instance that denotes
March 25th, 2011.

Additional Information:

y
Refer the following links for more information:

nl
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
https://dzone.com/articles/datetime-formattingparsing

O
Slides 43 and 44

se
Let us explore TimeZone.

rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
New Date and Time API

Explain about TimeZone class and the codes to display a simple example of how to get the
time-zone from a Calendar, how to set time-zone and the two ways to obtain a TimeZone
instance.

Explain that:
TimeZone class in Java represents the time-zones and is used in time-zone bound
calculations. You can get the time-zone using the getTimeZone method along with the time
zone ID.

Using slide 44, explain the code that shows a sample of time-zone.

y
nl
Explain that:

O
The TimeZone.getDefault() method displays the default time-zone of the system on
which the program is executed. TimeZone.getTimeZone(“Europe/Paris”) method

se
returns the Time-Zone instance corresponding to the given TimeZoneID, in this example
Europe/Paris.

Additional Information: rU
Refer the following link for more information:
te
http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html
en

In-Class Question:
C

After you finish explaining slide 44, you will ask the students some In-Class questions. This
will help you in reviewing their understanding of the topic.
h
ec

What would be the output for this program?


pt

import java.time.LocalDate;
rA

import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.Clock;
Fo

public class HelloWorld {


public static void main(String[] args)
{
LocalDate dateFromString = LocalDate.parse("2014-
05-05");
System.out.println("LocalDate from a String: " +
dateFromString);

LocalDate date1 =
LocalDate.now(Clock.systemDefaultZone());

© Aptech Limited
New Date and Time API

System.out.println("LocalDate from default time-


zone clock: " + date1);
}
}

Answer:
LocalDate from a String: 2014-05-05
LocalDate from default time-zone clock: 2016-11-11

y
nl
What would be the output for the following program?

O
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;

se
import java.time.Clock;

public class HelloWorld {


rU
public static void main(String[] args)
{
LocalDate localDate = LocalDate.now();
te
System.out.println(localDate.toString());
en

System.out.println(localDate.getDayOfWeek().toString());
System.out.println(localDate.getDayOfMonth());
C

System.out.println(localDate.getDayOfYear());
System.out.println(localDate.isLeapYear());
h

System.out.println(localDate.plusDays(12).toString());
ec

}
}
pt

Answer:
Suppose today's date is: 11-11-2016, the output would be:
rA

2016-11-11
FRIDAY
Fo

11
316
true
2016-11-23

© Aptech Limited
New Date and Time API

What would be the output for the following program?

import java.time.Duration;
import java.time.LocalTime;

public class HelloWorld {


public static void main(String[] args) {
Duration duration =

y
Duration.between(LocalTime.MIDNIGHT,LocalTime.NOON);

nl
duration = duration.plusNanos(1000);
System.out.println(duration.getNano());

O
}
}

se
Answer: 1000

rU
te
What would be the output for the following program?
en

import java.time.LocalDate;

public class HelloWorld {


C

public static void main(String[] args) {


LocalDate a = LocalDate.of(2014, 6, 30);
h

LocalDate b = a.plusMonths(8);
System.out.println(b);
ec

}
}
pt

Answer:
rA

2015-02-28
Fo

© Aptech Limited
New Date and Time API

Slide 45

Let us summarize the session.

SUMMARY
❖ The new Date-Time API introduced in Java 8 is a solution for many
unaddressed drawbacks of the previous API.
❖ Date-Time API contains many classes to reduce coding complexity and
provides various additional features to work on date and time.
❖ Enum in Java denotes fixed number of well-known values.

y
❖ TemporalAdjuster is a functional interface and a key tool for altering a
temporal object.

nl
❖ Java TimeZone class is a class that denotes time-zones and is helpful when
doing calendar arithmetic across time-zones.

O
❖ A time-zone offset is the quantity of time that a time-zone differs from
Greenwich/UTC.

se
© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 45

rU
Use this slide to summarize the session. You will end the session, with a brief summary of
what has been taught in the session. Tell the students pointers of the session. This will be a
te
revision of the current session.
en

Explain that:
The new Date-Time API introduced in Java 8 is a solution for many unaddressed drawbacks of
C

the previous API. Date-Time API contains many classes to reduce coding complexity and
provides various additional features to work on date and time. Enum in Java denotes fixed
number of well-known values. TemporalAdjuster is a functional interface and a key tool
h

for altering a temporal object. Java Time-Zone class is a class that denotes time-zones and
ec

is helpful when doing calendar arithmetic across time-zones. A time-zone offset is the
quantity of time that a time-zone differs from Greenwich/UTC.
pt

13.3 Post Class Activities for Faculty


rA

You should familiarize yourself with the topics of the next session.
Fo

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to
gain additional information related to the topics covered in the next session. You can also
connect to online tutors on the Online Varsity site to ask queries related to the sessions.

© Aptech Limited
Annotations and Base64 Encoding

Session 14 - Annotations and Base64 Encoding


14.1 Pre-Class Activities

Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.

14.1.1 Objectives

y
By the end of this session, learners will be able to:

nl
➢ Explain declaring an annotation type in Java

O
➢ Describe predefined annotation types
➢ Explain Type annotations

se
➢ Explain Repeating annotations
➢ Describe Base64 encoding

14.1.2 Teaching Skills rU


To teach this session, you should be well versed with the concepts of Java Programming.
te
You should be familiar with the concept of annotations, various types of annotations, and
how to create and use them.
en

You should teach the concepts in the theory class using the images provided. For teaching in
C

the class, you are expected to use slides and LCD projectors.

Tips:
h

It is recommended that you test the understanding of the students by asking questions in
ec

between the class.


pt

In-Class Activities
rA

Follow the order given here during In-Class activities.

Overview of the Session


Fo

Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.

© Aptech Limited
Annotations and Base64 Encoding

Slide 2

y
nl
O
se
Show the slide and give the students a brief overview of the current session in the form of

rU
session objectives. Tell the students that they will get to know how to declare an annotation
type in Java. Describe about predefined annotation types. Explain type annotations and
repeating annotations. Finally, describe Base 64 encoding.
te
14.2 In-Class Explanations
en

Slides 3 to 5
Let us understand annotations.
C
h
ec
pt
rA
Fo

© Aptech Limited
Annotations and Base64 Encoding

y
nl
O
se
rU
te
en
C
h
ec

Using slide 3, give an introduction about annotations.

Explain that annotations are comments, notes, remarks, or explanations. They are used to link
pt

metadata to the elements. Annotations are declared using @ symbol followed by the
rA

interface keyword and annotation name. They can be declared at class level, field level,
and method level.
Fo

Using slide 4, state the elements that are annotated in Java.

Elements that are annotated in Java are namely, tables, methods, variables, classes, and
parameters. Java 5 allowed annotation processing during compilation of code as well as
execution. When Java source code is compiled, annotations are processed by compiler
plug-ins called annotation processor.

Using slide 5, state the benefits of Pluggable Annotation Processing API in Java 8.

© Aptech Limited
Annotations and Base64 Encoding

Java SE 6 consists of Pluggable Annotation Processing API that helps application developers to
plug a Customized Annotation Processor into the code to operate on the set of annotations
existing in a source file.

Additional Information:

Refer the following link for more information:

http://howtodoinjava.com/core-java/annotations/complete-java-annotations-tutorial/

y
Slide 6

nl
Let us explore the uses of annotations.

O
se
rU
te
en
C
h

Explain the uses of annotations.


ec

Say that some of the uses of annotations are:


pt

 Information for the compiler: Helps compiler to produce notifications or errors based on
rA

different rules. For example, the @FunctionalInterface annotation helps the


compiler to validate the annotated class and check whether it is a functional annotation
or not. When a type is annotated as @FunctionalInterface, compilers generate an
Fo

error message if:


o The type is an interface type and not an annotation type, enum, or class.
o The annotated type satisfies the requirements of a functional interface.
 Documentation: Decides the quality of the code or generate automatic reports.
 Code generation: Creates code or XML files automatically using metadata information
available in the code.
 Runtime processing: Annotations can be processed at runtime or compile time or both.
Annotation is available at runtime if it has the runtime RetentionPolicy. Helps
applications in purposes such as unit testing, dependency injection, validation, logging,
data access, and so on.

© Aptech Limited
Annotations and Base64 Encoding

Additional Information:

Refer the following link for more information:

http://beginnersbook.com/2014/09/java-annotations/

Slide 7

Let us see how to declare annotations.


Declaring Annotations

y
nl
To declare an annotation, prefix with @ as follows:
Syntax:

O
@<name>

@<name>

se
Example:
Here, @(at)symbol signals to the compiler that this is an annotation

@Item
rU
Here, the annotation name is Item
te
© Aptech Ltd. Fundamental Programming in Java -Session 14 / Slide 7
en

Explain the procedure to declare an annotation.


C

Explain that to write custom annotation, you must prefix the annotation name with @ symbol.
For example, @Author where author is the name of the annotation.
h
ec

Additional Information:
pt

Refer the following link for more information:


rA

https://www.mkyong.com/java/java-custom-annotations-example/
Fo

© Aptech Limited
Annotations and Base64 Encoding

Slides 8 to 11
Let us explore predefined annotations.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Annotations and Base64 Encoding

y
nl
O
se
rU
te
en
C
h
ec

Using slide 8, explain about predefined annotations.

Predefined annotations are the built-in annotations available in the compiler that can be
pt

readily used. Following are the three built-in annotations:


•@deprecated
rA

•@override
•@suppresswarnings
Fo

Using slide 9, explain each of the predefined annotation.

@deprecated annotation: Indicates parts of the code that are not required and hence need
not be executed. When a code consisting deprecated class, method, or field is compiled, the
compiler generates a warning message.

@override: Indicates that the annotated method is an overridden method.


@suppresswarnings: Suppresses the compiler warning. For example, the compiler
generates a warning message when a method calls a deprecated method.

© Aptech Limited
Annotations and Base64 Encoding

Using slide 10, explain the code snippets, describing each of the predefined annotation.

Explain that:
@deprecated annotation: In the code, using @deprecated annotation before the class
declaration turns the entire class as deprecated. When you try to generate an instance of the
class, you will get a compiler warning.

@override: Code Snippet shows class ClassOne has a method named show() and its
subclass also has a method show() whereas, the child class is not overriding the parent class
method, as it has a different parameter type String and int respectively.

y
nl
@suppresswarnings: Code Snippet shows that @SuppressWarnings annotation
type can be used with one or more warnings in the form of arguments. These warnings are

O
predefined by the compiler.

se
Explain using slide 11 the advantages of using @override annotation.

Explain that:
@override annotation:
rU
 Helps to identify any unintentional error such as wrong method, parameter type in the
code. Once the error is identified, the annotation can be used to instruct the compiler
te
to override the erroneous method.
 Makes the code easy to read and understand. You can understand the behavior of the
en

code and the impact of renaming methods and parameter type in the code.
C

Additional Information:

Refer the following links for more information:


h
ec

http://tutorials.jenkov.com/java/annotations.html
http://stackoverflow.com/questions/212614/should-we-override-an-interfaces-method-
pt

implementation
rA
Fo

© Aptech Limited
Annotations and Base64 Encoding

Slides 12 and 13
Let us see how to create custom annotations.

Creating Custom Annotations 1/2


Custom Annotations created in Java are defined in their own files.

@interface SampleAnnotate{
String samplValue();
String name();
int age();
String[] addNames();

y
}

nl
O
se
© Aptech Ltd. Fundamental Programming in Java -Session 14 / Slide 12

Creating Custom Annotations 2/2


Custom Annotations uses following syntax: rU
te
@Retention @Target @Inherited @Documented
en

import import
@Retention(RetentionPolic @Target({ElementType.METH
java.lang.annotation.Inhe java.lang.annotation.Docu
y.RUNTIME) OD})
rited; mented;
@interface SampleAnnotate public @interface
@Inherited @Documented
{ SampleAnnotate{...
public @interface @interface TestAnnotate {
... }
SampleAnnotate { . . .
C

} }
} @SampleAnnotate
class Person { ... } @TestAnnotate
public class Employee public class Employee {
extends Person { ... } ... }
h
ec

© Aptech Ltd. Fundamental Programming in Java -Session 14 / Slide 13


pt

Using slide 12, explain the code to create custom annotations.


rA

Explain that:
To create custom annotation, it is mandatory to use @interface keyword. The code defines
an annotation called SampleAnnotate, having four elements: samplValue, name, age, and
Fo

addNames.

Explain the syntax shown on slide 13.

Each element in an annotation is defined similar to a method in an interface. It consists of a


data type and a name.

@retention annotation specifies the way the annotation, SampleAnnotate must be


stored. RetentionPolicy determines the stopping point of annotation.

© Aptech Limited
Annotations and Base64 Encoding

@target annotation restricts the usage of the custom annotation on specific Java elements
such as interface, class, or methods. @Target restricts the usage of SampleAnnotate on
Methods.

@inherited annotation when applied to indicates that all the subclasses must inherit the
annotated class. Sub class Employee inherits from the class Person.
@documented annotation indicates the JavaDoc tool that custom annotations,
@TestAnnotate have to be visible in the JavaDoc for the Employee class using custom
annotation.

y
Slide 14

nl
Let us explore type annotations.

O
se
rU
te
en
C
h

Using slide 14, explain about type annotations also explain the Code Snippet that shows usage
ec

of type annotations.

Explain that:
pt

Java 8 does not consists built-in type checking annotation. Type annotations helps in type
checking in a program. You can apply annotations to types in instances such as creating class
rA

instance, implementing methods, type casting.

Additional Information:
Fo

Refer the following link for more information:

https://dzone.com/articles/java-8-type-annotations

© Aptech Limited
Annotations and Base64 Encoding

Slides 15 to 18
Let us understand repeating annotations.

Repeating Annotations 1/4

Helps to apply the same annotations at multiple times for the same declaration.

@ScoreSchedule(dayOfMonth="last")
@ScoreSchedule(dayOfWeek="Wed", hour="21")
public void scorePapers() { ... }

y
nl
Here, the annotation @ScoreSchedule has been applied twice, thus, it is a repeating
annotation. Repeating annotations can be applied not only to methods also to any item
that can be annotated.

O
se
© Aptech Ltd. Fundamental Programming in Java -Session 14 / Slide 15

rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Annotations and Base64 Encoding

y
nl
O
se
Using slide 15, explain about repeating annotations and also explain the code snippet that
shows usage of repeating annotations.

Explain that:
rU
Repeating annotations help to repeat the same annotations more than once in a program.
They can be applied not only to methods but also to any item that can be annotated.
te
public @interface Coaching {
en

String subject();
}
C

@ Coaching(subject= “Maths")
@ Coaching(subject=“Science")
h

@ Coaching(subject=“English")
public class school {
ec

}
pt

Here, @Coaching is the repeating annotation.


rA

Using slide 16, explain about the two necessary declarations in the code to use repeating
annotations using the Code Snippet.
Fo

Explain that:
To define repeating annotations:
• Annotate repeating annotation using @Repeatable for a annotation to be repeatable.
• Create a container annotation to store repeating annotations.

In the Code Snippet, annotating repeating annotation ScoreSchedules using


@Repeatable.

Using slide 17, explain the second necessary declarations in the code to use repeating
annotations from the Code Snippet.

© Aptech Limited
Annotations and Base64 Encoding

The second necessary declaration is to declare containing annotation type. The containing
annotation type contains an array type element value. The array type value must be the
repeatable annotation type. In the Code Snippet that shows the containing annotation type
declaration, ScoreSchedules is the class for @interface annotation.

Using slide 18, explain the complete Code Snippet that shows using the second necessary
declarations in the code to use repeating annotations.

In the Code Snippet @Repeatable(ScoreSchedules.class),


@interface ScoreSchedule enables to run a method scorePapers() at a given

y
time on the last day of a month and on every Wednesday at 09:00 p.m.

nl
Slides 19 to 22

O
Let us examine processing of annotations through reflection.

se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Annotations and Base64 Encoding

y
nl
O
se
rU
te
en
C
h
ec

Using slide 19, explain about processing annotations using Reflection API.

Explain that:
pt

In Java, Reflection API helps to access annotations on any type such as class, or interface, or
rA

methods. The API contains several methods to retrieve annotations.


For example, AnnotateElement.getAnnotationByType(Class <T>) remains
unchanged and returns only a single annotation when one annotation of the requisite type is
Fo

available. If more than one annotation is available, then it can be acquired by using the
container annotation.

Using slide 20, explain the Code Snippet that displays the usage of Reflection annotation.

Explain that:
Code Snippets shows the usage of Reflection annotation. In the code, SampleGenCl class
is reflected through sampMeth() method.

Using slide 21, discuss the output of the Code Snippet that displays the usage of Reflection
annotation.

© Aptech Limited
Annotations and Base64 Encoding

Using slide 22, explain @Functional interface using the Code Snippet that shows usage of
this annotation.

Explain that:

A functional interface has one abstract method (not default). When an annotation having
functional interface is compiled, the compiler will operate the annotated element as a
functional interface and generate an error if the element does not comply with the
requirements.

y
Additional Information:

nl
Refer the following links for more information:

O
http://tutorials.jenkov.com/java-reflection/annotations.html

se
https://www.tutorialspoint.com/java8/java8_functional_interfaces.htm

Slide 23
rU
Let us look at well-known Java libraries that use annotations.
te
en
C
h
ec
pt
rA

Using slide 23, explain about the well-known libraries that are using annotations.
Fo

Explain that:

Libraries use annotations for analysing code quality analysis, unit testing, XML parsing,
dependency injection. Some of these libraries include:

 Java Architecture for XML Binding (JAXB) which helps easier access to XML documents
from applications written in the Java programming language
 JUnit, which is a unit testing framework for Java programming language
 FindBugs, which is an open source static code analyzer which detects possible bugs in
Java programs

© Aptech Limited
Annotations and Base64 Encoding

Additional Information:

Refer the following link for more information:

https://www.javacodegeeks.com/2014/11/java-annotations-
tutorial.html#Known%20libraries%20using%20annotations

Slides 24 to 28
Let us explore Base64 encoding.

y
Base64 (java.util.Base64) Encoding 1/5

nl
Java 8 encloses an inbuilt encoder and decoder for Base64 encoding.

O
Three types of Base64 encoding:

se
Simple •Output is limited to a set of characters between A-Z, a-z, 0-9, and +.

URL
rU
•The final output is safe from filename and URL and is limited to a set of characters
between A-Z, a-z, 0-9, and +_.
te
MIME •Output is limited to MIME friendly format.
en

© Aptech Ltd. Fundamental Programming in Java -Session 14 / Slide 24


C
h
ec
pt
rA
Fo

© Aptech Limited
Annotations and Base64 Encoding

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Explain about Base64 encoding.

© Aptech Limited
Annotations and Base64 Encoding

Explain that:
The three types of Base64 encoding are:

Simple: The encoder do not add any line feed in output and the decoder declines any input
other than A-Z, a-z,0-9, and +/-.

Base64.getEncoder().encodeToString() method is used for encoding strings.

Base64.getDecoder().decode() method is used for decoding strings.

y
URL: This type of encoding helps to encode and decode filename or Url in an input. They

nl
return the output without the filename and URL. However, the output is limited to a set of
characters between A-Z, a-z, 0-9, and +_.

O
Base64.getUrlEncoder().encodeToString() method is used for encoding

se
filename and Url content in an input.

MIME: The output is MIME friendly and is denoted in lines with maximum 76 characters each.
rU
Base64.getMimeEncoder().encodeToString() method is used to encode using
the MIME type base 64 encoding scheme.
te
Using slide 25, explain about the two nested classes in Base64 encoding.
en

Explain that:
Base64 encoding has two nested classes, static class Base64.Encoder and
C

static class Base64.Decoder. Both the classes use the Base64 encoding scheme.
These class implements an encoder for encoding byte data and a decoder for decoding byte
data respectively.
h
ec

Using slide 26, explain the methods used for Base64 encoding.
pt

Explain that:
rA

getEncoder() and getDecoder() methods process basic strings.


getMIMEencoder() and getMIMEdecoder() methods processes the MIME type
input. getUrlEncoder() and getUrlDecoder() method process URLs and filename.
Fo

Using slides 27 and 28, explain the Code Snippet that shows how to encode a string to Base64,
then decode the same string back to a Base64 encoded output stream.

Explain that:
Base64 class inherits few methods from the java.lang.Object class. The recommended
encoding scheme to use is UTF-8.

When encoding a string, the alphanumeric characters “a” through “z”, “A” through “Z” and
“0” through “9” remains unchanged, the special characters “.”, “-”, “*”, and “_” remains

© Aptech Limited
Annotations and Base64 Encoding

unchanged, the space character ” ” is converted into a plus sign “+”, and all other characters
are unsafe and are first converted into one or more bytes using some encoding scheme.

In the Code Snippet, the string “AptechJava8” is encoded and decoded back to a Base64
encoded output.

Using slide 28, explain the output of the Code Snippet.

Additional Information:

y
Refer the following links for more information:

nl
https://dzone.com/articles/base64-encoding-java-8

O
https://www.tutorialspoint.com/java8/java8_base64.htm
http://howtodoinjava.com/java-8/base64-encoding-and-decoding-example-in-java-8/

se
In-Class Question:

rU
After you finish explaining slide 28, you will ask the students some In-Class questions. This
will help you in reviewing their understanding of the topic.
te
en

If a class method is implementing an interface method, which annotation will be


used?
C

Answer: @Override annotation


h
ec

Will the following code compile without error? Why or why not?
pt

public @interface Food { ... }


@Food("breakfast", item="porridge")
@Food("lunch", item=" spaghetti")
rA

@Food("dinner", item="pizza")
public void evaluateDiet() { ... }
Fo

Answer: The code will not compile. Since JDK 8, annotations should be defined as
repeatable. In the code, the Food annotation type is not defined as repeatable. Hence, it can
be fixed by adding the @Repeatable meta-annotation and defining a container annotation
type as follows:
@java.lang.annotation.Repeatable(FoodContainer.class)
public @interface Food { ... }

public @interface FoodContainer {


Food[] value();

© Aptech Limited
Annotations and Base64 Encoding

While compiling the following code, the program throws a warning, what is the
warning and how will you resolve the warning?

public interface Door {


@Deprecated
public void open();
public void openLeftDoor();

y
public void openRightDoor();

nl
}
public class Restaurant implements Door {

O
public void open() {}
public void openLeftDoor() {}
public void openRightDoor() {}

se
}

rU
Answer: Through the following ways, we can resolve warning message:

1. By deprecating the implementation of open() method.


te
public class Restaurant implements Door {
// The documentation is
en

// inherited from the interface.


@Deprecated
C

public void open() {}


public void openLeftDoor() {}
public void openRightDoor() {}
h

}
ec

2. The warning can also be suppressed as follows:


pt

public class Restaurant implements Door {


@SuppressWarnings("deprecation")
rA

public void open() {}


public void openLeftDoor() {}
public void openRightDoor() {}
Fo

© Aptech Limited
Annotations and Base64 Encoding

Slide 29
Let us summarize the session.

y
nl
O
se
rU
Use slide 29 to summarize the session. You will end the session, with a brief summary of what
has been taught in the session. Tell the students the key pointers of the session. This will be a
revision of the current session.
te
Explain that:
en

Annotations are comments, notes, remarks, or explanations. In Java, annotations help to


associate these additional information (also called metadata) to the program elements.
Annotations can be determined from source files or class files at runtime. The @Deprecated
C

annotation is used for deprecating or marking a class, method or field as deprecated,


signifying that the part of code no longer will be used. The @SuppressWarnings
h

annotation can suppress the compiler warnings in any available method. Since, annotation
ec

types are piled up and stored in byte code files such as classes, the annotations reverted by
these methods can be enquired as any systematic Java object. Base64 encoding has an in-built
encoder and a decoder. In Java 8, there are three types of Base64 encoding namely, Simple,
pt

URL, and MIME.


rA

14.3 Post Class Activities for Faculty

You should familiarize yourself with the topics of the next session.
Fo

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to
gain additional information related to the topics covered in the next session. You can also
connect to online tutors on the Online Varsity site to ask queries related to the sessions.

© Aptech Limited
Functional Programming in Java

Session 15 – Functional Programming in Java


15.1 Pre-Class Activities

Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.

15.1.1 Objectives

y
By the end of this session, learners will be able to:

nl
➢ Explain lambda expressions

O
➢ Describe method references
➢ Explain functional interfaces

se
➢ Explain default methods

15.1.2 Teaching Skills


rU
To teach this session, you should be well versed with functional programming in Java. You
should be familiar with lambda expressions, creating and using them, method references,
te
and various functional interfaces present in java.util.function package. You must also be
familiar with default methods. You should teach the concepts in the theory class using the
en

images provided. For teaching in the class, you are expected to use slides and LCD
projectors.
C

Tips:
It is recommended that you test the understanding of the students by asking questions in
h

between the class.


ec

In-Class Activities
pt

Follow the order given here during In-Class activities.


rA

Overview of the Session


Give the students an overview of the current session in the form of session objectives. Read
Fo

out the objectives on slide 2.

© Aptech Limited
Functional Programming in Java

Slide 2

y
nl
O
se
Show the slide and give the students a brief overview of the current session in the form of
rU
session objectives. Tell the students that this session defines Functional Programming in Java.
They will be introduced to lambda expressions. The session will describe method references
and functional interfaces. Finally, the session will explain about default methods and static
te
methods in interfaces.
en

15.2 In-Class Explanations

Slides 3 and 4
C

Let us learn about lambda expressions.


h

Introduction 1/2
ec
pt

Lambda expressions are newly


rA

introduced in Java 8 to facilitate


functional programming.
Fo

© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 3

© Aptech Limited
Functional Programming in Java

y
nl
O
se
Using slide 3, give an introduction about lambda expressions. Explain that functional
programming emphasizes on evaluation of expressions instead of executing commands.

rU
Functional programming makes a program modular, thread-safe, and more readable. A
program is considered to be thread-safe if it manages shared data structures in a manner that
ensures secure implementation by multiple threads simultaneously. Modular denotes dividing
te
the functionality of a program into independent and compatible modules.
en

Following code shows an example that can be used to explain to the students:
var str = function(text) {
return function() {
C

alert(text);
}
h

};
setTimer(str(‘Say Hi after 10 seconds'), 10000);
ec

On compilation, str() will be created. str() returns an anonymous function. The


pt

anonymous function alerts the argument text that is passed to str() function.
rA

Using slide 4, state the advantages of functional programming.

Say that lambda expressions are newly introduced in Java 8 to facilitate functional
Fo

programming.

© Aptech Limited
Functional Programming in Java

Slides 5 to 7
Let us explore lambda expressions in detail.

y
nl
O
se
Syntax:
rU
Syntax of Lambda Expressions
te
parameters → body
en

where,
parameters are variables
C

→ is the lambda operator


body is parameter values
h
ec

© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 6


pt
rA
Fo

© Aptech Limited
Functional Programming in Java

Using slide 5, describe lambda expressions.

Explain that:
Lambda expression facilitates functional programming. It is a function that does not belong to
any class. It is similar to shorthand which allows user to write a method at the same place
where it is going to be used.

Using slide 6, explain the syntax of lambda expressions.

Explain that:

y
Examples of declaration of lambda expressions are:

nl
(int a, int b) → { return a + b; }
() → System.out.println(“My Black Cat");

O
(String str) → { System.out.println(str); }
() → 102

se
() → { return 3.1415 };

Using slide 7, explain the rules of lambda expressions.

Explain that:
rU
The data type of the parameters in a lambda expression is optional. The body may consist of
te
a single expression such as () → System.out.println(“Hi"); or a statement block
such as:
en

() → {
one(() → { System.out.println("I am one."); });
C

two(() → { System.out.println(“Iam two."); });


}
h

For single expression, curly braces are optional and for single parameters, parentheses is
ec

optional.
pt

Additional Information:
rA

Refer the link for more information:


https://www.tutorialspoint.com/java8/java8_lambda_expressions.htm
Fo

© Aptech Limited
Functional Programming in Java

Slides 8 to 10
Let us learn about single method interfaces and lambdas.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Explain about single method interface and lambdas. Explain the code that shows an example
of a single method interface.

© Aptech Limited
Functional Programming in Java

Explain that:
The method onStateChange is called if a state change occurs. previousState and
presentState are parameters of the event.

Using slide 9, explain the code that shows how to add an event listener using an anonymous
method implementation.

Explain that:
In the code, objStateTest.addStateListener(new
StateChangeListener() is the event listener that is added to capture each state

y
change event, previousState and presentState.

nl
Using slide 10, explain the code that shows how to add an event listener using a lambda

O
expression.

se
Explain that:
In the code, objStateTest.addStateListener((previousState,
presentState) →
rU
System.out.println("State change event occurred"));
is the event listener that is added using a lambda expression → to capture each state change
event.
te
previousState and presentState are parameters of the event. The lambda
expression and the parameter type of addStateListener() method have to match each
en

other. If the type and expression is matched, lambda expression turns into a function which
creates the same interface as a parameter. This interface contains a single method. Thus, the
C

lambda expression is matched successfully.

Slides 11 to 13
h
ec

Let us understand lambda parameters and how to use them.


pt
rA
Fo

© Aptech Limited
Functional Programming in Java

y
nl
O
se
rU
te
en
C
h
ec

Using slide 11, explain about lambda parameters.


pt

Explain that:
Lambda expressions can handle parameters similar to methods. Here, the method takes one
rA

parameter, Seat s and returns True if seat is available.


CheckSeat interface:
Fo

interface CheckSeat{
boolean test(Seat s);
}

Using slide 12, explain about types of lambda parameters.

Explain that:
On the single method interface, it is must that the lambda expression parameters match the
parameters of the method. At least the number of parameters in the lambda expression and
the method must match.

© Aptech Limited
Functional Programming in Java

Using slide 13, explain the codes that shows usage of different types of parameters for lambda.

Explain that: Multiple line lambda expressions must be enclosed within brackets { }, while
single parameter does not needs a bracket.

Additional Information:

Refer the link for more information:

https://dzone.com/articles/java-lambda-expressions-basics

y
nl
Slide 14
Let us look at how to return values from a lambda expression.

O
Returning a Value

se
For returning values from lambda expression, a return statement can be added for specific
calculations.

(pA) → {
rU
System.out.println("The output will be: " + pA);
te
return "result value";// return statement
}
en
C

© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 14


h
ec

Using this slide, explain the procedure for returning values from Java lambda expressions.
Explain that:
For returning values from lambda expression, a return statement can be added for specific
pt

calculations. You add a return statement to the body of the lambda function. The return
rA

statement is enclosed within the braces ({ }). In the code, the compiler evaluates the
expression pA and then returns its value.
Fo

Additional Information:

Refer the link for more information:

http://tutorials.jenkov.com/java/lambda-expressions.html

© Aptech Limited
Functional Programming in Java

Slide 15

Let us understand use of lambdas as objects.

y
nl
O
se
rU
Using this slide, explain about using lambdas as objects.
te
Explain that:
A Java lambda expression is basically an object. The code shows how a Java lambda expression
en

can be assigned as a regular object to a variable. Here, iA and iB are the objects to be
compared. The second code shows implementation of lambda where the lambda object is
assigned to a variable and passed as an object. The values 3 and 6 are assigned to iA and
C

iB and then compared. In the last code, a lambda is used to sort strings by length. Here,
Arrays.sort method is used to sort the strings strA and strB by its length.
h
ec

Additional Information:

Refer the link for more information:


pt

http://tutorials.jenkov.com/java/lambda-expressions.html
rA
Fo

© Aptech Limited
Functional Programming in Java

Slides 16 to 18
Let us explore advantages and uses of lambda expressions.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slide 16, explain the advantages and uses of Java lambda expressions.

© Aptech Limited
Functional Programming in Java

Explain that:
Lambda expressions limits lengthy codes thus, assists in faster execution of code. It also makes
parallel processing easier.

Using slide 17, explain the code that shows a complete program utilizing lambda.

Explain that:
In the code, various types of lambda expressions are used to define the operation method of
MathOperation interface. They are:
• Receive results with type declaration (addition)

y
• Receive results without type declaration (subtraction)

nl
• Receive results with return statement along with curly braces (multiplication)
• Receive results without return statement and curly braces (division)

O
Using slide 18, explain the output of the code that shows a complete program utilizing lambda.

se
Explain that:

rU
The code performs basic math operations using lambda expressions. The input values are
taken as ab=20 and xy=5.
te
Additional Information:
en

Refer the link for more information:


C

http://www.nagarro.com/at/de/perspectives/post/26/Lambda-Expressions-in-Java-8-Why-
and-How-to-Use-Them
h
ec
pt
rA
Fo

© Aptech Limited
Functional Programming in Java

Slide 19
Let us understand scope for lambda expressions.

y
nl
O
se
rU
Using this slide, explain the code that shows usage of lambda expressions with Runnable
interface.
te
Explain that:
In the code, both the dA and dB lambdas call the toString() method of the MyWishes
en

class. Both lambdas use the run method and return Happy New Year as output.

Additional Information:
C

Refer the link for more information:


h
ec

http://www.codejava.net/java-core/the-java-language/java-8-lambda-runnable-example
pt
rA
Fo

© Aptech Limited
Functional Programming in Java

Slides 20 to 23
Let us examine method references.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Functional Programming in Java

y
nl
O
se
Using slide 20, explain about method references.

Explain that:
rU
In Java 8, method references are used to refer to constructors or methods without performing
an execution. There are six types of method references as shown on slide 20.
te
Then explain:
Reference to static methods: In the syntax, ReferenceStatic::demoMethod
en

ReferenceStatic is the class in which static method demoMethod is defined.


Reference to instance from the supertype of an object: In the syntax,
C

demoInstance::demoMethod
Here, demoInstance is an object reference for ReferenceStatic class and
demoMethod is instance method defined in class.
h

Reference to a constructor ClassName::new: In the syntax, String:: new is a reference


ec

to the String class constructor.


pt

Using slide 21, explain the code that shows a set of methods to determine a file type.
rA

Explain that:
In the code, the class File implements the interface FileFilters and to determine the
filenames with extensions such as jpeg, tiff, and png.
Fo

Using slide 22, explain the code that shows how to use method reference for file filtering.

Explain that:
In the code, a method is predefined as getFiles() that returns a Stream. The method
reference FileFilters::fileIsJpeg, FileFilters::fileIsTiff, and
FileFilters::fileIsPng is a reference to a static method.

© Aptech Limited
Functional Programming in Java

Explain about the various types of method references using slide 23.

Explain that:
Method references simply call a method which is already defined. They refer to the methods
by the method name. In a lambda expression, double colon(::) operator is used for method
reference.

A static method reference refers to a static method of the specified class.

public class Author {

y
static String DemoField1;

nl
}
Author.DemoField1 = "value";

O
System.out.println(Author.DemoField1);

Static fields belong to the class Author, hence, an instance of the class is not required to

se
access static fields.

Slide 24
rU
Let us understand static method references.
te
en
C
h
ec
pt
rA

Explain the code on the slide that demonstrates static method reference.
Fo

Explain that:

Static methods can be defined in an enum, a class, or an interface. The first lambda expression
funcA is created by defining an input value x and providing a lambda expression body.
This is the normal way of creating a lambda expression.

The second lambda expression funcB is created by referencing a static method from Integer
class.

© Aptech Limited
Functional Programming in Java

Additional Information:

Refer the link for more information:

http://java8.in/java-8-method-references/

Slide 25
Let us understand instant method references.

Instance Method References

y
nl
import java.util.function.Supplier;

O
public class MainTest{
public static void main(String[] argv){
Supplier<Integer>sampleSupA = () ->
"Aptech".length();

se
System.out.println(sampleSupA.get()); Output:
// display result
Supplier<Integer>sampleSupB= 6
"Aptech"::length; 6

// display result
}
} rU
System.out.println(sampleSupB.get());
te
© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 25
en

Using this slide, explain the code that demonstrates an instance method reference.
C

Explain that:
In the code, lambda expressions sampleSupA and SampleSupB gets the length of the
h

input value Aptech. Both produce the output as 6.


ec

Additional Information:
pt

Refer the link for more information:


rA

http://baddotrobot.com/blog/2014/02/18/method-references-in-java8/
Fo

© Aptech Limited
Functional Programming in Java

Slides 26 and 27
Let us understand functional interfaces.

Functional Interface 1/2


A functional interface is an interface with one method and is used as the type of a lambda
expression.

New functional interfaces included in the Java 8 package, java.util.function, are:

y
• Predicate<T> - Returns a Boolean value based on input of type T.
• Supplier<T> - Returns an object of type T.

nl
• Consumer<T> - Performs an action with given object of type T.
• Function<T, R> - Gets an object of type T and returns R.

O
• BiFunction - Similar to Function but with two parameters.
• BiConsumer - Similar to Consumer but with two parameters.

se
© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 26

Functional Interface 2/2


rU
The second line defines a function that represents '@'symbol to a String.
te
en

//Functional Interface sample use case


Function<String, Integer>sampleLengthA = (name) ->
name.length();//as int
Function<String, String>atr = (name) -> {return "@" +
C

name;};//as string
Function<String, Integer>samplLengthB = String::length;
//as int
h
ec

© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 27


pt

Explain about functional interface and the new functional interfaces included in
rA

java.util.function.

Explain that:
Fo

A functional interface is with one method and is used as a type of a lambda expression. A
functional interface type with an abstract method takes a String as a parameter and returns
an integer value.

Predicate interface creates lambda expressions that returns a boolean value based on the
input argument.
Supplier<T> returns a supplier of results.
Consumer<T> accepts a single input argument and returns no result.
Function<T, R> represents a function that accepts one argument of type T and produces a
result of type R.

© Aptech Limited
Functional Programming in Java

Additional Information:

Refer the link for more information

https://dzone.com/articles/function-interface-functional

Using slide 27, explain the code that shows sample functional interface use case.

Explain that:
Functional interface can process any type of parameter and return another type of parameter.

y
For example, String to Integer or String to String. In the code, the line Function<String,

nl
String>atr = (name) → {return "@" + name;}; defines a function that
represents @ symbol to a String.

O
Both the lines,

se
Function<String, Integer>sampleLengthA = (name) →
name.length();
and
Function<String, Integer>samplLengthB = String::length;rU
define the same process of calculating a length of a string, but using different approaches.
te
Slide 28
en

Let us look at default methods.


C

Default Methods
Default methods are Virtual Extensions that contains default implementations of forEach() method.
class Test{
h

public static void main(String args[]){


Book book = new Novel();
book.print();
ec

}
}
interface Book {
default void print(){
System.out.println("This is a book");
}
pt

static void turnPages(){


System.out.println("Turning pages.");
}
}
rA

interface Journal {
default void print(){
System.out.println("This is a journal");
}
}
class Novel implements Book, Journal {
public void print(){
Fo

Book.super.print();
Journal.super.print();
Book.turnPages();
System.out.println("This is a novel");
© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 28
} }

Explain the code that shows usage of default methods.

Explain that:
Default methods allow implementation for methods in an interface. Default methods are also
known as Virtual Extensions. Classes implementing an interface automatically inherits the
default implementation. The class Novel implementing Book and Journal interface
contains default implementations of print() method.

© Aptech Limited
Functional Programming in Java

Additional Information:

Refer the link for more information

https://dzone.com/articles/interface-default-methods-java

Slide 29
Let us explore the features of default methods.

Features of Default Methods

y
nl
Extend
interfaces
without
breaking

O
implementation
classes

Allow the Reduce


implementation differences

se
classes to between
decide interfaces and
automatically abstract classes
Default
Methods

rU
Enhance the
collection API
Eliminate the
need of utility
te
classes

© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 29


en

Explain the features of default methods.


C

Explain that:
Default methods help to include new functionalities to interfaces without breaking the
h

implementation classes that implements that interface. A default method cannot override a
ec

method from java.lang.object as the Object is the base class for all the other Java
classes.
pt

public interface TestInterface {


rA

void defaultmethod1(String str);


default void show(String str){
System.out.println(“This is the string"+str);
Fo

}
}

show(String str) is the default method in the TestInterface. When a class


implements TestInterface, it is not required to provide implementation for default
methods of interface.

© Aptech Limited
Functional Programming in Java

Slide 30
Let us view the difference between default methods and regular methods.

Default Method and Regular Method


Default method contains default modifier - that is the main difference between a regular method and
default method.
public class Java8Tester {
public static void main(String args[]){
Gadget gadget = new SmartGadget();
gadget.print();
} Output:
}
interface Gadget {
default void print(){ This is a Gadget!
System.out.println("This is a Gadget!"); With calling feature!
} With Text Messaging

y
static void call(){ feature!
System.out.println("With Calling feature!");
It is a Smartphone!
}
}

nl
interface TextMessage {
default void print(){
System.out.println("With Text Messaging feature!");
}

O
}
class SmartGadget implements Gadget, TextMessage {
public void print(){
Gadget.super.print();
TextMessage.super.print();
Gadget.call();
System.out.println("It is a Smartphone!");

se
}
}
© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 30

rU
Using this slide, explain the code that shows the difference between default methods and
regular methods.
te
Explain that:
The main difference between a regular method and default method is default method
en

contains default modifier. Methods in classes can access and modify method arguments and
fields of their class.
C

In the code sample, the same print() method gives different output based on the modified
method arguments for each of their class.
h
ec

Additional Information:

Refer the link for more information:


pt
rA

http://stackoverflow.com/questions/27833168/difference-between-static-and-default-
methods-in-interface
Fo

© Aptech Limited
Functional Programming in Java

Slides 31 to 33

Let us understand the concept of multiple interfaces.

Multiple Defaults 1/3

Multiple Defaults are multiple interfaces contained within Java class. Java throws a
compilation error if two or more interfaces defining the same default method.

public interface Green {


default void defaultMethod(){

y
System.out.println("Green default method");
}

nl
}
public interface Red {
default void defaultMethod(){

O
System.out.println("Red default method");
}
}
public class Impl implements Green, Red{
}

se
© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 31

rU
Multiple Defaults 2/3
te
Compiling the previous Code Snippet will result in an error. In order to fix this, provide
explicit default method implementation.
en

public class Impl implements Green, Red{


public void defaultMethod() {
C


}
}
h
ec
pt

© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 32


rA

Multiple Defaults 3/3


Further, to invoke default implementation provided by any of super interfaces, the code can
be as follows:
Fo

public class Impl implements Green, Red {


public void defaultMethod(){
// remaining code...
Green.super.defaultMethod();
}
}

© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 33

© Aptech Limited
Functional Programming in Java

Explain about multiple interfaces and the code that shows implementation of multiple
methods.

Explain that:
Multiple Defaults are multiple interfaces contained within Java class. The compiler will throw
a compilation error if two or more interfaces define the same default method. In the code
sample, the inherited methods, Green and Red conflicts with one another. On execution,
the compiler shows error as ‘java:class Impl inherits unrelated defaults for
defaultMethod() from types Green and Red.’

y
Using slide 32, explain how the error in the previously shown code can be rectified.

nl
Explain that:

O
To fix the error, provide explicit default method implementation. The default method is
defined within public class impl.

se
Using slide 33, explain how to invoke default implementation.

Explain that: rU
The code is revised as given to invoke default implementation by revising the default method
Green as super interface.
te
Additional Information:
en

Refer the link for more information:


C

https://www.tutorialspoint.com/java8/java8_default_methods.htm

Slides 34 and 35
h

Let us understand static methods on interfaces.


ec

Static Methods on Interfaces 1/2


pt
rA

Static Methods on Interfaces Description


Fo

Easy to organize and access helper For example, the new Stream interface
method in libraries contains many static methods

Eliminates the need of a separate Parentheses contains a value


class

© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 34

© Aptech Limited
Functional Programming in Java

Static Methods on Interfaces 2/2

All method declarations in an interface, including static methods, are implicitly public.

public interface ProductInfo {


...
static ProductId getProductId (String
ProductString) {
...
}
...

y
}

nl
O
© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 35

se
Explain about static methods on interfaces.

Explain using slide 34 that:


rU
A static method is a method that associates itself with the class in which it is defined. Each
instance of the class shares the static method of the class. In Java 8, Static methods can be
te
defined in interfaces to help default methods. Thus, static methods help to organize helper
methods in libraries. Static methods can be kept specific to an interface in the same interface
en

instead of a separate class.


C

Using slide 35, explain the code that shows example of implementation of static methods on
interfaces.
h

Explain that:
ec

static keyword is used to mark a method as static. The keyword is mentioned at the
pt

beginning of the method signature. As static methods are implicitly public, it is not required
to mention the public modifier explicitly in the declaration.
rA

In-Class Question:
Fo

After you finish explaining slide 34, you will ask the students some In-Class questions. This
will help you in reviewing their understanding of the topic.

Curly braces may or may not be present when declaring lambda expression. Is it true
or false?

Answer: True

© Aptech Limited
Functional Programming in Java

Returning the values from lambda expression return statement added to the body
of lambda function and the statement is enclosed within which brackets?

Answer: The return statement added to the body of lambda function and the statement is
enclosed within curly braces ({}).

y
nl
What will be the result of operation, if the operation() method of
MathOperation interface in lambda expression receives results without return

O
statement and curly braces?

se
Answer: The result of operation will be division.

rU
What will be the output for the following program, if the program runs without
error?
te
import java.util.function.Supplier;
en

public class MainTest{


public static void main(String[] argv){
Supplier<Integer>sampleSupA=()-> "Employee".length();
C

System.out.println(sampleSupA.get());
Supplier<Integer>sampleSupB="Employee"::length;
h

System.out.println(sampleSupB.get());
ec

}
}
pt

Answer:
8
rA

8
Fo

© Aptech Limited
Functional Programming in Java

Slide 36
Let us summarize the session.

Summary
❖ Functional programming emphasizes that utilization of functions and writing code
that does not change state.

❖ Using functional programming, you can pass functions as parameters to other


functions and return them as values.

❖ A lambda expression is a compact expression that does not require a separate


class/function definition. It facilitates functional programming.

y
❖ Depending on the parameters being passed to the lambda expression, you will

nl
use/omit parentheses.

❖ Default method is a new feature in Java 8 that allows default implementation for

O
methods in an interface.

❖ In addition to default methods, static methods can be defined in interfaces that

se
makes it easy to organize and access helper methods in libraries.
© Aptech Ltd. Fundamental Programming in Java -Session 15 / Slide 36

rU
Use this slide to summarize the session. You will end the session, with a brief summary of
what has been taught in the session. Tell the students pointers of the session. This will be a
revision of the current session.
te
Explain that:
en

Functional programming emphasizes that utilization of functions and writing code that does
not change state. Using functional programming, you can pass functions as parameters to
other functions and return them as values. A lambda expression is a compact expression that
C

does not require a separate class/function definition. It facilitates functional programming.


Depending on the parameters being passed to the lambda expression, you will use/omit
h

parentheses. Default method is a new feature in Java 8 that allows default implementation for
ec

methods in an interface. In addition to default methods, static methods can be defined in


interfaces that makes it easy to organize and access helper methods in libraries.
pt

15.3 Post Class Activities for Faculty


rA

You should familiarize yourself with the topics of the next session.
Fo

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to
gain additional information related to the topics covered in the next session. You can also
connect to online tutors on the Online Varsity site to ask queries related to the sessions.

© Aptech Limited
Stream API

Session 16 – Stream API


16.1 Pre-Class Activities

Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.

16.1.1 Objectives

y
By the end of this session, learners will be able to:

nl

O
Describe the Stream API
➢ Outline the differences between collections and streams
➢ Explain the classes and interfaces in Stream API

se
➢ Describe how to use functional interfaces with Stream API
➢ Describe the Optional class and Spliterator interface


Explain stream operations
Discuss the limitations of Stream APIrU
te
16.1.2 Teaching Skills
en

To teach this session, you should be well versed with the new Stream API in Java 8. You should
be aware of the difference between collections and streams. You must be familiar with
functional interfaces in the Stream API and operations performed by them.
C

You should teach the concepts in the theory class using the images provided. For teaching in
h

the class, you are expected to use slides and LCD projectors.
ec

Tips:
It is recommended that you test the understanding of the students by asking questions in
pt

between the class.


rA

In-Class Activities

Follow the order given here during In-Class activities.


Fo

Overview of the Session


Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.

© Aptech Limited
Stream API

Slide 2

y
nl
O
se
Show the slide and give the students a brief overview of the current session in the form of

rU
session objectives. Tell the students that this session explains about the new Stream API in
Java 8. The session will describe the differences between collections and streams and the
classes and interfaces in Stream API. Then, it describes how to use functional interfaces with
te
Stream API and concentrates on various operations supported by the Stream. Finally, the
session will discuss the limitations of Stream API.
en

16.2 In-Class Explanations


C

Slides 3 and 4
h

Let us look at an overview of the Stream API.


ec
pt
rA
Fo

© Aptech Limited
Stream API

y
nl
O
Explain about Stream API.

se
Using slide 3, explain that:

rU
Stream API is a new abstract layer introduced in Java 8 that supports parallel processing and
helps to express efficient, SQL-like queries and manipulations on data. Also, Stream API
supports sequential and parallel aggregate operations for data processing. Sequential
te
operations must be performed in a specific order. Aggregate operations process elements
from a stream and allows you to customize the behavior of a particular aggregate operation.
en

That means, dividing a process into sub processes, executing the sub processes
simultaneously, and then finally combining the results into one solution.
C

Stream API can also use lambda expressions.


h

Using slide 4, explain about Stream interface and Collectors class.


ec

Stream interface and Collectors class form the basic foundation of the Stream API.
java.util.stream package contains all the Stream API interfaces and classes. Few
pt

interfaces of Stream API are IntStream, LongStream, DoubleStream, Stream<T>,


rA

and so on.
Fo

© Aptech Limited
Stream API

Slide 5
Let us understand streams and collections and the differences between them.

y
nl
O
se
rU
Describe collections and using the content on this slide and differentiate between streams
and collections.
te
Explain that:
A stream is a series or set of elements that supports sequential and parallel aggregate
en

operations and a collection is an in-memory data structure. A collection is a set of data in the
form of objects or elements which holds data and before we start using collection. That is, all
the values should have been populated.
C

Stream is a data structure that is operated on user demand. It does not store data. It
h

operates on the source data structure (collection and array) and produces ordered data. You
ec

can create a stream from a list and filter it based on a condition.

The similarity between collections and streams is that both allow you to traverse them only
pt

once. If you use an iterator to traverse a list, you will have to create a new iterator to loop
through it again.
rA
Fo

© Aptech Limited
Stream API

Slides 6 to 11
Let us explore the process of generating a stream.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Stream API

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Explain how to generate streams.

© Aptech Limited
Stream API

Explain that:
java.util.Collection must be inherited to generate a stream from a data source.

Here, in the code snippet shown on slide 6, a list of strings is created.

The statement

Stream <String> stream = Stream.of("Apple", "Mango", "Orange",


"Guava");
shows creating a stream with four objects.

y
nl
Streams can be sequential or parallel. Operations on sequential stream are processed in
serial manner by a single thread and operations on a parallel stream are processed in

O
parallel using multiple threads.

The Collection interface provides stream() and parallelStream() methods,

se
which are inherited by all implementing classes and sub-interfaces.

rU
Using slide 7, explain about BufferedReader class and the code snippet demonstrating
its use.
te
Explain that:
en

BufferedReader class that is present in the java.io package contains a method


lines() that returns a Stream. In the code snippet shown on slide 7, a
BufferedReader instance is used with FileReader to read a text file, random_file.txt.
C

The statement
h
ec

BufferedReader sampleBR = new BufferedReader(sampleFR) indicates a


BufferedReader class being wrapped around FileReader instance named
pt

sampleFR. BufferedReader takes FileReader as input.


rA

SampleBR is created as a BufferedReader instance. It makes use of lines()


method to read and display data from the text file.
Fo

BufferedReader helps to read text from a character-input stream, buffering characters


so that characters, arrays, and lines are read efficiently.

Using slide 8, explain the code snippet that shows how to read a file as a
java.util.stream.Stream object using Files.lines(Path filePath).

Explain that:
We can read text from a file as a stream of strings. Each element in the stream represents
one line of text. The code reads the text file, random_file.txt using lines() and
forEach() methods. The Files.lines() method returns Stream of all lines in the
text file.

© Aptech Limited
Stream API

Using slide 8, explain about static methods in the Files class.

Explain that:
Static methods in the Files class assist in navigating file trees using a Stream. Files are
used to store data and are organized in directories in a file system. Files can be accessed
using streams, as streams present data in a sequential form.

File instance is created by passing a path string to the new File() constructor. The
File class consists of various methods to retrieve information about files and directories.
The table on slide 9 shows some of these methods.

y
nl
Explain about Pattern class.

O
Explain that:
Text patterns can be streamed using the Pattern class that contains a method,

se
splitAsStream(CharSequence) to generate a stream. The
splitAsStream(CharSequence) splits a CharSequence by a regular expression (a
special sequence of characters that helps you match or find other strings or sets of strings,
rU
using a specialized syntax held in a pattern).

In the code snippet shown on slide 10, in the class TextPatterns, a pattern object is
te
created as Pattern createPatt = Pattern.compile(",") to add a comma to
a set of names. The names are split as sequence of characters using
en

splitAsStream(CharSequence).
C

Using slide 11, explain the output of the code snippet that was shown on slide 10.
h

Explain that:
The example on slide 11 generates a Stream from a simple text pattern that contains a
ec

comma as separator and separates the text into a Stream by using the
splitAsStream() method.
pt

Then, each element in the Stream is printed out using a forEach loop. In practical
rA

scenarios, a similar code to match and display large collections of strings can be used.

Explain the output.


Fo

© Aptech Limited
Stream API

Slide 12
Let us look at Infinite Streams.

y
nl
O
se
rU
Explain about infinite streams and also explain the code snippet that shows creation of
infinite quantity of objects.
te
Explain that:
An infinite stream is a sequence or collection of elements that has no limit.
en

The code shown on this slide shows an infinite quantity of objects being created using
generate() method. The generate() method invokes Supplier functional
C

interface instance passed to it as input parameter.


h

You can also use the iterate() method to create infinite streams. For example,
ec

IntStream.iterate(0, i -> i + 2).limit(3);

Using iterator methods, you can define an initial value and a method modifies the value.
pt
rA
Fo

© Aptech Limited
Stream API

Slide 13
Let us understand Stream range.

y
nl
O
se
rU
Explain about stream range and also explain the code snippet that describes the usage of
range() on the IntStream interface.
te
Explain that:
The newly included primitive stream called IntStream can be used for Stream range
en

calculations. This can be useful in practical scenarios involving large ranges of numbers that
will be cumbersome to generate manually.
C

IntStream is a part of java.util.stream package.


h

Code snippet on slide 13 describes the usage of static method range() in the
ec

IntStream interface. In the code snippet, the integers within the range of 2 to 18 are
displayed.
pt

You can define a range of integers to create a stream using range() and
rA

rangeClosed() methods.

The rangeClosed() method includes the ending integer value while the range method
Fo

excludes it.

You can also use the of() method. For example, IntStream.of(1,2,3); creates a
IntStream based on the values 1, 2, and 3.

Besides IntStream, other primitive Stream interfaces such as DoubleStream and


LongStream also contain corresponding range() methods.

© Aptech Limited
Stream API

Slides 14 to 16
Let us explore operations that can be performed on streams.

Operations on Streams 1/3


Intermediate Operations

• In intermediate operations, operators (intermediate operators) apply logic thus, the


inbound Stream generates another stream.

• A Stream can contain 'n' number of intermediate operators, which has no limitations.

y
• Intermediate operators can start a pipeline of Stream elements to execute the process

nl
further.

O
se
© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 14

Operations on Streams 2/3


Terminal Operations rU
Following are commonly used terminal methods:
te
forEach

toArray
en

min

max
C

findFirst

findAny

anyMatch
h

allMatch
ec

noneMatch
© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 15
pt
rA
Fo

Explain about intermediate operations.

© Aptech Limited
Stream API

Explain that:
Stream operations that can be connected are called intermediate operations. It is possible to
connect stream operations as their return type is also Stream. In intermediate operations,
operators (intermediate operators) apply logic, thus, the inbound Stream generates another
stream. For example, filter and map operations can be connected to form a pipeline of
stream.

A Stream can contain 'n' number of intermediate operators, which has no limitations.

Read out the commonly used terminal operations.

y
nl
Explain that:
Terminal operations help to close a pipeline of stream. Intermediate operations do not

O
perform any action until the terminal operation is invoked. Use the collect operation to
collect the result of filter and map operations and return a result. Thus, collect operation

se
serves as a terminal operation.

Explain about short-circuiting operations.

Explain that:
rU
Short-circuiting operations are not standalone operations. Short-circuiting operations are
te
defined as operations generating finite Stream from infinite Stream. For example, when you
use the boolean operators || in an expression, if the left-side expression returns true, then
en

the right-side expression is not checked.


C

Slide 17
Let us understand map/filter/reduce operations with streams.
h
ec
pt
rA
Fo

Explain about map/filter/reduce methods implementation in lambda expressions.

© Aptech Limited
Stream API

Explain that:
Stream supports operations from functional programming languages similar to SQL
operations. For example, filter, map, reduce, find, and so on.

For example, you are checking your expenditure of credit card.

Map method is applied for mapping all the elements to its output. You extract information
from the bill.

Filter helps in choosing a set of element and eliminating other elements based on the

y
instructions. You apply filter to the mapping by giving a condition for example, filter by

nl
expenditure more than 500 USD.

O
Reduce method is applied to reduce the elements based on the given instructions. You
further reduce the findings by calculating the sum of all transactions more than 500 USD.

se
Slide 18
Let us understand streams and parallel arrays.
rU
te
en
C
h
ec
pt
rA

Explain about streams and parallel array. Also, explain the code snippet that shows usage of
the parallel approach.
Fo

Explain that:
Java 8 consists of new functionality of arrays which is parallelSort. For example,
parallelSort(int[] a, int fromIndex, int toIndex) helps to sort and
arrange integers. parallelSort() method assigns the process of sorting to various
threads existing in a thread pool.

© Aptech Limited
Stream API

Slide 19
Let us understand the limit() method of Stream.

y
nl
O
se
rU
Explain about limit and explain the code snippet that shows usage of limit() method.

Explain that:
te
limit() method can be applied to limit a Stream to a specified number of elements.
Here, sampleRand is used to return random integer values and limit() method is
en

applied to limit the numbers to display only 12 random numbers.


C

Slide 20

Let us understand how to perform sorting using sorted() method.


h
ec
pt
rA
Fo

Explain about sorted() method and explain the code snippet that shows usage of
sorted() method.

© Aptech Limited
Stream API

Explain that:
sorted() method is another method within Stream API that helps to sort the Stream. It is
known as ‘Lazy’ execution because no process is started until a terminal operation (such as
reduce or foreach) is called.

Note that a limiting operation must be called before the sorting operation on an infinite
Stream, a Stream that does not have a fixed size.

Slide 21
Let us understand collectors.

y
nl
O
se
rU
te
en
C

Explain about collectors and implementation of collectors.


h

Explain that:
ec

The three elements of collector are:


 Supplier: A supplier of an initial value.
pt

 Accumulator: An accumulator that adds to the initial value.


rA

 Combiner: A combiner that combines two outputs as a single output.

For example, from a Student list, Supplier, you collect the marks of two semesters
Fo

(Accumulator) and combine the result to find whether the student qualifies (Combiner).

The two methods to implement this are:


 collect(supplier, accumulator, combiner)
 collect(Collector)

© Aptech Limited
Stream API

Slides 22 to 24
Let us understand grouping and partitioning.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Stream API

Explain about grouping. Also, explain the code snippet that groups strings based on first
letter.

Explain that:
Grouping (groupingBy) collector groups elements based on a given function.

The groupingBy operation returns a map of values that are obtained by applying the
lambda expression specified as its parameter. For example,

Map<City, List<People>> byCity

y
= peoples.stream()

nl
.collect(Collectors.groupingBy(People::getCity));

O
Here, the parameter for grouping is city.

se
Explain about partitioning. Also, explain the code snippet that partitions the tiger list based
on whether it is white or not.

Explain that: rU
Partitioning (partitioningBy) method is parallel to Grouping method that creates a
te
map with a boolean key, True or False.
en

In the City example, of previous slide, you can mention the partition condition of more than
1 lakh population.
C

Map<Boolean, List<People>> partitioned =


peoples.stream()
h

.collect(partitioningBy(p -> p.getCity() >=


ec

100000);

Similarly, a Students map can be obtained for the boolean key, Pass or Fail.
pt

Thus, in partitioning the resultant is a map that contains two groups, Pass/Fail, Yes/No, and
rA

so on.

In the code snippet, the tiger list is partitioned by the boolean key, white or not. The code
Fo

line Map<Boolean, List<Tiger>> map =


tigers.stream().collect(partitioningBy(Tiger::isWhite)) counts
the number of tigers that are white.

Explain about parallel grouping. Also, explain the code snippet that displays parallel
grouping.

© Aptech Limited
Stream API

Explain that:
Parallel Grouping (groupingByConcurrent) executes grouping in parallel (without
ordering).

groupingByConcurrent returns a concurrent Collector implementing a ‘group by’


operation on input elements of type T, grouping elements according to a classification
function.

In the code snippet, from an unordered stream of list of Tigers, the input element ‘tigers’
are grouped based on their color (getColor).

y
nl
Slides 25 to 28

O
Let us explore functional interfaces in Java 8.

se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Stream API

y
nl
O
se
rU
te
en
C
h
ec

Explain about Function and BiFunction interfaces.


pt

Using slide 25, explain that:


Functional interfaces can be used with several new APIs in Java 8.
rA

BiFunction interface produces output from two argument.


Fo

BiFunction<String, String,String>
bi = (a, b) -> {

return a + b;
};

The two input arguments are: a and b.

© Aptech Limited
Stream API

Using slide 26, explain about Predicate and BiPredicate and their respective
methods.

Explain that:
Predicate and BiPredicate denote a predicate or boolean-valued function against
which arguments of the Stream are tested.

Consider the code:

BiPredicate<Integer, Integer> SamplebiPred = (t, u) -> t > u;

y
System.out.println(SamplebiPred .test(20, 10));

nl
The test() method evaluates the arguments 20 and 10 to find whether 20 is greater than

O
10. The output is true.

se
Using slides 27 and 28, explain about Consumer and BiConsumer. Explain the code
snippet that demonstrates Consumer methods.

Explain that:
rU
Consumer <T> denote operations that accept a single input element and produce no
output and Biconsumer<T,U> operation accepts two input arguments and returns no
te
result.
en

Continue to explain the code snippet that demonstrates Consumer and Biconsumer
methods.
C

Explain that:
The displayAllEmployee() method iterates through the list of employees and invokes
h

the accept() method of the consumer object for every employee in the list. The
ec

accept() method shown in printer.accept(e) is the primary abstract method of


the Consumer functional interface that displays the name and salary of every employee.
pt

Stream methods in which Consumer, BiConsumer, or other primitive interfaces are


rA

used:
void forEach(Consumer<? super T> action)

Stream<T> peek(Consumer<? super T> action) // peek action



Fo

void forEachOrdered(Consumer<? super T> action)


SampleDemo is a class with three methods main(), displayAllEmployee(), and


display. In main() method, an array of employees are taken. Then, the main method
displays all employee name after multiplying salary of each employee by 1.5 that is,
displayAllEmployee(employees, e → { e.salary *= 1.5);

The salaries after increment displayAllEmployee(employees, e


→System.out.println(e.empname + ": " + e.salary));. Here two
arguments are displayed e.empname and e.salary showing BiConsumer operation.

© Aptech Limited
Stream API

Additional Information:
Use the following links for additional reference:

http://www.java2s.com/Tutorials/Java/java.util.function/BiFunction/index.htm
https://www.safaribooksonline.com/library/view/java-8-
lambda/9780133750867/part23.html
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
http://www.java2s.com/Tutorials/Java/java.util.function/BiPredicate/index.htm
http://data-structure-learning.blogspot.in/2015/07/java-lambda-bipredicate-functional.html
http://www.concretepage.com/java/jdk-8/java-8-biconsumer-bifunction-bipredicate-

y
example

nl
Slide 29

O
Let us understand about Optional class and Spliterator interface.

se
Optional and Spliterator API

rU
Optional is a container object that optionally contains a value (non-null).
If it contains a value, isPresent()shows true and get()returns the value.
Following are Stream terminal operations that return an Optional object:

• Optional<T> min(Comparator<? super T> comparator)


te
// minimum
• Optional<T> max(Comparator<? super T> comparator)
// maximum
en

• Optional<T> reduce(BinaryOperator<T> accumulator)


// to reduce
• Optional<T>findFirst()
// to find first
C

• Optional<T>findAny()
// to find any

Spliterator interface is used to support the parallel execution.Spliterator(trySplit)


h

method which produces a new Spliterator that manages a subset of the elements of the original
Spliterator.
ec

© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 29


pt

Explain that:
The Optional class and Spliterator interface defined in java.util package are
rA

used with Stream API.

Optional is a container object that optionally contains a value (non-null). Stream


Fo

operators use optional, when it is not sure about the result. isPresent() function is
called to check for any contents in the stream. The get() method is used to extract the
output, if Option has values.

Spliterator interface is used to support parallel execution of processes. The


trySplit() method produces a new Spliterator that manages a subset of the
elements of the original Spliterator.

Using a Spliterator, the input array or collection is divided into a numerous sub-arrays
or collections. For each of these sub-arrays or collections, a parallel thread is used to execute
the stream pipeline.

© Aptech Limited
Stream API

Slide 30

Let us understand about parallelism.

Parallelism

• Parallelism is splitting a task into its sub-tasks and then simultaneously running these tasks to
merge their outputs.

• Adding a parallel() method to the Stream instructs the library to deal with the complexities
of threading. Thus, the library controls the process of forking.

y
nl
O
se
© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 30

Explain about parallelism. rU


te
Explain that:
Parallelism is splitting a task into its sub-tasks and then simultaneously running these tasks
en

to merge their outputs. Parallelism executes with parallel streams. It divides streams into
multiple subtasks and merges them. Thus, parallel() method helps in dividing a work. It
C

is similar to an intermediate operation.

Adding a parallel() method to the Stream instructs the library to deal with the
h

complexities of threading. Java 8 consists of fork/join framework that aids in implementation


ec

of parallel computing by splitting the work into subtasks. After splitting, the task waits until
all the subtask finish executing. Then, the task joins all the results into one single result.
pt
rA
Fo

© Aptech Limited
Stream API

Slides 31 to 34

Let us understand how to execute streams in parallel.

Executing Streams in Parallel 1/4


❖ Aggregate operations are implemented to combine the results.

❖ This process is known as concurrent reduction.

❖ Following conditions must be true for performing a collect operation in the process:

y
• The Stream must be parallel.

nl
• The parameter of the collect operation, the collector, contains the
characteristic Collector.Characteristics.CONCURRENT.

O
• Stream must be unordered or the collector must contain the
Collector.Characteristics.UNORDERED.

se
© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 31

rU
Executing Streams in Parallel 2/4
Following example shows a complete program with various Stream API operations:
te
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
en

import java.util.stream.Collectors;
public class AptechJavaStreamAPI {
public static void main(String args[]) {
List<String> clientList = Arrays.asList("Flipkart",
"Snapdeal", "PayTm", "King","","", "MaBeats", "Miniclip");
C

System.out.println("^The new Client List: " + clientList);


System.out.println("Result2:no. of clients with name length > 5: " + lengthCount);
//To receive the client name starts with letter 'A' and display count
long startCount = clientList.stream().filter(x –> x.startsWith("M")).count();
System.out.println("Result3:no. of clients which name starts with letter M: " +
h

startCount);
// To eliminate all empty Strings from List
List<String>removeEmptyStrings =
ec

clientList.stream().filter(x → !x.isEmpty()).collect(Collectors.toList());
System.out.println("Result4:no. New Client List without empty list" +
removeEmptyStrings);
// To display the client names with > 8 characters
Fundamental Programming in Java -Session 16 / Slide 32
pt

© Aptech Ltd.

Executing Streams in Parallel 3/4


rA

List<String>newList = clientList.stream().filter(x –>x.length() >


8).collect(Collectors.toList());
System.out.println("Result5: New client list with letter count > 8: " + newList + "\n");
List<Integer>aptechInt = Arrays.asList(77,66,888, 22, 33,7, 121, 89,55);
IntSummaryStatistics aptechStats = aptechInt.stream().mapToInt((x) ->
Fo

x).summaryStatistics();
System.out.println("^ A list of Random numbers: " + aptechInt);
System.out.println("Highest number in the lot -" + aptechStats.getMax());
System.out.println("Lowest number in the lot -" + aptechStats.getMin());
System.out.println("Combined value of All: " + aptechStats.getSum());
System.out.println("Average value of all numbers: " + aptechStats.getAverage() + "\n");
// To convert a Message in UPPERCASE and join them using space
List<String>aptechTips = Arrays.asList("java8", "has", "some", "great", "features");
String joinList = aptechTips.stream().map(x ->
x.toUpperCase()).collect(Collectors.joining(" "));
System.out.println("- To Join and Display the message with UPPERCASE: " + joinList);
// To display the cube value of the numbers
List<Integer> numbers = Arrays.asList(5,10,15,20,25);
List<Integer> cubes = numbers.stream().map(myInt ->myInt *
myInt * myInt).distinct().collect(Collectors.toList());
System.out.println("- Display the cube value of the numbers : " + cubes + "\n");
}
}
© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 33

© Aptech Limited
Stream API

Executing Streams in Parallel 4/4

Output:
$javac AptechJavaStreamAPI.java 2>&1
^The new Client List: [Flipkart, Snapdeal, PayTm, King, , , MaBeats, Miniclip]
Result1:no. of Empty Strings: 2
Result2:no. of clients with name length > 5: 4
Result3:no. of clients which name starts with letter M: 2
Result4:no. New Client List without empty list[Flipkart, Snapdeal, PayTm, King,
MaBeats, Miniclip]
Result5: New client list with letter count > 8: []
^ A list of Random numbers: [77, 66, 888, 22, 33, 7, 121, 89, 55]
Highest number in the lot -888
Lowest number in the lot -7
Combined value of All: 1358
Average value of all numbers: 150.88888888888889
- To Join and Display the message with UPPERCASE: JAVA8 HAS SOME GREAT FEATURES

y
- Display the cube value of the numbers : [125, 1000, 3375, 8000, 15625]

nl
O
© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 34

se
Explain about aggregate operations.

Explain that:
rU
Aggregate operations are implemented to combine the results. This process is known as
concurrent reduction. Aggregate operations process elements from a stream. A sequence of
aggregate operations is known as pipeline. You can customize the behavior of an aggregate
te
operator by using lambda expression as parameter. Aggregate operations do not contain a
method such as next to process the next element within a collection.
en

Explain the code snippet that shows a complete program with various Stream API
C

operations.

Explain that:
h

In the code snippet, a list is created for strings Flipkart, Snapdeal, PayTm, King, MaBeats, and
ec

Miniclip, including two empty lists.

The line System.out.println("^The new Client List: " +


pt

clientList) is used to count the number of empty strings.


rA

Then, the line System.out.println("Result2:no. of clients with name


length > 5: " + lengthCount); shows name of clients with length of more than
Fo

five characters.

The line long startCount = clientList.stream().filter(x –>


x.startsWith("M")).count(); shows the client name starts with letter ‘M' and
displays the count.

The line List<String>removeEmptyStrings =


clientList.stream().filter(x →
!x.isEmpty()).collect(Collectors.toList()); eliminates all empty strings
from lists and lists the client names without the empty strings.

© Aptech Limited
Stream API

Continue the explanation of the code snippet that shows a complete program with various
Stream API operations.

Explain that:
Finally, the client names with more than eight characters are displayed, in the code snippet
List<String>newList = clientList.stream().filter(x –
>x.length() >8).collect(Collectors.toList());

An array of numbers are taken 77, 66, 888, 22, 33, 7, 121, 89, 55 then,
aptechStats.getMax() method picks the highest number in the list,

y
aptechStats.getMin() method picks the lowest number in the lot,

nl
aptechStats.getSum() method gets the sum of all the values and
aptechStats.getAverage() method is used to calculate the average value of all

O
numbers.

se
A list of strings, ("java8", "has", "some", "great", "features") is created and they are
converted into uppercase, aptechTips.stream().map(x ->
x.toUpperCase()).collect(Collectors.joining(" "));
rU
Finally, an array of numbers is created with 5, 10, 15, 20, and 25 and its cubic value is
calculated, numbers.stream().map(myInt ->myInt *myInt *
te
myInt).distinct().collect(Collectors.toList());
en

Using slide 34, explain the output of the code snippet that shows a complete program with
various Stream API operations.
C

Slide 35
h

Let us look at the limitations of Java Stream API.


ec

Limitations of Java Stream API


pt
rA

• Once a Stream is consumed, it cannot be used


later.
Fo

• Learning is time-consuming and cumbersome due


to overloaded Stream APIs.

© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 35

Explain the limitations of Java Stream API.

© Aptech Limited
Stream API

Explain that:

There are many advantages of the Java Stream API, however, there are a few drawbacks too.

Some of these are:


• Once a Stream is consumed, it cannot be used later.
• There are vast number of methods in Stream APIs. Therefore, learning is time-consuming
and cumbersome due to overloaded Stream APIs.
• Parallel processing is not always beneficial as it may speed up or slow down an
application based on the nature of the application.

y
• Parallel streams are unpredictable and are complex to use.

nl
Additional Information:

O
Use the following links for additional reference:

se
http://www.javaworld.com/article/2095503/java-se/uses-and-limitations-of-the-stream-api-
in-java-8.html
https://blog.jooq.org/2014/06/13/java-8-friday-10-subtle-mistakes-when-using-the-
streams-api/

Slide 36
rU
te
Let us summarize the session.
en

Summary
❖ The new Stream API in Java 8 supports many sequential and parallel aggregate
C

operations
❖ Stream API interfaces and classes are contained within java.util.stream
package
h

❖ The foundation of the Stream API is Stream interface and Collectors class
❖ Some of the interfaces in the API include IntStream, LongStream, and
ec

DoubleStream
❖ Streams are lazily implemented and support parallel operation
❖ Function denotes a function that gets one type of element and produces another
pt

type of element
❖ The Optional class and Spliterator interface defined in java.util package can
rA

be used with Stream API


❖ Commonly used functional interfaces with Stream API include Function and
BiFunction, Predicate and BiPredicate, Consumer and BiConsumer, and Supplier
Fo

© Aptech Ltd. Fundamental Programming in Java -Session 16 / Slide 36

Use the slide to summarize the session. You will end the session, with a brief summary of
what has been taught in the session. Tell the students pointers of the session. This will be a
revision of the current session.

Explain that:
The new Stream API in Java 8 supports many sequential and parallel aggregate operations.
Stream API interfaces and classes are contained within java.util.stream package. The
foundation of the Stream API is Stream interface and Collectors class. Some of the interfaces
in the API include IntStream, LongStream, and DoubleStream. Streams are lazily

© Aptech Limited
Stream API

implemented and support parallel operation. Function denotes a function that gets one type
of element and produces another type of element. The Optional class and Spliterator
interface defined in java.util package can be used with Stream API. Commonly used
functional interfaces with Stream API include Function and BiFunction, Predicate and
BiPredicate, Consumer and BiConsumer, and Supplier.

16.3 Post Class Activities for Faculty

You should familiarize yourself with the topics of the next session.

y
Tips:

nl
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to gain
additional information related to the topics covered in the next session. You can also connect

O
to online tutors on the OnlineVarsity site to ask queries related to the sessions.

se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
More on Functional Programming

Session 17 – More on Functional Programming


17.1 Pre-Class Activities

Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.

17.1.1 Objectives

y
By the end of this session, learners will be able to:

nl
➢ Explain functional interfaces

O
➢ Describe immutability in Java
➢ Define and explain concurrency in Java

se
➢ Explain Recursion in Java

17.1.2 Teaching Skills


rU
To teach this session, you should be well versed with the concepts of advanced functional
programming in Java. You should be familiar with various functional interfaces, immutability,
te
reinforcing immutability, and implementing concurrency. You must also be familiar with
recursion techniques in Java.
en

You should teach the concepts in the theory class using the images provided. For teaching in
C

the class, you are expected to use slides and LCD projectors.

Tips:
h

It is recommended that you test the understanding of the students by asking questions in
ec

between the class.


pt

In-Class Activities
rA

Follow the order given here during In-Class activities.

Overview of the Session


Fo

Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.

© Aptech Limited
More on Functional Programming

Slide 2

y
nl
O
se
Show the slide and give the students a brief overview of the current session in the form of

rU
session objectives. Tell the students that this session explains about functional interfaces.
The session will cover immutability in Java and explains about concurrency in Java. Finally, it
explains about recursion in Java.
te
17.2 In-Class Explanations
en

Slide 3
C

Let us see an introduction to functional interfaces.


h
ec
pt
rA
Fo

Tell the students that they learnt about functional programming in an earlier session. Explain
that Java is basically an object-oriented programming language. With the introduction of
lambda expressions and method references, it is possible to implement functional
programming in Java 8.

© Aptech Limited
More on Functional Programming

An interface with only one abstract method is known as a functional interface. Some examples
of functional interfaces are Runnable, Comparable, and Cloneable. Comparable
interface has a method called compareTo() used for comparison purposes.

Additional Information:

Refer the following link for more information:

https://www.tutorialspoint.com/java8/java8_functional_interfaces.htm

y
Slide 4

nl
Let us understand Function <T, R> interface.

O
se
rU
te
en
C
h

Explain about Function <T, R> interface.


ec

Explain that:
pt

In Java, java.util.Function package defines a list of functional interfaces to be used in


rA

lambda expressions.

Function<T, R> is a function that accepts one argument as input to produce the output.
Fo

An argument of type T is given as input to the lambda expression. It produces an object of


type R as output. This function is mainly used when an object of specific type is given as input
and is converted into another type.

For example, the following lambda expression can be used to define an interface to check for
new products:
IProduct newProductChecker = (Product p) ->
p.getStatus().equals("New");

© Aptech Limited
More on Functional Programming

Here, the argument p returns an output of type boolean by checking the type of the product
whether new or old.

Slides 5 and 6

Let us explore the key points under functional interfaces.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slide 5, explain about the parameters of Function <T, R> interface and about
apply(), compose() and andThen() methods.

Explain that:
The apply() method is the primary abstract method of Functional interface. It is
generally used to convert a list to map or transform one object to another. In this example, a
student is mapped to a course.

Function<Student, Course> mapStudenttoCourse = new


Function<Student, Course>() {

© Aptech Limited
More on Functional Programming

public Course apply(Student student) {


Course crse = new Course(Student.getStudentId(),
student.getName());
return crse;
}

Using slide 6, explain the difference between compose() and andThen() methods.

Consider the following code:

y
Function<Integer, Integer> prod2 = x -> x * 2;
Function<Integer, Integer> squaredprod = x -> x * x;

nl
prod2.compose(squared).apply(3);
prod2.andThen(squared).apply(3);

O
The compose() method returns 18, while andThen() method returns 36.

se
Slides 7 and 8

rU
Let us understand the andThen() and compose() methods.
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
More on Functional Programming

y
nl
O
se
Using slide 7, explain the syntax of andThen() method.

Explain that:

rU
The following code converts a given input into lowercase:
import java.util.function.Consumer;
te
public class Main {
public static void main(String[] args) {
en

Consumer<String> change = (a) ->


System.out.println(a.toLowerCase());
change.andThen(change).accept(“YOU WILL SEE THIS LINE IN
C

LOWER CASE”);
}
h

}
ec

Using slide 8, explain the syntax of compose() method.


pt

Additional Information:
rA

Refer to the following link to explain how to achieve functional composition using
andThen() and compose() methods:
Fo

http://www.deadcoderising.com/2015-09-07-java-8-functional-composition-using-compose-
and-andthen

© Aptech Limited
More on Functional Programming

Slides 9 and 10

Let us understand the identity() function and see an example how to use the method.

y
nl
O
se
rU
te
en
C
h
ec
pt

Using slide 9, explain about identity() method.


rA

Explain that:
Identity method always return its input argument. For example, the following code produces
Fo

an output of 9.

Function<Integer,Integer> id = Function.identity();
System.out.println(id.apply(9));

Using slide 10, explain the method that can be used in a chain for creating a method shown in
the code.

© Aptech Limited
More on Functional Programming

Explain that:
Resultant method will acquire an integer, multiply it by 2 and finally, append ‘sampleStr’
to it.

Additional Information:

Refer the following link for more information:

http://www.java2s.com/Tutorials/Java/java.util.function/Function/1080__Function.identity.
htm

y
nl
Slide 11
Let us see a complete program demonstrating the methods.

O
se
rU
te
en
C
h
ec

Using this slide, explain the code how to implement displayDateTime() method.

Explain that:
pt

The code iterates through days and displays date and time two months from today's date using
functional interfaces and use the limit() method to limit the stream to a size of 10, map()
rA

method converts Integer stream to String stream, and collect() method joins the results.
Fo

When you execute the code, the output will be:

2016-12-31T02:02, 2017-01-01T02:02, 2017-01-02T02:02, 2017-01-03T02:02, 2017-01-


04T02:02, 2017-01-05T02:02, 2017-01-06T02:02, 2017-01-07T02:02, 2017-01-08T02:02,
2017-01-09T02:02

© Aptech Limited
More on Functional Programming

Slides 12 to 17

Let us understand currying.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
More on Functional Programming

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slide 12, explain about currying process.

© Aptech Limited
More on Functional Programming

Explain that:
The currying process works by subdividing the task and working on the in-between results.

Consider in the given example, we use the method for calculating sum of two numbers say
f(a,b)= a+b.

The currying process subdivides the task as:


f(2,b)=2+b
g(b)=2+b
f(2,b)=g(b)=2+b

y
f(2,3)=g(3)=2+3=5

nl
Using slide 13, explain the basic pattern of all unit conversions. Using slide 14, explain about

O
the usage of curry converter method. Then, using slide 15, explain the pattern of all unit
conversions.

se
Explain that:

rU
Conversion factor and baseline(e and b) is passed to the code which returns a function
to do the expected calculation. DoubleUnaryOperator defines a method
applyAsDouble().
te
Using slide 16, explain the code that demonstrates the usage of the compose() method.
en

Explain that:
C

In the curryfunction() method, adder.apply(x,y) will add the two integers 2, 7


and display the result. In the method addFour.compose(timesFive), values 7 and 4
h

are added and the result is multiplied with 5. In the method


ec

timesFive.compose(addFour), 7 and 5 are multiplied and the result is added with 4.


pt

Using slide 17, explain the output of the code.


rA

Additional Information:

Refer the following links for more information:


Fo

http://www.beyondjava.net/blog/java-8-functional-programming-language/
https://gist.github.com/timyates/7674005

© Aptech Limited
More on Functional Programming

Slides 18 to 21
Let us explore immutability.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
More on Functional Programming

y
nl
O
se
Explain that:
Immutability remains unchanged. If a class has only static members, then the objects of the
class are immutable. Immutability helps to ensure thread safety.

rU
Using slide 19, explain about immutability objects.
te
Explain that:
Immutable objects are consistent, thread safe, and hence, can be shared safely among
en

threads. All its members must be final and private.


C

Using slide 20, explain about immutable class.

Explain that:
h
ec

An immutable class is stateless. Its properties does not change once it is initialized. All class
members of immutable class are declared final. The child objects of immutable class are also
immutable.
pt
rA

Using slide 21, explain the steps to implement immutable class.

Additional Information:
Fo

Refer the link


https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html to explain
about immutable objects and the strategy to define immutable objects.

Refer the link http://stackoverflow.com/questions/6305752/how-to-create-immutable-


objects-in-java to explain the features of immutable class.

Refer the following link for more information:


https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html

© Aptech Limited
More on Functional Programming

Slides 22 and 23

Let us understand concurrency.

y
nl
O
se
rU
Concurrency 2/2
te
en

❖ Concurrency also has the method ❖The CompletableFuture class


C

thenAccept() which accepts a calls on the specified supplier in a


Consumer that manages diverse thread and executes the
completion of the task. consumer when it is complete.
h
ec
pt

© Aptech Ltd. Fundamental Programming in Java -Session 17 / Slide 23


rA

Using slide 22, explain about concurrency. Mention that concurrency was supported in Java
in earlier versions too (since Java 5) but is made better in Java 8. Give some examples to
illustrate the concept of concurrency. Say that end-users assume that their systems can
Fo

perform multiple actions at a time. Often, even a single program is expected to perform
more than one task at a time. Software that can do such tasks is known as concurrent
software. A well-written program uses concurrency to ensure that the program is always
responsive to user interaction, even when it is already doing something else.

Explain that:

CompleteableFuture class in Java 8 implements the Future interface and


CompletionStage interface. It supports lambda expressions, parallelism, and is event
driven. supplyAsync() method helps to run tasks asynchronously.

© Aptech Limited
More on Functional Programming

Using slide 23, explain about thenAccept method and CompleteableFuture class.

thenAccept() method takes a Consumer as an argument and applies Consumer to


handle the result of the preceding computation and returns CompleteableFuture.

Additional Information:

Refer the following links for more information:


http://docs.oracle.com/javase/tutorial/essential/concurrency/procthread.html
https://examples.javacodegeeks.com/core-java/util/concurrent/java-8-concurrency-tutorial/

y
http://www.deadcoderising.com/java8-writing-asynchronous-code-with-completablefuture/

nl
Slides 24 to 28

O
Let us understand recursion.

se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
More on Functional Programming

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slide 24, explain about recursion.


Explain that:
A method that calls itself is said to be recursive.

© Aptech Limited
More on Functional Programming

Using slides 25 to 28, explain the difference between recursion and factorial constructs.

Recursion is faster when there are lesser elements. When the value of the nth element
increases recursion becomes slower and iteration becomes faster.

Additional Information:

Refer the following links for more information:

https://dzone.com/articles/do-it-java-8-recursive-and

y
http://www.programcreek.com/2012/10/iteration-vs-recursion-in-java/

nl
https://howtoprogramwithjava.com/java-recursion/

O
In-Class Question:

se
After you finish explaining slide 28, you will ask the students some In-Class questions. This
will help you in reviewing their understanding of the topic.

rU
te
What is the output for the following method?
en

Function<Integer, Integer> times2 = e -> e * 2;


Function<Integer, Integer> squared = e -> e * e;
times2.compose(squared).apply(4);
C

times2.andThen(squared).apply(4);

Answer:
h

32
ec

64
pt
rA

What would be the output for the following program?

public static void main(String[] args)


Fo

{
IntBinaryOperator simpleAdd = (a, b) -> a + b;
IntFunction<IntUnaryOperator> curriedAdd = a -> b -
> a + b;
out.println(simpleAdd.applyAsInt(4, 5));
out.println(curriedAdd.apply(4).applyAsInt(5));
IntUnaryOperator adder5 = curriedAdd.apply(5);
out.println(adder5.applyAsInt(4));
out.println(adder5.applyAsInt(6));
}

© Aptech Limited
More on Functional Programming

Answer:
9
9
9
11

Will the program compile without error, if yes, what will be the output?

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

nl
Function<Integer,Integer> id = Function.identity();
System.out.println(id.apply(3));

O
}

se
Answer: Yes, the program compiles without any error.

The output will be: 3


rU
te
What will be the output for the following code? Also, explain the output.
en

class Testimmutablestring{
public static void main(String args[]){
C

String a="Anthony";
a.concat(" Mathews");
System.out.println(a);
h

}
ec

}
Answer: The output is Anthony
pt

It will print Anthony since strings are immutable objects.


rA
Fo

© Aptech Limited
More on Functional Programming

Slide 29

Let us summarize the session.

y
nl
O
se
rU
Use slide 29 to summarize the session. You will end the session, with a brief summary of what
has been taught in the session. Tell the students pointers of the session. This will be a revision
te
of the current session.
en

Explain that:
Functional interfaces acts as a key element to implement functional programming in Java.
Functional interfaces are defined in java.util.function package, which is new to Java
C

8. A functional interface has only one abstract method. Currying is a process that transforms
a method having multiple arguments into a method with a single entity that returns a method.
h

Immutability is the capability of an object to resist or prevent change. In Java programming, a


ec

feature that permits a method to call itself is called recursion.

17.3 Post Class Activities for Faculty


pt

You should familiarize yourself with the topics of the next session.
rA

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to gain
Fo

additional information related to the topics covered in the next session. You can also connect
to online tutors on the OnlineVarsity site to ask queries related to the sessions.

© Aptech Limited
Additional Features of Java 8

Session 18 – Additional Features of Java 8


18.1 Pre-Class Activities

Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.

18.1.1 Objectives

y
By the end of this session, learners will be able to:

nl
➢ Explain the Nashorn Engine

O
➢ Describe the jjs tool and its use for scripting
➢ Explain the new mathematical functions in Java 8

se
18.1.2 Teaching Skills

rU
To teach this session, you should be well versed with JavaScript and Nashorn. You should be
aware of how to invoke JavaScript code from within Java programs through Nashorn.
te
You should teach the concepts in the theory class using the images provided. For teaching in
en

the class, you are expected to use slides and LCD projectors.

Tips:
C

It is recommended that you test the understanding of the students by asking questions in
between the class.
h

In-Class Activities
ec

Follow the order given here during In-Class activities.


pt

Overview of the Session


rA

Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.
Fo

© Aptech Limited
Additional Features of Java 8

Slide 2

y
nl
O
se
Show the slide 2 and give the students a brief overview of the current session in the form of
session objectives. Tell the students that they will be introduced to the Nashorn Engine. Then,
rU
describe the jjs tool and explain how it is used for scripting. Finally, explain the new
mathematical functions in Java 8.
te
18.2 In-Class Explanations
en

Slides 3 and 4

Let us see an introduction to Nashorn.


C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

y
nl
O
se
Explain about Nashorn Engine. Explain the reason for Nashorn replacing the Rhino engine that
is the JavaScript engine in versions up to Java 7. Also, list the advantages of using Nashorn.

Explain that:
rU
Nashorn is a new JavaScript engine of Java 8. A German tank destroyer named Rhinoceros was
used in World War II. Nashorn is a German term, which means Rhinoceros. Jim Laskey of
te
Oracle was the main developer of Nashorn.
en

Using slide 4, explain the main goal of Nashorn.


C

Explain that:
Nashorn is made available to Java applications using javax.script API and also using a
new command-line tool called jjs.
h
ec

Additional Information:
pt

Refer to the following links for more information on Nashorn:


rA

http://openjdk.java.net/jeps/174
https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jjs.html
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
Fo

http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

© Aptech Limited
Additional Features of Java 8

Slide 5

Let us explore the goals for which Nashorn was designed.

y
nl
O
se
rU
Using this slide, explain the primary goals of Nashorn.
te
Explain that:
Nashorn follows the ECMAScript-262 Edition 5.1 language specification and complies with
en

ECMAScript-262 compliance tests.

Additional Information:
C

Refer to the following links to know more about Nashorn:


h
ec

https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jjs.html
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
pt

http://www.javaworld.com/article/2144908/scripting-jvm-languages/nashorn--javascript-
made-great-in-java-8.html
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slide 6

Let us look at jjs tool.

y
nl
O
se
Using slide 6, explain about jjs tool.
rU
te
Explain that:
jjs is the command line tool used for running JavaScript through Nashorn. It is located in
en

JDK_HOME\bin directory. You can use the command to execute shell scripts and script files.
C

Additional Information:

Refer to the following link to know more about jjs:


h
ec

https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jjs.html
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slides 7 and 8

Let us view some code demonstrating use of jjs tool.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA

Using slide 7, explain the code to execute a JavaScript program using Nashorn, launch the jjs
interpreter in interactive mode and to exit from the interactive mode of jjs.
Fo

Using slide 8, explain the code to find the sum of some numbers.

Explain that:
In the code, the function returns sum of 1 and 3. Then, in the subsequent iterations, the
function adds the result to the next number in the array. Finally, the answer obtained is 27.

© Aptech Limited
Additional Features of Java 8

Slide 9
Let us understand the structure of jjs tool.

y
nl
O
se
Explain the structure of jjs tool.
rU
You can use the following syntax to print a list of options:
te
jjs –xhelp
en

The options -classpath <path> and -cp <path> both are used to set CLASSPATH.
C

–fv option prints the full version of the Nashorn engine. Some options may start with double
hyphens.
h
ec

If you do not mention any option, jjs is run in interactive mode. In interactive mode, the script
is interpreted as you enter it.
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slide 10

Let us view some code demonstrating interactive mode using jjs.

y
nl
O
se
rU
Using this slide, explain the code that shows how to invoke Nashorn in interactive mode and
assign sampleValue to the property named sampleKey and then retrieve it using
te
getProperty() method.
en

Explain that:
C

The syntax for –D option is


-D<name>=<value>
h

You can use the option to set system properties for Java runtime.
ec

option –Dname = value can be repeated with appropriate modifications to set multiple
runtime properties.
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slide 11
Let us understand how to set multiple properties with jjs.

y
nl
O
se
rU
Using this slide, explain the method to set multiple properties in the jjs tool.

Explain that:
te
jjs tool automatically enables the scripting mode if a script file run by the jjs tool begins with
# sign. Then, the entire script is executed in scripting mode.
en

Slide 12
C

Let us understand scripting in jjs.


h
ec
pt
rA
Fo

Using this slide, explain about the scripting option of jjs tool.

© Aptech Limited
Additional Features of Java 8

Explain that:
Using the -scripting option, jjs is run in scripting mode. The option allows you to use any
operating system-specific shell commands.

When a script file begins with the # sign, executing the script file automatically enables
scripting mode.

Slides 13 to 17
Let us explore the ScriptEngine in Nashorn.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

Using slides 13 and 14, explain about the ScriptEngine interface and
ScriptEngineManager class.

© Aptech Limited
Additional Features of Java 8

Explain that:
The instances of ScriptEngine interface executes scripts written in a scripting language.

Using slide 14, explain about the ScriptEngineManager class. Explain the code that
shows how to use ScriptEngineManager class in Java.

Explain that:
The method in the following code returns the final value as an object:

import javax.script.ScriptEngine;

y
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

nl
public class mymath {

O
public static void main(String[] args) throws ScriptException
{

se
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(“Nashorn”);

Object findings= null;


rU
findings = engine.eval(“5 * 6; 2 * 4; 3 * 4; 2 * 9; 2 * 3;”);
System.out.println(findings);
te
}
en

On compilation, the answer obtained will be 6.


C

Explain how evaluation of JavaScript is done.


h
ec

Explain that:
ScriptException is a checked Exception, so the compiler will force you to handle this.
The try-catch block is necessary in a code to handle the ScriptException properly.
pt

Additional Information:
rA

Refer the following link of sample codes to learn on ScriptException.


Fo

https://github.com/shekhargulati/java8-the-missing-tutorial/blob/master/10-nashorn.md

Using slide 16, continue to explain the code and then, describe FileReader instance and
explain the code that demonstrates the usage of FileReader instance.

Explain that:
A .js file can be parsed by passing a FileReader object pointing to the file. For example,

ScriptEngine myengine = new


ScriptEngineManager().getEngineByName("nashorn");

© Aptech Limited
Additional Features of Java 8

myengine.eval(new FileReader(“newfile.js"));
You can also pass a string to the eval method of the engine object.

ScriptEngine myengine = new


ScriptEngineManager().getEngineByName("nashorn");
myengine.eval(“Learning Nashorn");

Using slide 17, explain the code that demonstrates the usage of newEngManager, an
instance of ScriptEngineManager.

y
Explain that:
You can use Nashorn engine names such as "nashorn", "javascript", and "js".

nl
O
Slides 18 and 19

Let us explore how to import Java classes and packages into JavaScript.

se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Using slides 18 and 19, explain the code to import java.util package and other packages
into a JavaScript program so that Java classes, interfaces, and methods can be used in
JavaScript.

Explain that:
JavaImporter is a function object that accepts a list of Java packages and classes.

To import all classes from the java.lang package, you can specify:
var importlangpackage = new JavaImporter(Packages.java.lang);

y
Similarly, you can import all classes from various packages. For example, to import the

nl
java.lang and java.util packages, you can specify:

O
var importlangpackagenew = JavaImporter(java.lang, java.util);

se
Note that, in this code, the new operator is not used, because here, JavaImporter is being
used as a function.

rU
Using slide 19, explain the code that shows usage of .write() method.

Explain that:
te
To write a string to a stream, it must be converted to bytes.
The .write() method helps to write character data to a stream. getBytes() method
en

returns the byte array of the string.


C

Additional Information:

Refer to the following link for more practical examples:


h
ec

https://github.com/gAmUssA/java-scripting-experiments
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slide 20
Let us look at how to extend Java classes and interfaces in JavaScript.

y
nl
O
se
rU
Using this slide, describe the functions that are used to extend Java classes. Explain the code
that shows an example with Callable interface and call method implementation.
te
Explain that:
Callable interface binds a task and passes it to a thread pool for executing it
en

asynchronously. Callable interface returns a value. The interface consists a call()


method that holds the code that is to be executed asynchronously.
C

Additional Information:
h

Refer to the following link for more information:


ec

http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-
pt

examples/
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slides 21 and 22
Let us examine the Invocable interface.

y
nl
O
se
rU
te
en
C
h
ec
pt

Using slide 21, describe Invocable Interface.


rA

Explain that:
Invocable interface helps to invoke procedures, functions, and methods. A script engine
Fo

class invoking procedure must implement the Invocable interface. The


invokeMethod() method helps to invoke a method of an object. The
invokeFunction() method helps to invoke the top level functions in the script. The
getInterface() method is used to get the implementation of a Java interface.

Using slide 22, describe the invokeFunction() method.

© Aptech Limited
Additional Features of Java 8

Additional Information:

Refer to the following link for more examples on Invocable interface:

http://www.programcreek.com/java-api-examples/index.php?api=javax.script.Invocable

Slides 23 to 29
Let us explore mathematical methods in Java 8.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

y
nl
O
se
rU
te
en
C
h
ec

Using slide 23, state various mathematical methods available in java.lang package. Tell
pt

the students that they may need to use these methods in complex calculations or in
calculations related to everyday tasks too. For example, while calculating price of products or
rA

weight of some item.

Using slide 24, explain Math.abs() method and using slide 25, explain various parameters
Fo

that are used to overload Math.abs() method.

Using slide 26, explain the Math.ceil() method and using slide 27, explain the
Math.floor() method.

Using slide 28, explain the difference between the Math.floor() and Math.ceil()
method, tell them the Math.floor() and Math.ceil() methods works fine in itself, but
they will return same value only when the input value is an integer. Using slide 29, explain the
remaining Math methods.

© Aptech Limited
Additional Features of Java 8

Additional Information:
Refer the following links for more information:

http://www.jchq.net/tutorial/09_01Tut.htm
http://www.cafeaulait.org/course/week4/40.html

In-Class Question:

After you finish explaining slide 29, you will ask the students some In-Class questions. This
will help you in reviewing their understanding of the topic.

y
nl
O
What will be output of the statement System.out.println(Math.abs(-
52.1))?

se
Answer: 52.1
Code:
import java.lang.Math;
public class BasicMathDemo {
public static void main(String args[]) {
rU
System.out.println(Math.abs(-52.1));
te
}
}
en
C

What will be output of the statement System.out.println(Math.ceil(-


52.1));?
h

Answer: -52.0
ec

Code:
import java.lang.Math;
public class BasicMathDemo {
pt

public static void main(String args[]) {


System.out.println(Math.ceil(-52.1));
rA

}
}
Fo

What will be output of the statement


System.out.println(Math.floor(-52.1));?

Answer: -53.0
Code:
import java.lang.Math;
public class BasicMathDemo {
public static void main(String args[]) {

© Aptech Limited
Additional Features of Java 8

System.out.println(Math.floor(-52.1));
}
}

Slides 30 to 34
Let us understand the usage of exponential and logarithmic methods in Java 8.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Using slides 30 to 34, explain various exponential and logarithmic Math methods in Math
class. These methods include Math.exp(), Math.log(), Math.pow(), and
Math.sqrt().

Additional Information:
Refer the following links for more information:

http://www.jchq.net/tutorial/09_01Tut.htm
http://www.cafeaulait.org/course/week4/40.html

y
In-Class Question

nl
After you finish explaining slide 34, you will ask the students some In-Class questions. This

O
will help you in reviewing their understanding of the topic.

se
rU
What will be the output of the expression Math.exp(0)?

Answer: 1.0
te
Code demonstrating the output:
en

import java.lang.Math;
public class BasicMathDemo {
C

public static void main(String args[]) {


System.out.println(Math.exp (0));
}
h

}
ec
pt

What will be the output of the expression Math.log(1)?


rA

Answer: 0.0
Fo

Code demonstrating the output:

import java.lang.Math;
public class BasicMathDemo {
public static void main(String args[]) {
System.out.println(Math.log(1));
}
}

© Aptech Limited
Additional Features of Java 8

What will be the output of the expression Math.sqrt(7)?

Answer: 2.6457513110645907

Code demonstrating the output:

import java.lang.Math;
public class BasicMathDemo {

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

nl
System.out.println(Math.sqrt(7));
}

O
}

se
rU
What will be the output of the expression Math.pow(7, 2)?

Answer: 49.0
te
Code demonstrating the output:
en

import java.lang.Math;
public class BasicMathDemo {
C

public static void main(String args[]) {


System.out.println(Math.pow(7, 2));
}
h

}
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slides 35 to 45

Let us explore the various trigonometric methods available in Math class.

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

y
nl
O
se
rU
te
en
C
h
ec

Using slides 35 to 45, explain about the various trigonometric methods available in Math
class.
pt

Additional Information:
rA

Refer to the following links for more information:


Fo

https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin
http://www.cafeaulait.org/course/week4/40.html

© Aptech Limited
Additional Features of Java 8

In-Class Questions:

After you finish explaining slide 34, you will ask the students some In-Class questions. This
will help you in reviewing their understanding of the topic.

What will be the output of


System.out.println(Math.sin(Math.PI/2));?

y
Answer: 1.0

nl
Code:
import java.lang.Math;

O
public class BasicMathDemo {
public static void main(String args[]) {

se
System.out.println(Math.sin(Math.PI/2));
}
}
rU
te
What will be the output of System.out.println(
en

Math.sinh(0));?

Answer: 0.0
C

Code:
h

import java.lang.Math;
public class BasicMathDemo {
ec

public static void main(String args[]) {


System.out.println(Math.sinh(0));
pt

}
}
rA
Fo

What will be output of System.out.println(Math.cosh(0));?

Answer: 1.0

Code:
import java.lang.Math;
public class BasicMathDemo {
public static void main(String args[]) {
System.out.println(Math.cosh(0));
}
}

© Aptech Limited
Additional Features of Java 8

What will be the output of System.out.println(Math.cos(2 *


Math.PI));?

Answer: 1.0

Code:
import java.lang.Math;
public class BasicMathDemo {

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

nl
System.out.println(Math.cos(2 * Math.PI));
}

O
}

se
rU
What will be output of System.out.println(Math.tanh(0));?

Answer: 0.0
te
Code:
en

import java.lang.Math;
public class BasicMathDemo {
C

public static void main(String args[]) {


System.out.println(Math.tanh(0));
}
h

}
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slides 46 and 47
Let us examine exact numeric operations.

y
nl
O
se
rU
te
en
C
h
ec
pt

Using slide 46, explain various methods that are used to perform exact numeric operations.
Mention that this category of methods is new in Java 8. They did not exist in Java 7.
rA

Explain that:
addExact(): Returns the sum of its argument.
Fo

subtractExact(): Returns the difference of its arguments.


multiplyExact(): Returns the product of its arguments.
incrementExact() : Returns the argument incremented by one.
decrementExact() : Returns the argument decremented by one.
negateExact() : Returns the negation of the argument.
toIntExact(): Returns the value of the long argument.

© Aptech Limited
Additional Features of Java 8

Additional Information:

Refer to the following link for more information:


http://javatutorialhq.com/java/lang/math-class-tutorial/

Using slide 47, demonstrate the usage of addExact() method using the code shown on the
slide.

Explain that:
In the code, addExact() method returns the sum of ex1 and ex2. ex1 and ex2 must be

y
of datatype long and the result is also of datatype long. The method throws an exception

nl
if the result overflows a long.

O
Slides 48 and 49
Let us explore next numeric operations.

se
rU
te
en
C
h
ec
pt
rA
Fo

© Aptech Limited
Additional Features of Java 8

Using slide 48, explain various methods that are used to perform next numeric operations.
Mention that this category of methods is new in Java 8. They did not exist in Java 7.

Explain that:
The syntax of nextAfter() method is as follows:
public static double nextAfter(double start, double direction)

nextAfter() method returns the floating-point number next to the first argument in the
path of the second argument.

y
Following code shows usage of nextAfter method:

nl
double x=12345.678;

O
double y=125.6589;
System.out.println("You will see value after x: " +
Math.nextAfter(x, y));

se
If you execute the code, the answer will be:

rU
You will see value after x: 12345.677999999998

In-Class Question:
te
Ask the students what would be the answer if they interchange x and y.
en

Hint:
double x=12345.678;
C

double y=125.6589;
System.out.println("Now You will see value after y: " +
h

Math.nextAfter(y, x));
ec

If you execute the code, the answer will be:


Now, you will see value after y: 125.65890000000002
pt

Using slide 49, explain about the nextDown() method with the help of code on the slide.
rA
Fo

© Aptech Limited
Additional Features of Java 8

Slide 50
Let us summarize the session.

y
nl
O
se
rU
Use this slide to summarize the session. You will end the session, with a brief summary of
what has been taught in the session. Tell the students pointers of the session. This will be a
revision of the current session.
te
Explain that:
en

Nashorn and Rhino implements a JavaScript engine to enable its use with JVM. Slower
functioning of Rhino caused the need for Nashorn. jjs is a command line tool to launch
C

Nashorn. Various jjs command options control the conditions in which scripts are interpreted
by Nashorn. Nashorn enables JavaScript functions to be invoked directly from Java. Also, Java
objects can be passed as function arguments, and the resultant data can be returned back to
h

the Java method. Advanced mathematical operations can be performed with new methods in
ec

Math class.

18.3 Post Class Activities for Faculty


pt
rA

Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to gain
additional information related to the topics covered in the session. You can also connect to
Fo

online tutors on the OnlineVarsity site to ask queries related to the sessions.

© Aptech Limited

You might also like