Programming 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

Programming 2 Educor ©

DIPLOMA IN INFORMATION TECHNOLOGY

PROGRAMMING 2

STUDY GUIDE
2022

1
Programming 2 Educor ©

COPYRIGHT © EDUCOR, 2019

All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any
form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of Educor Holdings. Individual’s found guilty of
copywriting will be prosecuted and will be held liable for damages.

2
Programming 2 Educor ©

TABLE OF CONTENTS

1. About Brand .............................................................................................................................. 5


2. Our Teaching and Learning Methodology................................................................................... 6
Icons .................................................................................................................................. 6
3. Introduction to the Module ....................................................................................................... 8
Module Information ........................................................................................................... 8
Module Purpose ................................................................................................................. 8
Outcomes .......................................................................................................................... 9
Assessment ........................................................................................................................ 9
Lesson Plan ...................................................................................................................... 11
Planning Your Studies ....................................................................................................... 11
4. Prescribed Reading .................................................................................................................. 12
Prescribed Book ............................................................................................................... 12
Recommended Articles .................................................................................................... 12
Recommended Multimedia .............................................................................................. 12
5. Module Content ...................................................................................................................... 13
5.1. Unit 1: Introduction To Java Applications Objectives ................................................. 14
5.1.1. History of Programming Languages and Java...……………………………………………………… 14

5.1.2. What Is Object-Oriented Programming..................................................................... 15

5.1.3. What Is Java............................................................................................................... 15

5.1.4. Java Identifiers……………………………………………………………………………………………………… 16

5.1.5. Variable Initialization……………………………………………………………………………………………. 16

5.1.6. Primitive Data Types……………………………………………………………………………………….……. 19

5.1.7. Structure of A Java Program……………………………..…………………………………………..……… 26

5.1.8. What Is an Algorithm?............................................................................................... 26

5.1.9. How to Start Using Java?........................................................................................... 27

5.1.10. Basic Input and Output…………………………………………………………………………………………. 28

5.1.11. Revision Questions……………………………………………………………………………………………….. 28

5.2. Unit 2: Java Programming Basics Objectives ............................................................. 31


5.2.1. Arithmetic Operators and Precedence……………………………………..…………………………… 31

5.2.2. Relational Operators………………………………………………………………………..…………………… 33

5.2.3. Operator Precedence……………………………………………………………………………………………. 34

3
Programming 2 Educor ©

5.2.4. Revision Questions………………………………………………………………………………………………. 34

5.3. Unit 3: Sequence, Selection And Repetition Objectives………………………………………….. 35


5.3.1. Java’s Selection Statements…………………………………………………………………………………. 35

5.3.1.1. If Statement…………………………………………………………………………………………….. 35

5.3.1.2. Nested If’s……………………………………………………………………………………………….. 37

5.3.1.3. The If-Else-If Ladder……………………………………………………………………………….… 38

5.3.1.4. Switch……………………………………………………………………………………………………… 39

5.3.1.5. Nested Switch Statements………………………………………………………………………. 43

5.3.2. Repetition – Looping With For, While and Do … While………………………………………… 44

5.3.2.1. While Loop……………………………………………………………………………………………… 44

5.3.2.2. Do-While Loop………………………………………………………………………………….…….. 46

5.3.2.3. For Loop………………………………………………………………………………………….………. 49

5.3.3. The Scope and Lifetime of Variables…………………………………………………………….………. 51

5.4. Unit 4: Strings, String Methods and Concatenation………………………………………….….... 52

5.4.1. Concatenation……………………………………………………………………………………………………… 52

5.4.2. String Methods……………………………………………………………………………………………….…… 53

5.4.3. Formatted Output…………………………………………………………………………………………….…. 54

5.4.4. Strings, String Methods and Concatenation…………………………………………………………. 55

5.5. Unit 5: Arrays And Conditional Looping Objectives………………………………………………. 61

5.5.1. Declaring And Initializing Arrays…………………………….…………………………………………….. 61

5.5.2. Arrays……………………………………………..……………………………………………………………..…….. 61

5.5.3. Processing Arrays……………………………………………………………………………………………….… 62

5.5.4. Array Declaration……………………………………………………………………………………………….… 63

5.5.5. Some points to note about arrays………………………………………………………………………... 65

5.5.6. Sorting……………………………………………………………………………………………………………….…. 65

5.5.6.1. Bubble Sort………………………………………………………………………………………….…… 65

5.5.6.2. Selection Sort……………………………………………………………………………………..……. 67

6. References ............................................................................................................................... 71
7. Version Control ........................................................................................................................ 70

4
Programming 2 Educor ©

1. ABOUT ICESA

With over 21 years of “legacy and thousands of successful graduates, ICESA has cemented its place
in the sphere of quality, affordable education.” ICESA encompass the ideologies of our mission and
vision and it is imperative to adopt teaching and learning methods that shadows Professional
Development, Quality Academic Content Development, Conducive Teaching and Learning
Environments, Enhanced Student Support and Development, Experiential Learning and Continuous
Quality Assurance initiatives. ICESA prides itself in implementing polices and strategies that are not
only achievable and sustainable but also effective.

At ICESA our Motto is, Success and Nothing Less and that is exactly what we aim to produce in our
students lives. We want to embark on an educational journey of excellence, creativity and cutting-
edge digital learning. We integrate both theoretical and practical teaching into our curriculum and
we provide full and part-time programmes to suit your lifestyle. Set yourself up for Success and
Nothing Less in the competitive job market.

ICESA strives to provide vocationally, quality assured education, to provide economically active
citizens. Teaching and learning are the founding principles of the Institution.
The development of relevant curriculum and syllabi that meet the needs and demands
of industry

To make The ICESA a private higher and further education Institution of repute by promoting
teaching and learning.

To foster tolerance, spiritual understanding and multicultural attitudes promoting


harmony among learners and staff.

To provide graduates with employable market related skills.

To promote a culture of learning that facilitates innovative and critical thinking.

Enhancing the capabilities of individual learners for personal development, as well as the
requirements of socio-economic development, and employment growth.

5
Programming 2 Educor ©

2. OUR TEACHING AND LEARNING METHODOLOGY

ICESA strives to promote a learning-centered and knowledge-based teaching and learning


environment. Teaching and learning activities primarily take place within academic programmes
and guide students to attain specific outcomes.

A learning-centered approach is one in which not only lecturers and students, but all sections
and activities of the institution work together in establishing a learning community that
promotes a deepening of insight and a broadening of perspective with regard to learning and the
application thereof. An outcomes-oriented approach implies that the following categories of
outcomes are embodied in the academic programmes:


Culminating outcomes that are generic with specific reference to the critical cross-
field outcomes including problem identification and problem-solving, co-operation,
 skills,
self-organization and self-management, research skills, communication
 entrepreneurship and the application of science and technology.


Empowering outcomes that are specific, i.e. the context specific competencies
 learning areas and at specific levels before
students must master within specific
 they exit or move to a next level.

 of community service learning to cultivate discipline-appropriate
Discrete outcomes
competencies.

ICESA accepts that students’ learning is influenced by a number of factors, including their previous
educational experience, their cultural background, their perceptions of particular learning tasks and
assessments, as well as discipline contexts.

Students learn better when they are actively engaged in their learning rather than when they are
passive recipients of transmitted information and/or knowledge. A learning-oriented culture that
acknowledges individual student learning styles and diversity and focuses on active learning and
student engagement, with the objective of achieving deep learning outcomes and preparing
students for lifelong learning, is seen as the ideal. Effective learning entails the engagement of
students as active participants in the learning process, while acknowledging that all learning must
involve a complex interplay of active and receptive processes, the constructing of meaning by the
student, and learning with and from others. These principles are supported through the use of an
engaged learning approach that involves interactive, reflective, cooperative, experiential, creative or
constructive learning, as well as conceptual learning.

Icons
The icons below act as markers, that will help you make your way through the study guide.

6
Programming 2 Educor ©

Additional information
Find the recommended information listed.

Case study/Caselet
Apply what you have learnt to the case study presented.

Example
Examples of how to perform a calculation or activity with the solution
/ appropriate response.

Practice
Practice the skills you have learned.

Reading
Read the section(s) of the prescribed text listed.

Revision questions
Complete the compulsory revision questions at the end of each unit.

Self-check activity
Check your progress by completing the self-check activity.

Study group / Online forum discussion


Discuss the topic in your study group or online forum.

Think point
Reflect, analyse and discuss, journal or blog about the idea(s).

Video / audio
Access and watch/listen to the video/audio clip listed.

Vocabulary
Learn and apply these terms.

7
Programming 2 Educor ©

3. INTRODUCTION TO THE MODULE

Welcome to Programming 2, your second module in your Diploma in Information Technology.

Java is one of the worlds most used programming languages to date. With its solid coding structure
and ability to be used in combination with other programming languages it is an important language
to understand in the programming world. It is used from system utilities through to databases. This
module will look at the basic functions and help with understanding the foundation of java along
with the rules of the language that need to be followed through its implementation.

Module Information
Qualification title Diploma in Information Technology
Module Title Programming 2
NQF Level 6
Credits 15
Notional hours 150

Module Purpose
The purpose of this module is to provide a basic understanding of java programming and the
concepts that are concerned with java. To give effect to this purpose, this module facilitates an
understanding of java and the basic functions that java employs to accomplish each of its tasks.

Basic java concepts such as if statements, case statements, looping and the arrays are covered.
These coding concepts provide a foundation for understanding java working which are still used till
today in the working world. At the same time, students are introduced to a variety of other java
theory such as flowcharts and algorithms.

Although students are encouraged to use this guide, it must be used in conjunction with
other prescribed and recommended text.

8
Programming 2 Educor ©

Outcomes
Briefly discuss the history of Java
Demonstrate their knowledge of Java naming rules and conventions
Declare and initialise Primitive data types
Write simple Java programs
Use Arithmetic Operators
Use Relational Operators
Demonstrate an ability to design programs that branch and
loop Declare and initialise single and multi-dimensional arrays
Reference and manipulate array elements

Assessment

You will be required to complete both formative and summative assessment activities.

Formative assessment:
These are activities you will do as you make your way through the course. They are designed to help
you learn about the concepts, theories and models in this module. This could be through case
studies, practice activities, self-check activities, study group / online forum discussions and think
points.

DP Test 1
DP Test 2
Group Assignment
Individual Assignment

You may also be asked to blog / post your responses online.

Summative assessment:
You are required to do one test and one assignment. For online students, the tests are made up of
the revision questions at the end of each unit. A minimum of five revision questions will be
selected to contribute towards your test mark.

Mid -Year Examination


Final Examination

9
Programming 2 Educor ©

Mark allocation
The marks are derived as follows for this module:

DP Test 1 20%
Individual 20%
Assignment
Mid-Year 20%
Exam + EXAM 50%
Group 20%
Assignment
DP test 2 20%
TOTAL 100%
(50%)

10
Programming 2 Educor ©

Lesson Plan
The table below will give you an indication of which topics you need to prepare for class.

Week UNIT TOPIC


1 1 THE HISTORY OF JAVA, INTRODUCTION TO
ECLIPSE IDE
2 1 NAMING RULES AND CONVENTIONS,
STRUCTURE OF A JAVA PROGRAM
3 1 BASIC INPUT AND OUTPUT
4 2 ARITHMETIC OPERATORS, RELATIONAL
OPERATORS, OPERATORS PRECEDENCE
5 DP1 REVISION DP1 REVISION
6 3 IF STATEMENT
7 3 NESTED IF, IF-ELSE LADDER,
8 3 SWITCH STATEMENT
9 MID-YEAR REVISION MID-YEAR REVISION
10 3 FOR LOOP
11 3 WHILE LOOP
12 3 DO-WHILE LOOP
13 4 CONCATENATION, FORMATTED OUTPUT
14 4 STRINGS, STRING METHODS AND
CONCATENATION
15 5 DECLARING AND INITIALISING ARRAYS,
ARRAYS
16 5 PROCESSING ARRAYS
17 DP2 REVISION DP2 REVISION
18 5 POINTS ABOUT ARRAYS
19 5 SORTING
20 FINAL EXAM FINAL EXAM REVISION
REVISION
Planning Your Studies
You will have registered for one or more modules in the qualification and it is important that
you plan your time. To do this look at the modules and credits and units in each module.

Create a time table / diagram that will allow you to get through the course content, complete the
activities, and prepare for your tests, assignments and exams. Use the information provided
above (How long will it take me?) to do this.
What equipment will I need? Access to a personal computer and internet.
This module will take you approximately 150 hours to complete. The following table will give you an
indication of how long each module will take you.

Unit Number Hours


1 30
2 30
3 30
4 30
5 30

11
Programming 2 Educor ©

4. PRESCRIBED READING

Prescribed Book
Deitel. (2009). Java For Programmers. Pearson India.

Recommended Articles
Cadenhead, R. 2016. Working with Objects in Java

Recommended Multimedia
Websites:
https://www.w3schools.com/java/default.asp
https://www.javatpoint.com/java-variables
https://www.tutorialspoint.com/java/index.htm
https://www.learnjavaonline.org/
https://www.guru99.com/java-tutorial.html

Video / Audio
https://www.youtube.com/watch?v=eIrMbAQSU34
https://www.youtube.com/watch?v=grEKMHGYyns
https://www.youtube.com/watch?v=3u1fu6f8Hto
https://www.youtube.com/watch?v=2dZiMBwX_5Q
https://www.youtube.com/watch?v=qQVqfvs3p48

12
Programming 2 Educor ©

5. MODULE CONTENT

You are now ready to start your module! The following diagram indicates the topics that will be
covered. These topics will guide you in achieving the outcomes and the purpose of this module.

Please make sure you complete the assessments as they are specifically designed to build you in
your learning.

Unit 1: Introduction To Java Applications Objectives

Unit 2: Java Programming Basics Objectives

Unit 3: Sequence, Selection And Repetition Objectives

Unit 4: Strings, String Methods And Concatenation

Unit 5: Arrays And Conditional Looping Objectives

13
Programming 2 Educor ©

STUDY UNIT 1: INTRODUCTION TO JAVA APPLICATIONS OBJECTIVES


5.1.1. HISTORY OF PROGRAMMING LANGUAGES AND JAVA
A program is written as a sequence of human understandable computer instructions which will be
read by a compiler and linker, and translated into code so a computer can comprehend and run it.
(Qureshiuniversity.com, 2020)

A programing language is employed to write down computer programs like:


• Applications
• Utilities
• Servers
• Systems Programs
(Anon, 2020)

Examples of Programming Languages:


These languages include Assembler, C or C++. A computer motherboard with the CPU, RAM and ROM),
the instructions besides the pc are limited to alittle amount of memory within the boot ROM chip then
are usually written in assembler. Operating systems like Linux or Windows are written in C and C++.
(Anon, 2020)

Traditional Programming Languages:


In the late 40s and early 50s, computer programs were entered by flicking switches. it had been
quickly realized how ineffective and slow that was and computer languages soon appeared.
Thousands of programming languages are invented since then, many as PhD research projects, but
only some are really successful.
All ruled the roost but declined when better languages came into being. Basic hung in there the
longest but is now declining.
(Anon, 2020)

What Programming Languages Are Now In Use?


It is mainly Java and C++ with C# getting down to gain acceptance and C holding its own. There are
many efforts to automate this process, and have computers write computer programs but the
problem is such for now, humans still write the simplest computer programs.
More advanced techniques, as an example using
• Objects
• Generics
• Multi-threading
Mean that the fashionable programming languages are much more powerful.
(Anon, 2020)

14
Programming 2 Educor ©

5.1.2. WHAT IS OBJECT-ORIENTED PROGRAMMING?


Object-Oriented Programming and Data Abstraction became quite common terms. Unfortunately,
few people agree on what they mean. I’ll offer informal definitions that appear to form sense within
the context of languages like Ada, C++, Modula2, and Smalltalk.
The general idea is to equate support for data abstraction with the power to define and use new
types and equate support for object-Oriented programming’ with the power to precise type
hierarchies. Features necessary to support these programming styles in an exceedingly general
purpose programing language are going to be discussed.

5.1.3. WHAT IS JAVA?


Java is a global computer-oriented language. It had been made known within the early 90’s. It had
been initially accustomed program electronic devices like microwaves and remote controls.
Java may be a creating by mental acts language developed by Sun Microsystems. A programing
language is employed to supply instructions to a computer to try to be specific tasks. Java may be a
new language created in 1995 and has been very successful for several reasons.
The one who created it wanted it to be flexible, so it could adapt to any needs (used for any needs)
which is what happened. Rather than just using it for more microwaves and controls, it's now used
for basically programming anything. E.g. Web pages, wireless controls. Meaning it's adaptable (multi-
functional, is used for various devices and technologies) then that's why it's so popular round the
world .It has many benefits. Also there are many pre-written codes (libraries) that you just can use in
your own programs, so it's time-efficient and helpful.
Java is accustomed develop many sorts of applications. There are simple text-based programs called
console applications. These programs just support text input and output to your video display. You’ll
also build graphical programme (GUI) applications. These are applications with menus, toolbars,
buttons, scroll bars, and other controls which rely upon the pc mouse for input. Samples of GUI
applications you will have used are word processors, spreadsheet programs and computer games. A
final application which will be built with Java are applets. These are small GUI applications which will
be run from within an internet page. Such applets make websites dynamic, changing with time.
Another popular feature of Java is that it's object-oriented. This is often a flowery way of claiming
that Java programs are many basic pieces which will be used over and once again. What this
suggests to you, the Java programmer, is that you just can build and alter large programs without
heaps of additional complication. As you're employed through this course, you'll hear the word
object many, many times.
A last advantage of Java is that it's an easy language. Compared to other languages, there's less to find
out. This simplicity is critical to assist insure the platform-independence (ability to run on any computer)
of Java applications. But, simply because it's an easy language doesn’t mean it lacks capabilities. You’ll do
anything with Java that you just can with any of the more complicated languages.
The evolution of Java: Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed
Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the
primary working version. This language was initially called Oak but was renamed Java in 1995.
Between the initial implementation of Oak within the fall of 1992 and therefore the public
announcement of Java within the spring of 1995, more people contributed to the planning and
evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm
were key contributors to the maturing of the first prototype.

15
Programming 2 Educor ©

5.1.4. JAVA IDENTIFIERS


All Java elements need names. Names used for categories, variables and ways ar referred to as
identifiers. Within the HelloWorld program, HelloWorld, String, args, main and println ar identifiers.
In Java, there ar many points to recollect regarding identifiers. They’re as follows:
• All identifiers ought to begin with a letter (A to Z or a to z), currency character ($) or
associate underscore (_).
• After the primary character identifiers will have any combination of characters.
• A key word can't be used as associate symbol.
• Most significantly identifiers ar case sensitive.
• Examples of legal identifiers: age, $salary, _value, __1_value
• Examples of embezzled identifiers: 123abc, -salary
5.1.5. VARIABLE INITIALIZATION
A variable provides US with named storage that our programs will manipulate. Every variable in Java
features a specific sort that determines the dimensions and layout of the variable's memory. The
vary of values which will be hold on among that memory; and therefore the set of operations which
will be applied to the variable.
You must declare all variables before they will be used. The essential kind of a variable declaration is
shown here
After declaring a variable, you'll store a value within the memory reserved for it. Once you have simply
declared a variable, it's going to not hold a major value. To understand the value it's, you must place
initial value into that memory house. Putting an initial value is referred to as initializing the variable.
To initialize a variable, on the correct aspect of its name, sort the assignment operator, followed by
the value you wish to place within the reserved memory. As we are going to see within the next few
sections, you cannot and may not place simply any variety of value in a very variable. We are going
to see that there are differing kinds used for various variables.
After declaring a variable and once it's a value, to show that value, you'll offer the name of the
variable to the parentheses (in future lessons, we are going to learn that this is often said as passing)
of the System.out.print() methodology.
This chapter can justify varied variable sorts out there in Java Language. There square measure 3
sorts of variables in Java:
• Local variables
• Instance variables
• Class/static variables

LOCAL VARIABLES:
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block. Access modifiers
cannot be used for local variables.
Local variables are visible only within the declared method, constructor or block.
Local variables are implemented at stack level internally.
There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.

16
Programming 2 Educor ©

EXAMPLE:
Here, age is a local variable. This is defined inside nameAge() method and its scope is limited to this
method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}

INSTANCE VARIABLES
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object in the heap, a slot for each instance variable value is created.
Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method, constructor or
block, or essential parts of an object's state that must be present throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class. Normally, it is
recommended to make these variables private (access level). However visibility for subclasses can be
given for these variables with the use of access modifiers.
Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for
object references it is null. Values can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class. However
within static methods and different class (when instance variables are given accessibility) should be
called using the fully qualified name.ObjectReference.VariableName

17
Programming 2 Educor ©

EXAMPLE:
import java.io.*;
public class Employee{
// this instance variable is visible for any child
class. public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the
constructor. public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee
details. public void printEmp(){
System.out.println ("name : " + name );
System.out.println ("salary:" + salary);
}
public static void main(String args[]){
Employee empOne = new Employee
("John"); empOne.setSalary(1000);
empOne.printEmp();
}
}

CLASS/STATIC VARIABLES:
Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many objects are
created from it.
Static variables are rarely used other than being declared as constants. Constants are variables that are
declared as public/private, final and static. Constant variables never change from their initial value.
Static variables are stored in static memory. It is rare to use static variables other than declared final
and used as either public or private constants.
“Static variables are created when the program starts and destroyed when the program stops.”

18
Programming 2 Educor ©

Visibility is similar to instance variables. However, most static variables are declared public since
they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is
false; and for object references, it is null. Values can be assigned during the declaration or within the
constructor. Additionally values can be assigned in special static initializer blocks.
Static variables can be accessed by calling with the class name ClassName.VariableName.
When declaring class variables as public static final, then variables names (constants) are all in upper
case. If the static variables are not public and final the naming syntax is the same as instance and
local variables.

Example:
import java.io.*;
public class Employee{
// salary variable is a private static
variable private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}

5.1.6. PRIMITIVE DATA TYPES


Java defines eight simple (or elemental) types of data:
1) byte
2) short
3) int
4) long
5) char
6) float
7) double
8) Boolean

19
Programming 2 Educor ©

These can be put in four groups:


1. Integers this group includes byte, short, int, and long, which are for whole valued signed
numbers.
2. Floating-point numbers this group includes float and double, which represent numbers
with fractional precision.
3. Characters this group includes char, which represents symbols in a character set, like
letters and numbers.
4. Boolean this group includes Boolean, which is a special type for representing true/false
values.

You can use these types as-is, or to construct arrays or your own class types. Thus, they form the basis for
all other types of data that you can create. The simple types represent single values—not complex
objects. Although Java is otherwise completely object-oriented, the simple types are not. They are
analogous to the simple types found in most other non–object-oriented languages. The reason for this is
efficiency. Making the simple types into objects would have degraded performance too much.
The simple types are defined to have an explicit range and mathematical behaviour. Languages such as C
and C++ allow the size of an integer to vary based upon the dictates of the execution environment.
However, Java is different. Because of Java’s portability requirement, all data types have a strictly defined
range. For example, an int is always 32 bits, regardless of the particular platform. This allows programs to
be written that are guaranteed to run without porting on any machine architecture. While strictly
specifying the size of an integer may cause a small loss of performance in some environments, it is
necessary in order to achieve portability. Let’s look at each type of data in turn.

1. INTEGERS
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers. Many other computer
languages, including C/C++, support both signed and unsigned integers.
However, Java’s designers felt that unsigned integers were unnecessary. Specifically, they felt that
the concept of unsigned was used mostly to specify the behaviour of the high-order bit, which
defined the sign of an int when expressed as a number. As you will, Java manages the meaning of the
high-order bit differently, by adding a special unsigned right shiftoperator. Thus, the need for an
unsigned integer type was eliminated.
The width of an integer type should not be thought of as the amount of storage it consumes, but
rather as the behaviour it defines for variables and expressions of that type. The Java run-time
environment is free to use whatever size it wants, as long as the types behave as you declared them.
In fact, at least one implementation stores bytes and shorts as 32-bit (rather than 8-bit and 16-bit)
values to improve performance, because that is the word size of most computers currently in use.
The width and ranges of these integer types vary widely, as shown in this table:

Name Width in Bits Range


Long 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

Int 32 -2,147,483,648
to 2,147,483,647

Short 16 -32,768 to 32,767


Byte 8 -128 to 127

20
Programming 2 Educor ©

Let’s look at each type of integer.

BYTE
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127.
Variables of type byte are especially useful when you’re working with a stream of data from a
network or file. They are also useful when you’re working with raw binary data that may not be
directly compatible with Java’s other built-in types.
Byte variables are declared by use of the byte keyword. For example, the following declares two
byte variables called b and c: byte b, c;

SHORT
Short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used Java
type, since it is defined as having its high byte first (called big-endian format). This type is mostly
applicable to 16-bit computers, which are becoming increasingly scarce.
Here are some examples of short variable declarations:
short s;
short t;

INTEGER (INT)
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays. Any time you have an integer expression involving
bytes, shorts, ints, and literal numbers, the entire expression is promoted to int before the
calculation is done.
The int type is the most versatile and efficient type, and it should be used most of the time when you
want to create a number for counting or indexing arrays or doing integer math. It may seem that
using short or byte will save space, but there is no guarantee that Java won’t promote those types to
int internally anyway. Remember, type determines behaviour, not size. (The only exception is arrays,
where byte is guaranteed to use only one byte per array element, short will use two bytes, and int
will use four.)

LONG
Long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to
hold the desired value. The range of a long is quite large. This makes it useful when big, whole
numbers are needed. For example, here is a program that computes the number of miles that light
will travel in a specified number of days

Example.
Compute distance light travels using long variables.
class Light {
public static void main(String args[])
{
int lightspeed;
long days;

21
Programming 2 Educor ©

long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here seconds
= days * 24 * 60 * 60; // convert to seconds distance
= lightspeed * seconds; // compute distance
System.out.print("In " + days); System.out.print("
days light will travel about ");
System.out.println(distance + " miles.");
}
}

This program generates the following output:


In 1000 days light will travel about 16070400000000 miles.

Clearly, the result could not have been held in an int variable.

2. FLOATING-POINT TYPES
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. For example; calculations such as square root or transcendental such as
sine and cosine, result in a value whose precision requires a floating-point type. Java implements the
standard (IEEE–754) set of floating-point types and operators. There are two kinds of floating-point
types, float and double, which represent single- and double-precision numbers, respectively.
Their width and ranges are shown here:

Name Width in Bits Approximate Range


Double 64 4.9e 324 to 1.8e+308
Float 32 1.4e 045 to 3.4e+038

Each of these floating-point types is examined next.

FLOAT
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster
on some processors and takes half as much space as double precision, but will become imprecise
when the values are either very large or very small. Variables of type float are useful when you need
a fractional component, but don’t require a large degree of precision. For example, float can be
useful when representing dollars and cents.
Here are some example float variable declarations:
float hightemp, lowtemp;

DOUBLE

22
Programming 2 Educor ©

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision
is actually faster than single precision on some modern processors that have been optimized for
high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and
sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations,
or are manipulating large-valued numbers, double is the best choice. Here is a short program that
uses double variables to compute the area of a circle:

Example.
Compute the area of a circle.
class Area {
public static void main(String args[])
{
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}

3. 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 of 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.
Here is a program that demonstrates char variables:
Example
class CharDemo {
public static void main(String args[])
{
char ch1, ch2;
ch1 = ‘X’;
ch2 = ‘Y’;

23
Programming 2 Educor ©

System.out.print("ch1 and ch2: ");


System.out.println (ch1 + " " + ch2);
}
}

This program displays the following output:


ch1 and ch2: X 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:
Example.
char variables behave like integers.

class CharDemo2 {
public static void main(String args[])
{
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}

The output generated by this program is shown here:


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.

24
Programming 2 Educor ©

4. BOOLEANS
Java has a simple type, called boolean, for logical values. It can have only one of two possible values,
true or false. This is the type returned by all relational operators, such as a < b. boolean is also the
type required by the conditional expressions that govern the control statements such as if and for.

Here is a program that demonstrates the boolean type:


Demonstrate boolean values.

class BoolTest {
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b)
System.out.println("This is
executed."); b = false;
if(b)
System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}

The output generated by this program is shown here:


b is false
b is true
This is executed.
10 > 9 is true

There are three interesting things to notice about this program. First, as you can see, when a Boolean
value is output by println( ), “true” or “false” is displayed. Second, the value of a Boolean variable is
sufficient, by itself, to control the if statement. There is no need to write an IF STATEMENT like this:
if(b == true) ...
Third, the outcome of a relational operator, such as <, is a Boolean value. This is why the expression
10 > 9 displays the value “true.” Further, the extra set of parentheses around 10 > 9 is necessary
because the + operator has a higher precedence than the >.

25
Programming 2 Educor ©

5.1.7.STRUCTURE OF A JAVA PROGRAM


Java, like any language (computer or spoken), has a terminology all its own. Let’s look at the structure of
a Java program and learn some of this new terminology. A Java program (or project) is made up of a
number of files. These files are called classes. Each of these files has Java code that performs some
specific task(s). Each class file is saved with the file extension.java. The filename used to save a class must
match the class name. One class in each project will contain something called the main method.
Whenever you run a Java program, your computer will search for the main method to get things started.
Hence, to run a program, you refer directly to the class containing this main method.

5.1.8. WHAT IS AN ALGORITHM?


A set of steps (from beginning to end) describing the tasks (job) to be performed, to achieve results.
Example 1 – Level 1.
To understand what an Algorithm is.
Write down the steps of making a cup of tea.
Begin.
Get a cup.
Get a teabag, milk, sugar.
Boil the water.
Add the water to the cup. Add teabag, milk, sugar.
Stir.
End.

Example 2 – High Level.


To understand the steps in doing a calculation, using the input, output, process.
Write an algorithm to calculate and print your telephone bill.
Begin
Perform Read-Number-of-Calls.
Perform Calculation.
Perform Print.
End.

Note that we have only mentioned the name of the tasks to do, so we create sub-algorithms to show
what we are going to do in these tasks.
Sub-algorithms help us to manage/neaten our code and makes understanding it better.

26
Programming 2 Educor ©

5.1.9. HOW TO START USING JAVA?


As mentioned, in order to write code, you must understand the task first - what is needed,
understand the problem and then get the solution. Start with your algorithm, make sure it makes
sense and is logical. We can test the algorithms, using various methods, to check if they make sense
and produce a good result (Testing will be discussed @ later stage). Then we can convert the
algorithm to actual Java code.

BASIC SYNTAX:
About Java programs, it is very important to keep in mind the following points.”
Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different
meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter should
be in Upper Case.
Example public void myMethodName()
Program File Name - Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and
append '.java' to the end of the name (if the file name and the class name do not match your
program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'”

public static void main(String args[]) - Java program processing starts from the main() method
which is a mandatory part of every Java program.

Simple Code.
// This prints the words on the
screen. Public Class Hello
{
Public static void main (String[] args)
{
System.out.println(“HelloWorld”);
}
}

5.1.10. BASIC INPUT AND OUTPUT


Input

27
Programming 2 Educor ©

This program tells you how to get input from user in a java program. We are using Scanner class to
get input from user. This program firstly asks the user to enter a string and then the string is printed,
then an integer and entered integer is also printed and finally a float and it is also printed on the
screen. Scanner class is present in java.util package so we import this package in our program. We
first create an object of Scanner class and then we use the methods of Scanner class. Consider the
statement
Scanner kb = new Scanner(System.in);
Here Scanner is the class name, kb is the name of object, new keyword is used to allocate the memory
and System.in is the input stream. Following methods of Scanner class are used in the program below:
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
4) nextDouble “to input a double

Java programming source code below.

import java.util.Scanner;
class inputExample
{
public static void main(String args[])
{
int a;
float b;
String s;
double d;
Scanner read = new Scanner(System.in);
System.out.println("Enter a string");
s = read.nextLine();
System.out.println("You entered string "+s);
System.out.println("Enter an integer");
a = read.nextInt();
System.out.println("You entered integer "+a);
System.out.println("Enter a float");
b = read.nextFloat();
System.out.println("You entered float "+b);
System.out.println("Enter a Double");
d = read.nextDouble();
System.out.println("You entered Double "+d);
}
}
Below shows the output results of the above code:

28
Programming 2 Educor ©

Output
We have ways to name and declare variables and ways to do math with them, but once we have
results, how can those results be displayed? We will use the method seen in our little Welcome
program, the Java println (recall, you pronounce it “print line”) method. What this method does is
print a string result on a single line:
System.out.println(stringValue);

In this expression, stringValue could be a String variable that has been evaluated somewhere
(perhaps using the concatenation operator) or a literal (an actual value). In the Welcome example,
we used a literal:
System.out.println(“Welcome to Beginning Java!”);

And saw that


→ Welcome to Beginning Java!
Was output to the screen.

What if you want to output numeric information? It’s really quite easy. The println method will
automatically convert a numeric value to a string for output purposes. For example, look at this little
code segment:
numberBananas = 45;
System.out.println(numberBananas);

If you run this code, a 45 will appear on the output screen.

You can also combine text information with numeric information using the concatenation operator.
For example:

29
Programming 2 Educor ©

numberBananas = 45;
System.out.println(“Number of Bananas is ” + numberBananas);

Will print Number of Bananas is 45 on the output screen. The numeric data (numberOfBananas) is
converted to a string before it is concatenated with the text data

When we consider a Java program it can be defined as a collection of objects that communicate via
invoking each other's methods. Let us now briefly look into what do class, object, methods and
instance variables mean.

Object - Objects have states and behaviours. Example: A dog has states - colour, name, breed as well
as behaviours -wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describes the behaviours/states that
object of its type support.

Methods - A method is basically a behaviour. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.

Instance Variables - Each object has its unique set of instance variables. An object's state is created
by the values assigned to these instance variables.

5.1.11. Revision Questions

Define the following terms:


1.1 Algorithm
1.2 Case Sensitivity
1.3 Class Names
1.4 Method Names
1.5 Program File Name
1.6 Class

2.1 List 8 primitive data types in java


2.2 There are several points to remember about java identifiers list 5 of these
2.4 State what an algorithm is and provide a written example of an algorithm

30
Programming 2 Educor ©

STUDY UNIT 2: JAVA PROGRAMMING BASICS OBJECTIVES


5.2.1. ARITHMETIC OPERATORS AND PRECEDENCE
One thing computer programs are very good at is doing arithmetic. They can add, subtract, multiply,
and divide numbers very quickly. We need to know how to make our Java projects do arithmetic.
There are five arithmetic operators we will use from the Java language.
Addition is done using the plus (+) sign and subtraction is done using the minus (-) sign. Simple
examples are:
Operation Example Result

Addition 7+2 9
Addition 3+8 11
Subtraction 6–4 2

Subtraction 11–7 4

Multiplication is done using the asterisk (*) and division is done using the slash (/). Simple examples
are:
Operation Example Result
Multiplication 8*4 32
Multiplication 2 * 12 24
Division 12/2 6

Division 42/6 7

The other arithmetic operator we use is called the remainder operator (%). This operator gives you
the remainder that results from dividing two whole numbers.”
Example Division Result Remainder Result

7%4 1 Remainder 3 3

14%3 4 Remainder 2 2

25%5 5 Remainder 0 0

What happens if an assignment statement contains more than one arithmetic operator? Does it
make any difference? Look at this example:
7+3*4

31
Programming 2 Educor ©

What’s the answer? Java takes away the possibility of such confusion by having rules of precedence
[Please refer to the section on the following pages]. This means there is a specific order in which
arithmetic operations will be performed.

That order is:


1. Multiplication (*) and division (/)
2. Remainder (%)
3. Addition (+) and subtraction (-)
So, in an assignment statement, all multiplications and divisions are done first, then remainder
operations, and lastly, additions and subtractions. In our example (7 + 3 * 4), we see the
multiplication will be done before the addition, so the answer provided by Java would be 19.
If two operators have the same precedence level, for example, multiplication and division, the
operations are done left to right in the assignment statement. For example:

24/2*3
The division (24 / 2) is done first yielding a 12, then the multiplication (12 * 3), so the answer is 36.
But what if we want to do the multiplication before the division - can that be done? Yes - using the
Java grouping operators - parentheses (). By using parentheses in an assignment statement, you
force operations within the parentheses to be done first. So, if we rewrite our example as:

24/(2*3)
The multiplication (2 * 3) will be done first yielding 6, then the division (24 / 6), yielding the desired
result of 4. You can use as many parentheses as you want, but make sure they are always in pairs -
every left parenthesis needs a right parenthesis. If you nest parentheses, that is have one set inside
another, evaluation will start with the innermost set of parentheses and move outward. For
example, look at:

((2+4)*6)+7
The addition of 2 and 4 is done first, yielding a 6, which is multiplied by 6, yielding 36. This result is
then added to 7, with the final answer being 43. You might also want to use parentheses even if they
don’t change precedence. Many times, they are used just to clarify what is going on in an
assignment statement.

Some examples of Java assignment statements with arithmetic operators:

totalBananaCost = numberBananas * bananaCost;


numberOfWeeks = numberOfDays / 7;
averageScore = (score1 + score2 + score3) / 3;

Notice the parentheses in the averageScore calculation forces Java to add the three scores before
dividing by 3. Also, notice the use of white space, spaces separating operators from variables. This is
a common practice in Java that helps code be more readable.

32
Programming 2 Educor ©

5.2.2. RELATIONAL OPERATORS


The relational operators determine the relationship that one operand has to the other. Specifically,
they determine equality and ordering. The relational operators are shown here: The outcome of
these operations is a Boolean value. The relational operators are most frequently used in the
expressions that control the if statement and the various loop statements. Any type in Java,
including integers, floating-point numbers, characters, and Booleans can be compared using the
equality test, ==, and the inequality test !=. Notice that in Java (as in C and C++) equality is denoted
with two equal signs, not one. (Remember: a single equal sign is the assignment operator.) Only
numeric types can be compared using the ordering operators. That is, only integer, floating-point,
and character operands may be compared to see which is greater or less than the other. As stated,
the result produced by a relational operator is a Boolean value.

Comparison Operator Description


> Greater than
< Less than
== Equal to
>= Greater than or Equal to
<= Less than or equal to
!= Not equal to

For example, the following code fragment is perfectly valid:


int a = 4;
int b = 1;
boolean c = a < b;
In this case, the result of a<b (which is false) is stored in c.
If you are coming from a C/C++ background, please note the following. In C/C++, these types of
statements are very common:
int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not in Java.

In Java, these statements must be written like this:


if(done == 0)) ... // This is Java-style.
if(done != 0) ...
The reason is that Java does not define true and false in the same way as C/C++. In C/C++, true is any
nonzero value and false is zero. In Java, true and false are nonnumeric values which do not relate to
zero or nonzero. Therefore, to test for zero or nonzero, you must explicitly employ one or more of
the relational operators.

33
Programming 2 Educor ©

5.2.3. Operator Precedence


The order in which operators are applied is known as precedence. Operators with a higher precedence
are applied before operators with a lower precedence. The operator precedence order of Java is shown
below. Operators at the top of the table are applied before operators lower down in the table. If two
operators have the same precedence, they are applied in the order they appear in a statement.
That is, from left to right. You can use parentheses to override the default precedence.
postfix [] . () expr++ expr–

unary ++expr – expr +expr -expr ! ~


creation/caste New (type)expr
multiplicative * / %

additive + -
shift >> >>>
relational < <= > >= instanceof

equality == !=
bitwise AND &
bitwise exclusive OR ^

bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = op=
“ ”

Example
In an operation such as,
result = 4 + 5 * 3”
“First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that ‘*’
takes higher precedence than ‘+’ according to chart shown above. This kind of precedence of one
operator over another applies to all the operators.

5.2.4. Revision Questions

2.1 Write each of the arithmetic symbols with their name and an example of how each works
2.2 Provide the symbol and name of the 6 relational operators in java

34
Programming 2 Educor ©

STUDY UNIT 3: SEQUENCE, SELECTION AND REPETITION OBJECTIVES


SEQUENTIAL PROGRAM FLOW AND BRANCHING (SELECTION) USING IF-ELSE AND SWITCH.

5.3.1. JAVA’S SELECTION STATEMENTS


Java supports two selection statements: if and switch. These statements allow you to control the
flow of your program’s execution based upon conditions known only during run time. You will be
pleasantly surprised by the power and flexibility contained in these two statements.
5.3.1.1. IF STATEMENT
The if statement was introduced in Chapter 2. It is examined in detail here. The if statement is Java’s
conditional branch statement. It can be used to route program execution through two different
paths. Here is the general form of the if statement:
Syntax
if (condition) statement1;
else statement2;

Here, each statement may be a single statement or a compound statement enclosed in curly braces
(that is, a block). The condition is any expression that returns a boolean value.

The else clause is optional.

The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it
exists) is executed. In no case will both statements be executed. For example, consider the following:

int a, b;
// ...
if(a <
b) a =
0; else
b = 0;

Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In no case are they both set
to zero.

Most often, the expression used to control the if will involve the relational operators.

35
Programming 2 Educor ©

However, this is not technically necessary. It is possible to control the if using a single boolean
variable, as shown in this code fragment:

boolean dataAvailable;
// ...
if (dataAvailable)
ProcessData();
else
waitForMoreData();

Remember, only one statement can appear directly after the if or the else. If you want to include
more statements, you’ll need to create a block, as in this fragment:

int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
}else
waitForMoreData();

Here, both statements within the if block will execute if bytesAvailable is greater than zero. Some
programmers find it convenient to include the curly braces when using the if, even when there is
only one statement in each clause. This makes it easy to add another statement at a later date, and
you don’t have to worry about forgetting the braces. In fact, forgetting to define a block when one is
needed is a common cause of errors.

For Example,
Consider the following code fragment:

int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else
waitForMoreData();
bytesAvailable = n;

36
Programming 2 Educor ©

Inside the else clause, because of the indentation level. However, as you recall, whitespace is
insignificant to Java, and there is no way for the compiler to know what was intended. This code will
compile without complaint, but it will behave incorrectly when run. The preceding example is fixed
in the code that follows:

int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else {
waitForMoreData();
bytesAvailable = n;
}

5.3.1.2. Nested IF’S


A nested if is an if statement that is the target of another if or else. Nested ifs are very common in
programming. When you nest ifs, the main thing to remember is that an else statement always
refers to the nearest if statement that is within the same block as the else and that is not already
associated with an else. Here is an example:

if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else
a = d; // this else refers to if(i == 10)

As the comments indicate, the final else is not associated with if(j<20), because it is not in the same
block (even though it is the nearest if without an else). Rather, the final else is associated with
if(i==10). The inner else refers to if(k>100), because it is the closest if within the same block.

37
Programming 2 Educor ©

5.3.1.3. THE IF-ELSE-IF LADDER


A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
It looks like this:

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

The if statements are executed from the top down. As soon as one of the conditions controlling the
if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If
none of the conditions is true, then the final else statement will be executed. The final else acts as a
default condition; that is, if all other conditional tests fail, then the last else statement is performed.
If there is no final else and all other conditions are false, then no action will take place.

Here is a program that uses an if-else-if ladder to determine which season a particular month is in.
// Demonstrate if-else-if statements.
import java.util.scanner; //import Scanner
class IfElse {
public static void main(String args[])
{

int month = 4; // April


String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}

38
Programming 2 Educor ©

Here is the output produced by the program:


April is in the Spring.

5.3.1.4. SWITCH
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression.
As such, it often provides a better alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:

switch (expression) {
case value1:
// statement
sequence break;
case value2:
// statement
sequence break;
...
case valueN:
// statement
sequence break;
default:
// default statement sequence
}

Rules for a Switch Statement


The expression must be of type byte, short, int, or char;
Each of the values specified in the case statements must be of a type compatible with the
expression.
Each case value must be a unique literal (that is, it must be a constant, not a variable).
Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is compared with each of the
literal values in the case statements. If a match is found, the code sequence following that case
statement is executed. If none of the constants matches the value of the expression, then the
default statement is executed. However, the default statement is optional. If no case matches and
no default is present, then no further action is taken.

39
Programming 2 Educor ©

The break statement is used inside the switch to terminate a statement sequence. When a break
statement is encountered, execution branches to the first line of code that follows the entire switch
statement. This has the effect of “jumping out” of the switch. Here is a simple example that uses a
switch statement:

// A simple example of the switch.


class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}”

The output produced by this program is shown here:


i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.

As you can see, each time through the loop, the statements associated with the case constant that
matches i are executed. All others are bypassed. After i is greater than 3, no case statements match,
so the default statement is executed. The break statement is optional. If you omit the break,
execution will continue on into the next case. It is sometimes desirable to have multiple cases
without break statements between them.

40
Programming 2 Educor ©

For example,
consider the following program:

// In a switch, break statements are


optional. class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println(i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than
10"); break;
default:
System.out.println("i is 10 or more");
}
}
}
This program generates the following output:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more

41
Programming 2 Educor ©

As you can see, execution falls through each case until a break statement (or the end of the switch)
is reached.

While the preceding example is, of course, contrived for the sake of illustration, omitting the break
statement has many practical applications in real programs. To sample its more realistic usage,
consider the following rewrite of the season example shown earlier. This version uses a switch to
provide a more efficient implementation.

class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}

42
Programming 2 Educor ©

5.3.1.5.Nested switch Statements


You can use a switch as part of the statement sequence of an outer switch. This is called a nested
switch. Since a switch statement defines its own block, no conflicts arise between the case constants
in the inner switch and those in the outer switch. For example, the following fragment is perfectly
valid:

switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...

Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the
outer switch. The count variable is only compared with the list of cases at the outer level. If count is
1, then target is compared with the inner list cases.

In summary, there are three important features of the switch statement to note:
The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression. That is, the switch looks only for a match between
the value of the expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a switch
statement enclosed by an outer switch can have case constants in common.
A switch statement is usually more efficient than a set of nested ifs.

The last point is particularly interesting because it gives insight into how the Java compiler works.
When it compiles a switch statement, the Java compiler will inspect each of the case constants and
create a “jump table” that it will use for selecting the path of execution depending on the value of
the expression. Therefore, if you need to select among a large group of values, a switch statement
will run much faster than the equivalent logic coded using a sequence of if-elses. The compiler can
do this because it knows that the case constants are all the same type and simply must be compared
for equality with the switch expression. The compiler has no such knowledge of a long list of if
expressions.

43
Programming 2 Educor ©

5.3.2. REPETITION – LOOPING WITH FOR, WHILE AND DO … WHILE


Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of instructions
until a termination condition is met. As you will see, Java has a loop to fit any programming need.
5.3.2.1. WHILE LOOP
The while loop is Java’s most fundamental looping statement. It repeats a statement or block while
its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}

The condition can be any Boolean expression. The body of the loop will be executed as long as the
conditional expression is true. When condition becomes false, control passes to the next line of code
immediately following the loop. The curly braces are unnecessary if only a single statement is being
repeated.
Here is a while loop that counts down from 10:

// Demonstrate the while


loop. class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println(n);
n--;
}
}
}

When you run this program, it will look like this:


10
9
8
7
6
5
4
3
2
1

44
Programming 2 Educor ©

Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop
will not execute even once if the condition is false to begin with. For example, in the following
fragment, the call to println( ) is never executed:

int a = 10, b = 20;


while(a > b)
System.out.println("This will not be displayed");

The body of the while (or any other of Java’s loops) can be empty. This is because a null statement
(one that consists only of a semicolon) is syntactically valid in Java. For example, consider the
following program:

// The target of a loop can be


empty. class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j) ; // no body in this loop
System.out.println("Midpoint is " + i);
}
}

This program finds the midpoint between i and j. It generates the following output:
Midpoint is 150

Here is how the while loop works. The value of i is incremented, and the value of j is decremented.
These values are then compared with one another. If the new value of i is still less than the new
value of j, then the loop repeats. If i is equal to or greater than j, the loop stops. Upon exit from the
loop, i will hold a value that is midway between the original values of i and j.
(Of course, this procedure only works when i is less than jto begin with.) As you can see, there is no
need for a loop body; all of the action occurs within the conditional expression, itself. In
professionally written Java code, short loops are frequently coded without bodies when the
controlling expression can handle all of the details itself.

45
Programming 2 Educor ©

5.3.2.2. DO-WHILE LOOP


As you just saw, if the conditional expression controlling a while loop is initially false, then the body
of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a
while loop at least once, even if the conditional expression is false to begin with. In other words,
there are times when you would like to test the termination expression at the end of the loop rather
than at the beginning. Fortunately,
Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at
least once, because its conditional expression is at the bottom of the loop. Its general form is”
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates. As with all of Java’s loops, condition must be a Boolean expression.
Here is a reworked version of the “tick” program that demonstrates the do-while loop. It generates
the same output as before.
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println(n);
n--;
}
while(n > 0);
}
}

The loop in the preceding program, while technically correct, can be written more efficiently as
follows:
do
{
System.out.println(n);
}
while(--n > 0);

In this example, the expression (– –n > 0) combines the decrement of n and the test for zero into
one expression. Here is how it works. First, the – –n statement executes, decrementing n and
returning the new value of n. This value is then compared with zero. If it is greater than zero, the
loop continues; otherwise it terminates.
The do-while loop is especially useful when you process a menu selection, because you will usually
want the body of a menu loop to execute at least once. Consider the following program which
implements a very simple help system for Java’s selection and iteration statements:

46
Programming 2 Educor ©

import java.util.Scanner;
// Using a do-while to process a menu
selection class Menu {
public static void main(String args[])
throws java.io.IOException { Scanner
read=new Scanner(System.in); char
choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = read.nextLine().charAt(0);
}
while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1': System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;"); break;

case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement
sequence"); System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition)
statement;"); break;
case '4':

47
Programming 2 Educor ©

System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
Here is a sample run produced by this program:

In the program, the do-while loop is used to verify that the user has entered a valid choice. If not,
then the user is reprompted. Since the menu must be displayed at least once, the do-while is the
perfect loop to accomplish this.
A few other points about this example: Notice that characters are read from the keyboard by calling
kb.nextLine(). This is one of Java’s console input functions (Where kb short for keyboard, is just a
name of a scanner class representing an input from a keyboard from the user).
Although Java’s console I/O methods won’t be discussed in detail until, nextLine() method is used
here to obtain the user’s choice. It reads characters from standard input (returned as a String, which
is why the return value was chopped to one character by using a charAt() method.).
By default, standard input is line buffered, so you must press ENTER before any characters that you
type will be sent to your program.
Java’s console input is quite limited and awkward to work with. Further, most real-world Java programs
and applets will be graphical and window-based. For these reasons, not much use of console input has
been made in this book. However, it is useful in this context. One other point: Because

48
Programming 2 Educor ©

nextLine is being used, the program must specify the throws java.io.IOException clause. This line is
necessary to handle input errors. It is part of Java’s exception handling features.

5.3.2.3 FOR LOOP


You were introduced to a simple form of the for loop in Chapter 2. As you will see, it is a powerful
and versatile construct. Here is the general form of the for statement:
for(initialization; condition; iteration)
{
// body
}
If only one statement is being repeated, there is no need for the curly braces. The for loop operates
as follows. When the loop first starts, the initialization portion of the loop is executed. Generally, this
is an expression that sets the value of the loop control variable, which acts as a counter that controls
the loop.
It is important to understand that the initialization expression is only executed once. Next, condition
is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a
target value. If this expression is true, then the body of the loop is executed.
If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an
expression that increments or decrements the loop control variable. The loop then iterates, first
evaluating the conditional expression, then executing the body of the loop, and then executing the
iteration expression with each pass.
This process repeats until the controlling expression is false.
Here is a version of the “tick” program that uses a for loop:

// Demonstrate the for loop.


class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println(n);
}
}”

49
Programming 2 Educor ©

DECLARING LOOP CONTROL VARIABLES INSIDE THE FOR LOOP


Often the variable that controls a for loop is only needed for the purposes of the loop and is not
used elsewhere. When this is the case, it is possible to declare the variable inside the initialization
portion of the for. For example, here is the preceding program recoded so that the loop control
variable n is declared as an int inside the for:

// Declare a loop control variable inside the


for. class ForTick {
public static void main(String args[]) {
// here, n is declared inside of the for loop
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}

When you declare a variable inside a for loop, there is one important point to remember: the scope
of that variable ends when the for statement does. (That is, the scope of the variable is limited to
the for loop.) Outside the for loop, the variable will cease to exist. If you need to use the loop control
variable elsewhere in your program, you will not be able to declare it inside the for loop. When the
loop control variable will not be needed elsewhere, most Java programmers declare it inside the for.
For example, here is a simple program that tests for prime numbers. Notice that the loop control
variable, i, is declared inside the for since it is not needed elsewhere.

// Test for primes.


class FindPrime {
public static void main(String args[]) {
int num;
boolean isPrime =
true; num = 14;
for(int i=2; i <= num/2; i++) {
if((num % i) == 0) { isPrime =
false;
break;
}
}
if(isPrime) System.out.println("Prime");
else System.out.println("Not Prime");
}
}”

50
Programming 2 Educor ©

5.3.3. THE SCOPE AND LIFETIME OF VARIABLES


During the execution of a Java program, each variable has its own time within which it can be accessed.
This is called the lifetime of the variable. We can determine the lifetime of variables by looking at the
context in which they're defined. Anyway, we can distinguish between three contexts: Instance variables:
Instance variables are class members. Every time you create an object from a class, a brand new copy of
these instance variables is created for this object. Actually, creating an object from a class means,
partially, creating copies of instance variables for that object. So each object has its own copy of instance
variables which exist as long as the object they belong to exists. The values of these variables constitute
what we call: the state of the object. Static variables: Static variables are also members of a class but can't
belong to any object created from that class. So created objects from the class don't get their own copies
of static variables. Therefore static variables are created only when the class is loaded at runtime. The
existence of static variables is dependent only on the class itself. As a result, a static variable exists as long
as its class exists. Please note that an object of a class may still manipulate a static variable even though
this object can't have its own copy of this static variable.
Local variables: Also called automatic variables, are called local because their scope is the method or
block within which they are declared. After the execution of the method or block completes, these
local (non-final) variables are no longer accessible

51
Programming 2 Educor ©

STUDY UNIT 4: STRINGS, STRING METHODS AND CONCATENATION


5.4.1. Concatenation
We can apply arithmetic operators to numerical variables (type int and type double). String variables
can also be operated on. Many times in Java projects, you want to take a string variable from one
place and ‘tack it on the end’ of another string. The fancy word for this is string concatenation. The
concatenation operator is a plus sign (+) and it is easy to use. As an example:

String newString = “Beginning Java ” + “is Fun!”;

After this statement, the string variable newString will have the value Beginning Java is Fun!
Also, two strings can be joined together or concatenated using the concat (string2) method, which
returns a new string consisting of the argument string (string2) joined to the end of the invoking
string. For example,
aString = "abed";
bString = "xyz";
cString = aString.concat(bString);
will store "abcdxyz" in cString,
while
cString = bString.concat(aString);
will store "xyzabcd" in cString.

Note that the operators + and += have been overloaded for strings to perform concatenation, and
hence one can use statements such as
cString = aString + bString; // abcdxyz
cString += aString; // abcdxyzabcd

To summarise, the string methods discussed above are tabulated below. There are a number of
other methods, as well as variations on these methods (different arguments etc), but the ones
shown here are the more common and useful methods.

52
Programming 2 Educor ©

5.4.2. STRING METHODS


Method Name Function
Length() returns the (int) length of the string
charAt (int) returns the char at the given index
toUppercase ( ) returns the string as upper case
toLowerCase() returns the string as lower case

trim() returns the string with leading and trailing


whitespace removed
equals (String) returns true if the string argument equals the
invoking string, and false otherwise
equalsIgnoreCase (String) returns true if the string argument equals the
invoking string, ignoring case, and false
otherwise
compareTo (String ) returns a negative, zero or positive int to
indicate the invoking string is less than, equal to,
or greater than the argument string

indexOf (String ) returns the first occurrence of the index position


of the argument string in the invoking string
lastIndexOf(String ) returns the last occurrence of the index position
of the argument string in the invoking string
substring (startPosition , endPosition) returns the substring starting at the given index
in the invoking string

concat (String ) returns a new string consisting of the invoking


string with the argument string joined at the
end.

53
Programming 2 Educor ©

Example Read in a list of names and sort them into alphabetical order. If we have an array of strings,
the standard sorting algorithms can be adapted to compare strings and sort the array into
alphabetical order.
while (startlndex<n) // if >1 element, process sublist
{
minlndex = startlndex;
for(int i=startIndex+1;i<n;i++)
{
comp = name[I].compareTo(names[minIndex]);
if (comp<0)
minIndex = I;
}
if (startIndex!=minIndex)
{
String temp = names [startIndex];
names [startIndex] = names [minIndex];
names [minIndex] = temp;
}
startlndex++; // start sublist at next element
}

5.4.3. FORMATTED OUTPUT


The format() method's first parameter is a string that specifies how to convert a number. For
integers you would typically use a % followed by the number of columns you want the integer to be
right justified in, followed by a decimal conversion specifier "d". The second parameter would be the
number you want to convert. For example,
int n = 2;
System.out.format("%3d", n);
This would print the number in three columns, that is with two blanks followed by 2.
You can put other non-% characters in front or back of the conversion specification, and they will
simply appear literally. For example,
int n = 2;
System.out.format("| %3d |", n);
would print
|2|

54
Programming 2 Educor ©

5.4.4. STRINGS, STRING METHODS AND CONCATENATION


We have already encountered string literals or constants which are lists of characters enclosed in
double quotes, such as "Hello there!" In Java, String is a class, so strings are objects and not
variables. There are in fact 2 classes for manipulating strings: class string for which the contents,
once assigned, may not be changed, and class stringBuffer which enables changes to the contents of
strings. Java distinguishes constant strings and modifiable strings for optimisation purposes — in
particular, Java can perform certain optimisations involving string objects because it knows these
objects will not change. String Class
This class is used to manipulate string and character values in a class.

Methods in String class


The following methods are used in string manipulation.

Length – to get the number of letters in a string.


String name = “hello”; int num = name.length(); → 5

Equals – to check if two strings match.


String name=”hello”
If (name.equals(“HELLO”))
{
System.out.println(“same”);
}
else
{
System.out.println(“Differ”);
}
→ Same

EqualsIgnoreCase – to check if two strings match regardless of the case.


String name=”hello”
If (name.equalsIgnoreCase(“HELLO”))
{
System.out.println(“same”);
}
else
{
System.out.println(“Differ”);
}
→ Differ

Uppercase – to change the contents of the string to uppercase.

55
Programming 2 Educor ©

String name = “hello”;


System.out.println(name.toUpperCase());
→ HELLO

Lowercase – to change the contents of the string to small letters.


String name = “HELLO”;
System.out.println(name.toUpperCase());
→ hello

Trim – returns string with spaces removed.


String p = “ hello ”; p.trim();
→ hello

charAt – returns character @ a certain position.


String greet = “hello”; greet.charAt(0)
→ ‘h’

Substring – returns part of a string from position stated to the end of the
string. String name = “hello”; name.substring(2) → “llo”

IndexOf – returns the 1st position of the character/string stated.


String name = “hello”; name.indexOf(“l”)
→2

LastIndexOf –returns the last position of the character/string stated.


String name = “hello goodbye”; name.indexOf(“o”)
→8

“There is a special notation for creating strings with known contents - unlike other objects the new
operator is not needed. A string is created by assigning it another string, or a character array, or a
StringBuffer. For example, if the following variables are all declared as String,
aString = "Hello";
bString = "";
cString = Keyboard.readstring();
are all valid assignments.

A string variable can be assigned different string values at different times - it is not a constant - but
once assigned, the characters comprising the string may not be changed. The entire string must be
reassigned as an entity.

56
Programming 2 Educor ©

As with all objects, a string instance must be declared before it is used, and may be initialised at the
same time.
String bString = "";
String dString;

There is a difference between an empty (but initialised) string, and a null (ie. not initialised) string. In the
example above, dString is uninitialised and will have a special value called null until it is given some other
string value in an assignment statement. Such a string is not valid for string manipulation methods, and if
an attempt is made to access it, a NullPointerException will be thrown by the system. On the other hand,
bstring is initialised and can be used in string manipulation - it just has no contents.

Like arrays, strings know their own size, and a method length () will give the length of the string.
Note that with arrays, length is an instance variable and is accessed as myArray. length. With strings,
length () is a method call, and brackets are required:
int size = myString.length();

A string is made up of a sequence of characters, and although it cannot be indexed directly (eg
mystring [7]), the character at any index position can be obtained using the method charAt(int).
String myName = "Percival";
char initial = myName.charAt(0);

If an attempt is made to access a character outside string bounds (ie. -<0 or >length), a
StringlndexOutOf BoundsException is obtained.

Methods toLowerCaseO and toUpperCase () return a new string composed of all lower case or upper
case characters respectively. Special characters are unaffected, and the original string is unchanged,
unless it is reassigned to the new string.

For example,
String original,upper,lower;
original = " dit 2a";
upper = original.toUpperCase();
lower = original.toLowerCase();
System.out.println("original string: " + original + "\n in upper case: " + upper + "\n in lower case: " +
lower);

will output original string:


original string: dit 2a
dit 2a in upper case: DIT 2A
in lower case: dit 2a

57
Programming 2 Educor ©

Another useful method is trim (), which returns a new string without any of the whitespace
characters (blanks, newlines or tabs) that may appear at the beginning or end of the original string.
Internal whitespace is untouched.

For example
String original,trimmed;
original = " Dit 2A ";
trimmed = original .trim ();
System.out.println("original string: *" + original + "*"
+ "\nafter trimming : *" + trimmed + "*"),-
will output original string:
original string : * Dit 2A *
after trimming : *Dit2A *

Strings may be compared in two ways. The Boolean methods equals (string) and equalsIgnoreCase
(String) will return true or false depending on whether the string supplied as argument is equal to
the string instance invoking the method, or not.
For example
aString = "CS1A";
bString = "CS1B";
cString = "csla";
if (aString.equals(bString))
System.out.println(aString+" equals "+bString);
else
System.out.println(aString+" does not equal "+bstring);
if (aString.equals(cString))
System.out.println(aString+" equals "+cString);
else
System.out.println(aString+" does not equal "+cString);
if (aString.equalsIgnoreCase(cString))
System.out.println(aString+" equals (no case) "+cString);
else
System.out.println(aString+" does not equal "+cString);
will output CS1A does not equal CS1B
CS1A does not equal csla
CS1A equals (no case) csla

Note that the equals operator (= or <, > for that matter) should not be used with objects, only with
variables. The reason will be explained more fully in a later section, but is to do with the fact that
objects are stored as references to data values, while variables store the values themselves.

58
Programming 2 Educor ©

Using = to compare two objects will compare the references of the two objects - do they refer to the
same storage? are the values equal?
On the other hand the compareTo(string) method compares the 2 strings on their respective
UNICODE codes, and returns an integer result, where 0 means the two strings are equal, a negative
number means the string that invoked compareTo is less than the string passed as argument, and a
positive number means the string that invoked compareTo is greater than the string passed as
argument (the actual number is the code , difference between the first pair of unequal characters).
The method works by comparing pairs of characters from the left, and the first unequal pair
determines the result.

For example,
aString = "hello";
bString = "Hello";
cString = "goodbye";
dString = "good" ;
System.out.print In ( "Comparing "+aString+" and "+bString+" : "
+ aString.compareTo(bString)) ;
System. out . print In ( "Comparing "+bstring+" and "+cString+ " : "
+ bString.compareTo (cString)) ;
System. out .print In ( "Comparing "+cString+" and "+dString+" : " + cString. compareTo (dString));
System.out.print In ( "Comparing "+dString+" and "+dString+" : "
+ dString. compareTo (dString)) ;

Will Output
Comparing hello and Hello : 32
Comparing Hello and goodbye : -31
Comparing goodbye and good : 3
Comparing good and good : 0

For the first, the code for 'h1 is 104, while that for 'H1 is 72, hence "hello" is greater than "Hello". In
the next, the code for 'H' is 72, while that for 'g' is 103, hence "Hello" is smaller than "goodbye". In
the third, the first 4 chars match, but "goodbye" is longer so is considered greater than "good", while
the last pair register as equal.

If you know the start location of a substring, it can be copied into another string using the method
substring (startindex) or substring (startindex, endindex), where startindex is the index position of
the start of the substring, and endindex is the index position after the last position to be copied. If
the endindex is not specified, the remainder.of the string is copied. For example, we could use a
combination of indexOf and substring to split string containing a name into the firstname and
surname:

String aName, firstname, lastname;

59
Programming 2 Educor ©

int pos;
System.out .println();
System.out.print("Enter a name as firstname space surname : ");
aName = Keyboard.readString(); pos = aName.indexOf(" ");

if(pos<0)
System.out.println("no space entered");
else
{
firstname = aName.substring(0,pos);
lastname = aName.substring(pos+1);
System.out.println("First name is " + firstname + " and surname is " + lastname);

This displays
Enter a name as firstname space surname : Nelson Mandela
First name is Nelson and surname is Mandela”

60
Programming 2 Educor ©

STUDY UNIT 5: ARRAYS AND CONDITIONAL LOOPING OBJECTIVES

5.5.1. DECLARING AND INITIALISING ARRAYS


In the programs written so far, each variable was associated with a single memory cell. There are
many cases where it is convenient to store a related set of values without having to create a
separate variable for each value - for example, the marks of all the students in a class.

5.5.2. ARRAYS
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
Arrays are a group of variables containing values of the same type. The 1st index of an array is index
number zero (0). The elements of an array are the values that are store in the indexes.
num = xyz[1] → num contains the value in the 2nd index.
int [] a; → creates an array ‘a’.
int [] a = new int [12]; → stores 12 indexes.
a.length(); → the length of the array, number of elements.
Following picture represents array myList. Here, myList holds ten double values and the indices are
from 0 to 9.

61
Programming 2 Educor ©

5.5.3. Processing Arrays


When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known. Example: Here is a
complete example of showing how to create, initialize and process arrays: Simple arrays”

public class TestArray {


public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

An array is a data structure which stores a collection of data items all of the same type. Using an
array, we can associate a single name with a set of data items, and reference the individual items by
a number representing their position in the array.
This means we can use integer variables - for example, the loop control variable of a for loop - to
access each element in an array in turn. If all the data values were stored using individual variable
names this would not be possible as variable names have to be directly specified and cannot be
generated by the program.
An array is bounded - it has a fixed size which is specified when the array is created, and the
individual elements of an array are indexed by a number in the range 0 to this upper limit. In
contrast to some other languages (eg Pascal), all arrays are indexed by numeric values starting at 0.

62
Programming 2 Educor ©

5.5.4. ARRAY DECLARATION

The first form merely declares an array variable to be of a certain array type; the next two create the
array variable and initialise it. The first form would be require the array to be initialised at a later stage
- perhaps when its size is

known. Some examples:

int [] marks = new int [30]; // assuming 30 students in the class


or
double [] examMarks;
int numStudents;
System.out.print("How many students wrote? ");
numStudents = keyboard.nextInt();
examMarks = new double [numStudents];
or
char []vowels = { 'A' , 'E' , ' I' , '0' , ‘U' };
This creates an array of 5 elements - the size is deduced from the number of values given.

Note that it is also possible to write the array declaration as


type arrayname [] ;
eg int marks [] = new int [30] ;
but this splits the array type which is actually int [ ].
The declaration is read as an integer array called marks ...

The marks array declared above will have 30 integer elements numbered from 0 to 29. The number
of elements in the examMarks array depends on the value read for numStudents, and its elements
will be indexed 0 to numStudents-1. The vowels array has 5 character elements (deduced from the
number of values specified) indexed 0 to 4.
To reference a specific item in an array 'we use the array name and a numeric subscript which
identifies a particular element. For example,
System. out .println (marks [0] ) ;
will output the first element in the marks array, while
System.out.println (marks [10] ) ;
will output the 11th element.

63
Programming 2 Educor ©

The subscript must be in the range of the arraysize or an exception will be thrown
(ArraylndexOutOfBoundsException).

A for loop is frequently used to process all elements in an array. For example, to read in 30 marks
and store them in the marks array:

for (int count=0 ; count<30 ; count++)


{
System. out .println ( "Enter mark "+ (count+1)
+">"); marks [count] = Keyboard. get Int () ; }

Similarly, we could output all the marks in the array:


for (int count=0;count<30,-count++)
{
System.out .println (marks [count] ) ;
}

Or add them up and calculate the average:

int total = 0;
double average;
for (int count=0;count<30;count++)
{
total += marks [count] ;
average = total/30;
}

Or find the top mark and which student got it:


int maxMark = marks [ 0 ] ;
int topSt = 0;
for (int count=l;count<30;count++)
{
if (marks [count] >maxMark)
{ maxMark = marks [count]
; topSt = count ;
}
}
System.out.println ( "Top mark of " + maxMark +"was obtained by student " + topSt) ;

64
Programming 2 Educor ©

5.5.5. Some points to note about arrays:


Arrays can be of any element type or class, for example arrays of Reals, arrays of characters,
arrays of Strings, arrays of Dates, and even arrays of arrays. These are called 2-dimensional
arrays and will be considered in more detail later.
An array can be any size (subject to the constraints of memory), but the size is fixed when
the array is created and cannot be changed.
double [] rainfall; rainfall = new double [31] ;
When the second statement is executed the size of rainfall is fixed at 31 elements. They do
not all have to be used, but the storage for 31 double values is reserved.
Each array has a special property associated with it, its length. This is the size of the array
as specified in its declaration, and can be accessed. For example,
System.out.printIn(rainfall.length);
Would output 31. Note that length is a property, not a method, and does not have brackets
after it.
Java is strict about index checking. Only array elements that actually exist can be referenced.
Each time an array is accessed, the subscript supplied is checked against the array size given
in the declaration. If the subscript used is below 0 or greater than or equal to the size
declared, an ArraylndexOurOfBoundsException is thrown. The exception can be caught and
handled, or else the program stops.
A simple variable such as an integer stores the actual numeric value in its memory location.
An array variable does not actually store all the array values, or even the first value, in its
memory location. Instead it stores a reference to the place in memory where the array is
stored. When the array is declared the reference is set up, and when its size is specified the
storage will be created and its location stored in the array variable.
Arrays can be passed as parameters to methods. In the method header it is sufficient to use
square brackets to indicate that the parameter is an array, its size does not have to be
specified. This means we can, for example, write a general isEqual method that accepts 2
integer arrays and returns true only if all corresponding elements are equal. The same
method can then be passed arrays of 10 elements or 100 elements

5.5.6. Sorting
When working with sequences of numbers, a common requirement is to be able to sort the
numbers into ascending or descending order. For example, you may wish to sort an array of student
marks so that the highest marks is first and the lowest mark is last. We will consider 2 of the simple
sorts, Bubble Sort and Selection sort, which have the advantage of being easy to understand and are
adequate for our purposes.

5.5.6.1. Bubble Sort


Bubble Sort compares pairs of adjacent elements and if they are out of order, exchanges them. In
this way the smaller (or larger) elements bubble their way to the top of the sequence, while the
larger (or smaller) elements move to the bottom.
Assume we wish to sort the n elements of array A into ascending order. The basic method is:
Compare A[0] and A[1]; swap if necessary so that the larger value is in A[1]
Compare A[1] and A[2] ; swap if necessary so that the larger value is in A[2]
Compare A[n-2] and A[n-1]; swap if necessary so that the larger value is in A[n-1]
This is called a pass.

65
Programming 2 Educor ©

Repeat this pass as many times as are necessary until no values are swapped during a pass. This
means that the values are all in the right order, so the array A is then sorted.

For example, consider the sequence


A=<5,3,1,7,4,6>
5 3 1 7 4 6

5 ? 3 1 7 4 6
Switch
3 5 ? 1 7 4 6
Switch
3 1 5 ? 7 4 ? 6
No Switch No Switch
3 1 5 7 ? 4 6
Switch
3 ? 1 5 ? 4 7 ? 6
Switch Switch Switch
1 3 4 5 6 7
No Swaps Left

This means that the sequence is now sorted.

The method to perform a simple Bubble Sort to sort an array of integers into ascending order is
shown below. It forms part of class mySort which contains a number of sorting algorithms.

66
Programming 2 Educor ©

public static void Bubble (int [] A, int n)


//implements a Bubble sort to sort n elements in A
into // ascending order
{ int pass =0; // counts the number of passes
boolean swapped;
do {
pass + + ; swapped = false; // no swaps made
for (int i=0; i < (n-pass; i++)
{
if (A[i] >A[i + l])
{
int temp = A[i]; // exchange values
A[i] = AEi + 1] ; A[i+l] = temp;
swapped = true ;
}
}
}
while (swapped) ; // repeat while not sorted

One point to note is that, because arrays are passed by reference, any changes made to an array
during the sort (ie. repositioning of elements) will be effective and visible outside the sort method.

5.5.6.2. Selection Sort


Selection sort considers each position in the array in turn, and selects the correct value to be in that
position. An ascending selection sort will look for the smallest value in the array and store that at
index 0, then look for the next smallest value and store that at index 1, and so on.

Once again, assume we wish to sort the n elements of array A into ascending order. The basic
method is:
Find the smallest of the n elements A[0] ... A[n-1] and swap it with the first element A[0] so
that the smallest value is in the first position.
Then find the smallest of the n-1 elements A[1] ... A[n-1] and swap it with the second
element A[1] so that the next smallest value is in the second position.
Continue like this until there is only 1 element A[n-1] to be considered. The array is then
sorted.

67
Programming 2 Educor ©

For example, consider the sequence A = <5,1,4,6,7,3>


Consider the 6 elements A[0]... A[5]
Smallest is A[1]=1, swap A[1] and A[0]: A= < 1,5,4,5,7,3 >

Consider the 5 elements A[1] ... A[5]


Smallest is A[5]=3, swap A[5] and A[1]: A= < 1,3,4,6,7,5 >

Consider the 4 elements A[2]... A[5]


Smallest is A[2]=4, in correct position: A = < 1,3,4,6,7,5 >

Consider the 3 elements A[3]... A[5]


Smallest is A[5]=5, swap A[5] and A[3]: A = < 1,3,4,5,7,6 >

Consider the 2 elements A[4] ... A[5]


Smallest is A[5]=6, swap A[5] and A[4]: A= < 1,3,4,5, 6, 7 >

Consider 1 element -> array is sorted.

68
Programming 2 Educor ©

The method to perform a simple Selection Sort to sort an array of integers into ascending order is
shown below. It also forms part of class mySort.

public static void Select (int [] A, int n)


//_________________________
// implements a Selection sort to sort n elements in A into
// ascending order
{ int startlndex =0; // the start of the sub list
int minlndex; // index of min value in sub list
while (startlndex<n) // if >1 element, process sub list
{ minlndex = startlndex; // assume first value is smallest
for (int i=startlndex+l;i<n;i++)
{ // scan sub list for smaller value
if (A [i] <A [minlndex] )
minlndex = i ;
}
if ( startlndex !=minlndex) // check min value not at start
{
int temp = A [startlndex] ; // and exchange values
A[startlndex] = A [minlndex] ;
A[minlndex] = temp ;
}
startlndex++; // start sub list at next element
}
}

69
Programming 2 Educor ©

6. REFERENCES

Alvaro, D.A 2015. Easy Java Programming for Beginners, Your Step-By-Step Guide to Learning
Java Programming.
Qureshiuniversity.com. (2020). Qureshi University, Advanced courses, via cutting edge technology,
News, Breaking News | Latest News And Media | Current News. [online] Available at:
https://qureshiuniversity.com/programminglanguages.html [Accessed 23 Nov. 2019].

Anon, (2020). [online] Available at: http://www.eventtrainingaus.com.au/news/?p=1009


[Accessed 22 Nov. 2019].

Cosmina, L 2018. Java for Absolute Beginners- Learn to Program the Fundamentals the Java 9+ Way.

70
Programming 2 Educor ©

7. VERSION CONTROL

Initials Version Date Description of


Amendments
AGC 1.1.2019 19/06/2019 Creation of template
TR 1.2.2019 06/09/2019 Content development
TR 1.3.2019 11/09/2019 Formatting and T&L
TR 1.4.2019 16/09/2019 Improving flow of
content

71

You might also like