Programming 2A - Study Guide
Programming 2A - Study Guide
Module: Programming 2A
STUDY GUIDE
Contents
Module Information ............................................................................................................... 3
STUDY UNIT 1: CREATING YOUR FIRST JAVA CLASSES ............................................. 4
1.1 Introduction.................................................................................................................. 4
1.2 The Programming Process .......................................................................................... 4
1.3 Procedural and Object-Oriented Programming ............................................................ 5
1.4 Procedural and object-oriented programming .............................................................. 6
1.5 Summary .............................................................................................................. 12
1.6 Key Terms ................................................................................................................. 12
STUDY UNIT 2 USING DATA WITHIN A PROGRAM ...................................................... 14
2.1 Introduction................................................................................................................ 14
2.2 Variables ................................................................................................................... 14
2.3 Predefined data type ................................................................................................. 15
2.4 Use the Scanner class to accept keyboard input ................................................... 19
2.5 Using the JOptionpane class to accept gui input ................................................... 20
2.6 Summary .............................................................................................................. 25
2.7 Key Terms ............................................................................................................ 26
STUDY UNIT 3 USING METHODS, CLASSES, AND OBJECTS ..................................... 28
3.1 Introduction................................................................................................................ 28
3.2 Introduction to Classes .............................................................................................. 28
3.3 Introduction to Objects ............................................................................................... 29
3.4 Introduction to Built-In Classes .................................................................................. 31
3.5 Class Fundamentals .................................................................................................. 31
3.6 The General Form of a Class..................................................................................... 31
3.7 Returning a Value ...................................................................................................... 36
3.8 Instance Methods ...................................................................................................... 38
3.9 Constructors .............................................................................................................. 38
STUDY UNIT 4 MORE OBJECT CONCEPTS ................................................................. 43
4.1 Introduction................................................................................................................ 43
4.2 Using Blocks of Code ................................................................................................ 43
4.3 Overloading Methods................................................................................................. 45
4.4 Overloading Constructors .......................................................................................... 49
4.5 A Closer Look at Argument Passing .......................................................................... 52
STUDY UNIT 5 MAKING DECISIONS ............................................................................. 56
5.1 Introduction................................................................................................................ 56
5.2 Understanding Logic-Planning Tools and Decision Making ................................... 56
5.2.1 Logic-Planning Tools ........................................................................................... 56
1
5.3 Making Decisions Using the if Statement .............................................................. 58
5.4 Making Decisions Using the if-else Statement ...................................................... 61
5.5 Making Decisions Using the switch Statement ...................................................... 63
5.6 Summary .............................................................................................................. 63
5.7 Key Terms ............................................................................................................ 64
STUDY UNIT 6 LOOPING ............................................................................................... 66
6.1 Introduction................................................................................................................ 66
6.2 Loops ........................................................................................................................ 66
6.2 Summary ................................................................................................................... 69
6.2 Key Terms ............................................................................................................ 69
STUDY UNIT 7 CHARACTERS, STRINGS, AND THE STRING BUFFER ...................... 71
7.1 Introduction................................................................................................................ 71
7.2 Characters ............................................................................................................ 71
7.3 Strings .................................................................................................................. 73
STUDY UNIT 8 ARRAYS ................................................................................................. 81
8.1 Introduction................................................................................................................ 81
8.2 Arrays ................................................................................................................... 81
8.3 Array Lists ............................................................................................................. 82
8.4 Using the BinarySearch(), Sort(), and Reverse() Methods .................................... 83
8.4 Using Multidimensional Arrays .............................................................................. 83
8.5 Summary .............................................................................................................. 84
8.6 Key Terms ............................................................................................................ 84
References ...................................................................................................................... 86
2
Module Information
Self-check activity
Bright ideas
Think point
Case Study
Vocabulary
3
STUDY UNIT 1: CREATING YOUR FIRST JAVA CLASSES
1.1 Introduction
Study unit 1 introduces programming. Students will learn basic programming terminology and
apply this to the Java programming environment. They will also learn how to create a simple
Java application that produces output to the console. The chapter covers the basic
components of a Java application and how to compile and run a Java program. Students will
also create a simple GUI application.
Computer program is also known as software and it is a set of instructions that tells a computer
what to do (Farell, 2018). Software comes in two broad categories namely: System software,
a set of instructions or programs that operate the computer. Application software, programs
that allows users to complete specific or certain tasks.
Programmers write the instructions using high-level programming languages such as Java or
C-sharp. These instructions are converted, or compiled, through a series of steps into machine
language (a series of 1s and 0s), the language the computer understands (Bishop & Horspool,
2006).
It is a language that uses reasonable keywords such as “read,” “write,” or “add” instead of the
sequence of on/off switches that perform these tasks. It allows you to give or assign
reasonable or meaningful names to areas of computer memory and it has its own syntax.
Syntax is known as the rules of the language (Farell, 2018).
4
Definition a compiler
A compiler is a program which translates high-level language statements into machine code
(Cifuentes, et al., 1998). The differences between compilers, interpreters, and assemblers are:
1. Compiler – a computer program that translates high-level language statements into machine
code.
2. Interpreter – a computer program that reads the source code created in a high-level
language such as Dartmouth Basic and executes that program line by line.
Programming Logic
Programming logic involves executing the various statements and procedures in the correct
order to produce the desired results. Different programmers can write the same program in
differing ways and all get the correct result (Farell, 2016).
Debugging
Debugging is the process of removing all syntax errors and logical errors from a program.
Syntax errors are discovered through compilation and Logical errors are discovered through
testing (Farell, 2018).
In procedural programming, programmers create and name computer memory locations that
can hold values (variables) and write a series of steps or operations to manipulate those
values. The program and its procedures are separate from the stored data on which they
operate. Procedures or methods are logical units that group individual operations used in a
computer program. Procedures and methods are called or invoked by other procedures or
methods (Farell, 2016).
5
1.3.2 Features of Object-Oriented Programming Languages
1.Objects – an instance of a class. Software objects are like concrete objects in the real world.
They contain their own attributes and behaviours. The attributes of an object represent its
characteristics. The state of an object is the collective value of all its attributes. The behaviours
of an object, or methods, are the things it “does” (Farell, 2018).
2.Classes – A category of objects or a type of object. Describes the attributes and behaviours
of every object that is an instance, or object, of that class.
4.Interfaces – The interaction between a method and an object’s exposed behaviours. Uses
message-passing to request and receive information.
6.Inheritance – the process of creating sub-classes that are derived from and used to extend
a super (parent) class.
The following is a demonstration on how to create a very simple program, to clarify and see
what a Java project is made up of. At the end of this demonstration, students would have
learnt the following (Farell, 2016):
6
The following are the steps to create a Console Application:
1. Open the Net Beans software from the programs menu or desktop shortcut icon for
NetBeans IDE. If it’s the first time you are opening, you should see the screen below.
2. Click File from the menu bar at the top. From the File menu, select New Project (refer
to picture below):
7
3. Click New Project, and the following dialogue box will appear:
4. Click on Categories from the list on the left and select Java. You'll then choose Java
Application on the right panel (Projects:).
5. Select Java Application. Then click Next.
After clicking Next, you will get a window depicted in the image below:
8
You need to provide a Project Name and Project Location, and click Finish, then you will get
the image below:
When you create a Console application, Java prepares the code in the screen below for you.
9
The package line has the name of your application. Related code is grouped together in a
package in Java.
Java is object oriented so all the code will be written in classes. The word class used to declare
a class. The name of the class above is TestJavaApp.
The above code block is called a method. Main is the name of the method. This method is the
entry point to program execution. When a program starts to run, Java looks for the Main
method and then executes the lines of code between those two curly brackets. The blue words
in the above picture are known as keywords.
10
Code for the Main method goes in between the two curly brackets as indicated in the image
below.
Click Run from the menu at the top of NetBeans. From the drop-down menu, select Run Main
Project. If you see the output window below, it means that the program has executed
successfully:
To display the same message in a GUI message box, type the following as indicated in the
image below:
11
Click Run from the menu at the top of NetBeans. From the drop-down menu, select Run Main
Project. If you see the output window below, it means that the program has executed
successfully:
1.5 Summary
A computer program is a set of instructions that tell a computer what to do. Procedural
programming involves creating variables and methods. In object-oriented programming, the
focus is on objects that encapsulate variables and methods. Objects are instances of classes
and are made up of attributes and methods. The Java programming language is an object-
oriented and component-oriented language. To produce a line of console output, you must
pass a literal string as an argument to the System.out.println() method.
▪ Application software is the programs which are designed to carry out specific tasks.
▪ Attributes belong to an object and are known as its characteristics.
▪ The behaviours are methods of an object.
▪ A black box is a device you use without regard for the internal mechanisms.
▪ Block comments start with a forward slash and an asterisk (/*) and end with an
asterisk and a forward slash (*/). Block comments can appear on a line by themselves,
on a line before executable code, or after executable code. They can also extend
across as many lines as needed.
▪ The Java programming language was developed as an object-oriented and
component-oriented language.
▪ A program calls or invokes methods.
▪ A class is a category of objects or a type of object.
12
▪ A compiler is a computer program that translates high-level language statements into
machine code.
▪ Debugging a program is the process of removing all syntax and logical errors from the
programs.
▪ Encapsulation is the technique of packaging an object’s attributes and methods into a
cohesive unit that can be used as an undivided entity.
▪ Hardware comprises all the physical devices associated with a computer.
▪ A high-level programming language allows you to use a vocabulary of keywords
instead of the sequence of on/off switches that perform these tasks.
▪ An identifier is the name of a program component such as a variable, class, or method.
▪ Inheritance is the ability to extend a class to create a more specific class that contains
all the attributes and methods of a more general class; the extended class usually
contains new attributes or methods as well.
▪ An instance of a class is an object.
▪ The logic behind any program involves executing the various statements and methods
in the correct order to produce the desired results.
▪ Machine language is the most basic circuitry-level language.
▪ The method body of every method is contained within a pair of curly braces ({}) and
includes all the instructions executed by the method.
▪ Semantic errors are the type of logical errors that occur when you use a correct word
in the wrong context, generating incorrect results.
▪ Software is computer programs.
▪ The println() method displays a line of output on the screen, positions the cursor on
the next line, and waits for additional output.
Self-Evaluation Questions
1) Describe a computer and programs.
2) Explain the following: a) Complier b) Program c) Programming Language.
3) Compare procedural vs object oriented programming language.
4) Distinguish the following: compiler and interpreter.
5) List and explain 5 features of object oriented programming languages.
6) Create a Java console application to perform basic arithmetic operations like addition,
subtraction, multiplication and division. You must prompt user for values during each
operation.
13
STUDY UNIT 2 USING DATA WITHIN A PROGRAM
2.1 Introduction
This introduces the eight primitive data types in the Java language. Students will learn to work
with integer, floating-point, Boolean, and character values. Arithmetic and comparison
operators are introduced. Finally, students will learn to create input and confirm dialog boxes
using the JOptionPane class.
2.2 Variables
A variable is a location in computer memory used to contain or store a value(s). The following
syntax demonstrates how a variable is declared: Data_type identifier (variable name);
The above statement declares an integer variable named num1. In Java, the compiler won’t
allow use of this variable until it is initialized it with a value, but the declaration allocates four
bytes on the stack to hold the value.
Once it has been declared, we can assign a value to the variable using the assignment
operator, =, e.g. num1=10;
We can also declare the variable and initialize its value at the same time: int num1 = 10;
If we declare and initialize more than one variable in a single statement, all the variables will
be of the same data type: e.g. int x = 10, y=20; //x and y are both integers
NB: To declare variables of different types, you need to use separate statements.
14
Variables initialization demonstrates another example of Java’s emphasis on safety. Briefly,
the Java compiler requires that any variable be initialized with some starting value before we
refer to that variable in an operation.
Java has two methods for ensuring that variables are initialized before use:
• Variables that are fields in a class, if not initialized explicitly, are by default zeroed out
when they are created.
• Variables that are local to a method must be explicitly initialized in your code prior to
any statements in which their values are used. In this case, the initialization doesn’t
have to happen when the variable is declared, but the compiler will check all possible
paths through the method and will flag an error if it detects any possibility of the value
of a local variable being used before it is initialized.
int num;
The scope of a variable is the extent to which the variable is accessed. Variable scope is
determined by the following rules:
• A field (also known as a member variable) of a class is in scope for as long as its
containing class is in scope.
• Local variable is in scope until a closing brace indicates the end of the block statement
or method in which it was declared.
• A local variable that is declared in a for, while, or similar statement is in scope in the
body of that loop.
15
2.3.1 Predefined Value Types
The built-in value types represent primitives, such as integer and floating-point numbers,
character, and Boolean types.
Java supports a variety of integer types also known as whole number types. It supports a rich
palette of signed and unsigned integer types ranging in size from 8 to 64 bits. All integer-type
variables can be assigned values in decimal or in hex notation. The latter require the 0x prefix:
1. Float - Can hold up to 7 significant digits of accuracy. Put an F after a number to make
it a float.
2. Double - Can hold 15 or 16 significant digits of accuracy. Put a D after it to make it a
double (default).
The Java boolean type is used to contain Boolean values of either true or false.
For storing the value of a single character, Java supports the char data type. Represents a
single 16-bit (Unicode) character.
16
Literals of type char are signified by being enclosed in single quotes, for example ‘A’. If we try
to enclose a character in double quotes, the compiler will treat this as a string and throw an
error. As well as representing chars as character literals, we can represent them with 4-digit
hex Unicode values (for example ‘\u0041’), as integer values with a cast (for example, (char)
65). Then can also be represented by an escape sequence:
A string is a reference type regardless of the demonstrated assignment above. A string object
is allocated on the heap, not the stack. When one string variable is assigned to another string,
the result is two references (memory addresses) to the same string in computer memory.
Nevertheless, the string behaves from other reference types. For example, if changes are
made to any one of the strings above, an entirely new string object is created leaving the other
string unchanged.
Using system;
Class stringExample
17
{
s1 = “another string”;
strOne is a string
strTwo is a string
18
2.4 Use the Scanner class to accept keyboard input
So far, we started declared variables and assign values to them, and the user may want more
than that. And the user needs may be to want a different value on run time meaning user may
want an interactive program.
From the previous chapters, we learned that System.out.println() was used to display program
output. Herein we will use the System.in, which refers to the standard input device (Keyboard).
Hereafter is the statement to create a Scanner object and connect to the System.in object:
Scanner class contains methods that retrieve values from an input device. This means that
data is separated from the next set by whitespace. This also means that data is accepted
when a user presses enter key.
Method Description
nextDouble() Retrieves input as a double
nextInt() Retrieves input as a integer
nextLine() Retrieves the next line of data and return it as a String
next () Retrieves the next complete token as a String
nextShort() Retrieves input as a Short
nextByte() Retrieves input as a Byte
nextFloat() Retrieves input as a float.
nextLong() Retrieves input as a Long.
19
Interactive program (Input & Output)
Just like you learned how to display output through a command line and GUI message boxes
to display String objects. Earlier you also learned to accept input from keyboard at the
command line. Now we are going to them with JOptionPane class.
In doing this you can use two Dialog boxes to accept input from the user:
1.InputDialog – to ask the user for input
• showInputDialog();
2.confirmDialog – asks users questions and provide buttons that the user can click for to
respond.
20
• showConfirmDialog();
Except for top-level containers, all Swing components whose names begin with "J" descend
from the JComponent class. For example, JPanel, JScrollPane, JButton, and JTable all inherit
from JComponent. However, JFrame and JDialog don't because they implement top-level
containers.
The JComponent class extends the Container class, which itself extends Component. The
Component class includes everything from providing layout hints to supporting painting and
events. The Container class has support for adding components to the container and laying
21
hem out. This section's API tables summarize the most often used methods of Component
and Container, as well as of JComponent.
JComponent Features
• Tool tips
• Painting and borders
• Application-wide pluggable look and feel
• Custom properties
• Support for layout
• Support for accessibility
• Support for drag and drop
• Double buffering
• Key bindings
Tool tips
By specifying a string with the setToolTipText method, you can provide help to users of a
component. When the cursor pauses over the component, the specified string is displayed in
a small window that appears near the component. See How to Use Tool Tips for more
information.
The setBorder method allows you to specify the border that a component displays around its
edges. To paint the inside of a component, override the paintComponent method. See How to
Use Borders and Performing Custom Painting for details.
Behind the scenes, each JComponent object has a corresponding ComponentUI object that
performs all the drawing, event handling, size determination, and so on for that JComponent.
Exactly which ComponentUI object is used depends on the current look and feel, which you
22
can set using the UIManager.setLookAndFeel method. See How to Set the Look and Feel for
details.
Custom properties
You can associate one or more properties (name/object pairs) with any JComponent. For
example, a layout manager might use properties to associate a constraints object with each
JComponent it manages. You put and get properties using the putClientProperty and
getClientProperty methods.
Although the Component class provides layout hint methods such as getPreferredSize and
getAlignmentX, it doesn't provide any way to set these layout hints, short of creating a subclass
and overriding the methods. To give you another way to set layout hints, the JComponent
23
class adds setter methods — setMinimumSize, setMaximumSize, setAlignmentX, and
setAlignmentY.
The JComponent class provides API and basic functionality to help assistive technologies
such as screen readers get information from Swing components, For more information about
accessibility
The JComponent class provides API to set a component's transfer handler, which is the basis
for Swing's drag and drop support.
Double buffering
Double buffering smooths on-screen painting. For details, see Performing Custom Painting.
message inputbox
24
message box
2.6 Summary
The study unit explored how to store, manipulate, and display data in a C# program. Students
learnt about declaring variables and displaying variable values.
25
2.7 Key Terms
26
represent whole numbers, and the ninth type, char, is used for characters such as ‘A’
or ‘a’.
• A float data type can hold a floating-point number with as many as seven significant
digits of accuracy.
• A double data type can hold a floating-point number with 15 or 16 significant digits of
accuracy.
• The decimal data type is a floating-point type that has a greater precision and a
smaller range than a float or double, which makes it suitable for financial and monetary
calculations.
• Arithmetic operators are used to perform arithmetic; they include 1, -, *, /, and %.
• A Boolean variable can hold only one of two values—true or false.
• Hexadecimal, or base 16, is a mathematical system that uses 16 symbols to represent
numbers.
• The string data type is used to hold a series of characters; a literal string is contained
between double quotation marks.
Self-Evaluation Questions
1. Should variables that contain numbers always be declared as integer or floating-point data
types? Why or why not? Name potential examples.
2. Write a Java program that asks your name and prints the following message:
Hello, yourName!
3. Create a Java program that asks for three integers and prints the average value as a double.
Example (3 + 6 + 7) / 3 = 5.33333333333333
27
STUDY UNIT 3 USING METHODS, CLASSES, AND OBJECTS
3.1 Introduction
Study unit 3 introduces students to the creation of classes, variables, and methods. Students
will learn to create methods that accept arguments and return values. They will learn to create
a class composed of instance variables and methods. Students will create and invoke
constructor methods to initialize instances of a class.
• Create a class
• Organize classes
The class is at the core of Java. It is the logical construct upon which the entire Java language
is built because it defines the shape and nature of an object. As such, the class forms the
basis for object-oriented programming in Java. Any concept you wish to implement in a Java
program must be encapsulated within a class.
Because the class is so fundamental to Java, this and the next few chapters will be devoted
to it. Here, you will be introduced to the basic elements of a class and learn how a class can
be used to create objects. You will also learn about methods, constructors, and the this
keyword.
Book
Book Title
Author
Publisher
Year Published
28
In the computer world, the work Book in the above example is referred to as a class: A class
is a list of criteria used to describe something. Each word or group of words, in bold in the
above example, is called a property of the class. In our example, Book Title is a property of
the Book class. In the same way, Author is another property of the of the Book class. In Java,
there is never space between two words that represent the same entity. This means that the
above list is better represented as follows:
Book
BookTitle
Author
Publisher
YearPublished
One class can also be a property of another class (unfortunately, we need to mention these
issues in our introduction but don't make too much effort to understand them: everything will
be clearer in future lessons). For example, imagine you create another class that can be used
to describe each author of a book. The list of properties can be created as follows:
Author
Name
Nationality
You can then use this class to define a criterion in the Book class, exactly as done above: only
the Author word is necessary in the Book class, its Name and Nationality criteria are directly
represented.
Every property that is created in the class is referred to as its member. For example, in the
above lists, Nationality is a member of the Author class while Publisher is a member of the
Book class.
Author: Mojang
Name: Ferdinand
Nationality: American
In the same way, you can describe each author of the collection by filling out its characteristics
using the above criteria. When describing an object as done in this example, you must first
give a name to the object (this is not always necessary as we will see in future lessons). In the
above example, Modjang is the name of the object. Author is (still) the name of the class. This
name is necessary because you would need it in a class where Author must be used as a
member. Based on this, you can use the name of the above class when describing a Book
object. Here is an example:
29
Book: First Item
Author: Modjang
Publisher: Heinemann
It is important to understand the difference between a class and an object. An object is the
result of describing something using the preset criteria of a (known) class. In the strict sense,
you must first create a class by specifying each criterion you want to use to eventually describe
some objects. On the other hand, you can create an object only that is based on an existing
class.
Everything statement in Java must end with a semi-colon. This results in the following:
Author: Modjang;
Publisher: Heinemann;
Methods
In many cases, only characteristics are necessary to have a class on which complete objects
can be described. Still, an object may be expected to perform one or more assignments or
actions. An assignment that an object can perform is called a method.
Imagine you have books that that can open or close themselves when asked to do so (Sci-Fi
anyone?). The action used to open may be called Open. To differentiate an assignment, or
method, from a property, the name of a method must be followed with parentheses. Here are
two examples:
Book
BookTitle
Author
Publisher
YearPublished
Open()
30
Close()
Although this list shows the methods last, this is not a rule, the methods can be the first, the
last, or included between, if they belong to the class. In the same way, a class that is made a
property (member) of a class can also have its own methods.
One of the classes that ship with Java is called System. One of the jobs of the System class
is to display something on the screen. To perform this job, the System class is equipped with
a property called out. Actually, out itself is a class as we mentioned earlier that one class can
be used as a property of another class. To display something on the screen, the out class is
equipped with a method called println. To display something, you can write it between the
parentheses of this method. If the item to display is a word, you must include it between
double-quotes.
We will see that another job it can handle is to get a value from the user.
Perhaps the most important thing to understand about a class is that it defines a new data
type. Once defined, this new type can be used to create objects of that type.
Thus, a class is a template for an object, and an object is an instance of a class. Because an
object is an instance of a class, you will often see the two words object and instance used
interchangeably.
31
A class is declared by use of the class keyword. The classes that have been used up to this
point are actually very limited examples of its complete form. Classes can (and usually do) get
much more complex. The general form of a class definition is shown here:
class Chapter3
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
// body of method
type methodname2(parameter-list)
// body of method
// ...
type methodnameN(parameter-list)
// body of method
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. In most classes, the instance variables are acted upon and
accessed by the methods defined for that class. Thus, it is the methods that determine how a
class’ data can be used. Variables defined within a class are called instance variables because
each instance of the class (that is, each object of the class) contains its own copy of these
variables.
Thus, the data for one object is separate and unique from the data for another. We will come
back to this point shortly, but it is an important concept to learn early.
32
All methods have the same general form as main( ), which we have been using thus far.
However, most methods will not be specified as static or public. Notice that the general form
of a class does not specify a main( ) method. Java classes do not need to have a main( )
method. You only specify one if that class is the starting point for your program. Further,
applets don’t require a main( ) method at all.
C++ programmers will notice that the class declaration and the implementation of the methods
are stored in the same place and not defined separately. This sometimes makes for very large
.java files, since any class must be entirely defined in a single source file.
This design feature was built into Java because it was felt that in the long run, having
specification, declaration, and implementation all in one place makes for code that is easier to
maintain.
A Simple Class
Let’s begin our study of the class with a simple example. Here is a class called Box that
defines three instance variables: width, height, and depth. Currently, Box does not contain
class Box
double width;
double height;
double depth;
As stated, a class defines a new type of data. In this case, the new data type is called Box.
You will use this name to declare objects of type Box. It is important to remember that a class
declaration only creates a template; it does not create an actual object. Thus, the preceding
code does not cause any objects of type Box to come into existence.
To create a Box object, you will use a statement like the following:
After this statement executes, mybox will be an instance of Box. Thus, it will have
“physical” reality. For the moment, don’t worry about the details of this statement.
Again, each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class. Thus, every Box
object will contain its own copies of the instance variables width, height, and depth. To
access these variables, you will use the dot (.) operator. The dot operator links the name
33
of the object with the name of an instance variable. For example, to assign the width
variable of mybox the value 100, you would use the following statement:
mybox.width = 100;
This statement tells the compiler to assign the copy of width that is contained within
the mybox object the value of 100. In general, you use the dot operator to access both
*/
class Box {
double width;
double height;
double depth;
class BoxDemo {
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
You should call the file that contains this program BoxDemo.java, because the main( )
method is in the class called BoxDemo, not the class called Box. When you compile this
34
program, you will find that two .class files have been created, one for Box and one for
BoxDemo. The Java compiler automatically puts each class into its own .class file. It is
not necessary for both the Box and the BoxDemo class to be in the same source
file. You could put each class in its own file, called Box.java and BoxDemo.java,
respectively.
To run this program, you must execute BoxDemo.class. When you do, you will see
Volume is 3000.0
As stated earlier, each object has its own copies of the instance variables. This
means that if you have two Box objects, each has its own copy of depth, width, and
object have no effect on the instance variables of another. For example, the following
class Box {
double width;
double height;
double depth;
class BoxDemo2 {
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
instance variables */
35
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
Volume is 3000.0
Volume is 162.0
As you can see, mybox1’s data is separate from the data contained
in mybox2.
class Box {
double width;
double height;
double depth;
double volume() {
36
}
class BoxDemo4 {
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
vol = mybox1.volume();
vol = mybox2.volume();
As you can see, when volume( ) is called, it is put on the right side of an assignment
statement. On the left is a variable, in this case vol, that will receive the value returned by
volume( ). Thus, after
vol = mybox1.volume(); executes, the value of mybox1.volume( ) is 3,000 and this value then
is stored in vol.
• The type of data returned by a method must be compatible with the return type
specified by the method. For example, if the return type of some method is boolean,
you could not return an integer.
37
• The variable receiving the value returned by a method (such as vol, in this case) must
also be compatible with the return type specified for the method.
One more point: The preceding program can be written a bit more efficiently because there is
no need for the vol variable. The call to volume( ) could have been used in the println( )
statement directly, as shown here:
byte[ ] getAddress( ) Returns a byte array that represents the object’s Internet address in
network byte order.
String getHostAddress( ) Returns a string that represents the host address associated with
the InetAddress object.
String getHostName( ) Returns a string that represents the host name associated with the
InetAddress object.
String toString( ) Returns a string that lists the host name and the IP address for convenience.
3.9 Constructors
Constructor is a method that is invoked automatically when a new instance of a class is
created. Constructors are used to initialize the variables of the newly created object. The
constructor method has the same name as the class.
It can be tedious to initialize all the variables in a class each time an instance is created. Even
when you add convenience functions like setDim( ), it would be simpler and more concise to
have all of the setup done at the time the object is first created. Because the requirement for
initialization is so common, Java allows objects to initialize themselves when they are created.
This automatic initialization is performed using a constructor.
A constructor initializes an object immediately upon creation. It has the same name as the
class in which it resides and is syntactically like a method. Once defined, the constructor is
automatically called immediately after the object is created, before the new operator
completes. Constructors look a little strange because they have no return type, not even void.
This is because the implicit return type of a class’ constructor is the class type itself. It is the
constructor’s job to initialize the internal state of an object so that the code creating an instance
will have a fully initialized, usable object immediately.
38
You can rework the Box example so that the dimensions of a box are automatically initialized
when an object is constructed. To do so, replace setDim( ) with a constructor. Let’s begin by
defining a simple constructor that simply sets the dimensions of each box to the same values.
This version is shown here:
dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
double volume() {
class BoxDemo6 {
double vol;
vol = mybox1.volume();
39
// get volume of second box
vol = mybox2.volume();
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
when they were created. Since the constructor gives all boxes the same dimensions, 10 by
10 by 10, both mybox1 and mybox2 will have the same volume. The println( ) statement
inside Box( ) is for the sake of illustration only. Most constructors will not display anything.
They will simply initialize an object.
Before moving on, let’s reexamine the new operator. As you know, when you allocate an
object, you use the following general form:
Now you can understand why the parentheses are needed after the class name. What is
happening is that the constructor for the class is being called. Thus, in the line Box mybox1 =
new Box();
new Box( ) is calling the Box( ) constructor. When you do not explicitly define a constructor
for a class, then Java creates a default constructor for the class. Therefore, the preceding line
of code worked in earlier versions of Box that did not define a constructor. The default
constructor automatically initializes all instance variables to zero. The default constructor is
often sufficient for simple classes, but it usually won’t do for more sophisticated ones. Once
you define your own constructor, the default constructor is no longer used.
Parameterized Constructors
While the Box( ) constructor in the preceding example does initialize a Box object, it is not
very useful—all boxes have the same dimensions. What is needed is a way to construct Box
objects of various dimensions. The easy solution is to add parameters to the constructor. As
you can probably guess, this makes them much more useful. For example, the following
version of Box defines a parameterized constructor which sets the dimensions of a box as
specified by those parameters. Pay special attention to how Box objects are created.
*/
40
class Box {
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
double volume() {
class BoxDemo7 {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
Volume is 3000.0
41
Volume is 162.0
As you can see, each object is initialized as specified in the parameters to its constructor. For
example, in the following line, Box mybox1 = new Box (10, 20, 15); the values 10, 20, and 15
are passed to the Box() constructor when new creates the object. Thus, mybox1’s copy of
width, height, and depth will contain the values 10, 20, and 15, respectively.
Self-Evaluation Questions
1. Compare and contrast the difference between reference parameters and output
parameters? When should you use each?
2. Evaluate the advantages of using methods in your programs? Is it possible to write a
complete large-scale program without methods?
3. Write a method with the following signature: public static int Fibonacci (int n)
This method receives an integer as a parameter and returns the index of n in the Fibonacci
series. If n does not exist, the method returns -1. For example, assume the first elements
in the Fibonacci series are 1 1 2 3 5 8 13 21 34. If n = 3, then the method returns 4. But
if n = 12, the method returns -1.
42
STUDY UNIT 4 MORE OBJECT CONCEPTS
4.1 Introduction
This study unit introduces students to blocks and scope, overriding, and overloading. Students
will learn to create overloaded methods and constructors. They will learn about static variables
and how to create constants using the final keyword. Finally, students will learn to use
prewritten classes in the java.lang and java.util packages, and other packages.
• Overload a method
• Avoid ambiguity
This is done by enclosing the statements between opening and closing curly braces. Once a
block of code has been created, it becomes a logical unit that can be used any place that a
single statement can. For example, a block can be a target for Java’s if and for statements.
Consider this if statement:
x = y;
y = 0;
} // end of block
Here, if x is less than y, then both statements inside the block will be executed. Thus, the two
statements inside the block form a logical unit, and one statement cannot execute without the
other also executing. The key point here is that whenever you need to logically link two or
more statements, you do so by creating a block.
Let’s look at another example. The following program uses a block of code as the target of a
for loop.
43
/*
*/
class BlockTest {
int x, y;
y = 20;
y = y - 2;
This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
44
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
In this case, the target of the for loop is a block of code and not just a single statement.
Thus, each time the loop iterates, the three statements inside the block will be executed.
This fact is, of course, evidenced by the output generated by the program.
When an overloaded method is invoked, Java uses the type and/or number of arguments as
its guide to determine which version of the overloaded method to actually call. Thus,
overloaded methods must differ in the type and/or number of their parameters. While
overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method. When Java encounters a call to an overloaded method,
it simply executes the version of the method whose parameters match the arguments used in
the call.
class OverloadDemo {
void test() {
System.out.println("No parameters");
void test(int a) {
45
void test(int a, int b) {
double test(double a) {
return a*a;
class Overload {
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
No parameters
a: 10
a and b: 10 20
double a: 123.25
As you can see, test( ) is overloaded four times. The first version takes no parameters, the
second takes one integer parameter, the third takes two integer parameters, and the fourth
takes one double parameter. The fact that the fourth version of test( ) also returns a value is
46
of no consequence relative to overloading, since return types do not play a role in overload
resolution.
When an overloaded method is called, Java looks for a match between the arguments used
to call the method and the method’s parameters. However, this match need not always be
exact. In some cases Java’s automatic type conversions can play a role in overload resolution.
For example, consider the following program:
class OverloadDemo {
void test() {
System.out.println("No parameters");
void test(double a) {
class Overload {
int i = 88;
ob.test();
ob.test(10, 20);
No parameters
47
a and b: 10 20
Inside test(double) a: 88
As you can see, this version of OverloadDemo does not define test(int). Therefore, when
test( ) is called with an integer argument inside Overload, no matching method is found.
However, Java can automatically convert an integer into a double, and this conversion can
be used to resolve the call. Therefore, after test(int) is not found, Java elevates i to double
and then calls test(double). Of course, if test(int) had been defined, it would have been called
instead. Java will employ its automatic type conversions only if no exact match is found.
Method overloading supports polymorphism because it is one way that Java implements the
“one interface, multiple methods” paradigm. To understand how, consider the following. In
languages that do not support method overloading, each method must be given a unique
name. However, frequently you will want to implement essentially the same method for
different types of data. Consider the absolute value function. In languages that do not support
overloading, there are usually three or more versions of this function, each with a slightly
different name. For instance, in C, the function abs( ) returns the absolute value of an integer,
labs( ) returns the absolute value of a long integer, and fabs( ) returns the absolute value of
a floating-point value. Since C does not support overloading, each function has to have its
own name, even though all three functions do essentially the same thing. This makes the
situation more complex, conceptually, than it actually is. Although the underlying concept of
each function is the same, you still have three names to remember. This situation does not
occur in Java, because each absolute value method can use the same name. Indeed, Java’s
standard class library includes an absolute value method, called abs( ). This method is
overloaded by Java’s Math class to handle all numeric types. Java determines which version
of abs( ) to call based upon the type of argument.
The value of overloading is that it allows related methods to be accessed by use of a common
name. Thus, the name abs represents the general action which is being performed. It is left
to the compiler to choose the right specific version for a particular circumstance. You, the
programmer, need only remember the general operation being performed. Through the
application of polymorphism, several names have been reduced to one. Although this example
is simple, if you expand the concept, you can see how overloading can help you manage
greater complexity.
When you overload a method, each version of that method can perform any activity you desire.
There is no rule stating that overloaded methods must relate to one another. However, from a
stylistic point of view, method overloading implies a relationship. Thus, while you can use the
same name to overload unrelated methods,you should not. For example, you could use the
name sqr to create methods that return the square of an integer and the square root of a
floating-point value. But these two operations are fundamentally different. Applying method
overloading in this manner defeats its original purpose. In practice, you should only overload
closely related operations.
48
4.4 Overloading Constructors
In addition to overloading normal methods, you can also overload constructor methods. In
fact, for most real-world classes that you create, overloaded constructors will be the norm, not
the exception. To understand why, let’s return to the Box class developed in the preceding
chapter. Following is the latest version of Box:
class Box {
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
double volume() {
As you can see, the Box( ) constructor requires three parameters. This means that all
declarations of Box objects must pass three arguments to the Box( ) constructor. For
example, the following statement is currently invalid:
Since Box( ) requires three arguments, it’s an error to call it without them. This raises some
important questions. What if you simply wanted a box and did not care (or know) what its initial
dimensions were? Or, what if you want to be able to initialize a cube by specifying only one
value that would be used for all three dimensions?
As the Box class is currently written, these other options are not available to you. Fortunately,
the solution to these problems is quite easy: simply overload the Box constructor so that it
handles the situations just described. Here is a program that contains an improved version of
Box that does just that:
49
*/
class Box {
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
Box() {
Box(double len) {
double volume() {
class OverloadCons {
50
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
C h a p t e r 7 : A C l o s e r L o o k a t M e t h o d s a n d C l a s s e s 161
vol = mycube.volume();
As you can see, the proper overloaded constructor is called based upon the parameters
specified when new is executed.
Ambiguity
Java does not support operator overloading. Operator overloading is sometimes a source of
ambiguity in a C++ program, and the Java design team felt that it causes more trouble than
benefit.
This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated. Let’s look at the details of this procedure.
In the preceding sample programs, a line like the following is used to declare an object of type
Box:
This statement combines the two steps just described. It can be rewritten like this to show
each step more clearly:
51
Box mybox; // declare reference to object
The first line declares mybox as a reference to an object of type Box. After this line executes,
mybox contains the value null, which indicates that it does not yet point to an actual object.
Any attempt to use mybox at this point will result in a compile-time error. The next line
allocates an actual object and assigns a reference to it to mybox.
After the second line executes, you can use mybox as if it were a Box object. But , mybox
simply holds the memory address of the actual Box object. The effect of these two lines of
code is depicted.
In Java, when you pass a simple type to a method, it is passed by value. Thus, what occurs
to the parameter that receives the argument has no effect outside the method.
class Test {
i *= 2;
j /= 2;
class CallByValue {
ob.meth(a, b);
52
a + " " + b);
As you can see, the operations that occur inside meth( ) have no effect on the values of a and
b used in the call; their values here did not change to 30 and 10.
When you pass an object to a method, the situation changes dramatically, because objects
are passed by reference. Keep in mind that when you create a variable of a class type, you
are only creating a reference to an object. Thus, when you pass this reference to a method,
the parameter that receives it will refer to the same object as that referred to by the argument.
This effectively means that objects are passed to methods by use of call-by-reference.
Changes to the object inside the method do affect the object used as an argument.
Understanding static
There will be times when you will want to define a class member that will be used
independently of any object of that class. Normally a class member must be accessed only in
conjunction with an object of its class. However, it is possible to create a member that can be
used by itself, without reference to a specific instance. To create such a member, precede its
declaration with the keyword static. When a member is declared static, it can be accessed
before any objects of its class are created, and without reference to any object. You can
declare both methods and variables to be static. The most common example of a static
member is main( ). main( ) is declared as static because it must be called before any objects
exist.
Instance variables declared as static are, essentially, global variables. When objects of its
class are declared, no copy of a static variable is made. Instead, all instances of the class
share the same static variable.
If you need to do computation to initialize your static variables, you can declare a static block
which gets executed exactly once, when the class is first loaded.
The following example shows a class that has a static method, some static variables, and a
static initialization block:
class UseStatic {
53
THE JAVA LANGUAGE
static int a = 3;
static int b;
static {
b = a * 4;
meth(42);
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set
to 3, then the static block executes (printing a message), and finally, b is initialized to a * 4 or
12. Then main( ) is called, which calls meth( ), passing 42 to x.
The three println( ) statements refer to the two static variables a and b, as well as to the local
variable x.
x = 42
a=3
b = 12
Outside of the class in which they are defined, static methods and variables can be
used independently of any object. To do so, you need only specify the name of their class
followed by the dot operator. For example, if you wish to call a static method from outside its
class, you can do so using the following general form:
classname.method( )
Here, classname is the name of the class in which the static method is declared.
54
As you can see, this format is similar to that used to call non-static methods through object-
reference variables. A static variable can be accessed in the same way—by use of the dot
operator on the name of the class. This is how Java implements a controlled version of global
methods and global variables.
Here is an example. Inside main( ), the static method callme( ) and the static variable b are
accessed outside of their class.
class StaticDemo {
class StaticByName {
StaticDemo.callme();
a = 42
b = 99
Self-Evaluation Questions
1. Use the Character class to create a program that analyzes a password entered by the user.
The program will count the number of digits, punctuation marks, lowercase letters, and
uppercase letters in the password. The program will then assign a score of weak,
medium, or strong to the password.
2. Create a program that prompts the user to enter two Strings and then displays the Strings
in alphabetical order. If the two Strings are equal, the program should display a message
that they are equal rather than printing them in alphabetical order.
55
STUDY UNIT 5 MAKING DECISIONS
5.1 Introduction
This study unit introduces decision structures using the if, if…else, and switch statements.
Students will learn to execute program statements based on the result of a Boolean
expression. They will also learn to use the logical operators AND, OR, and NOT, as well as
the conditional operator.
Pseudocode - A tool that helps programmers plan a program’s logic by writing plain English
statements
Flowchart - You write the steps in diagram form as a series of shapes connected by arrows
or flowlines
Sequence structure - One step follows another unconditionally and sequentially. Sometimes,
logical steps do not follow in an unconditional sequence.
56
Decision structure - Involves choosing between alternative courses of action based on some
value within a program. All computer decisions are true-or-false decisions when reduced to
their most basic form. See diagram below:
57
5.3 Making Decisions Using the if Statement
if(testedExpression)
statement;
The if expression that precedes the block is the control statement for the decision structure.
For multiple statements to depend on an if, they must be blocked with braces.
Consider the diagram below which indicates a flowchart and code including a typical if
statement followed by a separate statement.
Flowchart and code including an if statement with a semicolon following the if expression
58
Flowchart and code including a typical if statement containing a bock
Flowchart and code including an if statement that is missing curly braces or that has no proper
indenting:
59
Nested if
This is when one decision structure, or if statement, is contained within another. Decision
structures can be nested to multiple levels. If an outer level if statement fails or returns a false
result, all inner blocks of code are ignored.
60
Program using nested if:
Dual-alternative decisions have two possible resulting actions e.g. if-else statement. The if-
else statement is used to perform one action when a Boolean expression evaluates as true,
and an alternate action when it evaluates as false.
Example:
if(isProjectUnderBudget)
bonus = 4500;
else
bonus = 0;
61
5.4.1 Using Compound Expressions in if Statements
It is possible to combine multiple decisions into a single if statement through the use a
combination of AND and OR operators.
The conditional AND operator determines whether two expressions are both true. It uses two
ampersands (&&) and must include a complete Boolean expression on each side of the
operator. Short-circuit evaluation is one of the characteristic of the AND operator where
expressions in each part of an AND expression are evaluated only as much as necessary to
determine whether the entire expression is true or false.
The conditional OR operator is used when you want some action to occur even if only one of
two conditions is true. It is written as two pipes || and must include a complete Boolean
expression on each side of the operator.
62
5.5 Making Decisions Using the switch Statement
The switch structure tests a single variable against a series of exact matches.
switch – starts the structure and is followed immediately by a test expression enclosed in
parentheses.
case – followed by one of the possible values that might equal the switch expression.
default – optionally is used prior to any action that should occur if the test expression does
not match any case.
5.6 Summary
A flowchart is a pictorial tool that helps you understand a program’s logic. The if statement
makes a single-alternative decision using the keyword if, followed by parentheses that contain
a Boolean expression. When you make a dual-alternative decision, you can use an if-else
statement. The conditional AND operator (&&) acts when two operand Boolean expressions
are both true. The conditional OR operator (||) acts when at least one of two operand Boolean
63
expressions is true. The switch statement tests a single variable against a series of exact
matches
• A block is a collection of one or more statements contained within a pair of curly braces.
• The Boolean logical AND operator determines whether two expressions are both true;
it is written using a single ampersand (&). Unlike the conditional AND operator, it does
not use short-circuit evaluation.
• The Boolean logical inclusive OR operator determines whether at least one of two
conditions is true; it is written using a single pipe (|). Unlike the conditional OR operator,
it does not use short-circuit evaluation.
• The keyword break optionally terminates a switch structure at the end of each case.
• The keyword case in a switch structure is followed by one of the possible values that
might equal the switch expression.
• The conditional AND operator (or simply the AND operator) determines whether two
expressions are both true; it is written using two ampersands (&&).
• The conditional OR operator (or simply the OR operator) determines whether at least
one of two conditions is true; it is written using two pipes (||).
• A decision structure is a unit of program logic that involves choosing between
alternative courses of action based on some value.
• The keyword default optionally is used prior to any action that should occur if the test
expression in a switch structure does not match any case.
• Dual-alternative decisions have two possible outcomes.
• An if statement is used to make a single-alternative decision.
• An if-else statement performs a dual-alternative decision.
Self-Evaluation Questions
1. Create a small Java program using the Scanner class to ask people to enter their age. Use
Conditional Logic to test how old they are. Display the following messages, depending
on how old they are:
Less than 16: "You're still a youngster."
Over 16 but under 25: "Fame beckons!"
Over 25 but under 40: "There's still time."
Over 40: "Oh dear, you've probably missed it!"
Only one message box should display, when you Run the main project.
64
2. Formulate a Java program that asks for a numeric grade between 0 and 4, and converts it
to a letter grade using the following conversion table:
3. Write a Java program that asks the intensity of an earthquake using the Richter scale and
prints a message accordingly. Write two versions of this program: one using a series of
if statements and the other using a switch structure.
65
STUDY UNIT 6 LOOPING
6.1 Introduction
This study unit covers looping structures. Students will learn to create definite and indefinite
loops using the while statement. Next, they will learn to use Java’s accumulating and
incrementing operators. Students will use for loops to create a definite loop and do…while
loops for use when a posttest loop is required. Finally, students will learn how to create nested
loops and how to improve loop efficiency.
6.2 Loops
A loop is a structure that allows repeated execution of a block of statements. A loop body is a
block of statements within a looping structure. A loop executes the Boolean expression to
determine whether to continue to execute the loop or exit. Each execution is an Iteration.
A while loop is used to execute a body of statements continuously if some condition continues
to be true. It consists of: The keyword while, a Boolean expression within parenthesis and
the loop body.
Infinite loop is a loop that never ends. A program with an infinite loop might eventually fail and
end due to computer memory and hardware capacities.
To make a while loop end correctly, three separate actions should occur:
66
Empty body is a loop with no statements. Incrementing is adding to the loop control variable.
Decrementing is Subtracting from the loop control variable. Definite loop is a loop for which
the number of iterations is predetermined. Indefinite loop is a loop for which the value of a
loop control variable is not altered by arithmetic, but instead is altered by user input. Sentinel
value is a value such as ‘Y’ or ‘N’ that a user must supply to stop the loop.
No-matter what loop is used, the idea is to loop through and execute the same code until an
end condition is met. The difference between the Do and While statements is in the structure.
The Do-loop looks like:
do
{
} while (true);
Note where the semi-colon is positioned in the code above. It is at the end, after the curved
brackets. At the start, there is the word do, followed by a pair of curly brackets. After the curly
brackets, then comes the while key word. The condition is specified in between the round
brackets after while keyword. Java will loop through until the end condition between the round
brackets is met.
While loops are easier to use than Do loops because the condition is met or evaluated first
before entering the loop whereas on the Do-loop, the condition is found at the end as indicated
above. The difference between the two structures is that the code in a Do loop will get
executed at least once, because the while part is at the end.
67
Creating Loops with the Do Statement
The for loop is used to create definite loops. Its structure indicates the starting value for the
loop control variable, test the condition that controls loop entry and allow the expression to
alter the loop control variable known as the step value. Sections of the loop are control variable
initialization, testing and updating.
NB: Variables created inside the loop cease to exist when the loop ends.
When a variable is declared inside a loop, it can be reference only for the duration of the loop
body. If that variable can still be accessed, it is in scope. When a loop body ends, any
declarations made within it are out of scope.
• Perform more than one test in the middle section of the for statement by evaluating
compound conditions
• Perform tasks other than incrementing at the end of the loop’s execution
• Perform multiple tasks at the end of the loop’s execution by separating the actions with
commas
• Leave one or more portions of the for-expression empty, although the two semicolons
are still required as placeholders to separate the three sections
68
6.2 Summary
A while loop is used to execute a body of statements continuously while some condition
continues to be true.
The do loop checks the “bottom” of the loop after one repetition has occurred. You can nest
any combination of loops to achieve the desired results.
69
• A while loop executes a body of statements continuously while a test condition
continues to be true; it uses the keyword while.
Self-Evaluation Questions
1. What is a loop? When do you use a loop versus a selection statement?
2. Explain when is it advantageous to use a do loop rather than other kinds of loops?
3. Demonstrate with some examples when an infinite loop is appropriate?
4. Write a Java program that asks for a number between 2 and 10 and outputs a multiplication
table that runs from 1 to the input number.
5. Write a Java program that asks for a value for a variable n and computes n!
70
STUDY UNIT 7 CHARACTERS, STRINGS, AND THE STRING BUFFER
7.1 Introduction
Study unit 7 covers working with character strings in Java. Students will learn to use the
Character, String, and StringBuilder classes. The Character class provides methods for
working with single characters. The String class is most commonly used to represent a
character string and is immutable. The StringBuilder class provides a mutable representation
of a character string.
7.2 Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware:
char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8
bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters.
Unicode defines a fully international character set that can represent all the characters found
in all human languages. It is a unification of dozens of character sets, such as Latin, Greek,
Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more.
For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char
is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII
still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges
from 0 to 255. Since Java is designed to allow applets to be written for worldwide use, it makes
sense that it would use Unicode to represent characters. Of course, the use of Unicode is
somewhat inefficient for languages such as English, German, Spanish, or French, whose
characters can easily be contained within 8 bits. But such is the price that must be paid for
global portability.
class CharDemo {
71
char ch1, ch2;
ch2 = 'Y';
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127
values in the Unicode character set. For this reason, all the “old tricks” that you have used
with characters in the past will work in Java, too.
Even though chars are not integers, in many cases you can operate on them as if they were
integers. This allows you to add two characters together, or to increment the value of a
character variable. For example, consider the following program:
class CharDemo2 {
char ch1;
ch1 = 'X';
ch1 contains X
ch1 is now Y
In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1
containing Y, the next character in the ASCII (and Unicode) sequence.
72
7.3 Strings
As you may have noticed, in the preceding discussion of data types and arrays there has been
no mention of strings or a string data type. This is not because Java does not support such a
type—it does. It is just that Java’s string type, called String, is not a simple type. Nor is it
simply an array of characters (as are strings in C/C++). Rather, String defines an object, and
a full description of it requires an understanding of several object-related features. As such, it
will be covered later in this book, after objects are described. However, so that you can use
simple strings in example programs, the following brief introduction is in order.
The String type is used to declare string variables. You can also declare arrays of strings. A
quoted string constant can be assigned to a String variable. A variable of type String can be
assigned to another variable of type String. You can use an object of type String as an
argument to println( ). For example, consider the following fragment:
System.out.println(str);
Here, str is an object of type String. It is assigned the string “this is a test”. This string is
displayed by the println( ) statement.
As you will see later, String objects have many special features and attributes that make them
quite powerful and easy to use. However, for the next few chapters, you will be using them
only in their simplest form.
Although the String class will be examined in depth in Part II of this book, a short exploration
of it is warranted now, because we will be using strings in some of the example programs
shown toward the end of Part I. String is probably the most commonly used class in Java’s
class library. The obvious reason for this is that strings are a very important part of
programming.
The first thing to understand about strings is that every string you create is actually an object
of type String. Even string constants are String objects. For example, in the statement
System.out.println("This is a String, too"); the string “This is a String, too” is a String constant.
Fortunately, Java handles String constants in the same way that other computer languages
handle “normal” strings, so you don’t have to worry about this. The second thing to understand
about strings is that objects of type String are
immutable; once a String object is created, its contents cannot be altered. While this may
seem like a serious restriction, it is not, for two reasons:
• If you need to change a string, you can always create a new one that contains the
modifications.
• Java defines a peer class of String, called StringBuffer, which allows strings to be
altered, so all the normal string manipulations are still available in Java.
73
Strings can be constructed a variety of ways. The easiest is to use a statement like this:
Once you have created a String object, you can use it anywhere that a string is
System.out.println(myString);
Java defines one operator for String objects: +. It is used to concatenate two strings.
// Demonstrating Strings.
class StringDemo {
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
First String
Second String
The String class contains several methods that you can use. Here are a few. You can test
two strings for equality by using equals( ). You can obtain the length of a string by calling the
length( ) method. You can obtain the character at a specified index within a string by calling
charAt( ). The general forms of these three methods are shown here:
int length( )
74
char charAt(int index)
class StringDemo2 {
strOb1.length());
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
Length of strOb1: 12
strOb1 != strOb2
strOb1 == strOb3
Of course, you can have arrays of strings, just like you can have arrays of any other
class StringDemo3 {
75
public static void main(String args[]) {
str[i]);
str[0]: one
str[1]: two
str[2]: three
Modifying a String
Because String objects are immutable, whenever you want to modify a String, you must
either copy it into a StringBuffer or use one of the following String methods, which will
construct a new copy of the string with your modifications complete.
substring( )
You can extract a substring using substring( ). It has two forms. The first is String substring(int
startIndex)
Here, startIndex specifies the index at which the substring will begin. This form returns a copy
of the substring that begins at startIndex and runs to the end of the invoking string.
The second form of substring( ) allows you to specify both the beginning and ending index of
the substring:
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The
string returned contains all the characters from the beginning index, up to, but not including,
the ending index.
The following program uses substring( ) to replace all instances of one substring
// Substring replacement.
class StringReplace {
76
String org = "This is a test. This is, too.";
int i;
System.out.println(org);
= org.indexOf(search);
if(i != -1) {
org = result;
} while(i != -1);
77
StringBuffer
StringBuffer is a peer class of String that provides much of the functionality of strings. As you
know, String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences. StringBuffer may have
characters and substrings inserted in the middle or appended to the end.
StringBuffer will automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth. Java uses both
classes heavily, but many programmers deal only with String and let Java manipulate
StringBuffers behind the scenes by using the overloaded + operator.
StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
78
StringBuffer(String str)
The default constructor (the one with no parameters) reserves room for 16 characters without
reallocation. The second version accepts an integer argument that explicitly sets the size of
the buffer. The third version accepts a String argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without reallocation.
StringBuffer allocates room for 16 additional characters when no specific buffer length is
requested, because reallocation is a costly process in terms of time. Also, frequent
reallocations can fragment memory. By allocating room for a few extra characters,
StringBuffer reduces the number of reallocations that take place.
The current length of a StringBuffer can be found via the length( ) method, while the total
allocated capacity can be found through the capacity( ) method. They have the following
general forms:
int length( )
int capacity( )
class StringBufferDemo {
Here is the output of this program, which shows how StringBuffer reserves extra space for
additional manipulations:
buffer = Hello
length = 5
capacity = 21
Since sb is initialized with the string “Hello” when it is created, its length is 5. Its capacity is 21
because room for 16 additional characters is automatically added.
79
Self-Evaluation Questions
1. Use the Character class to create a program that analyzes a password entered by the user.
The program will count the number of digits, punctuation marks, lowercase letters, and
uppercase letters in the password. The program will then assign a score of weak,
medium, or strong to the password.
2. Create a program that prompts the user to enter two Strings and then displays the Strings
in alphabetical order. If the two Strings are equal, the program should display a message
that they are equal rather than printing them in alphabetical order.
80
STUDY UNIT 8 ARRAYS
8.1 Introduction
Study unit 8 introduces the concept of arrays. An array is a list of elements of the same data
type. Students will learn to create arrays of primitive data types and objects. They will work
with arrays by searching, sorting, and passing them to methods.
• Declare arrays
• Initialize an array
• Use variable subscripts with an array
• Declare and use arrays of objects
• Search an array and use parallel arrays
• Pass arrays to and return arrays from methods
8.2 Arrays
An array is known as a multivalued variable containing values of the same data type. In Java,
Arrays are declared by putting a set of square brackets to the end of the variable data type of
the individual elements.
For example, while int represents a single integer, int [] represents an array of integers:
int [] myInts;
To initialize the array with specific dimensions, you can use the new keyword, giving the size
in the square brackets after the type name:
All arrays are reference types and follow reference semantics. So, in the above code, even
though the individual elements are primitive value types, the myInts array is a reference type.
So, if you consider the following code:
This will assign the variable copy to refer to the same array but will not create a new array.
To access individual elements inside the array, the usual syntax of placing the index of the
element in square brackets after the name of the array is used. All arrays in Java use zero-
based indexing, where the first element is referenced with the index zero:
myInts[0] = 20;
81
myInts[9] = 50;
Java has a very flexible array syntax. In Java you can declare arrays without initializing them,
so that the array can be dynamically sized later in the program. With this technique, you will
basically be creating a null reference, and later pointing the reference at a dynamically
allocated stretch of memory locations requested with the new keyword:
int [] myInts;
The following syntax is used to figure out the number of elements in an array:
A loop is a structure that allows repeated execution of a block of statements. A loop body is a
block of statements within a looping structure. A loop executes the Boolean expression to
determine whether to continue to execute the loop or exit. Each execution is an Iteration.
An array list is like the array except that it can grow. The ArrayList class also has some
similarities with the StringBuilder class. Just as a StringBuilder allocates enough space in
memory to store a certain number of characters, and allows you to manipulate characters
within the space, the ArrayList allocates enough memory to store a certain number of object
references. You can then efficiently manipulate these object references. If you try to add more
objects to the ArrayList than permitted, then it will automatically increase its capacity by
allocating a new area of memory big enough to hold twice as many elements as the current
capacity, and relocate the objects to this new location.
You can instantiate an array list by indicating the initial capacity you want. For this example,
we will assume we are creating a list of vectors:
Vector.add(new vector(2,2,2));
The ArrayList treats all its elements as object references. That means you can store whatever
objects you like in an ArrayList, but when accessing the objects, you will need to cast them
back to the appropriate data type:
82
8.4 Using the BinarySearch(), Sort(), and Reverse() Methods
System.Array class contains a variety of useful, built-in methods that can search, sort, and
manipulate array elements.
The BinarySearch() method finds a requested value in a sorted array and is a member of the
System.Array class.
▪ If your array holds duplicate values and you want to find all of them
The Reverse() method reverses the order of items in an array. For instance, the element that
starts in position 0 is relocated to position Length – 1.
A one-dimensional or single-dimensional array can be pictured as a row of values, and that its
elements can be accessed using a single subscript. Multidimensional arrays require multiple
subscripts to access the array elements. The most commonly used multidimensional array is
the two-dimensional array. A two-dimensional array has two or more columns of values for
each row and is also called a rectangular array, a matrix, or a table.
83
8.5 Summary
An array is a list of data items. All data items have the same type and the same name. Items
are distinguished using a subscript or an index. In C#, arrays are objects of a class named
System.Array. Arrays are most powerful when variable subscripts are used to process array
elements. The subscript you use remains in the range of 0 through Length – 1. The
BinarySearch() method finds a requested value in a sorted array. The Sort() method arranges
array items in ascending order. The Reverse() method reverses the order of items in an array.
• An array is a list of data items that all have the same data type and the same name,
but are distinguished from each other by a subscript or an index.
• Each object in an array is an array element.
• A binary search is an algorithm that attempts to find an item in a list by splitting the
sorted list of objects in half repeatedly as the search gets closer to a match.
• The BinarySearch() method finds a requested value in a sorted array.
• An initializer list is the list of values provided for an array.
• A jagged array is a one-dimensional array in which each element is another array.
• The Length property is a member of the System. Array class that automatically holds
an array’s length.
• Multidimensional arrays require multiple subscripts to access the array elements.
• A one-dimensional or single-dimensional array is an array whose elements you can
access using a single subscript.
• The Reverse() method reverses the order of items in an array.
• The Sort() method arranges array items in ascending order.
• A subscript (also called an index) is an integer contained within square brackets that
indicates the position of one of an array’s elements.
• The System. Array class defines fields and methods that belong to every array.
• Two-dimensional arrays have two or more columns of values for each row.
Self-Evaluation Questions
84
3. How would you declare an array if you do not know in advance how many elements you will
have in each execution of a program?
4. Use the Internet to read about a sorting algorithm called merge sort. Compare the merge
sort to another popular sort called quicksort.
5. Write a Java program that reverses the elements in a two-dimensional array. Assuming you
have a matrix of size m x n, the element in position (0, 0) will be swapped with the
element in position (m-1, n-1). The element in position (0, 1) will be exchanged with the
element in position (m-1, n-2), and so on.
85
References
Bishop, J. & Horspool, N., 2006. Cross-platform development: Software that lasts.
Computer, 39(10), pp. 26-35.
Budd, T., 2002. Understanding Object-oriented programming with Java.. s.l.:Pearson
Education.
Cifuentes, C., Simon, D. & Fraboulet, A., 1998. Assembly to high-level language translation.,
IEEE.
Farell, J., 2016. Microsoft Visual C#: 2015 An Introduction to Object. 6th ed. Chicago:
cencage.
Farell, J., 2018. Microsoft Visual C#: 2017 An Introduction to Object-Oriented Programming.
Chicago: Cengage.
86