Ict2215 Computer Programming 4
Ict2215 Computer Programming 4
INSTRUCTIONAL MATERIALS
FOR
ICT2215
COMPUTER PROGRAMMING 4
COMPILED BY:
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.
References............................................................................................................................. 80
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:
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
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:
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:
ASSIGNMENTS/ASSESSMENTS:
1. What is JAVA?
2. What are the features in JAVA?
3. How does Java enable high performance?
LEARNING OUTCOMES:
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.
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. 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:
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.
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:
COURSE MATERIALS:
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.
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.
• 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.
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.
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.
The New Java Project wizard can be used to create a new java project. There are many ways to
open this wizard −
The New Java Project Wizard has two pages. On the first page −
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.
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.
The quickest way to run a Java program is by using 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:
ASSIGNMENTS/ASSESSMENTS:
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:
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:
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)
• 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.
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:
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.
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.
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 {
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{
/*Comment line 1
Comment line 2
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
• 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 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.
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.
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.
Default Value: 0
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.
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.
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.
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.
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;
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.
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.
Below is the basic syntax for declaring a string in Java programming language.
Example:
• 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
• Local Variables
• Instance Variables
• Static Variables
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:
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;
Output:
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.
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"; }
• 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.
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.
** 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
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,
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.
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-
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-
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;
Example:
// Java program to illustrate If statement
class IfDemo {
int i = 10;
if (i > 15)
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:
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 {
int i = 10;
if (i < 15)
else
if (condition1)
{ // Executes when condition1 is true
if (condition2) {// Executes when condition2 is true}}
Example:
class NestedIfDemo{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
if (i < 12)
else
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{
int i = 20;
Output: i is 20
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 {
int i = 9;
switch (i) {
break;
break;
break;
Loops in Java
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 :
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.
class whileLoopDemo {
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.
class forLoopDemo {
Output:
Value of x:2
Value of x:3
Value of x:4
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:
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-
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.
class dowhileloopDemo {
int x = 21;
x++; }
Output:
Value of x: 21
READ:
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
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.
LEARNING OUTCOMES:
COURSE MATERIALS:
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
For example:
return (x + y); }
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
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10.5, 20.5));} }
Output:
30
60
31.0
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.
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.
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.
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
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:
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
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:
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.
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”.
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
String name;
String breed;
int age;
this.name = name;
this.breed = breed;
this.age = age;
return color; }
@Override
this.getBreed()+"," + this.getAge()+
","+ this.getColor()); }
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:
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).
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:
Using clone() method: clone() method is present in Object class. It creates and returns a copy of
the object.
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.
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 {}
READ:
ASSIGNMENTS/ASSESSMENTS:
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.
M 1000
D 500
C 100
L 50
X 10
V 5
I 1
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:
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.
class Geek
{
.......
// A Constructor
new Geek() {}
.......
}
• 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
// no-argument constructor
import java.io.*;
class Geek {
int num;
String name;
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 {
// 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
import java.io.*;
class Geek{
String name;
int id; // constructor would initialize data members with the values of passed arguments while
this.name = name;
this.id = id; } }
class GFG {
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:
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.*;
Geek(String name) {
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) {
class GFG {
// Creating the objects of the class named 'Geek' by passing different arguments
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'.
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(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:
ASSIGNMENTS/ASSESSMENTS:
What is a constructor?
Suppose that automobile is the name of the class. What is the name of a constructor of this
class?
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:
COURSE MATERIALS:
Method Declaration
• 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)
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:
import java.io.*;
class Addition {
int sum = 0;
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
// calling addTwoInt() method to add two integer using instance created in above step.
int s = add.addTwoInt(1,2);
Output :
READ:
ASSIGNMENTS/ASSESSMENTS:
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:
COURSE MATERIALS:
Below is the basic syntax for declaring a string in Java programming language.
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.
import java.io.*;
import java.lang.*;
class Test {
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.
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
o String literal
String s = “GeeksforGeeks”;
Syntax:
Syntax:
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:
Syntax:
READ:
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.
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;
ch= str.charAt(0);
ch= str.charAt(10);
len= str.length();
position= str.indexOf(‘t’);
position= str.indexof(“park”);
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:
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:
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.
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:
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[];
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.
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:
OR
Note :
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.
• 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
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.
Implementation:
class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;
//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.
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.
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name) {
this.roll_no = roll_no;
this.name = name; } }
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");
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
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:
class multiDimensional {
// printing 2D array
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
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.
class Test {
// Driver method
sum(arr); }
int sum = 0;
sum+=arr[i];
Output :
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.
class Test {
// Driver method
System.out.print(arr[i]+" "); }
// returning array
Output:
123
READ:
ASSIGNMENTS/ASSESSMENTS:
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.
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];
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:
COURSE MATERIALS:
• 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.
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.
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:
Important Points/Observations:
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:
LEARNING OUTCOMES:
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 :
class ThrowsExecp{
System.out.println(str.length()); } }
Output :
Let us see an example that illustrate how run-time system searches appropriate exception
handling code on the call stack :
class ExceptionThrown {
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.
int i = a/b;
return i;
try{
res = divideByZero(a,b); }
catch(NumberFormatException ex) {
System.out.println("NumberFormatException is occured"); }
return res; }
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) {
System.out.println(ex.getMessage()); } } }
Output :
/ by zero.
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.
class GFG {
// array of size 4.
int i = arr[4];
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 :
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.
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:
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
Quizzes
Project/Assignment
Case Study
Midterm/Final Examination 30%
100%
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