0% found this document useful (0 votes)
5 views67 pages

Programming Using Java 1 COM 123 ND1

The document provides an introduction to programming fundamentals, particularly focusing on Java programming. It explains the definition of a program, the importance of programming languages, and the basic building blocks of Java programs, including data types, variables, and control structures. Additionally, it outlines the significance of programming as both a science and an art, emphasizing the need for understanding the programming environment and tools.

Uploaded by

kaysam2357
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)
5 views67 pages

Programming Using Java 1 COM 123 ND1

The document provides an introduction to programming fundamentals, particularly focusing on Java programming. It explains the definition of a program, the importance of programming languages, and the basic building blocks of Java programs, including data types, variables, and control structures. Additionally, it outlines the significance of programming as both a science and an art, emphasizing the need for understanding the programming environment and tools.

Uploaded by

kaysam2357
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/ 67

PROGRAMMING WITH

JAVA

COM 123

MR BABALOLA OLAWALE
1
CHAPTER ONE
Introduction: Programming Fundamentals
The knowledge of what a program is will be required to adequately understand the word programming /coding.
A computer program lists the objects needed to solve a problem and orchestrates their interaction. Computer is
not intelligent (Nell.Det.al,2008); it neither analyze a problem nor come up with a general solution. A human
(the programmer) must do these (write the solution) before the computer can just repeat the instruction very
quickly and consistently again.
Therefore, human being must have written the solution before the computer can now execute it in a more
efficient way otherwise the powerful machine will not be useful for a computer, for this so called powerful
machine to be useful, it must first be programmed
A Program is defined as a set of unambiguous instructions written in a programming language whereby the
instructions are meant to be followed mechanically and systematically by the computer to achieve a purpose or
solve people-oriented problem. It can also be seen as a set or sequence of instructions written and compiled in a
specific programming language given to a computer to perform a specific task. It should be noted that
Programming languages are not native (the mother-tongue) of computers hence they are needed to be
converted/translated first to the language the computer understands. This language that computer understands
contains bunch of zeros and ones i.e., 0 and 1. The language is called machine language
e.g. 00101110
A software is made up of several independent programs working together to perform some tasks. For instance,
an operating system is a system program having several functional modules (programs) working to achieve the
goal of coordinating the entire hardware resources. Computer is a programmable device that can store, retrieve
and process data. Software wise, it can be put as a machine capable of automatically processing data according to
instruction list given to solve people-oriented problem
Programming
Much of human behaviors and thoughts are characterized by logical sequences of action involving object.
Instance to make a call, sequences of actions are involved, that is, unlocking your phone, searching through the
contacts, dial etc.
Fortunately, we do not need to consciously think of every step involved in some of these processes; as another
instance, if a computer is to direct a robot to open a door, “open a door” as a process this time around, stages
involved in this process have to be analyzed thus: -
i. Stretch your hand towards the handle - - -
ii. Grasp the hand of the door
iii. Hold and push towards or outward
iv. Release the door
In computing sense, the above represent programming steps required for the robot to perform a task: open a
door. Programming involves writing out instruction for solving problem or performing a task.
We create order, both consciously and unconsciously, though a process called PROGRAMMING. It can also be
seen as the art and science of creating (developing) computer programs.

2
Programming as a science:
i. Set of principles and axioms of programming are clearly stated and defined first
ii. This set of principles and axioms are systematically applied to solve a problem
iii. The mathematical correctness of the set of unambiguous instructions (program) can be routinely
demonstrated at any stage.
iv. The implication of this viewpoint stresses the need for the varieties programming languages
As an art
i. While writing a program or developing computer programs, understanding of the medium or application area
is required.
ii. Programming involves development of creative solutions to problems, so that the overall quality of activity
within that application area will be enhanced.
iii. The implication of this viewpoint stresses the need for the varieties and choices of tools or programming
environment when all programming activities take place.
iv. The programming environment tools include the following
a) Text editors
b) Compilers
c) Interpreters
d) Diagnostic tools
e) Optimizers
f) Measurement tools
They are required for design, development, testing, implementation and maintenance of a system of programs.
Programming Language Defined
A programming language is actually a collection of libraries or API’s, which are based on a core programming
paradigm and supports some other programming paradigms as well. For example, C++ is basically an Imperative
programming language, but it supports Object-Oriented and others (M. Selvakumar Samuel,2017). There are
huge number of programming numbers, however about 27 (P.Van Roy, 2008) are being used even very few are
actively being used.

3
Fundamental Building Blocks of Programs
There are two basic aspects of programming: data and instructions. To work with data, you need to understand
variables and types; to work with instructions, you need to understand control structures and subroutines.
VARIABLE:A variable is just a memory location (or several locations treated as a unit) that has been given a
name so that it can be easily referred to and used in a program. The programmer only has to worry about the
name; it is the compiler’s responsibility to keep track of the memory location.
In Java and most other languages, a variable has a type that indicates what sort of data it can hold. One type of
variable might hold integers—whole numbers such as 3,-7, and 0— while another holds floating point
numbers—numbers with decimal points such as 3.14,-2.7, or 17.0. ( different inside the computer.) There could
also be types for individual characters (’A’, ’;’, etc.), strings (“Hello”, “A string can include many characters”,
etc.), and less common types such as dates, colors, sounds, or any other type of data that a program might need
to store.
These basic commands—for moving data from place to place and for performing computations—are the building
blocks for all programs. These building blocks are combined into complex programs using control structures and
subroutines. ∗ ∗ ∗ A program is a sequence of instructions. In the ordinary “flow of control,” the computer
executes the instructions in the sequence in which they appear, one after the other. However, this is obviously
very limited: the computer would soon run out of instructions to execute.
Control structures are special instructions that can change the flow of control. There are two basic types of
control structure: loops, which allow a sequence of instructions to be repeated over and over, and branches,
which allow the computer to decide between two or more different courses of action by testing conditions that
occur as the program is running. The structure and the behaviors of java program are determined by the
following components:

4
There are several essential components in Java programming:
1. Data Types
2. Variables
3. Methods
4. Identifiers
5. Operators
6. Control Structures
7. Arrays
8. Strings
9. Classes and Objects
10. Interfaces
11. Exceptions
JAVA FIRST PROGRAM AND INTERPRETATION The first program, as a beginner, that you must have
written with Java programming language is a “hello world” program. That is a program that just outputs “hello
world” on the screen. We shall start by describing each of the lines of code and possibly what it’s doing. This
helps getting acquainted with the essential components of a Java porgram

5
Line No The Purpose/Name Description
Keyword/opera
tor/Symbol

1-3 /* Comment i. This is a symbol for multiple line


documentation.
ii. Whatever written within these lines
aren’t executable by the compiler,
compiler just ignores it.
iii. This describes the purpose of or what
problem a program is solving.
iv. It helps readability and easy
interpretation of every line of codes in a
program
v. It should be noted that the line numbers
aren’t also part of the source code, in the
above, they are line 1-20
4 Package i. Packages act as containers for classes
and other subordinate packages.
ii. A java package is a group of similar
types of classes, interfaces and sub-
packages.

iii. Package in java can be categorized in


two form, built-in package and user-
defined package.

iv. There are many built-in packages such


as java, lang, awt, javax, swing, net, io,
util, sql etc

v. The name of the above package is called


“hello.world”

10 Public class An access Specifier i. It serves as the header of the program


ii. Here, a class named or declared
HelloWorld is created, we keep on
creating classes in Java
iii. Each of the created classes can have one
or more methods
iv. A class without the main() cannot be
executed, it is there for other program to
6
use
v. Every class must have a method or
function that will be used to manipulate
the data in the class. The default name
given to that method is main
vi. The curly brace { begins the first block
vii. Java sees a program as a class and the
name of class must be the same as the
name of the file. i.e. the name you use to
save the file
viii. public means that the contents of the
following block (the function/method)
are accessible from all other classes
ix. It indicates the starting of the class
definition
Class A class is the blueprint from which individual
objects are created.
15 Public This line explains how the i. It indicates that main() can be called
method main() will be outside the class.
used ii. The content of the following block is/are
accessible from other classes
iii.
Static i. It is an access specifier, which indicates
that main () can be called directly
without creating an object to the class.
ii.
Void i. It indicates that the method main ()
doesn’t‘ return a value.
ii.
Main() i. Every class must have a method or
function that will be used to manipulate
the data in the class.
ii. The default name given to that method is
main, the class has Hello.world as its
name
iii. The content: Strings [] args represents
the method’s argument which is an
array of strings. By default, it is args
iv. It serves as an entry point to the
program
v. String args [ ]: String is a class, which
belongs to java.lang package. It can be
used as a string data type in java.
7
{ The opening Curly brace This begins the second block, the nested or inner
block which contains the action (s) the method
main () is to perform
} The closing curly brace This closes the inner block that belongs to the
method
16 System A class System: It is a class, which belongs to java.lang
package.
out Object out: It is an output stream object, which is a
member of System class.
Print() Method i. println(): It is a method supported by
the output stream object ―out.
ii. It is used to display any kind of output
on the screen. It gives a new line after
printing the output.
iii. print(): It is similar to println(). But
doesn‘ t give a new line after printing the
output.

Basic Java constructs


Fundamentally, Java constructs are the building block of java programming which are always involved in
developing programs. They range from simple variable structure to more complex programming constructs such
as control structure
Notably, we have the following examples
1. Control statement construct e.g if , elif , for- statements etc
2. Continue statement construct
3. Exception Handling constructs such as throw, try and catch
4. Compound assignment idioms. Modifying the value of a variable is something that we do so often in
programming that Java provides a variety of different shorthand notations for the purpose. For example,
the following four statements all increment the value of i by 1 in Java: i = i + 1; i++; ++i; i +=
1;You can also say i-- or --i or i -= 1 or i = i-1 to decrement that value of i by 1. Most programmers use
i++ or i-- in for loops, though any of the others would do. The ++ and -- constructs are normally used for
integers, but the compound assignment constructs are useful operations for any arithmetic operator in any
primitive numeric type.
5. Arrays: The primary purpose of an array is to facilitate storing and manipulating large quantities of data.
Arrays play an essential role in many data processing tasks. They also correspond to vectors and
matrices, which are widely used in science and in scientific programming. Arrays are the fourth basic
element (after assignments, conditionals, and loops) found in virtually every programming language,
completing our cover age of basic Java constructs.
8
Concept of data types, variables and constant.
Data Types
Every variable must have a data type. A variable’s data type determines the values that the variable can contain
and the operations that can be performed on it. For example, declaring a variable to be int var means that var is
an integer data type. Integers can contain only integral (whole numbers) values (both positive and negative) and
we can perform arithmetic operations, such as addition on integer variables.
A data type defines a set of values and the operations that can be defined on those values. Data types in Java can
be divided into two groups: a. Primitive Data Types b. Reference Data Types (or Non-Primitives) Data types are
especially important in Java because it is a strongly typed language. This means that all operations are type
checked by the compiler for type compatibility. Illegal operations will not be compiled. Thus, strong type
checking helps prevent errors and enhances reliability. To enable strong type checking, all variables, expressions,
and values have a type. There is no concept of a “type-less” variable, for example. Furthermore, the type of a
value determines what operations are allowed on it. An operation allowed on one type might not be allowed on
another.
Java programming has two categories of data types:
1. Primitive and
2. Reference.

Primitive Data Types


The term primitive is used here to indicate that these types are not objects in an object-oriented sense, but rather,
normal binary values. These primitive types are not objects because of efficiency concerns. All of Java’s other
data types are constructed from these primitive types. Java strictly specifies a range and behavior for each
primitive type, which all implementations of the Java Virtual Machine must support. Because of Java’s
portability requirement, Java is uncompromising on this account. For example, an int is the same in all execution
environments. This allows programs to be fully portable. There is no need to rewrite code to fit a specific
platform. Although strictly specifying the size of the primitive types may cause a small loss of performance in
9
some environments, it is necessary in order to achieve portability. There are eight primitive data types in Java:
four subsets of integers, two subsets of floating point numbers, a character data type, and a Boolean data type.
Everything else is represented using objects. Let’s examine these eight primitive data types in some detail.
A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a
character, or a Boolean value.
The table below lists all of the primitive data types along with their sizes and formats.

Keyword Description Size/Format


(Integers: numbers without decimal places, eg. 45,
456)
Byte-length 8-bit two's
Byte
integer complement
16-bit two's
Short Short integer
complement
32-bit two's
Int Integer
complement
64-bit two's
Long Long integer
complement

(Real numbers: numbers with decimal places, e.g.


3.21)
Single-precision
Float 32-bit IEEE 754
floating point
Double-precision
Double 64-bit IEEE 754
floating point

(other types)
16-bit Unicode
Char A single character
character
A boolean value
Boolean true or false
(true or false)

float is designed for real data whose number of decimal places may run not more than 5 places, e.g. 245.234. But
double is used if we ha
Java insists that whenever we are carrying out division, the variable to assign the result to must be declared as
double, so as to avoid loss of precision.
NB: In other languages, the format and size of primitive data types may depend on the platform on which a
program is running. In contrast, the java programming language specifies the size and format of its primitive data
types. Hence, we don’t have to worry about system-dependencies.
10
int are integers in the range of 1 to a few thousands. However, if a variable is going to run into millions, we’d
better declare it as long. For instance, when we are writing a factorial program, the factorial of big numbers like
20 may run into large values. short and byte are usually used in systems programming dealing with registers and
memory addresses.
Reference (Non-primitive Data Types)
Reference or non-primitive type data is used to represent objects. An object is defined by a class, which can be
thought of as the data type of the object. The operations that can be performed on the object are defined by the
methods in the class. The attributes or qualities of the objects of a class are defined by the fields – which in
essence are primitive type data values. Every object belongs to a class and can be referenced using identifiers.
An identifier is a name which is used to identify programming elements such as memory location, names of
classes, Java statements and so on. The names used for identifying memory locations are commonly referred to
as memory variables or variables for short. Variable names are created by the programmer for representing
values to be stored in the computer memory. Each memory location is associated with a type, a value, and a
name.
Primitive data such as int (integer) can hold a single value and that value must correspond to the data type
specified by the programmer. Reference data types on the other hand contain not the objects in memory but the
addresses of where the objects (their method and fields etc) are stored in memory. Examples of reference data
types include arrays, strings and objects of any class declared by the programmer. Pertinent data about any object
can be gathered and used to represent attributes (fields) and tasks the objects can perform (methods) by using a
well-defined interface. Once a class has been declared several objects can be created from
Arrays, classes and interfaces are reference data types. The value of a reference type variable, in contrast to that
of primitive type, is a reference to (an address of) the value or set of values represented by the variable. A
reference is called a pointer, or a memory address in other languages. The java programming does not support
the explicit use of addresses like other languages do. We use the variable’s name instead.
Java Variables and Objects
These hold data in Java. A variable has a type and hold a single value. An object is an instance of a class and
may contain many variables, the composite of whose values is called the “state” of the object. Whereas, every
variable has a unique name, on being declared, objects have references instead of names, and they need not be
unique.
An object is created by using the “new” operator to invoke a “Constructor” and it dies when it has no references.
E.g. in the Circle program above, r and area are the 2 variables while reader, input, text, x, and System.out are
the five objects in the program. These objects are instances of the classes inputStreamReader, BufferedReader,
String, Double and PrintStream respectively.
In the Java programming language, the following must hold true for a simple name:
1. It must be a legal identifier. An identifier is an unlimited series of Unicode characters that begins with a letter.
2. It must not be a keyboard, a Boolean literal (true or false), or the reserved word null.
3. It must not unique within its scope. A variable may have the same name as a variable whose declaration
appears in a different scope. In some situations, a variable may share the same name as another variable if it is
declared within a nested block of code. (We will cover this in the next section, Scope).
11
4. It must not be a Java reserved identifier such as swing, String, int, short, etc. Reserved words are pre-defined
in Java, and so, cannot be re-defined. By Convention: Variable names begin with a lowercase letter, and class
names begin with an uppercase letter. If a variable name consists more than one word, the words are joined
together, and each word after the first begins with an uppercase letter, like this: isVisible. The underscore
character (_) is acceptable anywhere in a name, but by convention, is used only to separate words in constants
(because constants are all caps by convention and thus cannot be case-delimited).
Scope of Variables
A variable's scope is the region of a program within which the variable can be referred to by its simple name.
Secondarily, scope also determines when the system creates and destroys memory for the variable. Scope is
distinct from visibility, which applies only to member variables and determines whether the variable can be used
from outside of the class within which it is declared. Visibility is set with an access modifier. The lifetime of
these variables is the same as the lifetime of the object to which it belongs. Object once created do not exist for
ever. They are destroyed by the garbage collector of Java when there are no more reference to that object. We
shall see about Java's automatic garbage collector later on. The scope of a variable defines the section of the code
in which the variable is visible. As a general rule, variables that are defined within a block are not accessible
outside that block. The lifetime of a variable refers to how long the variable exists before it is destroyed.

Destroying variables refers to deallocating the memory that was allotted to the variables when declaring it. We
have written a few classes till now. You might have observed that not all variables are the same. The ones
declared in the body of a method were different from those that were declared in the class itself. There are three
types of variables: instance variables, formal parameters or local variables and local variables.

The location of the variable declaration within your program establishes its scope and places it into one of these
four categories:
 member variable
 local variable
 method parameter
 exception-handler parameter

12
A member variable (or global variable) is a member of a class or an object. It is declared within a class but
outside of any method or constructor. A member variable's scope is the entire declaration of the class. However,
the declaration of a member needs to appear before it is used when the use is in a member initialization
expression.
A local variable is the one that is declared within a method or a constructor (not in the header). The scope and
lifetime are limited to the method itselfYou declare local variables within a block of code. In general, the scope
of a local variable extends from its declaration to the end of the code block in which it was declared.
Instance variables
Instance variables are those that are defined within a class itself and not in any method or constructor of the
class. They are known as instance variables because every instance of the class (object) contains a copy of these
variables. The scope of instance variables is determined by the access specifier that is applied to these variables.
We have already seen about it earlier.
Argument variables
These are the variables that are defined in the header oaf constructor or a method. The scope of these variables is
the method or constructor in which they are defined. The lifetime is limited to the time for which the method
keeps executing. Once the method finishes execution, these variables are destroyed.
One important distinction between these three types of variables is that access specifiers can be applied to
instance variables only and not to argument or local variables. In addition to the local variables defined in a
method, we also have variables that are defined in bocks life an if block and an else block. The scope and is the
same as that of the block itself.
Parameters are formal arguments to methods or constructors and are used to pass values into methods and
constructors. The scope of a parameter is the entire method or constructor for which it is a parameter.
Exception-handler parameters are similar to parameters but are arguments to an exception handler rather than
to a method or a constructor. The scope of an exception-handler parameter is the code block between { and } that
follow a catch statement. We shall deal with this topic later.
Consider the following code sample:
if (...) {
int i = 17;
...
}
System.out.println("The value of i = " + i); // error
The final line won't compile because the local variable i is out of scope. The scope of i is the block of code
between the { and }. The i variable does not exist anymore after the closing }. Either the variable declaration
needs to be moved outside of the if statement block, or the println method call needs to be moved into the if
statement block.

13
Variable Initialization
Local variables and member variables can be initialized with an assignment statement when they're declared.
The data type of the variable must match the data type of the value assigned to it. Parameters and exception-
handler parameters cannot be initialized in this way. The value for a parameter is set by the caller.
Final Variables / Java Constants AND DECLARATION
You can declare a variable in any scope to be final. The value of a final variable cannot change after it has been
initialized. Such variables are similar to constants in other programming languages. To declare a final variable,
use the final keyword in the variable declaration before the type:
final int aFinalVar = 0;
The previous statement declares a final variable and initializes it, all at once. Subsequent attempts to assign a
value to aFinalVar result in a compiler error. You may, if necessary, defer initialization of a final local variable.
Simply declare the local variable and initialize it later, like this:
final int blankfinal; ...
blankfinal = 0;
A final local variable that has been declared but not yet initialized is called a blank final. Again, once a final
local variable has been initialized, it cannot be set, and any later attempt to assign a value to blankfinal is an
error.
We can put a literal primitive value directly in our codes. For example, if we need to assign the literal integer
value 4 to an integer variable we can write this:
int anInt = 4;
Process of creating and running Java programs
When a computer is performing the tasks that a program tells it to do ; we say that the computer is running or
executing the program. The CPU is the major unit of a computer that does the execution of a program , it’s the
main brain of the computer for running a program . One can think of processors as workers and programs as the
workers’ workflow instruction manual. Programs define a sequence of instructions and processors perform the
instructions one after another at the defined sequence. This inherently means that a processor can only do one
thing at a time
1. Save the written Java program in a .java file.
2. Then compile it into a .class file.
3. The .class file is executed by the Java Virtual Machine.
4. You have to create your program and compile it before it can be executed.
5. This process is repetitive, as shown in the figure below
6. If your program has compile errors, you have to modify the program to fix
7. Them, and then recompile it.

14
8. If the program has runtime errors or does not produce the correct result, you have to modify the program,
recompile it, and execute it again.

Java instantiable classes and objects


Classes can either be instantiable or non-instantiable
The syntax for a class in Java is:
accessSpecifier class NameOfClass {
// definitions of the class’s features
// includes methods and instance fields
}

15
The classes do not (and often cannot) stand alone: they are the building blocks for constructing or building stand-
alone programs.
Essentially, there are three aspects to consider when we are writing our own classes.
(i) The class fields, which are the private variables to be declared and used in the class,
(ii) The class constructor, which is a special method/function that will be used to instantiate the class,
and
(iii) Other methods that will be used to manipulate the private data in the class.

Every class has at least one constructor to instantiate it, classes which have a constructor to instantiate them are
referred to as instantiable classes. For a class without one, the compiler will automatically declare one with no
arguments. This is called a default constructor. A default constructor has no arguments. Java provides this type
of constructor if we design a class with no constructor. The default constructor sets all the instance variables to
their default values. All numeric data contained in the instance fields would be zeroed out, all booleans would be
false and all object variables would point to null.
Classes without Explicit Constructor: Non-instantiable Class
We could define a class without an explicit constructor. Just as was mentioned earlier, in this type of class, the
compiler will automatically declare one with no arguments. This is called a default constructor. A default
constructor has no arguments. The default constructor sets all the instance variables to their default values. All
numeric data contained in the instance fields would be set to zero, all Booleans would be false and all object
variables would point to null. Consider the example below
Java Constructors
Constructors are special methods for creating and initializing new instances of classes.
Constructors initialize the new object and its variables, create any other objects that object needs, and generally
perform any other operations the object needs to run.Multiple constructor definitions in a class can each have a
different number or type of arguments—then, when you use new, you can specify different arguments in the
argument list, and the right constructor for those arguments will be called. That’s how each of those different
versions of new that were listed previously can create different things.
When you create your own classes, you can define as many constructors as you need to implement that class’s
behavior. Constructors are special methods invoked whenever objects of the class are created
Classes can have three kinds of members: fields, methods and constructors.
 A field is a variable that is declared as a member of a class. Its type may be any of the eight primitive data
types - boolean, char, byte, short, int, long, float, double) or a reference to an object.
 A Method is a function that is used to perform some action for instances of the class.
 A constructor is a special function/method whose only purpose is to create the class’s objects. This is
called instantiating the class, and the objects are called instances of the class.
The constructor in our Account class is:
7. // constructor
8. public Account(String name, double bal) {
9. custName = name;
10. balance = bal;
11. }

16
This constructor is used to initialize objects of the class -giving the instance variables the initial state you want
them to have.
The Keyword: new
What does new do? When you use the new operator, several things happen: first, the new instanceof the given
class is created, and memory is allocated for it. In addition (and most importantly), when the new object is
created, a special method defined in the given class is called. This special method is called a constructor
For example, in creating an instance of the class with code
Account acc = new Account(“Akinola S.O.”, 500);
We set the instance fields, as follows
custName = “Akinola S.O”;
balance = 500;
We could see that the new method is always used together with a constructor to create an object of the class.
This forces us to set the initial state of our objects either explicitly or implicitly. An object created without a
correct initialization is useless and occasionally dangerous. It can cause a general memory protection fault
(GPF), i.e. memory corruption.
Properties of Constructors
The following are the general properties of constructors
1. A constructor has the same name as the class itself.
2. A constructor may take one or more (or none) parameters.
3. A constructor is always called with the new keyword.
4. A constructor returns no value.
5. A constructor is simply a (non static) method of a class that has the same name as the class and does not have
an explicit return value (not even void).
6.
Invocation of a constructor
A constructor is automatically called by the run-time support (the Java Virtual Machine) when an object
iscreated using the new operator. For example, with the following code fragment
Person p = new Person("John Smith", "London");
// constructor name-residence is called
System.out.println(p.getResidence());
// prints "London"
The run-time support calls the constructor Person(String,String), which creates (i.e., allocates the memoryfor) an
object of the class Person and initializes explicitly the fields name and residence to the values passed as
parameters. The reference to the newly created object is then assigned to the variable p.
Consider the following code fragment:
Person p;
17
// (1)
p = new Person("John Smith", "London"); // (2)
In (1), we define a variable p of type reference to an object of type Person, while in (2) we create a new object
Person, and we assign the reference to it to the variable p.
Note: The new operator uses a constructor to create an object, and returns a reference to it. Such a reference can:
• be passed as actual parameter to a method that has a formal parameter of type reference to Person.
• be returned as result of a method whose return value is of type reference to Person.
Note: It is important that all constructors are declared as public fields of the class. If they were declared private,
then any attempt to create an object of the class would generate an error
Overriding Constructors
Constructors cannot technically be overridden. Because they always have the same name as the current class,
you’re always creating new constructors instead of inheriting the ones you’ve got. Much of the time, this is fine,
because when your class’s constructor is called, the constructor with the same signature for all your superclass is
also called, so initialization of all the parts of a class you inherit can happen.
However, when you’re defining constructors for your own class, you may want to change how your object is
initialized, not only by initializing the information your class adds, but also to change the information that is
already there. You can do this by explicitly calling your superclass’s constructors. To call a regular method in a
superclass, you use super.methodname(arguments). Because with constructors you don’t have a method name to
call, however, you have to use a different form: super(arg1, arg2, ...); Similar to using this(...) in a constructor,
super(...) calls the constructor method for the immediate superclass (which may, in turn, call the constructor of
its superclass, and so on).
CONSTRUCTOR OVERLODAING
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ
in parameter lists. The compiler differentiates these constructors by taking into account the number of parameters
in the list and their type.
Example of Constructor Overloading

class Student5{
int id; String
name;
intage;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
18
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = newStudent5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Concepts of methods
What is a Method?
Methods are techniques employed for breaking large programs into small functional modules. It is popularly
called functions in some languages. These modules in java are called methods and classes. There are some built-
in methods and classes such as mathematical calculations, string manipulation, error checking, etc. Methods are
written to define specific tasks that may be used at any points in a program.
A method is invoked by a method call. A method call is characterized by its name and the information
(arguments) that the called method need to do its task. When the method call completes, the method either
returns a result to the calling method (or caller) or simply returns control to the calling method. We can then
infer from this fact that the caller is not interested in the way the called method will perform the job given to it
and the called method can also call another method to do some job for it. In the following assignment statements;
Y = Math.sqrt(x);
Y = Integer.parseInt(x);
Math.sqrt and Integer.parseInt are the method names and x is the argument in the above arithmetic
expressions.
Methods in Java could be programmer-declared or prepackaged. The prepackaged methods are available in the
Java Application Programming Interface Java API or Java Class Library. The java API provides a rich collection
of classes that contain methods for performing common mathematical calculations, string manipulations,
character manipulations, input/output operations, error checking and many other useful operations. Methods
allow the programmer to modularize a program by separating its task into self-contained functional units. The
actual statements implementing the methods are written only once and are hidden from other methods.
Advantages of Using Methods in Programs
(1) Program manageability: Methods and classes in java make program development more manageable.
(2)Software reusability: Using existing methods and classes as building blocks to create new programs is one of
the today’s programming paradigms. We create programs from standardized methods and classes rather than by
building customized codes. For example, in earlier programs, we did not have to define how to convert strings to
integers and floating-point numbers; Java provides these capabilities in class Integer (static method parseInt) and
class Double (static method parseDouble), respectively.
(3)Reduction in code repetition: Repeating codes in programs is highly reduced using methods. Packaging code
as a method allows a program to execute that code from several locations in a program simply by calling the
method.
19
(4)Ease of program maintenance and debugging: Methods make programs easier to debug and maintain.Note:
(i)To promote software reusability, each method should be limited to performing a single, well-defined task, and
the name of the method should express that task effectively.
(ii)A method should usually be no longer than one printed page. Better yet, a method should usually be no longer
than half a printed page. Regardless of how long a method is, it should perform one task well. Small methods
promote software reusability.
The Math-Class Methods

Method Overloading in java


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the
program. In this example, we have created two methods, first add() method performs addition of two numbers
and second add method performs addition of three numbers.

20
In this example, we are creating static methods so that we don't need to create instance for calling methods.
classAdder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
classTestOverloading1{
public static void main(String[] args){ System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
In this example, we have created two methods that differs in data type. The first add method receives two integer
arguments and second add method receives two double arguments.
Private and public modifiers.
Note: The instance variables and the methods represent the properties of the objects of a Java class. Moreover,
through suitable access modifiers, we can specify: • which fields should be visible to the outside the class, i.e., to
the clients of the class– such fields are called public; • which fields should be hidden to the clients since they are
not relevant for them– such fields are called private.
Controlling the access to the fields of a class : The access modifiers public and private have the following
meaning:
1. Public indicates that the method / instance variable is visible outside the class, i.e., by the clients of the
class.
2. Private indicates that the method / instance variable is not visible outside the class, and hence can only
be used inside the class itself and not by its clients.
Example:
public class ClientClassPerson2 {
public static void main(String[] args) {
Person p1;
p1 = new Person();
p1.setResidence("Roma");
//OK! the field setResidence is public
System.out.println(p1.getResidence())
//OK! the field getResidence is public
System.out.println(p1.residence);

21
//ERROR! the field residence is private
}
}
This example shows a client that tries to access the public and private fields of the class Person. While the acces
to the public fields, setResidence and getResidence, is allowed, the access to the private field, residence, causes
an error at compile time.
Rules for accessing the fields of a class
Typically, the access to the fields of a class is done as follows:
a) The methods that correspond to functionalities of the class that are of interest for the clients are declared
as public.
b) The instance variables and the auxiliary methods, i.e., those methods that help to realize the methods
representing the functionalities of interest, are declared as private. In this way, the methods that
correspond to functionalities of interest for the clients are visible to the outside the class, while the
instance variables and the auxiliary methods that are needed to support those functionalities, but that are
not of interest for the clients, are visible only inside the class.
The set of public fields of a class is called the public interface of the class.
Note: In Java, there are two additional access modalities, namely protected and “visible in the package” (the
latter is obtained by omitting the access modifier)
Parameter passing method
As said, the definition of a method contains in the header a list of formal parameters. Such parameters are used in
the same way as variables inside the body of the method. The call of a method contains the parameters that have
to be used as arguments for the method. Such parameters are called actual parameters, to distinguish them from
the formal parameters appearing in the header of the method definition. When we call a method and thus activate
it, we have to bind the actual parameters to the formal parameters. In general, there are various ways of
establishing such a binding. In Java, there is just one way: the so called call by value.
Discriminating data Members and Variables Declared inside Methods
When declaring a method inside a class, it is okay to name the variables inside the input argument list of the
method with the identifier similar to a variable used for a data member of the class. However, since both data
members and variables declared in the method can be used inside the method, programmers need to know how to
distinguish between variables for data members and variables declared in the method with the same identifiers.
Situations in which programmers choose to use ambiguous variable names are not uncommon at all. Some
examples of such situations can be seen in accessor and mutator methods which will be discussed shortly after
this. The this keyword is used with the dot operator for this situation. Suppose that there is a data member that is
represented by a variable var. In the same class, there is a method whose input argument list contains another
variable that is also named var. The expression this.var will refer to var that is the data member, while using var
without the this keyword will refer to var that is declared inside the method.

22
Writing Your Own Methods
The general format of a method declaration is that we firstly write the method header, which is the first line.
Following the method header, declarations and statements in braces form the method body, which is a block.
Variables can be declared in any block and blocks can be nested, but a method cannot be declared inside another
method. The basic format of a method declaration is
return-value-type method-name(para1, para2,…. paraN) {
Declarations and statements
}
Note para means parameter.
The method-name is any valid identifier. The return-value-type is the type of the result returned by the method to
the caller (int, char, double, …). Methods can return at most one value.
The parameters are declared in a comma-separated list enclosed in parentheses that declares each parameter’s
type and name. There must be one argument in the method call for each parameter in the method declaration.
Also, each argument must be compatible with the type of the corresponding parameter. For example, a parameter
of type double can receive values of 8.56, 67 or –0.89567, but not “year” (because a string cannot be implicitly
converted to a double variable). If a method does not accept any arguments, the parameter list is empty (i.e., the
name of the method is followed by an empty set of parentheses). Parameters are sometimes called formal
parameters.
There must be a one-on-one correspondence between the arguments in the method call and the parameter list in
the method. For example, if we have the following in the method call avg(a,b,c), then x, y, and z will represent a,
b, c, respectively in the following method declaration
static double avg(float x, float y, float z) {
Parameters x, y and z in the method avg are sometimes called the dummy arguments or formal parameters,
simply because they are placeholders for the real and / or actual parameters or arguments that are coming from
the method call. There is no hard and fast rule about whether the parameters in the method call and that of the
method are the same. But for good programming principle, we always use different nomenclatures (names) for
them. What this means is that float x, float y, float z in the method could as well be written as float a, float b,
float c.
There are two major ways of passing parameters into methods/functions in a program. When the actual values of
variables are passed into a method, this is called parameter passing by value. Any changes on this data do not
affect the original data. Parameter passing by reference is a two-way communication process. Usually the
address of a variable is passed into a method and any changes made on the variable affects the original value of
the variable in wherever it is located in memory. Array address passing is an example.
There are three ways of returning control to the statement that calls a method.
1. If the method does not return a result, control returns when the program flow reaches the method’s
ending right brace;
2. Or when the statement return; is executed; and

23
3. If the method returns a result, the statement return expression; evaluates the expression, then returns the
resulting value to the caller.
When a return statement executes, control returns immediately to the statement that called the method. Below is
an example to illustrate programmer-defined methods.
Example 1: A Method that Returns the Cube of an Integer
public class TestCube {
public static void main(String[ ] args) {
for (int i = 0; i < 6; i++)
System.out.println(i + “\t” + Cube(i));
}
static int Cube(int n) {
return n * n * n;
}
}

Explain methods and types


Methods describe behaviors of objects of the class. there were two types of methods:
1. static (class) methods and
2. non-static (instance) methods.
A (public) method defined in a class definition is by default non-static and it can be invoked by other classes via
the instance name of an object of that class using the dot operator. To make a method static, the keyword static is
put in the method header. This way, the method can be invoked using the dot operator with the name of the class.
The general syntax of defining a method in a class is follows: (modifier)
(static) returnType methodName(argumentList){ methodBody }
An access level modifier (shown as (modifier)), being either public, private, or protected, can be specified at the
beginning of the method header. It determines whether which classes can make use of this method. The access
levels specified by public, private, and protected are similar to when they are used with data members. The
keyword static makes the method static, or a class method. If omitted, the method is considered as non-static, or
an instance method.
We can define as many methods as we would like in the class definition. If the definition contains a public
method named main(), the class can be executed by java.exe. In other words, the class is in fact a Java program

24
CHAPTER TWO
What is Object-oriented Programming?

Object-oriented programming (OOP) is a programming paradigm using "objects", which are data structures
consisting of data fields and methods together with their interactions, to design applications and computer
programs.

It is an approach that provides a way of modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies of such modules on demand.”

Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations
that can access the data. Since the memory partitions are independent, the objects can be used in a variety of
different programs without modifications.
One of the principal advantages of object-oriented programming techniques over procedural programming
techniques is that they enable programmers to create modules that do not need to be changed when a new type of
object is added. A programmer can simply create a new object that inherits many of its features from existing
objects. This makes object-oriented programs easier to modify and maintain.

To perform object-oriented programming, one needs an object-oriented programming language (OOPL). Java,
C++ and Smalltalk are three of the more popular languages, and there are also object-oriented versions of Pascal
and FORTRAN.

A Look at Procedure-Oriented Programming


Conventional programming, using high-level languages such as COBOL, FORTRAN and C, is commonly
known as procedure-oriented programming (POP). Simple, POP programs may be one "long" list of statements
(or commands). More complex programs will often group smaller sections of these statements into functions or
subroutines, each of which might perform a particular task. With designs of this sort, it is common for some of
the program's data to be 'global', i.e. accessible from any part of the program. As programs grow in size, allowing
any function to modify any piece of data means that bugs can have wide-reaching effects. In essence, while we
concentrate on the development of functions, very little attention is given to the data that are being used by
various functions. What happens to the data? How are they affected by the functions that work on them?

In a multi-function program, many important data items are placed as global so that they may be accessed by all
the functions. Each function may have its own local data. Global data are more vulnerable to an inadvertent
change by a function. In a large program it is very difficult to identify what data is used by which function. In
case we need to revise an external data structure, we also need to revise all functions that access the data. This
provides an opportunity for bugs to creep in.

Another serious drawback with the procedural approach is that it does not model real world problems very well.
This is because functions are action-oriented and do not really correspond to the elements of the problem.

Some characteristics exhibited by procedure-oriented programming are:


 Emphasis is on doing things (algorithms)
 Large programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

25
Object-Oriented Programming Paradigm
The major motivating factor in the invention of object-oriented approach is to remove some of the flaws
encountered in the procedural approach. OOP treats data as a critical element in the program development and
does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it,
and protects it from accidental modification from outside functions. OOP allows decomposition of a problem
into a number of entities called objects and then builds data and functions around these objects. The organization
of data and functions in object-oriented programs is shown in Figure below. The data of an object can be
accessed only by the functions associated with that object. However, functions of one object can access the
functions of other objects.

Object A Object B
Data Data
Communication

Functions Functions

Some of the striking features of object-oriented programming are:


 Emphasis is on data rather than procedure.
 Programs are divided into what are known as objects.
 Data structures are designed such that they characterize the objects.
 Functions that operate on the data of an object are tied together in the data structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follows bottom-up approach in program design.

Basic Concepts of Object-Oriented Programming


It is necessary to understand some of the concepts used extensively in object-oriented programming. These
include:
Objects

An object is a bundle, a clump, a gathering together of items of information that belong together, and functions
that work on those items of information. Software objects are modeled after real-world objects in that they too
have state and behaviour. A software object maintains its state in one or more variables. A variable is an item of
data named by an identifier. A software object implements its behaviour with methods. A method is a function
(or subroutine or procedure) associated with an object.

Therefore, an object is a software bundle of variables and related methods.

26
Everything that the software object knows (state) and can do (behaviour) is expressed by the variables and the
methods within that object.

Consider real life objects, dogs have state (name, colour, breed, hungry) and behaviour (barking, fetching and
wagging tail). Bicycles have state (current gear, current pedal cadence, two wheels, number of gears) and
behaviour (braking, accelerating, slowing down, changing gears).

A BankAccount object might gather up a customer number, account number, and current balance--these three
pieces of information are required for all bank accounts. Many languages provide a way to group related
information together into structures or records or whatever the language calls the feature. However, where an
object differs from these is in including functions, or behavior, as well as information. Our BankAccount object
will have Deposit( ), Withdraw( ), and GetBalance( ) functions, for example. Program objects should be chosen
such that they match closely with the real-world objects. Objects take up space in the memory and have an
associated address like a record in Pascal, or a structure in C.

When a program is executed, the objects interact by sending messages to one another. For example, if ‘customer’
and ‘account’ are two objects in a program, then the customer object may send a message to the account object
requesting for the bank balance. This information is passed along with the message as Parameters. Each object
contains data, and code to manipulate the data. Objects can interact without having to know details of each
other’s data or code. It is sufficient to know the type of message accepted, and the type of response returned by
the objects

27
Classes

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other
bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and
therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the
class of objects known as bicycles. A class is the blueprint from which individual objects are created. In essence,
“A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a
certain kind”.

Objects vs. Classes: you probably noticed that all the illustrations of objects and classes look very similar. And
indeed, the difference between them is often the source of some confusion. In the real world, it’s obvious that
classes are not themselves the objects they describe. A blueprint of a bicycle is not a bicycle. However, it’s a
little more difficult to differentiate classes and objects in software. This is partially because software objects are
merely electronic models of real-world objects or abstract concepts in the first place. But it’s also because the
term “object” is sometimes used to refer to both classes and instances.

Data Abstraction And Encapsulation

The wrapping up of data [variables or state] and functions [methods] into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside
world, and only those functions, which are wrapped in the class, can access it. These functions provide the
interface between the object’s data and the program. This insulation of the data from the direct access by the
program is called data hiding or information hiding. Encapsulating related variables and methods [functions]
into a neat software bundle is a simple yet powerful idea that provides two primary benefits to software
developers:
(1) Modularity: The source code for an object can be written and maintained independently of the
source code for other objects. Also, an object can be easily passed around in the system.
(2) Information hiding: an object has a public interface that other objects can use to communicate with
it. The object can maintain private information and methods/functions that can be changed at any time
without affecting the other objects that depend on it. For instance, you don’t need to understand the gear
mechanism on your bike to use it.

Abstraction refers to the act of representing essential features without including the background details or
explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size,
weight and cost, and functions to operate on these attributes. They encapsulate all the essential properties of the
objects that are to be created. The attributes are sometimes called data members because they hold information.
The functions that operate on these data are sometimes called methods or member functions.

Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).
Inheritance

Inheritance is the process by which objects of one class acquire the properties of another class. It supports the
concept of hierarchical classification. For example, the bird ‘Robin’ is a part of the class ‘flying bird’, which is
again a part of the class ‘ bird’. The principle behind this sort of division is that each derived class shares
common characteristics with the class from which it is derived.

28
In OOP, the concept of inheritance provides the ideal of reusability. This means that we can add additional
features to an existing class without modifying it. This is possible by deriving a new class from the existing one.
The new class will have the combined features of both the classes. The real appeal and power of the inheritance
mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what he wants, and to
tailor the class in such a way that it does not introduce any undesirable side-effects into the rest of the classes.

Note that each sub-class defines only these features that are unique to it. Without the use of classification, each
class would have to explicitly include all of its features.

Polymorphism

Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more
than one form. An operation may exhibit different behaviours in different instances. The behaviour depends
upon the types of data used in the operation. For example, consider the operation of addition (+). For two
numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third
string by concatenation. The process of making an operator to exhibit different behaviours in different instances
is known as operator overloading.

Polymorphism plays an important role in allowing objects having different internal structures to share the same
external interface. This means that a general class of operations may be accessed in the same manner even
though specific actions associated with each operation may differ. Polymorphism is extensively used in
implementing inheritance.
Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic
binding (also known as late binding) means that the code associated with a given procedure call is not known
until the time of the call at run - time. It is associated with polymorphism and inheritance. A function call
associated a polymorphic reference depends on the dynamic type of that reference.
Message Passing

An object-oriented program consists of a set of objects that communicate with each other. The process of
programming in an object-oriented language, therefore, involves the following basic steps:
1. Creating classes that define objects and their behaviour,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
The concept of message passing makes it easier to talk about building systems that directly model or simulate
their real-world counterparts. Message passing involves specifying the name of the object, the name of the
function /method and the information to be sent. E.g. employee.salary(name);

Bundling code into individual software objects provides a number of benefits, including:
 Modularity: The source code for an object can be written and maintained independently of the source code
for other objects. Once created, an object can be easily passed around inside the system.
 Information-hiding: By interacting only with an object's methods, the details of its internal implementation
remain hidden from the outside world.
 Code re-use: If an object already exists (perhaps written by another software developer), you can use that
object in your program. This allows specialists to implement/test/debug complex, task-specific objects,
which you can then trust to run in your own code.

29
 Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it
from your application and plug in a different object as its replacement. This is analogous to fixing
mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
 Message passing techniques for communication between objects makes the interface descriptions with
external systems much simpler.
 Software complexity can be easily managed.

The promising areas for OOP application include Real-time systems, Simulation and Modelling, Object-
oriented Databases, Hypertext, Hypermedia, AI, Expert Systems, Neural Networks, Decision support systems
CAM and CAD systems.

Summary

This chapter briefly introduced you to the basic principles of Object Oriented Programming paradigms. The two
main programming paradigms – Imperative and Declarative were discussed. You have also being introduced to
the basic concepts of OOP.

In summary, the five basic concepts of object-oriented design are the implementation level features that are built
into the programming language. These features are often referred to by these common names:

 Object/Class: A tight coupling or association of data structures with the methods or functions that act on
the data. This is called a class, or object (an object is created based on a class). Each object serves a separate
function. It is defined by its properties, what it is and what it can do. An object can be part of a class, which
is a set of objects that are similar.
 Information hiding: The ability to protect some components of the object from external entities. This is
realized by language keywords to enable a variable to be declared as private or protected to the owning
class.
 Inheritance: The ability for a class to extend or override functionality of another class. The so-called subclass
has a whole section that is derived (inherited) from the superclass and then it has its own set of functions
and data.
 Interface: The ability to defer the implementation of a method. The ability to define the functions or
methods signatures without implementing them.
 Polymorphism: The ability to replace an object with its subobjects. The ability of an object-variable to
contain, not only that object, but also all of its subobjects.

30
CHAPTER THREE
Concept of expression in Java
Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new value, although
sometimes an expression simply assigns a value to a variable. Expressions are built using values, variables,
operators and method calls.
An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value.
Expressions contain operators and operands. Expressions and Operators Expressions are the simplest form of
statement in Java that actually accomplishes something. Expressions are statements that return a value.
The parts of an expression must be arranged correctly. The syntax of Java describes the correct arrangements.
The rules for correct Java expressions are about the same as for algebra.
Essentially,
▪ Each operator must have the correct number of operands. Multiplication *, Division /, Addition +, Subtraction -
should have two operands, one on each side. Negation - and unary plus + should be followed by one operand.
▪ Parentheses () can surround a legal expression to make it an operand. In Java expressions, operators and
operands must be explicit. In 13 - 5 the 13 and the 5 are the operands and the - is the operator. In 14*sum 14 and
sum are the operands. The star for multiplication must be present.
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types of expressions in Java:
1. Those that produce a value, i.e. the result of (1 + 1)
2. Those that assign a variable, for example (v =10)
3. Those that have no result but might have a "side effect" because an expression can include a wide range
of elements such as method invocations or increment operators that modify the state (i.e. memory) of a
program.
OPERATORS
Operators are special symbols that are commonly used in expressions. Arithmetic and tests for equality and
magnitude are common examples of expressions. Because they return a value, you can assign that result to a
variable or test that value in other Java statements. Operators in Java include arithmetic, various forms of
assignment, increment and decrement, and logical operations.
An operator is a symbol such as +, -, *, or / that calls for an arithmetic operation. An operand is a value that is
acted upon by an operator.

31
Each operator takes two operands, one on either side of the operator. The subtraction operator (–) can also be
used to negate a single operand. Integer division results in an integer. Because integers don’t have decimal
fractions, any remainder is ignored. The expression 31 ÷ 9, for example, results in 3 (9 goes into 31 only 3
times). Modulus (%) gives the remainder once the operands have been evenly divided. For example, 31 % 9
results in 4 because 9 goes into 31 three times, with 4 left over. Note that, for integers, the result type of most
operations is an int or a long, regardless of the original type of the operands. Large results are of type long; all
others are int. Arithmetic wherein one operand is an integer and another is a floating point results in a floating-
point result

32
ASSIGNMENT OPEARTOR
More About Assignment Variable assignment is a form of expression; in fact, because one assignment
expression results in a value, you can string them together like this: x = y = z = 0; In this example, all three
variables now have the value 0. S S F R W T M The right side of an assignment expression is always evaluated
before the assignment takes place. This means that expressions such as x = x + 2 do the right thing; 2 is added to
the value of x, and then that new value is reassigned to x. In fact, this sort of operation is so common that Java
has several operators to do a shorthand version of this, borrowed from C and C++. Table 3.4 shows these
shorthand assignment operators

INCREAMENT AND DECEMENT OPERATORS


Incrementing and Decrementing As in C and C++, the ++ and –– operators are used to increment or decrement a
value by 1. For example, x++ increments the value of x by 1 just as if you had used the expression x = x + 1.
Similarly x–– decrements the value of x by 1. These increment and decrement operators can be prefixed or
postfixed; that is, the ++ or –– can appear before or after the value it increments or decrements. For simple
increment or decrement expressions, which one you use isn’t overly important. In complex assignments, where
you are assigning the result of an increment or decrement expression, which one you use makes a difference.
Take, for example, the following two expressions: y = x++; y = ++x; These two expressions give very different
results because of the difference between prefix and postfix. When you use postfix operators (x++ or x––), y gets
the value of x before before x is incremented; using prefix, the value of x is assigned to y after the increment has
occurred.
Test of prefix and postfix increment operators.
1: class PrePostFixTest {
3: public static void main (String args[]) {
4: int x = 0;
5: int y = 0;
7: System.out.println(“x and y are “ + x + “ and “ + y );
8: x++;
9: System.out.println(“x++ results in “ + x);
10: ++x;
11: System.out.println(“++x results in “ + x);
12: System.out.println(“Resetting x back to 0.”);
13: x = 0;
14: System.out.println(“——————”);
15: y = x++;
16: System.out.println(“y = x++ (postfix) results in:”);
17: System.out.println(“x is “ + x);

33
18: System.out.println(“y is “ + y);
19: System.out.println(“——————”);
20:
21: y = ++x;
22: System.out.println(“y = ++x (prefix) results in:”);
23: System.out.println(“x is “ + x);
24: System.out.println(“y is “ + y);
25: System.out.println(“——————”);
26:
27: }
28:
29: }
x and y are 0 and 0
x++ results in 1
++x results in 2
Resetting x back to 0.
——————
y = x++ (postfix) results in:
x is 1
y is 0
——————
y = ++x (prefix) results in:
x is 2
y is 2
—————

Comparisons
Java has several expressions for testing equality and magnitude. All of these expressions return a boolean value
(that is, true or false). Table 3.5 shows the comparison operators:

34
Logical Operators
Expressions that result in boolean values (for example, the comparison operators) can be combined by using
logical operators that represent the logical combinations AND, OR, XOR, and logical NOT.
For AND combinations, use either the & or &&. The expression will be true only if both operands tests are also
true; if either expression is false, the entire expression is false. The difference between the two operators is in
expression evaluation. Using &, both sides of the expression are evaluated regardless of the outcome. Using &&,
if the left side of the expression is false, the entire expression returns false, and the right side of the expression is
never evaluated.
For OR expressions, use either | or ||. OR expressions result in true if either or both of the operands is also true; if
both operands are false, the expression is false. As with & and &&, the single | evaluates both sides of the
expression regardless of the outcome; with ||, if the left expression is true, the expression returns true and the
right side is never evaluated.
In addition, there is the XOR operator ^, which returns true only if its operands are different (one
true and one false, or vice versa) and false otherwise (even if both are true).
In general, only the && and || are commonly used as actual logical combinations. &, |, and ^ are
more commonly used for bitwise logical operations.
For NOT, use the ! operator with a single expression argument. The value of the NOT expression
is the negation of the expression; if x is true, !x is false.
Bitwise Operators
Finally, here’s a short summary of the bitwise operators in Java. These are all inherited from C
and C++ and are used to perform operations on individual bits in integers. This book does not
go into bitwise operations; it’s an advanced topic covered better in books on C or C++. Table
3.6 summarizes the bitwise operators

35
Expressions using precedence rules.
Operator precedence determines the order in which expressions are evaluated. This, in some cases, can determine
the overall value of the expression.
For example, take the following expression:
y=6+4/2
Depending on whether the 6 + 4 expression or the 4 ÷ 2 expression is evaluated first, the value of y can end up
being 5 or 8.
Operator precedence determines the order in which expressions are evaluated, so you can predict the outcome of
an expression. In general,
a) increment and decrement are evaluated before arithmetic,
b) arithmetic expressions are evaluated before comparisons,
c) Comparisons are evaluated before logical expressions.
d) Assignment expressions are evaluated last.
The table shows the specific precedence of the various operators in Java.
Operators further up in the table are evaluated first; operators on the same line have the same precedence and are
evaluated left to right based on how they appear in the expression itself. For example, give that same expression
y = 6 + 4 ÷ 2, you now know, according to this table, that division is evaluated before addition, so the value of y
will be 8.
Operator Precedence and Associativity
Each operator in Java has a precedence associated with it. This precedence is used to determine how an
expression involving more than one operator is evaluated. There are distinct levels of precedence and an operator
may belong to one of the levels. The operators at the higher level of precedence are evaluated first. The operators
of the same precedence are evaluated either from left to right or from right to left, depending on the level. This is
known as the associativity property of an operator. The table below provides a complete lists of operators, their
precedence levels, and their rules of association. The groups are listed in the order of decreasing precedence
(rank 1 indicates the highest precedence level and 14 the lowest).
In addition
As an example, let's say we have the following line of Java code: int x = 4 + 3 * 5; The variable x gets the value
of evaluating the expression 4 + 3 * 5.
There are a couple of ways to evaluate that expression, though: We can either perform the addition first or
perform the multiplication first. By choosing which operation to perform first, we are actually choosing between
two different expressions: 1. (4 + 3) * 5 == 35 2. 4 + (3 * 5) == 19 In the absence of parentheses, which choice is
appropriate? Programming languages answer this question by defining precedence levels for each operator,
indicating which is to be performed first. In the case of Java, multiplication takes precedence over addition;
therefore, x will get the value 19.

36
For arithmetic expressions, multiplication and division are evaluated before addition and subtraction, just like in
mathematics. Of course, just as you might in a math class, you can always parenthesize Java expressions to
indicate which are to be evaluated first. Sensible use of parentheses will make your programs easier to read even
if your expressions all use the standard evaluation order

Operator associativity.
The order in which the expressions are evaluated is referred to as their association. When an expression has two
operators with the same precedence, the operators and operands are grouped according to their associativity. For
example 72 / 2 / 3 is treated as (72 / 2) / 3 since the division operator is left-to-right associate. You can use
parentheses to override the default operator associativity rules.
Most Java operators are left-to-right associative. One notable exception is the assignment operator, which is
right-to-left associative. As a result, the expression x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three
variables with the value 17. Recall that an assignment statement evaluates to the value of its right-hand side.
Associativity it not relevant for some operators. For example, x <= y <= z and x++-- are invalid expressions in
Java.
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
variable = expressions;

37
Variable is any valid Java variable name. When the statement is encountered, the expression is evaluated first
and the result then replaces the previous value of the variable on the left-hand side. All variables used in the
expression must be assigned value before evaluation is attempted.
Examples of evaluation statements are
x = a*b–c;
y = b/c*a;
z = a–b/c+d;
The blank space around an operator is optional and is added only to improve readability.
When these statements are used in program, the variables a,b,c and d must be defined before they are used in the
expressions.
An arithmetic expression without any parentheses will be evaluated from left to right using the rules of
precedence of operators. There are two distinct priority levels of arithmetic operators in Java:
The basic evaluation procedure includes two left-to-right passed through the expression. During the first pass,
the high priority operators (if any) are applied as they are encountered.
a) High priority * / %
b) Low priority + –
During the second pass, the low priority operators (if any) are applied as they are encountered. Consider the
following evaluation statement:
x = a–b/3 + c*2–1
When a = 9, b = 12, and c = 3, the statement becomes
x = 9–12/3+3*2–1 and is evaluated as follows:
First pass
Step1: x = 9–4+3*2–1 (12/3 evaluated)
Step2: x = 9–4+6–1 (3*2 evaluated)
Second pass
Step3: x = 5+6–1 (9–4 evaluated)
Step4: x = 11–1 (5+6 evaluated)
Step5: x = 10 (11–1 evaluated)
However, the order of evaluation can be changed by introducing parentheses into an expression. Consider the
same expression with parentheses as shown below:
9–12/(3+3)*(2–1)

38
Whenever the parentheses are used, the expressions within parentheses assume highest priority. If two or more
sets of parentheses appear one after another as shown above, the expression contained in the left-most set is
evaluated first and the right-most in the last. Given below are the new steps.
First pass
Step1: 9–12/6*(2–1)
Step2: 9–12/6*1
Second pass
Step3: 9–2*1
Step4: 9–2
Third pass
Step5: 7
This time, the procedure consists of three left-to-right passes. However, the number of evaluation steps remain
the same as 5 (i.e., equal to the number of arithmetic operators).
Parentheses may be nested, and in such cases, evaluation of the expression will proceed outward from the
innermost set of parentheses. Just make sure that every parentheses has a matching closing one. For example
9–(12/3(3+3)*2)–1 = 4
Whereas
9–((12/3)+3*2)–1 = –2
EXAMPLES
Now let us consider some examples in the light of the rules of operator precedence; we will list both the
algebraic expression and the equivalent java expression.
Algebra :
Java : (x+ y + z)/3;
This expression calculates the average of three values. The parentheses is required so that the values represented
by x, y and z will be added and the result divided by three. If the parentheses is omitted only z will be divided by
three because division has a higher precedence over addition.
Exercise 1
1) Show the result of the following code:
a) System.out.println(2 * (5 / 2 + 5 / 2));
b) System.out.println(2 * 5 / 2 + 2 * 5 / 2);
c) System.out.println(2 * (5 / 2));
d) System.out.println(2 * 5 / 2);

39
2) Are the following statements correct? If so, show the output.
a) System.out.println("25 / 4 is " + 25 / 4);
b) System.out.println("25 / 4.0 is " + 25 / 4.0);
c) System.out.println("3 + 2 is " + 3 + 2);
d) System.out.println("3 + 2 is " + (3 + 2));
e) System.out.println("3 * 2 / 4 is " + 3 * 2 / 4);
f) System.out.println("3.0 * 2 / 4 is " + 3.0 * 2 / 4);
3) Suppose m and r are integers. Write a Java expression for mr2 to obtain a floating-point result.
4) How would you write the following arithmetic expression in Java?
a) 43(r + 34)
b) 5.5 × (r +2.5)2.5+𝑡
−9(𝑎 +𝑏𝑐)+ 3 +𝑑(2 +𝑎)
𝑎+𝑏𝑑
5) Show the output of the following code:
double a = 6.5;
a += a + 1;
System.out.println(a);
a = 6;
a /= 2;
System.out.println(a);
6) Show the output of the following code:
int a = 6;
int b = a++;
System.out.println(a);
System.out.println(b);
a = 6;
b = ++a;
System.out.println(a);
System.out.println(b);
7) Is the following code going to print 0.1 and why?
System.out.println(1.0 - 0.9);
Exercise 2:
Choose the correct answer:
A. The value of 15 / 2 is: (i) 7 (ii) 7.5
B. The value of 18 / 3 is: (i) 6 (iii) 7 ½ (ii) 0.167 (iii) 6.0

40
C. The value of 22 % 7 is: (i) 3 (ii) 1 (iv) 0.75 (iv) none
(iii) 3.142 (iv) 22/7
D. The value of 5 % 7 is: (i) 0 (ii) 2 (iii) 5 (v) none (iv) undefined
E. The value of 17.0 / 4 is: (i) 4 (ii) 4.25
F. The value of 5 - 3.0 + 2 is: (i) 0 (ii) 0.0
G. The value of 7 - 5 * 2 + 1 is: (i) -2 (ii) 5 (iii) 4.0 (iii) 4 (iii) 6 (iv) undefined (iv) 4.0 (iv) none

41
42
CHAPTER FOUR
Conditional Statements in Java
A Java program am is a set of statements, which are normally executed sequentially in the order in which They
appear. This happens when options or repetitions of certain calculations are not necessary. However, in practice,
we have a number of situations, where we may have to change the order of execution of statements based on
certain conditions, or repeat a group of statements until certain specified conditions are met. This involves a kind
of decision making to see whether a particular condition has occurred or not and then direct the computer to
execute certain statements accordingly. When a program breaks the sequential flow and jumps to another part of
the code, it is called branching. When the branching is based on a particular condition, it is known as conditional
branching. If branching takes place without any decision, it is known as unconditional branching.
Java language possesses such decision making capabilities and supports the following statements nown as
control or decision making statements.

1. if statement
2. switch statement
3. Conditional operator statement

In the programs that we have examined to this point, each of the statements in the program is executed once, in
the order given. Most programs are more complicated because the sequence of statements and the number of
times each is executed can vary. We use the term control flow to refer to statement sequencing in a program. In
this section, we introduce statements that allow us to change the control flow, using logic about the values of
program variables. This feature is an essential component of programming.
Specifically, we consider Java statements that implement conditionals, where some other statements may or may
not be executed depending on certain conditions, and loops, where some other statements may be executed
multiple times, again depending on certain conditions. As you will see in numerous examples in this section,
conditionals and loops truly harness the power of the computer and will equip you to write programs to
accomplish a broad variety of tasks that you could not contemplate attempting without a computer.

43
Bock Statements
A block statement is a group of other statements surrounded by braces ({}). You can use a block anywhere a
single statement would go, and the new block creates a new local scope for the statements inside it. This means
that you can declare and use local variables inside a block, and those variables will cease to exist after the block
is finished executing. For example, here’s a block inside a method definition that declares a new variable y. You
cannot use y outside the block in which it’s declared:
void testblock() {
int x = 10;
{ // start of block
int y = 50;
System.out.println(“inside the block:”);
System.out.println(“x:” + x);
System.out.println(“y:” + y);
} // end of block
}
5
Blocks are not usually used in this way—alone in a method definition. You’ve mostly seen blocks up to this
point surrounding class and method definitions, but another very common use of block statements is in the
control flow constructs you’ll learn about in the remainder of today’s
IF Conditional Statement
Most computations require different actions for different inputs. One way to express these differences in Java is
the if statement:
if (<boolean expression>) { <statements> }
This description introduces a formal notation known as a template that we will use to specify the format of Java
constructs. We put within angle brackets (< >) a construct that we have already defined, to indicate that we can
use any instance of that construct where specified. In this case, <boolean expression> represents an expression
that has a boolean value, such as one involving a comparison operation, and <statements> represents a statement
block (a sequence of Java statements, each terminated by a semicolon). This latter construct is familiar to you:
the body of main() is such a sequence. If the sequence is a single statement, the curly braces are optional. It is
possible to make formal definitions of <boolean expression> and <statements>, but we refrain from going into
that level of detail. The meaning of an if statement is self-explanatory: the statement(s) in the sequence are to be
executed if and only if the expression is true.
As a simple example, suppose that you want to compute the absolute value of an int value x. This statement
does the job:

44
if (x < 0) x = -x;
You can also add an else clause to an if statement, to express the concept of executing either one statement (or
sequence of statements) or another, depending on whether the boolean expression is true or false, as in the
following template:
if (<boolean expression>) <statements T>
else <statements F>
As a simple example of the need for an else clause, consider the following code, which assigns the maximum of
two int values to the variable max:
if (x > y) max = x;
else max = y;
if conditionals contain the keyword if, followed by a Boolean test, followed by a statement (often a block
statement) to execute if the test is true:
if (x < y)
System.out.println(“x is smaller than y”);
An optional else keyword provides the statement to execute if the test is false:
if (x < y)
System.out.println(“x is smaller than y”);
else System.out.println(“y is bigger.”);
Technical Note: The difference between if conditionals in Java and C or C++ is that the test must return a
boolean value (true or false). Unlike in C, the test cannot return an integer.
if (engineState == true )
System.out.println(“Engine is already on.”);
else {
System.out.println(“Now starting Engine”);

if (gasLevel >= 1)
engineState = true;
else System.out.println(“Low on gas! Can’t start engine.”);
}
This example uses the test (engineState == false). For boolean tests of this type, a common shortcut is merely to
include the first part of the expression, rather than explicitly testing its value against true or false:
45
if (engineState)
System.out.println(“Engine is on.”);
else System.out.println(“Engine is off”);

The Conditional Operator


An alternative to using the if and else keywords in a conditional statement is to use the conditional operator,
sometimes called the ternary operator. A conditional operator is a ternary operator because it has three terms.
The conditional operator is an expression, meaning that it returns a value (unlike the more
general if, which can result in any statement or block being executed). The conditional operator is most useful
for very short or simple conditionals, and looks like this:
test ? trueresult : falseresult
The test is an expression that returns true or false, just like the test in the if statement. If the test is true, the
conditional operator returns the value of trueresult; if it’s false, it returns the value of falseresult. For example,
the following conditional tests the values of x and y, returns the smaller of the two, and assigns that value to the
variable smaller:
int smaller = x < y ? x : y;
The conditional operator has a very low precedence; that is, it’s usually evaluated only after all its
subexpressions are evaluated. The only operators lower in precedence are the assignment operators. See the
precedence chart in Day 3’s lesson for a refresher on precedence of all the operators.
Switch Conditionals
A common practice in programming in any language is to test a variable against some value, and if it doesn’t
match that value, to test it again against a different value, and if it doesn’t match that one to make yet another
test, and so on. Using only if statements, this can become unwieldy, depending on how it’s formatted and how
many different options you have to test. For example, you might end up with a set of if statements something
like this or longer:
if (oper == ‘+’)
addargs(arg1,arg2);
else if (oper == ‘=’)
subargs(arg1,arg2);
else if (oper == ‘*’)
multargs(arg1,arg2);
else if (oper == ‘/’)

46
divargs(arg1,arg2);
This form of if statement is called a nested if, because each else statement in turn contains yet another if, and so
on, until all possible tests have been made.
A common shorthand mechanism for nested ifs that you can use in some cases allows you tests and actions
together in a single statement. This is the switch or case statement; in Java it’s switch and behaves as it does in
C:
switch (test) {
case valueOne:
resultOne;
break;
case valueTwo:
resultTwo;
break;
case valueThree:
resultThree;
break;
...
default: defaultresult;
}
In the switch statement, the test (a primitive type of byte, char, short, or int) is compared witheach of the case
values in turn. If a match is found, the statement, or statements after the testis executed. If no match is found, the
default statement is executed. The default is optional, so if there isn’t a match in any of the cases and default
doesn’t exist, the switch statement completes without doing anything.
Note that the significant limitation of the switch in Java is that the tests and values can be only simple primitive
types (and then only primitive types that are castable to int). You cannot use larger primitive types (long, float)
or objects within a switch, nor can you test for any relationship other than equality. This limits the usefulness of
switch to all but the simplest cases; nested ifs can work for any kind of test on any type.

47
Here’s a simple example of a switch statement similar to the nested if shown earlier:
switch (oper) {
case ‘+’:
addargs(arg1,arg2);
break;
case ‘*’:
subargs(arg1,arg2);
break;
case ‘-’:
multargs(arg1,arg2);
break;
case ‘/’:
divargs(arg1,arg2);
break;
}
Note the break statement included in every line. Without the explicit break, once a match is made, the statements
for that match and also all the statements further down in the switch are executed until a break or the end of the
switch is found (and then execution continues after the end of the switch). In some cases, this may be exactly
what you want to do, but in most cases, you’ll want to make sure to include the break so that only the statements
you want to be executed are executed.
One handy use of falling through occurs when you want multiple values to execute the same statements. In this
instance, you can use multiple case lines with no result, and the switch will execute the first statements it finds.
For example, in the following switch statement, the string
“x is an even number.” is printed if x has values of 2, 4, 6, or 8. All other values of x print the string “x is an odd
number.”
switch (x) {
case 2:
case 4:
case 6:
case 8:
System.out.println(“x is an even number.”);
break;
default: System.out.println(“x is an odd number.”);
}
For Loops

48
The for loop, as in C, repeats a statement or block of statements some number of times until a condition is
matched. For loops are frequently used for simple iteration in which you repeat a block of statements a certain
number of times and then stop, but you can use for loops for just about any kind of loop.
It is an alternate Java construct to while loop that allows us even more flexibility when writing programs with
loops. This alternate notation is not fundamentally different from the basic while loop, but it is widely used
because it often allows us to write more compact and more readable programs than if we used only while
statements.
The for loop in Java looks roughly like this:
for (initialization; test; increment) {
statements;
}
The start of the for loop has three parts:
1. initialization is an expression that initializes the start of the loop. If you have a loop index, this expression
might declare and initialize it, for example,
int i = 0.
Variables that you declare in this part of the for loop are local to the loop itself; they cease existing after the loop
is finished executing. (This is different from C or C++.)
2. n test is the test that occurs after each pass of the loop. The test must be a boolean expression or function
that returns a boolean value, for example, i < 10. If the test is true, the loop executes. Once the test is
false, the loop stops executing.
3. n increment is any expression or function call. Commonly, the increment is used to change the value of
the loop index to bring the state of the loop closer to returning false and completing.
The statement part of the for loop is the statement that is executed each time the loop iterates.
Just as with if, you can include either a single statement here or a block; the previous example used a block
because that is more common. Here’s an example of a for loop that initializes all the values of a String array to
null strings:
String strArray[] = new String[10];
int i; // loop index
for (i = 0; i < strArray.length; i++)
strArray[i] = “”;

Any of the parts of the for loop can be empty statements, that is, you can simply include a semicolon with no
expression or statement, and that part of the for loop will be ignored. Note that if you do use a null statement in
your for loop, you may have to initialize or increment any loop variables or loop indices yourself elsewhere in
the program.
You can also have an empty statement for the body of your for loop, if everything you want to do is in the first
line of that loop. For example, here’s one that finds the first prime number higher than 4000:

49
for (i = 4001; notPrime(i); i += 2)
;
Note that a common mistake in C that also occurs in Java is accidentally to put a semicolon after the first line of
the for loop:
for (i = 0; i < 10; i++);
System.out.println(“Loop!”);
Because the first semicolon ends the loop with an empty statement, the loop doesn’t actually do anything. The
println function will be printed only once, because it’s actually outside the for loop entirely. Be careful not to
make this mistake in your own Java programs.
while and do Loops
Finally, there are while and do loops. while and do loops, like for loops, enable a block of Java code to be
executed repeatedly until a specific condition is met. Whether you use a for loop, a while, or a do is mostly a
matter of your programming style.
while and do loops, like for, are exactly the same as those same constructions in C and C++.
while Loops
Many computations are inherently repetitive. The basic Java construct for handling such computations has the
following format:
while (<boolean expression>) { <statements> }
The while statement has the same form as the if statement (the only difference being the use of the keyword
while instead of if), but the meaning is quite different. It is an instruction to the computer to behave as follows: if
the expression is false, do nothing; if the expression is true, execute the sequence of statements (just as with if)
but then check the expression again, execute the sequence of statements again if the expression is true, and
continue as long as the expression is true. We often refer to the statement block in a loop as the body of the loop.
As with the if statement, the braces are optional if a while loop body has just one statement.
A while loop is used to repeat a given statement over and over. Of course, it’s not likely that you would want to
keep repeating it forever. That would be an infinite loop, which is
The semantics of this statement go like this: When the computer comes to a while statement, it evaluates the
boolean-expression, which yields either true or false as the value. If the value is false, the computer skips over
the rest of the while loop and proceeds to the next command in the program. If the value of the expression is
true, the computer executes the statement or block of statements inside the loop. Then it returns to the beginning
of the while loop and repeats the process. That is, it re-evaluates the Boolean-expression, ends the loop if the
value is false, and continues it if the value is true. This will continue over and over until the value of the
expression is false; if that never happens, then there will be an infinite loop.

50
The while statement is equivalent to a sequence of identical if statements:
if (<boolean expression>) { <statements> }
if (<boolean expression>) { <statements> }
if (<boolean expression>) { <statements> }

The while loop is used to repeat a statement or block of statements as long as a particular condition is true. while
loops look like this:
while (condition) {
bodyOfLoop;
}
The condition is a boolean expression. If it returns true, the while loop executes the statements in bodyOfLoop
and then tests the condition again, repeating until the condition is false. I’ve shown the while loop here with a
block statement, because it’s most commonly used, although you can use a single statement in place of the block.
Here’s an example of a while loop that copies the elements of an array of integers (in array1) to an array of
floats (in array2), casting each element to a float as it goes. The one catch is that if any of the elements in the first
array is 0, the loop will immediately exit at that point. To cover both the cases wherein all the elements have
been copied and an element is 0, you can use a compound test with the && operator:

while ((ch != ‘ ‘) && (ch != ‘\t’) && (ch != ‘\n’) && (ch != ‘\r’)) {
addChar(ch, theName);
ch = instream.read();
}

51
Note that if the condition is initially false the first time it is tested (for example, if the first elemen in that first
array is 0), the body of the while loop will never be executed. If you need to execute the loop at least once, you
can do one of two things:
a) Duplicate the body of the loop outside the while loop.
b) Use a do loop (described below).

Here is an example of a while loop that simply prints out the numbers 1, 2, 3, 4, 5:
int number; // The number to be printed.
number = 1; // Start with 1.
while ( number < 6 ) { // Keep going as long as number is < 6.
System.out.println(number);
number = number + 1; // Go on to the next number.
}
System.out.println("Done!");
The variable number is initialized with the value 1. So the first time through the while loop, when the computer
evaluates the expression “number < 6”, it is asking whether 1 is less than 6, which is true. The computer therefor
proceeds to execute the two statements inside the loop.

52
The first statement prints out “1”. The second statement adds 1 to number and stores the result back into the
variable number; the value of number has been changed to 2. The computer has reached the end of the loop, so it
returns to the beginning and asks again whether number is less than 6. Once again this is true, so the computer
executes the loop again, this time printing out 2 as the value of number and then changing the value of number to
3. It continues in this way until eventually number becomes equal to 6. At that point, the expression “number <
6”evaluates to false. So, the computer jumps past the end of the loop to the next statement and prints out the
message “Done!”. Note that when the loop ends, the value of number is 6, but the last value that was printed was
5.
By the way, you should remember that you’ll never see a while loop standing by itself in a real program. It will
always be inside a subroutine which is itself defined inside some class. As an example of a while loop used
inside a complete program, here is a little program that computes the interest on an investment over several
years. This is an improvement over examples from the previous chapter that just reported the results for one
year:

do...while Loops
The do loop is just like a while loop, except that do executes a given statement or block until a condition is false.
The main difference is that while loops test the condition before looping, making it possible that the body of the
loop will never execute if the condition is false the first time it’s tested. do loops run the body of the loop at least
once before testing the condition.
do loops look like this:
do {
bodyOfLoop;
} while (condition);
Here, the bodyOfLoop part is the statements that are executed with each iteration. It’s shown here with a block
statement because it’s most commonly used that way, but you can substitute thebraces for a single statement as
you can with the other control-flow constructs. The condition is a boolean test. If it returns true, the loop is run
again. If it returns false, the loop exits. Keep in mind that with do loops, the body of the loop executes at least
once.
Here’s a simple example of a do loop that prints a message each time the loop iterates:
int x = 1;
do {
System.out.println(“Looping, round “ + x);
x++;
} while (x <= 10);
Here’s the output of these statements:
Output

53
Looping, round 1
Looping, round 2
Looping, round 3
Looping, round 4
Looping, round 5
Looping, round 6
Looping, round 7
Looping, round 8
Looping, round 9
Looping, round 10
Breaking Out of Loops
In all the loops (for, while, and do), the loop ends when the condition you’re testing for is met.
What happens if something odd occurs within the body of the loop and you want to exit the loop early? For
You’ve already seen break as part of the switch statement; it stops execution of the switch, and the program
continues. The break keyword, when used with a loop, does the same thing—it immediately halts execution of
the current loop. If you’ve nested loops within loops, execution picks up in the next outer loop; otherwise, the
program merely continues executing the next statement after the loop.
For example, suppose you have a while loop that copies elements from one array into another.
Each element in the array should be copied until the end of the array is reached or if an element contains 0. You
can test for that latter case inside the body of the while and then use a break to exit the loop:
while (count < array1.length) {
if (array1[count] == 0) {
break;
}
array2[count] = array1[count];
count++;
}
}
Continue Conditional Statement:
continue is similar to break except that instead of halting execution of the loop entirely, the loop starts over at
the next iteration. For do and while loops, this means the execution of the clock starts over again; for for loops,
the increment expression is evaluated and then block is executed. continue is useful when you want to special-
54
case elements within a loop. With the previous example of copying one array to another, you can test for whether
the current element is 0 and restart the loop if you find it so that the resulting array will never contain zero. Note
that because you’re skipping elements in the first array, you now have to keep track of two different array
counters:
while (count < array1.length) {
if (array1[count] == 0)
continue;
array2[count2++] = (float)array1[count++];
}
Labeled Loops
Both break and continue can have an optional label that tells Java where to break to. Without a label, break
jumps outside the nearest loop (to an enclosing loop or to the next statement outside the loop), and continue
restarts the enclosing loop. Using labeled breaks and continues enables you to break outside nested loops or to
continue a loop outside the current loop.
To use a labeled loop, add the label before the initial part of the loop, with a colon between them.
Then, when you use break or continue, add the name of the label after the keyword itself: out:
for (int i = 0; i <10; i++) {
while (x < 50) {
if (i * x == 400)
break out;
...
}
...
}
In this snippet of code, the label out labels the outer for loop. Then, inside both the for and the while loop, if a
particular condition is met inside both loops, a break causes the execution to break out of both loops and restart
back at the label (out).
Here’s another example. the following program contains a nested for loop. Inside the innermost loop, if the sum
values of the two counters is greater than four, both loops exit at once:
for (int i = 1; i <= 5; i++)
for (int j = 1; j <= 3; j++) {
System.out.println(“i is “ + i + “, j is “ + j);
if ((i + j) > 4)
55
break foo;
}
System.out.println(“end of loops”);
Here’s the output from this program:
Output
i is 1, j is 1
i is 1, j is 2
i is 1, j is 3
i is 2, j is 1
i is 2, j is 2
i is 2, j is 3
end of loops

The Analysis
As you can see, the loop iterated until the sum of i and j was greater than 4, and then both loops exited back to
the outer block and the final message was printed.
Control Flow Statements
The control flow statements in Java allow you to run or skip blocks of code when special conditions are met. A
repetition statement (also called a looping statement or a loop) allows the programmer to specify that a program
should repeat an action while some condition remains true.
The two types of control structures, loops and branches, can be used to repeat a sequence of statements over and
over or to choose among two or more possible courses of action. Java includes several control structures of each
type, and we will look at each of them in some detail.
The ability of a computer to perform complex tasks is built on just a few ways of combining simple commands
into control structures. In Java, there are just six such structures that are used to determine the normal flow of
control in a program—and, in fact, just three of them would be enough to write programs to perform any task.
The six control structures are:
1. the block,
2. the while loop,
3. the do..while loop,
4. the for loop,
5. the if statement, and the
6. switch statement.
56
They are already discussed.
Each of these structures is considered to be a single “statement,” but each is in fact a structured statement that
can contain one or more other statements inside itself.
Blocks
The block is the simplest type of structured statement. Its purpose is simply to group a
sequence of statements into a single statement. The format of a block is:
{
}
statements
CONTROL
That is, it consists of a sequence of statements enclosed between a pair of braces, “{” and “}”.
(In fact, it is possible for a block to contain no statements at all; such a block is called an empty block, and can
actually be useful at times. An empty block consists of nothing but an empty pair of braces.) Block statements
usually occur inside other statements, where their purpose is to group together several statements into a unit.
However, a block can be legally used wherever a statement can occur. There is one place where a block is
required: As you might have already noticed in the case of the main subroutine of a program, the definition of a
subroutine is a block, since it is a sequence of statements enclosed inside a pair of braces.
There are no syntax rules about how the language has to be arranged on a page. So, for example,you could write
an entire block on one line if you want. But as a matter of good programming style, you should lay out your
program on the page in a way that will make its structure as clear as possible. In general, this means putting one
statement per line and using indentation to indicate statements that are contained inside control structures. This is
the format that will generally use in my examples.
Here are two examples of blocks:
{
}
System.out.print("The answer is ");
System.out.println(ans);
{ // This block exchanges the values of x and y
int temp;
// A temporary variable for use in this block.
temp = x;
x = y;
y = temp;

57
}
// Save a copy of the value of x in temp.
// Copy the value of y into x.
// Copy the value of temp into y.
In the second example, a variable, temp, is declared inside the block. This is perfectly legal, and it is good style
to declare a variable inside a block if that variable is used nowhere else but inside the block. A variable declared
inside a block is completely inaccessible and invisible from outside that block. When the computer executes the
variable declaration statement, it allocates memory to hold the value of the variable. When the block ends, that
memory is discarded (that is, made available for reuse). The variable is said to be local to the block.
The block statement by itself really doesn’t affect the flow of control in a program. The five remaining control
structures do. They can be divided into two classes: loop statements and branching statements. You really just
need one control structure from each category in order to have a completely general-purpose programming
language. More than that is just convenience.

public class Interest3 {


/*
*/
This class implements a simple program that will compute the amount of interest that is earned on an investment
over a period of 5 years. The initial amount of the investment and the interest rate are input by the user.
The value of the investment at the end of each year is output.
public static void main(String[] args) {
double principal; // The value of the investment.
double rate;
// The annual interest rate.
/* Get the initial investment and interest rate from the user. */
TextIO.put("Enter the initial investment: ");
principal = TextIO.getlnDouble();
TextIO.put("Enter the annual interest rate: ");
rate = TextIO.getlnDouble();
/* Simulate the investment for 5 years. */
int years; // Counts the number of years that have passed.
years = 0;
while (years < 5) {
58
double interest; // Interest for this year.
interest = principal * rate;
principal = principal + interest;
years = years + 1;
// Add it to principal.
// Count the current year.
System.out.print("The value of the investment after ");
System.out.print(years);
System.out.print(" years is $");
System.out.printf("%1.2f", principal);
System.out.println();
} // end of while loop
} // end of main()
} // end of class Interest3
You should study this program, and make sure that you understand what the computer does
step-by-step as it executes the while loop.

59
CHAPTER FIVE
STRING AND CHARACTERS MANIPULATION
In Java, a string is an object. It is a reference data type. The String class is used to create and store immutable
strings. Immutable objects are objects that don’t change once created.
In problem-solving, we often need to deal with variables (objects) of character and string type. In Java the
following classes are proved to deal with characters and strings.
 Character Class: Objects of this class hold a single character value only. Some methods are defined
which can manipulate or check single-character data.
 String Class: Objects of the String class are used to deal with the strings. The objects created using this
class cannot be changed (immutable). This class proved many methods to perform different activities on
string objects.
 StrungBuilder Class: Objects of StringBuilder class are like String class objects, except that they can be
modified. Internally, objects of StringBuilder class are treated like variable-length arrays of characters.
At any point, you may change the length and content of the objects through the invocation of
StringBuilder class methods.
 StringBuffer Class: You can create string objects using this class, which is expected to be manipulated
during the process.
 Character Class An object of Character class can contain only a single character value. While
programming, if you need to use a single character value, most of the time you have to use the primitive
char type. For example:
char ch = 'A';
// an array of chars
char[] charArray = { 'A', 'B', 'C', 'D', 'E' };
You sometimes need to use a Character object instead of a primitive char variable. For example, when you are
required to pass a character value in a method while it changes the value passed as an argument or when you
need to place a character value in a Java defined data structure, where the requirement is to work on objects. For
example, Vector is one of the data structure that requires objects. You have already seen Java; we have wrapper
class that “wraps” the char in a Character object. As he Character class is immutable, i.e. once an object is
created, it cannot be changed.
You can create a Character object using the Character class constructor:
Character ch = new Character('a');
The ch is a character object created using Character class. Also, under some circumstances, the Java compiler
creates a Character object for you. In Java when you pass a primitive char into a method as an argument which
expects an object as an argument, then the Java compiler will automatically convert the char to a Character
object for you. The following table below shows common methods

60
Program
package characterclassexample;
public class CharacterClassExample
{
public static void main(String args[])
{
Character C1 = new Character('J');
Character C2 = new Character('a');
Character C3 = new Character('v');
Character C4 = new Character('a');
int diff;
diff = C1.compareTo(C2);
if (diff == 0)
System.out.println(C1+" is equal to "+ C2);
else
System.out.println(C1+" is not equal to "+ C2);
System.out.println("Value of C1 is: " + C1);
System.out.println("Value of C2 is: " + C2);
System.out.println("Value of C3 is: " + C3);
8
Multithreading and I/O
System.out.println("C1 in lower is: " + Character.toLowerCase(C1));
diff = C2.compareTo(C4);
if (diff == 0)
System.out.println(C2+" is equal to "+C4);
else
61
System.out.println(C1+" is not equal to "+C2);
}
}

STRING CLASS AND ITS METHODS


We use Strings widely in Java programming. Strings are a sequence of characters. In Java String, class is there to
create and manipulate strings. In Java programming we may create objects of String class and use them.
Strings value of the String class objects will not change because String is immutable.
For example, if you create the following string object. The string contained by the object MyString given below
cannot be changed.
String MyString = “This Java String cannot be changed!”.
Creating Objects of String Class
Following is the direct way to create a string:
String MyStringObj = "Welcome to Java String!";
Here " Welcome to Java String!" is a string literal. It is a series of characters in enclosed in double quotes (“ ”).
Whenever Java compiler encounters a string literal in a program code it creates a String object with its value. In
the above code, it is, Welcome to Java String!.
The String class has many constructors. Some of them are given below.
 public String(): This constructor creates a String object which represents an empty character sequence.
 public String(String value): This constructor is used for creating String objects that represent the same
sequence of characters as passed in the argument.
 public String(char value[]): This constructor you may use to create a new String object which is
contained in the character array argument.
 public String(byte bytes[], int offset, int length): This constructor is used to create a String object by
converting the given sub-array of bytes using the platform’s default character encoding.

62
 public String(byte bytes[]): This constructor is used to create a String object by converting the given
array of bytes using the platform’s default character encoding.
As String class have many important methods for:
I. Examining individual characters of the strings,
II. Comparing strings,
III. Searching strings,
IV. Extracting sub-strings, and
V. Creating a copy of a string
One important point to remember is that if you create a String object, and if it has the same value as another
String object, in that case, Java will point both the object's references to the same memory location.
Creating Strings Objects
As you create any other object, you can create objects of String class using the new keyword and a constructor.
The String class has many constructors which can be used to provide the initial value of the string using
different sources, such as an array of characters:
char[] MyString = { 'B', 'o', 'o', 'k' '.' };
String Str1 = new String(MyString);
System.out.println(Str1);
The last line of above code snippet will display: Book.
STRINGBUFFER CLASS AND ITS METHODS
The String class objects are of fixed length and cannot be modified. If there is a need of strings to be modified,
then you have another option of using StringBuffer class object. Now StringBuffer class is almost obsolete.
Almost all the features provided in StringBuffer class are supported by StringBuilder class which you have
learned in the previous section. Now let us have a look at StringBuffer class in detail. String buffers class is
generally used for constructing string objects dynamically when you need a string which may change. The
StringBuffer class and the StringBuilder class are the same, except that StringBuffer class is thread-safe
because its methods are synchronized, which means StringBuffer objects are safe for use by multiple threads.
Major operations on a StringBuffer are the append and insert methods. These methods are overloaded so that
they can accept data of any type.
StringBuffer Class Constructors
 StringBuffer(): Used to define StringBuffer object with no characters in it, and it has the initial capacity
of 16 characters.
 StringBuffer (int size): It is used to construct StringBuffer object with no characters in it and with an
initial capacity specified by the size argument.
 StringBuffer (String str): It is used to construct StringBuffer object with the given sequence of
characters as the string argument.
63
Some Methods of String Buffer Class
SrtingBuffer provides the functionality of String class methods plus some more methods which are used :
a. to modify strings by inserting substrings,
b. for deleting contents of string,
c. to append string, and
d. for altering size of string dynamically.
1. public int length(): This method returns the length of the string buffer object.
2. public int capacity(): This method returns the total allocated capacity to the string buffer.
Every string buffer object has a capacity. Until the length of the character sequence contained in the object is less
than this capacity, there is no need to allocate a new internal buffer array for the object. If the internal buffer
overflows (increases more than capacity), it is automatically made larger.
3. public void ensureCapacity (int MinCapacity): This method ensures the capacity of the buffer at least
equal to the specified MinCapacity. When the current capacity of the string buffer object ( on which
ensureCapacity method is called) is less than the argument value, then a new internal buffer is allocated
which has greater capacity . The new capacity of the object is the larger than StringBuffer Class in Java
The StringBuffer class in Java represents a sequence of characters that can be modified, which means we can
change the content of the StringBuffer without creating a new object every time. It represents a mutable
sequence of characters.
Features of StringBuffer Class
The key features of StringBuffer class are listed below : Unlike String, we can modify the content of the
StringBuffer without creating a new object.
i. StringBuffer has an initial capacity, and it can also be adjusted later with the help of the ensureCapacity()
method.
ii. With the help of the append() method, we can add characters, strings, or objects at the end of the
StringBuffer.
iii. With the help of the insert() method, we can insert characters, strings, or objects at a specified position in
the StringBuffer.
iv. With the help of the delete() method, we can remove characters from the StringBuffer.
v. With the help of reverse() method, we can reverse the order of characters in the StringBuffer.
//Demonstrating String Buffer
public class Geeks {
public static void main(String[] args){

// Creating StringBuffer
StringBuffer s = new StringBuffer();

64
// Adding elements in StringBuffer
s.append("Hello");
s.append(" ");
s.append("world");

// String with the StringBuffer value


String str = s.toString();
System.out.println(str);
}
}
Output
Hello world

Advantages of using StringBuffer in Java


i. Mutable: StringBuffer are mutable it means that we can change the content after the object has been
created, on the other hand String are immutable once it created it can not be modified.
ii. Efficient: Since StringBuffer objects are mutable, it is suitable in scenarios where we need to modify the
string multiple times. If we do the same thing with string, everytime a new object is created and the old
one is deleted, which is very bad in terms of performance and memory.
Note: Both String and StringBuffer objects are thread safe, but in different ways. StringBuffer is synchronized it
means it is thread-safe but keep in mind that this synchronization can cause performance issues if accessed by
multiple threads at the same time. On the other hand immutable objects like String are thread-safe because their
state can not be modified once they are created.

65
Examples of Java StringBuffer Method
1. append() Method
The append() method concatenates the given argument with this string.
Example:
import java.io.*;

class Geeks {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb);
}
}

Output
Hello Java

66
2. insert() Method
The insert() method inserts the given string with this string at the given position.
Example
import java.io.*;
class Geeks {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java");

// Now original string is changed


System.out.println(sb);
}
}

67

You might also like