0% found this document useful (0 votes)
96 views81 pages

Ict2215 Computer Programming 4

This document provides instructional materials for a Computer Programming 4 course. It contains 12 lessons that cover topics like Java programming basics, object-oriented programming concepts, classes and objects, constructors, methods, strings, arrays, exceptions handling, and more. The document explains how to set up the Java development environment on Windows, including downloading the Java Development Kit (JDK), installing it, and configuring environment variables to include the Java path. It aims to teach students how to design, create, build and debug Java applications and help them understand key Java concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views81 pages

Ict2215 Computer Programming 4

This document provides instructional materials for a Computer Programming 4 course. It contains 12 lessons that cover topics like Java programming basics, object-oriented programming concepts, classes and objects, constructors, methods, strings, arrays, exceptions handling, and more. The document explains how to set up the Java development environment on Windows, including downloading the Java Development Kit (JDK), installing it, and configuring environment variables to include the Java path. It aims to teach students how to design, create, build and debug Java applications and help them understand key Java concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Republic of the Philippines

POLYTECHNIC UNIVERSITY OF THE PHILIPPINES


INSTITUTE OF TECHNOLOGY
Management Technology Department

INSTRUCTIONAL MATERIALS
FOR
ICT2215
COMPUTER PROGRAMMING 4

COMPILED BY:

RAQUEL G. SALAZAR, MSIT


OVERVIEW
Java is one of the most popular and widely used programming language and platform. A
platform is an environment that helps to develop and run programs written in any programming
language.

Java is fast, reliable and secure. From desktop to web applications, scientific
supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and
corner.

Java is easy to learn and its syntax is simple and easy to understand. It is based on C++
(so easier for programmers who know C++). Java has removed many confusing and rarely-used
features e.g. explicit pointers, operator overloading etc. Java also takes care of memory
management and for that, it provides an automatic garbage collector. This collects the unused
objects automatically.

1|ICT2215COM PUTER PROGR AMMING 4


TABLE OF CONTENTS

Lesson 1 Introduction to Java Programming .......................................................................... 3

Lesson 2 Java Environment .................................................................................................... 5

Lesson 3 All About Eclipse ..................................................................................................... 8

Lesson 4 Java Programming Basics .................................................................................... 15

Lesson 5 Object Oriented Programming (OOPs) Concept in Java ..................................... 41

Lesson 6 Classes and Objects in Java ................................................................................. 47

Lesson 7 Constructors in Java .............................................................................................. 52

Lesson 8 Methods in Java .................................................................................................... 57

Lesson 9 Strings in Java ....................................................................................................... 60

Lesson 10 Arrays in Java ..................................................................................................... 63

Lesson 11 Stream in Java ..................................................................................................... 71

Lesson 12 Exceptions and Exception Handling in Java ....................................................... 74

Grading System ..................................................................................................................... 80

References............................................................................................................................. 80

2|ICT2215COM PUTER PROGR AMMING 4


COURSE OUTCOMES:
• Design, create, build and debug Java application and applets

• Apply algorithmic thinking to solve programming problems

• Implement syntax rules in Java programs

• Explain variables and data types used in program development

• Apply arithmetic operations for displaying numeric output

• Write and apply decision structures for determining different operations

• Write and apply loop structures to perform repetitive tasks

• Write user-defined methods

• Identify and implement arrays, array lists, and multidimensional arrays

LESSON 1 INTRODUCTION TO JAVA PROGRAMMING


OVERVIEW:

Java is one of the most popular and widely used programming language and platform. A
platform is an environment that helps to develop and run programs written in any programming
language.
Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to
gaming consoles, cell phones to the Internet, Java is used in every nook and corner.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:


• Understand what is Java Language
• Be able to set up java application program

COURSE MATERIALS

About Java

• Java is a simple language: Java is easy to learn and its syntax is clear and concise. It
is based on C++ (so it is easier for programmers who know C++). Java has removed

3|ICT2215COM PUTER PROGR AMMING 4


many confusing and rarely-used features e.g. explicit pointers, operator overloading etc.
Java also takes care of memory management and it also provides an automatic garbage
collector. This collects the unused objects automatically.
• Java is a platform-independent language: The programs written in Java language,
after compilation, are converted into an intermediate level language called the bytecode
which is a part of the Java platform irrespective of the machine on which the programs
run. This makes java highly portable as its bytecodes can be run on any machine by an
interpreter called the Java Virtual Machine(JVM) and thus java provides ‘reusability of
code’.
• Java is an object-oriented programming language: OOP makes the complete
program simpler by dividing it into a number of objects. The objects can be used as a
bridge to have data flow from one function to another. We can easily modify data and
function’s as per the requirements of the program.
• Java is a robust language: Java programs must be reliable because they are used in
both consumer and mission-critical applications, ranging from Blu-ray players to
navigation systems.
• Java is a multithreaded language: Java can perform many tasks at once by defining
multiple threads. For example, a program that manages a Graphical User Interface
(GUI) while waiting for input from a network connection uses another thread to perform
and wait’s instead of using the default GUI thread for both tasks. This keeps the GUI
responsive.
• Java programs can create applets: Applets are programs that run in web browsers.
• Java does not require any preprocessor: It does not require inclusion of header files
for creating a Java application.

Therefore, Java is a very successful language and it is gaining popularity day by day.

Setting up Java

You can download java from https://java.com/en/download/. Here you will find different versions
of java. Choose and download the one compatible with your operating system.

After you have set up the Java environment correctly, try running this simple program:

// A Java program to print Hi Java


public class GFG {
public static void main(String args[])
{
System.out.println("Hi Java");
}
}
Output:
Hi Java

If the environment is set up correctly and the code is correctly written, you shall see this output
on your console. That is your first Java program

READ:

4|ICT2215COM PUTER PROGR AMMING 4


Java An Introduction to Problem Solving and Programming, by Pearson
Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

1. What is JAVA?
2. What are the features in JAVA?
3. How does Java enable high performance?

LESSON 2 JAVA ENVIRONMENT


OVERVIEW:

Java is a general-purpose computer programming language that is concurrent, class-


based, object-oriented etc.
Java applications are typically compiled to bytecode that can run on any Java virtual machine
(JVM) regardless of computer architecture. The latest version is Java 11.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:


• Learn the difference between jdk, jre and jvm.
• How to set up Java Environment in windows.

COURSE MATERIALS

These are the environment settings for both Linux and Windows. JVM, JRE and JDK all three
are platform dependent because configuration of each Operating System is different. But, Java
is platform independent.

There are few things which must be clear before setting up the environment

1. JDK(Java Development Kit) : JDK is intended for software developers and includes
development tools such as the Java compiler, Javadoc, Jar, and a debugger.
2. JRE(Java Runtime Environment) : JRE contains the parts of the Java libraries required
to run Java programs and is intended for end users. JRE can be view as a subset of
JDK.
3. JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that
provides runtime environment in which java bytecode can be executed. JVMs are
available for many hardware and software platforms.

Steps for Setting up Java Environment for Windows

1. Java8 JDK is available at Download Java 8.


Click second last link for Windows(32 bit) and last link for Windows(64 bit) as highlighted

5|ICT2215COM PUTER PROGR AMMING 4


below.

2. After download, run the .exe file and follow the instructions to install Java on your
machine. Once you installed Java on your machine, you have to setup environment
variable.
3. Go to Control Panel -> System and Security -> System.
Under Advanced System Setting option click on Environment Variables as highlighted
below.

4. Now, you have to alter the “Path” variable under System variables so that it also
contains the path to the Java environment. Select the “Path” variable and click on Edit
button as highlighted below.

6|ICT2215COM PUTER PROGR AMMING 4


5. You will see list of different paths, click on New button and then add path where java is
installed. By default, java is installed in “C:\Program Files\Java\jdk\bin” folder OR
“C:\Program Files(x86)\Java\jdk\bin”. In case, you have installed java at any other
location,then add that path.

6. Click on OK, Save the settings and you are done !! Now to check whether installation is
done correctly, open command prompt and type javac -version. You will see that java is
running on your machine.
7. In order to make sure whether compiler is setup, type javac in command prompt. You
will see a list related to javac.

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

In the space provided below, write down at least five (5) otherd IDE’s that may be used
to create and execute java programs with their corresponding price and license type.

Example: NETBEANS – FREE – OPEN SOURCE

7|ICT2215COM PUTER PROGR AMMING 4


LESSON 3 ALL ABOUT ECLIPSE
OVERVIEW:

The Eclipse platform which provides the foundation for the Eclipse IDE is composed of
plug-ins and is designed to be extensible using additional plug-ins. Developed using Java, the
Eclipse platform can be used to develop rich client applications, integrated development
environments and other tools. Eclipse can be used as an IDE for any programming language for
which a plug-in is available.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:


• What is an IDE?
• What is Eclipse?
• What are the different parts of eclipse window and their functions?

COURSE MATERIALS:

In the context of computing, Eclipse is an integrated development environment (IDE) for


developing applications using the Java programming language and other programming
languages such as C/C++, Python, PERL, Ruby etc.

The Java Development Tools (JDT) project provides a plug-in that allows Eclipse to be
used as a Java IDE, PyDev is a plugin that allows Eclipse to be used as a Python IDE, C/C++
Development Tools (CDT) is a plug-in that allows Eclipse to be used for developing application
using C/C++, the Eclipse Scala plug-in allows Eclipse to be used an IDE to develop Scala
applications and PHPeclipse is a plug-in to eclipse that provides complete development tool for
PHP.

Downloading Eclipse

You can download eclipse from http://www.eclipse.org/downloads/. The download page lists a
number of flavors of eclipse.

8|ICT2215COM PUTER PROGR AMMING 4


The capabilities of each packaging of eclipse are different. Java developers typically use Eclipse
Classic or Eclipse IDE for developing Java applications.

The drop down box in the right corner of the download page allows you to set the operating
system on which eclipse is to be installed. You can choose between Windows, Linux and Mac.
Eclipse is packaged as a zip file.

Installing Eclipse

To install on windows, you need a tool that can extract the contents of a zip file. For example
you can use −

• 7-zip
• PeaZip
• IZArc

Using any one of these tools, extract the contents of the eclipse zip file to any folder of your
choice.

Launching Eclipse

On the windows platform, if you extracted the contents of the zip file to c:\, then you can start
eclipse by using c:\eclipse\eclipse.exe When eclipse starts up for the first time it prompts you for
the location of the workspace folder. All your data will be stored in the workspace folder. You
can accept the default or choose a new location.

If you select "Use this as the default and do not ask again", this dialog box will not come up
again. You can change this preference using the Workspaces Preference Page. See the
Preference tutorial page for more details.

9|ICT2215COM PUTER PROGR AMMING 4


Parts of an Eclipse Window

The major visible parts of an eclipse window are −

• Views
• Editors (all appear in one editor area)
• Menu Bar
• Toolbar

An eclipse perspective is the name given to an initial collection and arrangement of views and
an editor area. The default perspective is called java. An eclipse window can have multiple
perspectives open in it but only one perspective can be active at any point of time. A user can
switch between open perspectives or open a new perspective. A perspective controls what
appears in some menus and tool bars.

A perspective has only one editor area in which multiple editors can be open. The editor area is
usually surrounded by multiple views. In general, editors are used to edit the project data and
views are used to view the project metadata. For example the package explorer shows the java
files in the project and the java editor is used to edit a java file.

The eclipse window can contain multiple editors and views but only one of them is active at any
given point of time. The title bar of the active editor or view looks different from all the others.

Typical Eclipse Menus

The typical menus available on the menu bar of an Eclipse window are −

• File menu
• Edit menu
• Navigate menu
• Search menu
• Project menu
• Run menu
• Window menu

10 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
• Help menu

Plug-ins can add new menus and menu items. For example when the java editor is open you
will see the Source menu and when the XML editor is open, you will see the Design menu.

Brief Description of Menus


Sr.No Menu Name & Description

File
1
The File menu allows you to open files for editing, close editors, save editor content and
rename files. Among the other things, it also allows you to import and export workspace
content and shutdown Eclipse.
Edit
2
The Edit menu presents items like copy & paste.
Source
3
The Source menu is visible only when a java editor is open. It presents a number of
useful menu items related to editing java source code.
Navigate
4
The Navigate menu allows you to quickly locate resources and navigate to them.
Search
5
The Search menu presents items that allow you to search the workspace for files that
contain specific data.
Project
6
The menu items related to building a project can be found on the Project menu.
Run
7
The menu items on the Run menu allow you to start a program in the run mode or debug
mode. It also presents menu items that allow you to debug the code.
8 Window

11 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
The Window menu allows you to open and close views and perspectives. It also allows
you to bring up the Preferences dialog.
Help
9
The Help menu can be used to bring up the Help window, Eclipse Marketplace view or
Install new plug-ins. The about Eclipse menu item gives you version information.

Opening the New Java Project wizard

The New Java Project wizard can be used to create a new java project. There are many ways to
open this wizard −

• By clicking on the File menu and choosing New →Java Project.


• By right clicking anywhere in the Project Explorer and selecting New → Java Project.
• By clicking on the New button ( ) in the Tool bar and selecting Java Project.

Using the New Java Project wizard

The New Java Project Wizard has two pages. On the first page −

• Enter the Project Name


• Select the Java Runtime Environment (JRE) or leave it at the default
• Select the Project Layout which determines whether there would be a separate folder for
the source codes and class files. The recommended option is to create separate folders
for sources and class files.

You can click on the Finish button to create the project or click on the Next button to change the
java build settings.

12 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
On the second page you can change the Java Build Settings like setting the Project
dependency (if there are multiple projects) and adding additional jar files to the build path.

Viewing the Newly Created Project

The package explorer shows the newly created Java project. The icon that represents a Project
is decorated with a J to show that it is a Java Project. The folder icon is decorated to show that it
is a java source folder.

The package explorer shows the newly created Java project. The icon that represents a Project is
decorated with a J to show that it is a Java Project. The folder icon is decorated to show that it is
a java source folder.

Running a Java Program

The quickest way to run a Java program is by using the Package Explorer view.

In the Package Explorer view −

• Right click on the java class that contains the main method.
• Select Run As → Java Application.

The same action can be performed using the Package Explorer view by selecting the class that
contains the main method and clicking Alt + Shift + X, J.

Either actions mentioned above create a new Run Configuration and use it to start the Java
application.

If a Run configuration has already been created you can use it to start the Java application by
selecting Run Configurations from the Run menu, clicking on the name of the run configuration
and then clicking on the Run button.

13 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
The Run item on the Run menu can be used to restart the java application that was previously
started.

The shortcut key to launch the previously launched Java application is Ctrl + F11.

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

Identify the different parts of an Eclipse window and its function.

14 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
LESSON 4 JAVA PROGRAMMING BASICS

OVERVIEW:

Java is one of the most popular and widely used programming language and platform. A
platform is an environment that helps to develop and run programs written in any programming
language. Java is fast, reliable and secure. From desktop to web applications, scientific
supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and
corner.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:


• What are the nine (9) java basics?
• Describe the essential elements of java syntax
• Recognize comments, data types, variable, keywords, operators and iterations.

COURSE MATERIALS:

To become proficient in any programming language, one Firstly needs to understand the
basics of that language.

Therefore, below are the basics of Java in the format in which it will help you the most to get the
headstart:

1. Java Environment: The programming environment of Java consists of three


components mainly:
o JDK
o JRE
o JVM
2. Java Basic Syntax: Every programming language has its own set of rules to declare,
define and work on its components. Reading and learning about all of them together is
difficult.
3. Comments in Java: In a program, comments take part in making the program become
more human-readable by placing the detail of code involved and proper use of
comments makes maintenance easier and finding bugs easily. Comments are ignored
by the compiler while compiling the code.
4. Data Types in Java: Each variable in Java has an associated data type. Each data type
requires different amounts of memory and has some specific operations which can be
performed over it.
5. Variables in Java: A variable is the name given to a memory location. It is the basic unit
of storage in a program.
6. Keywords in Java: Keywords or Reserved words are the words in a language that are
used for some internal process or represent some predefined actions. These words are
therefore not allowed to use as variable names or objects. Doing this will result in a
compile-time error.

15 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
7. Operators in Java: Operators are the foundation of any programming language. Thus,
the functionality of Java programming language is incomplete without the use of
operators. We can define operators as symbols that help us to perform specific
mathematical and logical computations on operands. In other words, we can say that an
operator operates the operands.
8. Decision Making (Control Statements) in Java: Decision Making in programming is
similar to decision making in real life. In programming also we face some situations
where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the
program based on certain conditions. These are used to cause the flow of execution to
advance and branch based on changes to the state of a program.
9. Loops in Java: Looping in programming languages is a feature which facilitates the
execution of a set of instructions/functions repeatedly while some condition evaluates to
true. Java provides three ways for executing the loops. While all the ways provide similar
basic functionality, they differ in their syntax and condition checking time.

Java Environment

(Lesson 2 discussion)

Java Basic Syntax

The process of Java programming can be simplified in three steps:

• Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.
• Compile it by typing “javac HelloWorld.java” in the terminal window.
• Execute (or run) it by typing “java HelloWorld” in the terminal window.
• Below given program is the simplest program of Java printing “Hello World” to the
screen. Let us try to understand every bit of code step by step.

/* This is a simple Java program.


FileName : "HelloWorld.java". */
class HelloWorld {
// Your program begins with a call to main().
// Prints "Hello, World" to the terminal window.
public static void main(String args[]) {
System.out.println("Hello, World"); }

Output:

Hello, World

The “Hello World!” program consists of three primary components: the HelloWorld class
definition, the main method and source code comments. Following explanation will provide you
with a basic understanding of the code:

1. Class definition:This line uses the keyword class to declare that a new class is being
defined.

class HelloWorld

16 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
HelloWorld is an identifier that is the name of the class. The entire class definition,
including all of its members, will be between the opening curly brace { and the closing
curly brace } .

2. main method: In Java programming language, every application must contain a main
method whose signature is:

public static void main(String[] args)

public: So that JVM can execute the method from anywhere.


static: Main method is to be called without object.
The modifiers public and static can be written in either order.
void: The main method doesn't return anything.
main(): Name configured in the JVM.
String[]: The main method accepts a single argument:
an array of elements of type String.

The next line of code is shown here. Notice that it occurs inside main( ).

3. System.out.println("Hello, World");

This line outputs the string “Hello, World” followed by a new line on the screen. Output is
actually accomplished by the built-in println( ) method. System is a predefined class that
provides access to the system, and out is the variable of type output stream that is
connected to the console.

4. Comments: They can either be multi-line or single line comments.

/* This is a simple Java program.

Call this file "HelloWorld.java". */

This is a multiline comment. This type of comment must begin with /* and end with */.

The name of the class defined by the program is HelloWorld, which is same as name of
file(HelloWorld.java). This is not a coincidence. In Java, all codes must reside inside a class and
there is at most one public class which contain main() method.

By convention, the name of the main class(class which contain main method) should match the
name of the file that holds the program.

Comments in Java

In a program, comments take part in making the program become more human readable by
placing the detail of code involved and proper use of comments makes maintenance easier and
finding bugs easily. Comments are ignored by the compiler while compiling a code.

In Java there are three types of comments:

17 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
1. Single – line comments.
2. Multi – line comments.
3. Documentation comments.

Single-line Comments

A beginner level programmer uses mostly single-line comments for describing the code
functionality. Its the most easiest typed comments.
class Scomment {

public static void main(String args[]) {

// Single line comment here

System.out.println("Single line comment above"); }}

Multi-line Comments

To describe a full method in a code or a complex snippet single line comments can be tedious
to write, since we have to give ‘//’ at every line. So to overcome this multi line comments can be
used.
//Java program to show multi line comments

class Scomment{

public static void main(String args[]) {

System.out.println("Multi line comments below");

/*Comment line 1

Comment line 2

Comment line 3*/}}

Documentation Comments

This type of comments are used generally when writing code for a project/software package,
since it helps to generate a documentation page for reference, which can be used for getting
information about methods present, its parameters, etc.
For example http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html is an auto
generated documentation page which is generated by using documentation comments and a
javadoc tool for processing the comments.

/**Comment start
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*
*comment ends*/

18 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Data Types in Java

Java has two categories of data:

• Primitive Data Type: such as boolean, char, int, short, byte, long, float and double
• Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Primitive Data Type

Primitive data are only single values and have no special capabilities.

19 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
There are 8 primitive data types:

1. boolean: boolean data type represents only one bit of information either true or false,
but the size of boolean data type is virtual machine-dependent. Values of type boolean
are not converted implicitly or explicitly (with casts) to any other type. But the
programmer can easily write conversion code.

Syntax: boolean booleanVar;

Size: virtual machine dependent

Values: true, false

Default Value: false

2. byte: The byte data type is an 8-bit signed two’s complement integer. The byte data type
is useful for saving memory in large arrays.

Syntax: byte byteVar;

Size: 1 byte ( 8 bits )

Values: -128 to 127

Default Value: 0

3. short: The short data type is a 16-bit signed two’s complement integer. Similar to byte,
use a short to save memory in large arrays, in situations where the memory savings
actually matters.

Syntax: short shortVar;

Size: 2 byte ( 16 bits )

Values: -32, 768 to 32, 767 (inclusive)

Default Value: 0

4. int: It is a 32-bit signed two’s complement integer.

Syntax: int intVar;

Size: 4 byte ( 32 bits )

Values: -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)

Default Value: 0

20 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-
bit integer, which has value in the range [0, 232-1]. Use the Integer class to use int data
type as an unsigned integer.

5. long: The long data type is a 64-bit two’s complement integer.

Syntax: long longVar;

Size: 8 byte ( 64 bits )

Values: -9, 223, 372, 036, 854, 775, 808 to

9, 223, 372, 036, 854, 775, 807(inclusive)

Default Value: 0

Note: In Java SE 8 and later, you can use the long data type to represent an unsigned
64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The Long
class also contains methods like compareUnsigned, divideUnsigned etc to support
arithmetic operations for unsigned long.

6. float: The float data type is a single-precision 32-bit IEEE 754 floating point. Use a float
(instead of double) if you need to save memory in large arrays of floating point numbers.

Syntax: float floatVar;

Size: 4 byte ( 32 bits )

Values: upto 7 decimal digits

Default Value: 0.0

7. double: The double data type is a double-precision 64-bit IEEE 754 floating point. For
decimal values, this data type is generally the default choice.

Syntax: double doubleVar;

Size: 8 byte ( 64 bits )

Values: upto 16 decimal digits

Default Value: 0.0

Note: Both float and double data types were designed especially for scientific
calculations, where approximation errors are acceptable. If accuracy is the most prior
concern then, it is recommended not to use these data types and use BigDecimal class
instead.

8. char: The char data type is a single 16-bit Unicode character.

21 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Syntax: char charVar;

Size: 2 byte ( 16 bits )

Values: '\u0000' (0) to '\uffff' (65535)

Default Value: '\u0000'

Why is the size of char is 2 byte in java..?


In other languages like C/C++ uses only ASCII characters and to represent all ASCII characters
8-bits is enough,
But java uses Unicode system not ASCII code system and to represent Unicode system 8 bit is
not enough to represent all characters so java uses 2 byte for characters.

Unicode defines a fully international character set that can represent most of the world’s written
languages. It is a unification of dozens of character sets, such as Latin, Greeks,Cyrillic,
Katakana, Arabic and many more.

Non-Primitive Data Type or Reference Data Types

The Reference Data Types will contain a memory address of variable value because the
reference types won’t store the variable value directly in memory. They are strings, objects,
arrays, etc.

• String: Strings are defined as an array of characters. The difference between a


character array and a string is the string is terminated with a special character ‘\0’.

Below is the basic syntax for declaring a string in Java programming language.

Syntax: <String_Type> <string_variable> = “<sequence_of_string>”;

Example:

// Declare String without using new operator


String s = "ProfChe";

// Declare String using new operator


String s1 = new String("ProfChe");

• Class: A class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.

22 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
4. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
5. Body: The class body surrounded by braces, { }.
• Object: It is a basic unit of Object-Oriented Programming and represents the real-life
entities. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of
an object.
2. Behavior : It is represented by methods of an object. It also reflects the response
of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact
with other objects.
• Interface: Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
o Interfaces specify what a class must do and not how. It is the blueprint of the
class.
o An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies
a set of methods that the class has to implement.
o If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then class must be declared abstract.
o A Java library example is, Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
• Array: An array is a group of like-typed variables that are referred to by a common
name.Arrays in Java work differently than they do in C/C++. Following are some
important point about Java arrays.
o In Java all arrays are dynamically allocated.(discussed below)
o Since arrays are objects in Java, we can find their length using member length.
This is different from C/C++ where we find length using sizeof.
o A Java array variable can also be declared like other variables with [] after the
data type.
o The variables in the array are ordered and each have an index beginning from 0.
o Java array can be also be used as a static field, a local variable or a method
parameter.
o The size of an array must be specified by an int value and not long or short.
o The direct superclass of an array type is Object.
o Every array type implements the interfaces Cloneable and java.io.Serializable.

Variables in Java

There are three types of variables in Java:

• Local Variables
• Instance Variables
• Static Variables

Let us now learn about each one of these variables in detail.

23 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
1. Local Variables: A variable defined within a block or method or constructor is called
local variable.
o These variable are created when the block in entered or the function is called
and destroyed after exiting from the block or when the call returns from the
function.
o The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variable only within that block.
o Initilisation of Local Variable is Mandatory.

Sample Program 1:

public class StudentDetails {


public void StudentAge(){
// local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age); }

public static void main(String args[]) {


StudentDetails obj = new StudentDetails();
obj.StudentAge(); } }

Output: Student age is : 5

In the above program, the variable age is a local variable to the function StudentAge(). If
we use the variable age outside StudentAge() function, the compiler will produce an
error as shown in below program.

2. Instance Variables: Instance variables are non-static variables and are declared in a
class outside any method, constructor or block.
o As instance variables are declared in a class, these variables are created when
an object of the class is created and destroyed when the object is destroyed.
o Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier then the default access specifier will be used.
o Initilisation of Instance Variable is not Mandatory. Its default value is 0
o Instance Variable can be accessed only by creating objects.

Sample Program:

import java.io.*;
class Marks {
// These variables are instance variables.
// These variables are in a class
// and are not inside any function
int engMarks;
int mathsMarks;
int phyMarks; }

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

24 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
// first object
Marks obj1 = new Marks();
obj1.engMarks = 50;
obj1.mathsMarks = 80;
obj1.phyMarks = 90;

// second object
Marks obj2 = new Marks();
obj2.engMarks = 80;
obj2.mathsMarks = 60;
obj2.phyMarks = 85;

// displaying marks for first object


System.out.println("Marks for first object:");
System.out.println(obj1.engMarks);
System.out.println(obj1.mathsMarks);
System.out.println(obj1.phyMarks);

// displaying marks for second object


System.out.println("Marks for second object:");
System.out.println(obj2.engMarks);
System.out.println(obj2.mathsMarks);
System.out.println(obj2.phyMarks); } }

Output:

Marks for first object:


50
80
90
Marks for second object:
80
60
85

As you can see in the above program the variables, engMarks , mathsMarks ,
phyMarksare instance variables. In case we have multiple objects as in the above
program, each object will have its own copies of instance variables. It is clear from the
above output that each object will have its own copy of instance variable.

3. Static Variables: Static variables are also known as Class variables.


o These variables are declared similarly as instance variables, the difference is that
static variables are declared using the static keyword within a class outside any
method constructor or block.
o Unlike instance variables, we can only have one copy of a static variable per
class irrespective of how many objects we create.
o Static variables are created at the start of program execution and destroyed
automatically when execution ends.
o Initilisation of Static Variable is not Mandatory. Its default value is 0

25 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
o If we access the static variable like Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The
compiler will replace the object name to class name automatically.
o If we access the static variable without the class name, Compiler will
automatically append the class name.

To access static variables, we need not create an object of that class, we can simply
access the variable as

class_name.variable_name;

Sample Program:

import java.io.*;
class Emp {
// static variable salary
public static double salary;
public static String name = "Harsh"; }

public class EmpDemo {


public static void main(String args[]) {

// accessing static variable without object


Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:"
+ Emp.salary);} }

Output: Harsh's average salary:1000.0

Instance variable Vs Static variable

• Each object will have its own copy of instance variable whereas We can only have one
copy of a static variable per class irrespective of how many objects we create.
• Changes made in an instance variable using one object will not be reflected in other
objects as each object has its own copy of instance variable. In case of static, changes
will be reflected in other objects as static variables are common to all object of a class.
• We can access instance variables through object references and Static Variables can be
accessed directly using class name.

Keywords in Java

Keywords or Reserved words are the words in a language that are used for some internal
process or represent some predefined actions. These words are therefore not allowed to use as
a variable names or objects. Doing this will result into a compile time error.

Java also contains a list of reserved words or keywords. These are:

1. abstract -Specifies that a class or method will be implemented later, in a subclass


2. assert -Assert describes a predicate (a true–false statement) placed in a Java program
to indicate that the developer thinks that the predicate is always true at that place. If an

26 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
assertion evaluates to false at run-time, an assertion failure results, which typically
causes execution to abort.
3. boolean – A data type that can hold True and False values only
4. break – A control statement for breaking out of loops
5. byte – A data type that can hold 8-bit data values
6. case – Used in switch statements to mark blocks of text
7. catch – Catches exceptions generated by try statements
8. char – A data type that can hold unsigned 16-bit Unicode characters
9. class -Declares a new class
10. continue -Sends control back outside a loop
11. default -Specifies the default block of code in a switch statement
12. do -Starts a do-while loop
13. double – A data type that can hold 64-bit floating-point numbers
14. else – Indicates alternative branches in an if statement
15. enum – A Java keyword used to declare an enumerated type. Enumerations extend the
base class.
16. extends -Indicates that a class is derived from another class or interface
17. final -Indicates that a variable holds a constant value or that a method will not be
overridden
18. finally -Indicates a block of code in a try-catch structure that will always be executed
19. float -A data type that holds a 32-bit floating-point number
20. for -Used to start a for loop
21. if -Tests a true/false expression and branches accordingly
22. implements -Specifies that a class implements an interface
23. import -References other classes
24. instanceof -Indicates whether an object is an instance of a specific class or implements
an interface
25. int – A data type that can hold a 32-bit signed integer
26. interface – Declares an interface
27. long – A data type that holds a 64-bit integer
28. native -Specifies that a method is implemented with native (platform-specific) code
29. new – Creates new objects
30. null -Indicates that a reference does not refer to anything
31. package – Declares a Java package
32. private -An access specifier indicating that a method or variable may be accessed only
in the class it’s declared in
33. protected – An access specifier indicating that a method or variable may only be
accessed in the class it’s declared in (or a subclass of the class it’s declared in or other
classes in the same package)
34. public – An access specifier used for classes, interfaces, methods, and variables
indicating that an item is accessible throughout the application (or where the class that
defines it is accessible)
35. return -Sends control and possibly a return value back from a called method
36. short – A data type that can hold a 16-bit integer
37. static -Indicates that a variable or method is a class method (rather than being limited to
one particular object)
38. strictfp – A Java keyword used to restrict the precision and rounding of floating point
calculations to ensure portability.
39. super – Refers to a class’s base class (used in a method or class constructor)
40. switch -A statement that executes code based on a test value
41. synchronized -Specifies critical sections or methods in multithreaded code

27 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
42. this -Refers to the current object in a method or constructor
43. throw – Creates an exception
44. throws -Indicates what exceptions may be thrown by a method
45. transient -Specifies that a variable is not part of an object’s persistent state
46. try -Starts a block of code that will be tested for exceptions
47. void -Specifies that a method does not have a return value
48. volatile -Indicates that a variable may change asynchronously
49. while -Starts a while loop

** The keywords const and goto are reserved, even they are not currently in use.

• const -Reserved for future use


• goto – Reserved for future use

** true, false and null look like keywords, but in actual they are literals. However they still can’t
be used as identifiers in a program.

Operators in Java

Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
10. Precedence and Associativity

1. Arithmetic Operators: They are used to perform simple arithmetic operations on


primitive data types.
o * : Multiplication
o / : Division
o % : Modulo
o + : Addition
o – : Subtraction
2. Unary Operators: Unary operators need only one operand. They are used to increment,
decrement or negate a value.
o – :Unary minus, used for negating the values.
o + :Unary plus, used for giving positive values. Only used when deliberately
converting a negative value to positive.
o ++ :Increment operator, used for incrementing the value by 1. There are two
varieties of increment operator.
▪ Post-Increment : Value is first used for computing the result and then
incremented.
▪ Pre-Increment : Value is incremented first and then result is computed.

28 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
o — : Decrement operator, used for decrementing the value by 1. There are two
varieties of decrement operator.
▪ Post-decrement : Value is first used for computing the result and then
decremented.
▪ Pre-Decrement : Value is decremented first and then result is computed.
o ! : Logical not operator, used for inverting a boolean value.
3. Assignment Operator : ‘=’ Assignment operator is used to assign a value to any
variable. It has a right to left associativity, i.e value given on right hand side of operator is
assigned to the variable on the left and therefore right hand side value must be declared
before using it or should be a constant.
General format of assignment operator is, variable = value;

In many cases assignment operator can be combined with other operators to build a
shorter version of statement called Compound Statement. For example, instead of a =
a+5, we can write a += 5.

o +=, for adding left operand with right operand and then assigning it to variable on
the left.
o -=, for subtracting left operand with right operand and then assigning it to variable
on the left.
o *=, for multiplying left operand with right operand and then assigning it to variable
on the left.
o /=, for dividing left operand with right operand and then assigning it to variable on
the left.
o %=, for assigning modulo of left operand with right operand and then assigning it
to variable on the left.

int a = 5;
a += 5; //a = a+5;

4. Relational Operators : These operators are used to check for relations like equality,
greater than, less than. They return boolean result after the comparison and are
extensively used in looping statements as well as conditional if else statements. General
format is,

variable relation_operator value

Some of the relational operators are-

o ==, Equal to : returns true of left hand side is equal to right hand side.
o !=, Not Equal to : returns true of left hand side is not equal to right hand side.
o <, less than : returns true of left hand side is less than right hand side.
o <=, less than or equal to : returns true of left hand side is less than or equal to
right hand side.
o >, Greater than : returns true of left hand side is greater than right hand side.
o >=, Greater than or equal to: returns true of left hand side is greater than or
equal to right hand side.
5. Logical Operators : These operators are used to perform “logical AND” and “logical
OR” operation, i.e. the function similar to AND gate and OR gate in digital electronics.
One thing to keep in mind is the second condition is not evaluated if the first one is false,

29 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
i.e. it has a short-circuiting effect. Used extensively to test for several conditions for
making a decision.
Conditional operators are-
o &&, Logical AND : returns true when both conditions are true.
o ||, Logical OR : returns true if at least one condition is true.

6. Ternary operator : Ternary operator is a shorthand version of if-else statement. It has


three operands and hence the name ternary. General format is-

condition ? if true : if false

The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.

7. Bitwise Operators : These operators are used to perform manipulation of individual bits
of a number. They can be used with any of the integer types. They are used when
performing update and query operations of Binary indexed tree.
o &, Bitwise AND operator: returns bit by bit AND of input values.
o |, Bitwise OR operator: returns bit by bit OR of input values.
o ^, Bitwise XOR operator: returns bit by bit XOR of input values.
o ~, Bitwise Complement Operator: This is a unary operator which returns the
one’s compliment representation of the input value, i.e. with all bits inversed.
8. Shift Operators :These operators are used to shift the bits of a number left or right
thereby multiplying or dividing the number by two respectively. They can be used when
we have to multiply or divide a number by two. General format-

number shift_op number_of_places_to_shift;

o <<, Left shift operator: shifts the bits of the number to the left and fills 0 on
voids left as a result. Similar effect as of multiplying the number with some power
of two.
o >>, Signed Right shift operator: shifts the bits of the number to the right and
fills 0 on voids left as a result. The leftmost bit depends on the sign of initial
number. Similar effect as of dividing the number with some power of two.
o >>>, Unsigned Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit is set to 0.
9. Instance of operator : Instance of operator is used for type checking. It can be used to
test if an object is an instance of a class, a subclass or an interface. General format-

object instance of class/subclass/interface

Precedence and Associativity of Operators

Precedence and associative rules are used when dealing with hybrid equations involving more
than one type of operator. In such cases, these rules determine which part of the equation to
consider first as there can be many different valuations for the same equation. The below table
depicts the precedence of operators in decreasing order as magnitude with the top representing
the highest precedence and bottom shows the lowest precedence.

30 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Decision Making in Java

Decision Making in programming is similar to decision making in real life. In programming also
we face some situations where we want a certain block of code to be executed when some
condition is fulfilled.
A programming language uses control statements to control the flow of execution of program
based on certain conditions. These are used to cause the flow of execution to advance and
branch based on changes to the state of a program.
Java’s Selection statements:

• if
• if-else
• nested-if
• if-else-if
• switch-case

These statements allow you to control the flow of your program’s execution based upon
conditions known only during run time.

• if: if statement is the most simple decision making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a certain
condition is true then a block of statement is executed otherwise not.
Syntax:

if(condition)
{
// Statements to execute if
// condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements under it.

31 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if
statement will consider the immediate one statement to be inside its block. For example,

if(condition)
statement1;
statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block.

Example:
// Java program to illustrate If statement

class IfDemo {

public static void main(String args[]) {

int i = 10;

if (i > 15)

System.out.println("10 is less than 15"); // This statement will be executed

// as if considers one statement by default

System.out.println("I am Not in if");}}

Output: I am Not in if

• if-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else
if the condition is false. Here comes the else statement. We can use the else statement
with if statement to execute a block of code when the condition is false.
Syntax:

if (condition)
{
// Executes this block if condition is true
}else{
// Executes this block if condition is false}

Example:

// Java program to illustrate if-else statement

32 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
class IfElseDemo {

public static void main(String args[]) {

int i = 10;

if (i < 15)

System.out.println("i is smaller than 15");

else

System.out.println("i is greater than 15"); }

Output: i is smaller than 15

• nested-if: A nested if is an if statement that is the target of another if or else. Nested if


statements means an if statement inside an if statement. Yes, java allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:

if (condition1)
{ // Executes when condition1 is true
if (condition2) {// Executes when condition2 is true}}

Example:

// Java program to illustrate nested-if statement

class NestedIfDemo{

public static void main(String args[]) {

int i = 10;

if (i == 10) {

// First if statement

if (i < 15)

System.out.println("i is smaller than 15");

// Nested - if statement Will only be executed if statement above it is true

if (i < 12)

System.out.println("i is smaller than 12 too");

else

System.out.println("i is greater than 15"); }}}

Output: i is smaller than 15

33 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
i is smaller than 12 too

• if-else-if ladder: Here, a user can decide among multiple options.The if statements are
executed from the top down. As soon as one of the conditions controlling the if is true,
the statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.

if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Example:
// Java program to illustrate if-else-if ladder

class ifelseifDemo{

public static void main(String args[]) {

int i = 20;

if (i == 10) System.out.println("i is 10");

else if (i == 15) System.out.println("i is 15");

else if (i == 20) System.out.println("i is 20");

else System.out.println("i is not present"); }}

Output: i is 20

• switch-case The switch statement is a multiway branch statement. It provides an easy


way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:

34 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
statementN;
break;
default:
statementDefault;
}

o Expression can be of type byte, short, int char or an enumeration. Beginning with JDK7,
expression can also be of type String.
o Dulplicate case values are not allowed.
o The default statement is optional.
o The break statement is used inside the switch to terminate a statement sequence.
o The break statement is optional. If omitted, execution will continue on into the next
case.

Example:
// Java program to illustrate switch-case

class SwitchCaseDemo {

public static void main(String args[]){

int i = 9;

switch (i) {

case 0: System.out.println("i is zero.");

break;

case 1: System.out.println("i is one.");

break;

case 2: System.out.println("i is two.");

break;

default: System.out.println("i is greater than 2."); } } }

Output: i is greater than 2.

Loops in Java

Looping in programming languages is a feature which facilitates the execution of a set of


instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and condition checking time.

1. while loop: A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as a

35 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
repeating if statement.
Syntax :

while (boolean condition)


{
loop statements...
}

o While loop starts with the checking of condition. If it evaluated to true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason it is also called Entry control loop
o Once the condition is evaluated to true, the statements in the loop body are executed.
Normally the statements contain an update value for the variable being processed for
the next iteration.
o When the condition becomes false, the loop terminates which marks the end of its life
cycle.

// Java program to illustrate while loop

class whileLoopDemo {

public static void main(String args[]){

int x = 1; // Exit when x becomes greater than 4

while (x <= 4){ System.out.println("Value of x:" + x);

// Increment the value of x for next iteration

x++; }}}

Output:

Value of x:1
Value of x:2
Value of x:3
Value of x:4

2. for loop: for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement consumes the initialization, condition and increment/decrement in
one line thereby providing a shorter, easy to debug structure of looping.
Syntax:

36 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)}

Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already
declared variable can be used or a variable can be declared, local to loop only.

Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is
also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.

Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.

Increment/ Decrement: It is used for updating the variable for next iteration.

Loop termination:When the condition becomes false, the loop terminates marking the end of its life
cycle.

// Java program to illustrate for loop.

class forLoopDemo {

public static void main(String args[]) {

// for loop begins when x=2 and runs till x <=4

for (int x = 2; x <= 4; x++)

System.out.println("Value of x:" + x); } }

Output:

Value of x:2
Value of x:3
Value of x:4

Enhanced For loop

Java also includes another version of for loop introduced in Java 5. Enhanced for
loop provides a simpler way to iterate through the elements of a collection or array. It is
inflexible and should be used only when there is a need to iterate through the elements

37 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
in sequential manner without knowing the index of currently processed element.
Also note that the object/variable is immutable when enhanced for loop is used i.e it
ensures that the values in the array can not be modified, so it can be said as read only
loop where you can’t update the values as opposite to other loops where values can be
modified.
We recommend using this form of the for statement instead of the general form
whenever possible.(as per JAVA doc.)
Syntax:

for (T element:Collection obj/array)


{
statement(s)
}

Lets take an example to demonstrate how enhanced for loop can be used to simpify the
work. Suppose there is an array of names and we want to print all the names in that
array. Let’s see the difference with these two examples
Enhanced for loop simplifies the work as follows-

// Java program to illustrate enhanced for loop

public class enhancedforloop {

public static void main(String args[]) {

String array[] = {"Ron", "Harry", "Hermoine"}; //enhanced for loop

for (String x:array) {

System.out.println(x);} }}

Output:

Ron
Harry
Hermoine

3. do while: do while loop is similar to while loop with only difference that it checks for
condition after executing the statements, and therefore is an example of Exit Control
Loop.
Syntax:

do
{
statements..
}
while (condition);

38 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Flowchart:

do while loop starts with the execution of the statement(s). There is no checking of any condition for the
first time.

After the execution of the statements, and update of the variable value, the condition is checked for
true or false value. If it is evaluated to true, next iteration of loop starts.

When the condition becomes false, the loop terminates which marks the end of its life cycle.

It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.

// Java program to illustrate do-while loop

class dowhileloopDemo {

public static void main(String args[]) {

int x = 21;

do{ // The line will be printed even if the condition is false

System.out.println("Value of x:" + x);

x++; }

while (x < 20); } }

Output:

Value of x: 21

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

39 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
ASSIGNMENTS/ASSESSMENTS:

On the space provided at the right column, write valid if the give identifier is valid. Otherwise
write the valid form.

1. 50total
2. $salary
3. tuitionFee
4. _distance
5. net pay
6. gross-pay
7. rate / hour
8. score5
9. age_limit
10. %score

Evaluate the following Boolean expressions.

T && !F || T

T || T && F || T

!F || !T || F && (T || F)

!( T || F && !F || F && F || F )

F && ( T || F || ( T || F && T || F ))

Programming:

Sequential:

1. Write a program that will accept a measurement in inches, then input the equivalent
in ft. and centimeters.

40 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
2. Write a program that will acept a temperature in Fahrenheit and output the
equivalent in Celsius. Recall that the formula Fahrenheit to Celsius is (F-32) * 5 / 9;

Decision:

1. Write a program that will accept a numeric month (between 1-12) and output the month.
Include validation (i.e. display appropriate message for invalid numeric inputs).
2. Write a program that will accept a three integer numbers an output the highest.

Loop:

1. Write a program that will display the first 10 positive numbers. Implement the program
using while, do-while and for loop.
2. The factorial of N is the product of all positive integers less than or equal to n. Write a
program that will accept a positive integer and outputs its factorial. If the input is 4, the
program should output 24 as 1*2*3*4 which is equal to 24.

LESSON 5 OBJECT ORIENTED PROGRAMMING (OOPs)


CONCEPT IN JAVA
OVERVIEW:

Object Oriented paradigm views a solution as a collection of interacting objects. Objects


in general are things around us. Every object has its own state (characteristics or conditions). It
has a set of things that it can perform (behavior).

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:


• Explain the Object-oriented paradigm
• Describe the different concepts in object-oriented programming

COURSE MATERIALS:

Object-oriented programming: As the name suggests, Object-Oriented Programming or


OOPs refers to languages that uses objects in programming. Object-oriented programming aims
to implement real-world entities like inheritance, hiding, polymorphism etc in programming. The
main aim of OOP is to bind together the data and the functions that operate on them so that no
other part of the code can access this data except that function.

41 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
OOPs Concepts:

• Polymorphism
• Inheritance
• Encapsulation
• Abstraction
• Class
• Object
• Method
• Message Passing

Let us learn about the different characteristics of an Object-Oriented Programming language:

1. Polymorphism: Polymorphism refers to the ability of OOPs programming languages to


differentiate between entities with the same name efficiently. This is done by Java with
the help of the signature and declaration of these entities.

For example:

// Java program to demonstrate Polymorphism

// This class will contain 3 methods with same name,

// yet the program will compile & run successfully

public class Sum {

// Overloaded sum(). This sum takes two int parameters

public int sum(int x, int y) {

return (x + y); }

// Overloaded sum(). This sum takes three int parameters

public int sum(int x, int y, int z) {

return (x + y + z); }

42 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
// Overloaded sum().This sum takes two double parameters

public double sum(double x, double y) {

return (x + y); } // Driver code

public static void main(String args[]) {

Sum s = new Sum();

System.out.println(s.sum(10, 20));

System.out.println(s.sum(10, 20, 30));

System.out.println(s.sum(10.5, 20.5));} }

Output:

30
60
31.0

Polymorphism in Java are mainly of 2 types:

o Overloading in Java
o Overriding in Java
2. Inheritance: Inheritance is an important pillar of OOP(Object Oriented Programming). It
is the mechanism in java by which one class is allow to inherit the features(fields and
methods) of another class.
Important terminology:
o Super Class: The class whose features are inherited is known as superclass(or
a base class or a parent class).
o Sub Class: The class that inherits the other class is known as subclass(or a
derived class, extended class, or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.
o Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.

The keyword used for inheritance is extends.


Syntax:

class derived-class extends base-class


{
//methods and fields
}

3. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit.


It is the mechanism that binds together code and the data it manipulates. Another way to
think about encapsulation is, it is a protective shield that prevents the data from being
accessed by the code outside this shield.

43 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
o Technically in encapsulation, the variables or data of a class is hidden from any
other class and can be accessed only through any member function of own class
in which they are declared.
o As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
o Encapsulation can be achieved by Declaring all the variables in the class as
private and writing public methods in the class to set and get the values of
variables.

4. Abstraction: Data Abstraction is the property by virtue of which only the essential
details are displayed to the user.The trivial or the non-essentials units are not displayed
to the user. Ex: A car is viewed as a car rather than its individual components.

Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviours
of an object differentiate it from other objects of similar type and also help in
classifying/grouping the objects.

Consider a real-life example of a man driving a car. The man only knows that pressing
the accelerators will increase the speed of car or applying brakes will stop the car but he
does not know about how on pressing the accelerator the speed is actually increasing,
he does not know about the inner mechanism of the car or the implementation of
accelerator, brakes etc in the car. This is what abstraction is.

In java, abstraction is achieved by interfaces and abstract classes. We can achieve


100% abstraction using interfaces.

5. Class: A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
5. Body: The class body surrounded by braces, { }.

44 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
6. Object: It is a basic unit of Object Oriented Programming and represents the real life
entities. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of:
0. State : It is represented by attributes of an object. It also reflects the properties of
an object.
1. Behavior : It is represented by methods of an object. It also reflects the response
of an object with other objects.
2. Identity : It gives a unique name to an object and enables one object to interact
with other objects.

Example of an object: dog

7. Method: A method is a collection of statements that perform some specific task and
return result to the caller. A method can perform some specific task without returning
anything. Methods allow us to reuse the code without retyping the code. In Java, every
method must be part of some class which is different from languages like C, C++ and
Python.
Methods are time savers and help us to reuse the code without retyping the code.

Method Declaration

In general, method declarations has six components:

o Access Modifier: Defines access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 type of the access specifiers.
▪ public: accessible in all class in your application.
▪ protected: accessible within the package in which it is defined and in its
subclass(es)(including subclasses declared outside the package)
▪ private: accessible only within the class in which it is defined.
▪ default (declared/defined without using any modifier): accessible
within same class and package within which its class is defined.
o The return type: The data type of the value returned by the method or void if
does not return a value.
o Method Name: the rules for field names apply to method names as well, but the
convention is a little different.
o Parameter list: Comma separated list of the input parameters are defined,
preceded with their data type, within the enclosed parenthesis. If there are no
parameters, you must use empty parentheses ().
o Exception list: The exceptions you expect by the method can throw, you can
specify these exception(s).
o Method body: it is enclosed between braces. The code you need to be executed
to perform your intended operations.

45 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
8. Message Passing: Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a
procedure and therefore will invoke a function in the receiving object that generates the
desired results. Message passing involves specifying the name of the object, the name
of the function and the information to be sent.

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

Draw a class hierarchy in which several classes are subclasses of a single superclass.

Identify the superclass and the subclass in each of the following pairs of classes.

a. Employee, Person
b. Vehicle, Truck
c. Circle, Cylinder
d. BankAccount, SavingsAccount
e. GraduateStudent, Student
f. Dog, Animal

What is an abstract method?

What is the difference between an abstract class and an interface?

Why does java allow a class to implement more than one interface?

46 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
LESSON 6 CLASSES AND OBJECTS IN JAVA
OVERVIEW:

In the preceding lessons, you learn how to use various classes and their methods to
manipulate data. Java does not provide all the classes that you will ever need, so it permits you
to design and implement your own classes.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:


• Learn about user define classes
• Explore how classes are implemented
• Learn about various operations of classes
• Become aware of accessor methods

COURSE MATERIALS:

Classes and Objects are basic concepts of Object-Oriented Programming which revolve
around the real life entities.

Class

A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:

1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
5. Body: The class body surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provides the state of
the class and its objects, and methods are used to implement the behavior of the class and its
objects.

There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.

Object

It is a basic unit of Object Oriented Programming and represents the real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An
object consists of :

47 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
1. State : It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with
other objects.

Example of an object : dog

Objects correspond to things found in the real world. For example, a graphics program may
have objects such as “circle”, “square”, “menu”. An online shopping system might have objects
such as “shopping cart”, “customer”, and “product”.

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.

Example :

As we declare variables like (type name;). This notifies the compiler that we will use name to
refer to data whose type is type. With a primitive variable, this declaration also reserves the
proper amount of memory for the variable. So for reference variable, type must be strictly a
concrete class name. In general,we can’t create objects of an abstract class or an interface.

Dog tuffy;

If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an object
is actually created and assigned to it. Simply declaring a reference variable does not create an
object.

Initializing an object

48 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the class constructor.

// Class Declaration

public class Dog{ // Instance Variables

String name;

String breed;

int age;

String color; // Constructor Declaration of Class

public Dog(String name, String breed, int age, String color) {

this.name = name;

this.breed = breed;

this.age = age;

this.color = color; } // method 1

public String getName() {

return name;} // method 2

public String getBreed() {

return breed; } // method 3

public int getAge() {

return age; } // method 4

public String getColor(){

return color; }

@Override

public String toString() {

return("Hi my name is "+ this.getName()+

".\nMy breed,age and color are " +

this.getBreed()+"," + this.getAge()+

","+ this.getColor()); }

public static void main(String[] args) {

Dog tuffy = new Dog("tuffy","papillon", 5, "white");

System.out.println(tuffy.toString()); }}

Output:

49 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Hi my name is tuffy.
My breed,age and color are papillon,5,white

This class contains a single constructor. We can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The Java compiler differentiates the
constructors based on the number and the type of the arguments. The constructor in the Dog
class takes four arguments. The following statement provides “tuffy”,”papillon”,5,”white” as
values for those arguments:

Dog tuffy = new Dog("tuffy","papillon",5, "white");

Note : All classes have at least one constructor. If a class does not explicitly declare any,
the Java compiler automatically provides a no-argument constructor, also called the
default constructor. This default constructor calls the class parent’s no-argument
constructor (as it contain only one statement i.e super();), or the Object class constructor
if the class has no other parent (as Object class is parent of all classes either directly or
indirectly).

Ways to create object of a class

There are four ways to create objects in java.Strictly speaking there is only one way(by using
new keyword),and the rest internally use new keyword.

Using new keyword : It is the most common and general way to create object in
java. Example:

// creating object of class Test

Test t = new Test();

Using Class.forName(String className) method : There is a pre-defined class in java.lang


package with name Class. The forName(String className) method returns the Class object
associated with the class with the given string name.We have to give the fully qualified name for
a class. On calling new Instance() method on this Class object returns new instance of the class
with the given string name.

// creating object of public class Test


// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();

Using clone() method: clone() method is present in Object class. It creates and returns a copy of
the object.

// creating object of class Test


Test t1 = new Test();

// creating clone of above object


Test t2 = (Test)t1.clone();

50 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Deserialization : De-serialization is technique of reading an object from the saved state in a
file.

FileInputStream file = new FileInputStream(filename);


ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

Creating multiple objects by one type only (A good practice)

In real-time, we need different objects of a class in different methods. Creating a number of


references for storing them is not a good practice and therefore we declare a static reference
variable and use it whenever required. In this case,wastage of memory is less. The objects that
are not referenced anymore will be destroyed by Garbage Collector of java. Example:

Test test = new Test();


test = new Test();

In inheritance system, we use parent class reference variable to store a sub-class object. In this
case, we can switch into different subclass objects using same referenced variable. Example:

class Animal {}

class Dog extends Animal {}


class Cat extends Animal {}

public class Test


{// using Dog object
Animal obj = new Dog();// using Cat object
obj = new Cat();}

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

Mark the following statements as true or false.

a. The instance variables of a class must be of the same type


b. The methods of a class must be public
c. A class can have more than one constructor
d. A constructor can return a value of the int type
e. An accessor method of a class accesses and modifies the data members of the
class.

Write a program that converts a number entered in Roman numerals to decimal. Your program
should consist of a class, say, ROMAN. An object of type ROMAN should do the ff:

51 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
a. Store the number as a Roman Numeral
b. Convert and store the number into decimal
c. Print the number as a Roman numeral or decimal number as requested by
the user.

The decimal values of the Roman numerals are:

M 1000
D 500
C 100
L 50
X 10
V 5
I 1

d. Your class must contain the method romanToDecimal to convert a Roman


numeral into its equivalent decimal number.
e. Test your program using the following Roman numerals: MCXIV, CCCLIX
and MDCLXVI.

LESSON 7 CONSTRUCTORS IN JAVA


OVERVIEW:

Constructors are used to initialize the object’s state. Like methods, a constructor also
contains collection of statements(i.e. instructions) that are executed at time of Object
creation.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:


• Learn about constructors
• How constructors work with or without parameters

COURSE MATERIALS:

Think of a Box. If we talk about a box class then it will have some class variables (say
length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in
computer’s memory), then can a box be there with no value defined for its dimensions. The
answer is no.
So constructors are used to assign values to the class variables at the time of object creation,
either explicitly done by the programmer or by Java itself (default constructor).

52 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be default
constructor) is invoked to assign initial values to the data members of the same class.

A constructor is invoked at the time of object or instance creation. For Example:

class Geek
{
.......

// A Constructor
new Geek() {}

.......
}

// We can create an object of the above class


// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();

Rules for writing Constructor:

• Constructor(s) of a class must has same name as the class name in which it resides.
• A constructor in Java can not be abstract, final, static and Synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.

Types of constructor

There are two type of constructor in Java:

1. No-argument constructor: A constructor that has no parameter is known as default


constructor. If we don’t define a constructor in a class, then compiler creates default
constructor(with no arguments) for the class. And if we write a constructor with
arguments or no-arguments then the compiler does not create a default constructor.
Default constructor provides the default values to the object like 0, null, etc. depending
on the type.

// Java Program to illustrate calling a

// no-argument constructor

import java.io.*;

class Geek {

int num;

String name;

// this would be invoked while an object of that class is created.

Geek() {

53 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
System.out.println("Constructor called"); }}

class GFG {

public static void main (String[] args) {

// this would invoke default constructor.

Geek geek1 = new Geek();

// Default constructor provides the default values to the object like 0, null

System.out.println(geek1.name);

System.out.println(geek1.num); }}

Output :

Constructor called
null
0

2. Parameterized Constructor: A constructor that has parameters is known as


parameterized constructor. If we want to initialize fields of the class with your own
values, then use a parameterized constructor.

// Java Program to illustrate calling of parameterized constructor.

import java.io.*;

class Geek{

// data members of the class.

String name;

int id; // constructor would initialize data members with the values of passed arguments while

//Object of that class created.

Geek(String name, int id) {

this.name = name;

this.id = id; } }

class GFG {

public static void main (String[] args){

// this would invoke the parameterized constructor.

Geek geek1 = new Geek("adam", 1);

System.out.println("GeekName :" + geek1.name +

54 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
" and GeekId :" + geek1.id); }}

Output:

GeekName :adam and GeekId :1

Does constructor return any value?

There are no “return value” statements in constructor, but constructor returns current
class instance. We can write ‘return’ inside a constructor.

Constructor Overloading

Like methods, we can overload constructors for creating objects in different ways.
Compiler differentiates constructors on the basis of numbers of parameters, types of the
parameters and order of the parameters.

// Java Program to illustrate constructor overloading using same task (addition operation ) for different types of arguments.

import java.io.*;

class Geek { // constructor with one argument

Geek(String name) {

System.out.println("Constructor with one " + "argument - String : " + name); }

// constructor with two arguments

Geek(String name, int age) {

System.out.println("Constructor with two arguments : " + " String and Integer : " + name + " "+ age); }

// Constructor with one argument but with different type than previous.

Geek(long id) {

System.out.println("Constructor with one argument : " + "Long : " + id); } }

class GFG {

public static void main(String[] args) {

// Creating the objects of the class named 'Geek' by passing different arguments

// Invoke the constructor with one argument of type 'String'.

Geek geek2 = new Geek("Shikhar"); // Invoke the constructor with two arguments

Geek geek3 = new Geek("Dharmesh", 26); // Invoke the constructor with one argument of type 'Long'.

Geek geek4 = new Geek(325614567); } }

55 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Output:

Constructor with one argument - String : Shikhar


Constructor with two arguments - String and Integer : Dharmesh 26
Constructor with one argument - Long : 325614567

How constructors are different from methods in Java?

• Constructor(s) must have the same name as the class within which it defined while it is
not necessary for the method in java.
• Constructor(s) do not return any type while method(s) have the return type or void if
does not return any value.
• Constructor is called only once at the time of Object creation while method(s) can be
called any numbers of time.

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

What is a constructor?

Why would you include a constructor in a class?

Suppose that automobile is the name of the class. What is the name of a constructor of this
class?

What is the return type of a constructor?

How many default constructors can a class have?

56 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
LESSON 8 METHODS IN JAVA
OVERVIEW:

A method is a collection of statements that perform some specific task and return the
result to the caller. A method can perform some specific task without returning anything.
Methods allow us to reuse the code without retyping the code. In Java, every method must be
part of some class which is different from languages like C, C++, and Python.
Methods are time savers and help us to reuse the code without retyping the code.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:

• Define what is a method


• Basic parts of a method
• How to create method

COURSE MATERIALS:

Method Declaration

In general, method declarations has six components :

• Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
o public: accessible in all class in your application.
o protected: accessible within the class in which it is defined and in its
subclass(es)
o private: accessible only within the class in which it is defined.
o default (declared/defined without using any modifier) : accessible within same
class and package within which its class is defined.
• The return type : The data type of the value returned by the method or void if does not
return a value.
• Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
• Parameter list : Comma separated list of the input parameters are defined, preceded
with their data type, within the enclosed parenthesis. If there are no parameters, you
must use empty parentheses ().
• Exception list : The exceptions you expect by the method can throw, you can specify
these exception(s).
• Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.

57 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Method signature: It consists of the method name and a parameter list (number of parameters,
type of the parameters and order of the parameters). The return type and exceptions are not
considered as part of it.
Method Signature of above function:

max(int x, int y)

How to name a Method?

A method name is typically a single word that should be a verb in lowercase or multi-
word, that begins with a verb in lowercase followed by adjective, noun….. After the first word,
first letter of each word should be capitalized. For example, findSum,
computeMax, setX and getX

Generally, A method has a unique name within the class in which it is defined but sometime a
method might have the same name as other method names within the same class as method
overloading is allowed in Java.

Calling a method

The method needs to be called for using its functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:

• It completes all the statements in the method


• It reaches a return statement
• Throws an exception

// Program to illustrate methodsin java

import java.io.*;

class Addition {

int sum = 0;

public int addTwoInt(int a, int b){

// adding two integer value.

sum = a + b; //returning summation of two values.

58 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
return sum; } }

class GFG {

public static void main (String[] args) { // creating an instance of Addition class

Addition add = new Addition();

// calling addTwoInt() method to add two integer using instance created in above step.

int s = add.addTwoInt(1,2);

System.out.println("Sum of two integer values :"+ s); } }

Output :

Sum of two integer values :3

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

3. What method is used to create an input dialog box?


4. What method is used to create an output dialog box?
5. What is the name of the class that contains the methods to create input and output
dialog boxes?
6. What is the name of the package that contains the class described in number 3
question.

59 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
LESSON 9 STRINGS IN JAVA
OVERVIEW:

Strings in Java are Objects that are backed internally by a char array. Since arrays are
immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is
made, an entirely new String is created.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:

• Learn how to use String methods to manipulate strings.


• Different methods to process Strings

COURSE MATERIALS:

Below is the basic syntax for declaring a string in Java programming language.

Syntax: <String_Type> <string_variable> = “<sequence_of_string>”;

Example: String str = "Geeks";

Memory allotment of String

Whenever a String Object is created, two objects will be created- one in the Heap Area and one
in the String constant pool and the String object reference always points to heap area object.

For example: String str = "Geeks";

An Example that shows how to declare String


// Java code to illustrate String

import java.io.*;

import java.lang.*;

class Test {

public static void main(String[] args) {

// Declare String without using new operator

60 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
String s = "GeeksforGeeks"; // Prints the String.

System.out.println("String s = " + s); // Declare String using new operator

String s1 = new String("GeeksforGeeks"); // Prints the String.

System.out.println("String s1 = " + s1); } }

Output:

String s = GeeksforGeeks
String s1 = GeeksforGeeks
Interfaces and Classes in Strings in Java

• CharBuffer: This class implements the CharSequence interface. This class is used to
allow character buffers to be used in place of CharSequences. An example of such
usage is the regular-expression package java.util.regex.
• String: String is a sequence of characters. In java, objects of String are immutable which
means a constant and cannot be changed once created.

Creating a String

There are two ways to create string in Java:

o String literal

String s = “GeeksforGeeks”;

o Using new keyword

String s = new String (“GeeksforGeeks”);

• StringBuffer: StringBuffer is a peer class of String that provides much of the


functionality of strings. String represents fixed-length, immutable character sequences
while StringBuffer represents growable and writable character sequences.

Syntax:

StringBuffer s = new StringBuffer("GeeksforGeeks");

• StringBuilder: The StringBuilder in Java represents a mutable sequence of characters.


Since the String Class in Java creates and immutable sequence of characters, the
StringBuilder class provides an alternate to String Class, as it creates a mutable
sequence of characters.

Syntax:

StringBuilder str = new StringBuilder();


str.append("GFG");

61 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
• StringTokenizer: StringTokenizer class in Java is used to break a string into tokens.

Example:

A StringTokenizer object internally maintains a current position within the string to be


tokenized. Some operations advance this current position past the characters
processed.
A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.

• StringJoiner: StringJoiner is a class in java.util package which is used to construct a


sequence of characters(strings) separated by a delimiter and optionally starting with a
supplied prefix and ending with a supplied suffix. Though this can also be with the help
of StringBuilder class to append delimiter after each string, StringJoiner provides an
easy way to do that without much code to write.

Syntax:

public StringJoiner(CharSequence delimiter)

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

Suppose that str is a String variable. Write a java statement that uses the operator new to
instantiate the object str and assign the string “Java Programming” to str.

Which package contains class String? If a program uses this class, explain why it is not
necessary to explicitly import this class using the import statement.

Consider the ff. statements:

String str = “Going to the amusement park”;


char ch;
int len;

62 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
int position;

What value is stored in ch by the ff. statement?

ch= str.charAt(0);

What value is stored in ch by the ff. statement?

ch= str.charAt(10);

What value is stored in len by the ff. statement?

len= str.length();

What value is stored in position by the ff. statement?

position= str.indexOf(‘t’);

What value is stored in position by the ff. statement?

position= str.indexof(“park”);

LESSON 10 ARRAYS IN JAVA


OVERVIEW:

In this lesson a special data structure called an array, which allows the user to group
data items of the same type and process them in a convenient way. An array is a collection
(sequence) of a fixed number of variables called elements or components wherein all the
elements are of the same data type.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:

• Learn about arrays


• Explore how to declare and manipulate data in arrays
• Discover how to pass an array as a parameter to a method
• Learn about multi-dimensional arrays

63 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
COURSE MATERIALS:

Following are some important point about Java arrays.

• In Java all arrays are dynamically allocated(discussed below)


• Since arrays are objects in Java, we can find their length using member length. This is
different from C/C++ where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data type.
• The variables in the array are ordered and each have an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.

Array can contains primitives (int, char, etc) as well as object (or non-primitives)
references of a class depending on the definition of array. In case of primitives data
types, the actual values are stored in contiguous memory locations. In case of objects of
a class, the actual objects are stored in heap segment.

Creating, Initializing, and Accessing an Array

One-Dimensional Arrays :
The general form of a one-dimensional array declaration is

type var-name[];
OR
type[] var-name;

An array declaration has two components: the type and the name. type declares the
element type of the array. The element type determines the data type of each element
that comprises the array. Like array of int type, we can also create an array of other
primitive data types like char, float, double..etc or user defined data type(objects of a
class).Thus, the element type for the array determines what type of data the array will
hold.
Example:

// both are valid declarations


int intArray[];
or int[] intArray;

byte byteArray[];
short shortsArray[];

64 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

// an array of references to objects of


// the class MyClass (a class created by
// user)
MyClass myClassArray[];

Object[] ao, // array of Object


Collection[] ca; // array of Collection
// of unknown type

Although the above first declaration establishes the fact that intArray is an array
variable, no array actually exists. It simply tells to the compiler that this(intArray)
variable will hold an array of the integer type. To link intArray with an actual, physical
array of integers, you must allocate one using new and assign it to intArray.

Instantiating an Array in Java

When an array is declared, only a reference of array is created. To actually create or


give memory to array, you create an array like this:The general form of new as it applies
to one-dimensional arrays appears as follows:

var-name = new type [size];

Here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and var-name is the name of array variable that is linked to the
array. That is, to use new to allocate an array, you must specify the type and number
of elements to allocate.

Example:

int intArray[]; //declaring array


intArray = new int[20]; // allocating memory to array

OR

int[] intArray = new int[20]; // combining both statements in one

Note :

1. The elements in the array allocated by new will automatically be initialized to


zero (for numeric types), false (for boolean), or null (for reference types).Refer
Default array values in Java
2. Obtaining an array is a two-step process. First, you must declare a variable of the
desired array type. Second, you must allocate the memory that will hold the

65 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
array, using new, and assign it to the array variable. Thus, in Java all arrays are
dynamically allocated.

Array Literal

In a situation, where the size of the array and variables of array are already known,
array literals can be used.

int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };


// Declaring array literal

• The length of this array determines the length of the created array.
• There is no need to write the new int[] part in the latest versions of Java

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (total
array size)-1. All the elements of array can be accessed using Java for Loop.

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);

Implementation:

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

66 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]); }}

Output:

Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Arrays of Objects

An array of objects is created just like an array of primitive type data items in the
following way.

Student[] arr = new Student[7]; //student is a user-defined class

The studentArray contains seven memory spaces each of size of student class in which
the address of seven Student objects can be stored.The Student objects have to be
instantiated using the constructor of the Student class and their references should be
assigned to the array elements in the following way.

Student[] arr = new Student[5];

// Java program to illustrate creating an array of


// objects

class Student {
public int roll_no;
public String name;
Student(int roll_no, String name) {
this.roll_no = roll_no;
this.name = name; } }

// Elements of array are objects of a class Student.


public class GFG {
public static void main (String[] args) {
// declares an Array of integers.
Student[] arr;

// allocating memory for 5 objects of type Student.


arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1,"aman");

// initialize the second elements of the array


arr[1] = new Student(2,"vaibhav");

67 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
// so on...
arr[2] = new Student(3,"shikar");
arr[3] = new Student(4,"dharmesh");
arr[4] = new Student(5,"mohit");

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name); } }

Output:

Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

What happens if we try to access element outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with
an illegal index. The index is either negative or greater than or equal to size of array.

Multidimensional Arrays

Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array. These are also known as Jagged Arrays. A multidimensional array is
created by appending one set of square brackets ([]) per dimension. Examples:

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

class multiDimensional {

public static void main(String args[]) {

// declaring and initializing 2D array

int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

// printing 2D array

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

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

System.out.print(arr[i][j] + " ");

System.out.println(); } } }

68 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Output:

279
361
742

Passing Arrays to Methods

Like variables, we can also pass arrays to methods.For example, below program pass
array to method sum for calculating sum of array’s values.

// Java program to demonstrate

// passing of array to method

class Test {

// Driver method

public static void main(String args[]) {

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

// passing array to method m1

sum(arr); }

public static void sum(int[] arr) {

// getting sum of array values

int sum = 0;

for (int i = 0; i < arr.length; i++)

sum+=arr[i];

System.out.println("sum of array values : " + sum); } }

Output :

sum of array values : 15

69 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Returning Arrays from Methods

As usual, a method can also return an array. For example, below program returns an array from
method m1.

// Java program to demonstrate

// return of array from method

class Test {

// Driver method

public static void main(String args[]) {

int arr[] = m1();

for (int i = 0; i < arr.length; i++)

System.out.print(arr[i]+" "); }

public static int[] m1() {

// returning array

return new int[]{1,2,3}; } }

Output:

123

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:

Mark the following statements as true or false.

A double type is an example of a primitive data type.

A one-dimensional array is an example of a structures data type.

Arrays can be passed as parameters to a method.

A method can return a value of the type array.

The size of an array is determined at compile time.

70 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
If an array index goes out of bounds, the program terminated in an error.

Consider the following declaration:

double[] salary = new double [10];

In this declaration, identify the following:


a. The array name.
b. The array size
c. The data type of each array component
d. The range of values for the index of the array.

Determine whether the following array declarations are valid. If a declaration is invalid, give a
correct declaration.

a. int[75] list;
b. int size;
double[] list = new double[size];
c. int[] test = new int[-10];
d. double[] sales = new double [40.5];

LESSON 11 STREAM IN JAVA


OVERVIEW:

Introduced in Java 8, the Stream API is used to process collections of objects. A stream
is a sequence of objects that supports various methods which can be pipelined to produce the
desired result.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:

• Learn what is Java Stream classes


• How stream classes work using inheritance mechanism

COURSE MATERIALS:

The features of Java stream are –

• A stream is not a data structure instead it takes input from the Collections, Arrays or I/O
channels.

71 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
• Streams don’t change the original data structure, they only provide the result as per the
pipelined methods.
• Each intermediate operation is lazily executed and returns a stream as a result, hence
various intermediate operations can be pipelined. Terminal operations mark the end of
the stream and return the result.

Different Operations On Streams-


Intermediate Operations:

1. map: The map method is used to returns a stream consisting of the results of applying
the given function to the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x->x*x).collect(Collectors.toList());
2. filter: The filter method is used to select elements as per the Predicate passed as
argument.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
3. sorted: The sorted method is used to sort the stream.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().sorted().collect(Collectors.toList());

Terminal Operations:

1. collect: The collect method is used to return the result of the intermediate operations
performed on the stream.
List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
2. forEach: The forEach method is used to iterate through every element of the stream.
List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x).forEach(y->System.out.println(y));
3. reduce: The reduce method is used to reduce the elements of a stream to a single
value.
The reduce method takes a BinaryOperator as a parameter.

List number = Arrays.asList(2,3,4,5);


int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);

Program to demonstrate the use of Stream

//a simple program to demonstrate the use of stream in java


import java.util.*;
import java.util.stream.*;

class Demo {
public static void main(String args[]) {
// create a list of integers
List<Integer> number = Arrays.asList(2,3,4,5);
// demonstration of map method
List<Integer> square = number.stream().map(x -> x*x).
collect(Collectors.toList());

72 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
System.out.println(square);
// create a list of String
List<String> names =
Arrays.asList("Reflection","Collection","Stream");
// demonstration of filter method
List<String> result = names.stream().filter(s->s.startsWith("S")).
collect(Collectors.toList());
System.out.println(result);
// demonstration of sorted method
List<String> show =
names.stream().sorted().collect(Collectors.toList());
System.out.println(show);
// create a list of integers
List<Integer> numbers = Arrays.asList(2,3,4,5,2);
// collect method returns a set
Set<Integer> squareSet =
numbers.stream().map(x->x*x).collect(Collectors.toSet());
System.out.println(squareSet);
// demonstration of forEach method
number.stream().map(x->x*x).forEach(y->System.out.println(y));
// demonstration of reduce method
int even =
number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);

System.out.println(even); } }

Output:

[4, 9, 16, 25]


[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6

Important Points/Observations:

1. A stream consists of source followed by zero or more intermediate methods combined


together (pipelined) and a terminal method to process the objects obtained from the
source as per the methods described.
2. Stream is used to compute elements as per the pipelined methods without altering the
original value of the object.

73 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

LESSON 12 EXCEPTIONS AND EXCEPTION HANDLING IN JAVA


OVERVIEW:

An exception is an unwanted or unexpected event, which occurs during the execution of


a program i.e at run time, that disrupts the normal flow of the program’s instructions. For
example, division by zero and inputting an invalid data are exceptions. Similarly, trying to open
an input file that does not exists is an exception, as in an array index is outside the bounds of
the array.

LEARNING OUTCOMES:

After successful completion of this lesson, you should be able to:

• Learn what an exception is


• Learn how to handle exceptions
• Become acquainted with the hierarchy od exception classes
• Discover how to throw and rethrow an exception

COURSE MATERIALS:

Error vs Exception

Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.

Exception Hierarchy

All exception and errors types are sub classes of class Throwable, which is base class of
hierarchy.One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch. NullPointerException is an example of such an
exception.Another branch,Error are used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackOverflowError is an example of
such an error.

74 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
How JVM handle an Exception?

Default Exception Handling : Whenever inside a method, if an exception has occurred, the
method creates an Object known as Exception Object and hands it off to the run-time
system(JVM). The exception object contains name and description of the exception, and current
state of the program where exception has occurred. Creating the Exception Object and handling
it to the run-time system is called throwing an Exception.There might be the list of the methods
that had been called to get to the method where exception was occurred. This ordered list of the
methods is called Call Stack.Now the following procedure will happen.

• The run-time system searches the call stack to find the method that contains block of
code that can handle the occurred exception. The block of the code is called Exception
handler.
• The run-time system starts searching from the method in which exception occurred,
proceeds through call stack in the reverse order in which methods were called.
• If it finds appropriate handler then it passes the occurred exception to it. Appropriate
handler means the type of the exception object thrown matches the type of the exception
object it can handle.
• If run-time system searches all the methods on call stack and couldn’t have found the
appropriate handler then run-time system handover the Exception Object to default
exception handler , which is part of run-time system. This handler prints the exception
information in the following format and terminates program abnormally.
• Exception in thread "xxx" Name of Exception : Description
• ... ...... .. // Call Stack

See the below diagram to understand the flow of the call stack.

75 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Example :

// Java program to demonstrate how exception is thrown.

class ThrowsExecp{

public static void main(String args[]){

String str = null;

System.out.println(str.length()); } }

Output :

Exception in thread "main" java.lang.NullPointerException


at ThrowsExecp.main(File.java:8)

Let us see an example that illustrate how run-time system searches appropriate exception
handling code on the call stack :

// Java program to demonstrate exception is thrown

// how the runTime system searches th call stack

// to find appropriate exception handler.

class ExceptionThrown {

// It throws the Exception(ArithmeticException).

76 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
// Appropriate Exception handler is not found within this method.

static int divideByZero(int a, int b){

// this statement will cause ArithmeticException(/ by zero)

int i = a/b;

return i;

// The runTime System searches the appropriate Exception handler

// in this method also but couldn't have found. So looking forward

// on the call stack.

static int computeDivision(int a, int b) {

int res =0;

try{

res = divideByZero(a,b); }

// doesn't matches with ArithmeticException

catch(NumberFormatException ex) {

System.out.println("NumberFormatException is occured"); }

return res; }

// In this method found appropriate Exception handler.

// i.e. matching catch block.

public static void main(String args[]){

int a = 1;

int b = 0;

try{

int i = computeDivision(a,b); }

77 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
// matching ArithmeticException

catch(ArithmeticException ex) {

// getMessage will print description of exception(here / by zero)

System.out.println(ex.getMessage()); } } }

Output :

/ by zero.

How Programmer handles an exception?

Customized Exception Handling : Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally. Briefly, here is how they work. Program statements that you
think can raise exceptions are contained within a try block. If an exception occurs within the try
block, it is thrown. Your code can catch this exception (using catch block) and handle it in some
rational manner. System-generated exceptions are automatically thrown by the Java run-time
system. To manually throw an exception, use the keyword throw. Any exception that is thrown
out of a method must be specified as such by a throws clause. Any code that absolutely must
be executed after a try block completes is put in a finally block.

Need of try-catch clause(Customized Exception Handling)

Consider the following java program.

// java program to demonstrate

// need of try-catch clause

class GFG {

public static void main (String[] args) {

// array of size 4.

int[] arr = new int[4];

// this statement causes an exception

int i = arr[4];

// the following statement will never execute

System.out.println("Hi, I want to execute"); } }

78 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
Output :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4


at GFG.main(GFG.java:9)

Explanation : In the above example an array is defined with size i.e. you can access elements
only from index 0 to 3. But you trying to access the elements at index 4(by mistake) that’s why it
is throwing an exception.In this case, JVM terminates the program abnormally. The statement
System.out.println(“Hi, I want to execute”); will never execute. To execute it, we must handled
the exception using try-catch. Hence to continue normal flow of the program, we need try-catch
clause.

How to use try-catch clause

try {
// block of code to monitor for errors
// the code you think can raise an exception}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2}
// optional
finally {
// block of code to be executed after try block ends}

READ:

Java An Introduction to Problem Solving and Programming, by Pearson


Introduction to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel

ASSIGNMENTS/ASSESSMENTS:
Fill-in the blanks

• In a method, there can be _______ one statements that might throw exception, So put
all these statements within its own ________ and provide separate exception handler
within own __________ for each of them.
• If an exception occurs within the ___________, that exception is handled by the
exception handler associated with it. To associate exception handler, we must put _____
block after it. There can be more than one exception handlers. Each catch block is a
exception handler that handles the exception of the type indicated by its argument. The
argument, _______________ declares the type of the exception that it can handle and
must be the name of the class that inherits from _________ class.
• For each try block there can be zero or more catch blocks, but _________ finally block.
• The __________is optional. It always gets executed whether an exception occurred in
try block or not. If exception occurs, then it will be executed after ____________. And if
exception does not occur then it will be executed after the __________ block. The finally
block in java is used to put important codes such as clean up code e.g. closing the file or
closing the connection.

79 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4
GRADING SYSTEM

Class Standing 70%

Quizzes
Project/Assignment
Case Study
Midterm/Final Examination 30%
100%

MIDTERM GRADE + FINAL GRADE = FINAL AVERAGE GRADE


2

REFERENCES:
Java An Introduction to Problem Solving and Programming, by Pearson
Java Programming, Neil H. Datu
Introdcution to Java Programming, Jake R. Pomerada, MAED-IT
Java Programming, Joyce Farrel
Java Programming, D. S. Malik
https://www.geeksforgeeks.org/
https://www.tutorialspoint.com/java/java_overview.html
http://www.beginwithjava.com/java/loops/questions.html
https://www.w3resource.com/java-exercises/array/index.php

80 | I C T 2 2 1 5 C O M P U T E R P R O G R A M M I N G 4

You might also like