programming in java - wordpress.com · the unit is not specific to one instance of the java...

108
Programming in Java C_ITJA211

Upload: others

Post on 24-Sep-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Programming in Java C_ITJA211

Page 2: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Compiled by Michael Mapundu and Susan Snyman

Quality assured by Ndai Mapaso

Edited by Isobel Coetzee

Version 1.0

NQF Level 6

Credit value: 12

January 2016 CTI EDUCATION GROUP

Page 3: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

TABLE OF CONTENTS

INTRODUCTION .......................................................................................................... 1

MODULE AIM .............................................................................................................. 1

MODULE ABSTRACT .................................................................................................... 1 Learning outcomes and assessment criteria ......................................................... 2 Summary of learning outcomes and assessment criteria ............................................... 2

MODULE CONTENT ...................................................................................................... 3 Lectures................................................................................................................ 5 Class exercises and activities ............................................................................... 5 Information resources .......................................................................................... 5 Prescribed textbook ............................................................................................. 6 The prescribed textbook for Programming in Java ........................................................ 6 Recommended information sources ...................................................................... 6 Books ................................................................................................................. 6 Websites ................................................................................................................ 6 Using the Study Guide .......................................................................................... 6 Purpose ................................................................................................................ 7 Structure .............................................................................................................. 7 Individual units .................................................................................................... 8 Glossary ............................................................................................................... 8 The use of icons .................................................................................................... 8 Alignment to prescribed textbook ........................................................................ 9 Study Guide/Prescribed textbook alignment ........................................................ 9 Concluding remarks ............................................................................................ 10

UNIT 1: INTRODUCTION TO THE JAVA ENVIRONMENT ............................................. 11 Learning objectives ............................................................................................ 11 Prescribed reading ............................................................................................. 12 Introduction ....................................................................................................... 12 1.1 Java development environment .............................................................. 12 1.1.1 Java Virtual Machine (JVM) .......................................................................... 12 1.2 Java class libraries/API packages .......................................................... 14 1.3 Variables................................................................................................. 15 1.3.1 Data types ................................................................................................. 19 1.4 Access modifiers ..................................................................................... 21 1.4.1 The three different kinds of modifiers ............................................................ 21 1.4.2 Types of access modifiers for class members (variables and methods) .............. 22 1.5 The this reference ................................................................................... 24 1.5.1 Using the super keyword ............................................................................. 24 1.6 Static class members .............................................................................. 25 1.7 Interfaces ............................................................................................... 26 1.8 Garbage collection through the method finalize ..................................... 27 1.9 Creating packages .................................................................................. 27 1.10 Relational operators ............................................................................... 27 1.11 Characteristics of object-oriented programming .................................... 28 1.11.1 Objects...................................................................................................... 28 1.11.2 Attributes .................................................................................................. 28 1.11.3 Classes ...................................................................................................... 29 1.11.4 Methods .................................................................................................... 30 1.11.5 Events ....................................................................................................... 31 1.11.6 Event handlers ........................................................................................... 31 1.12 Object-oriented programming principles ................................................ 31 1.12.1 Abstraction ................................................................................................ 31 1.12.2 Encapsulation ............................................................................................. 31 1.12.3 Inheritance ................................................................................................ 32 1.12.4 Polymorphism ............................................................................................ 33 1.12.4.1 Method overloading ............................................................................... 33

Page 4: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

1.12.4.2 Method overriding ................................................................................. 34 1.13 Applying the concepts covered in this unit ............................................. 35 Self-assessment ................................................................................................. 36

UNIT 2: GUI COMPONENTS ....................................................................................... 38 Learning objectives ............................................................................................ 38 Prescribed reading ............................................................................................. 38 Introduction ....................................................................................................... 39 2.1 Simple GUI input/output with JOptionPane ............................................ 39 2.2 Input dialogues ...................................................................................... 39 2.3 Swing components ................................................................................. 39 2.3.1 JButton ..................................................................................................... 40 2.3.2 JCheckBox ................................................................................................. 40 2.3.3 JRadioButton .............................................................................................. 40 2.3.4 JTextArea .................................................................................................. 40 2.4 Using JOptionPane – Addition program .................................................. 41 2.5 Displaying text and images in a window using the JFrame ..................... 43 2.6 Event handling ........................................................................................ 44 2.6.1 GUI components for events .......................................................................... 44 2.6.1.1 Steps for setting up event handling for GUI .................................................... 45 2.7 Connecting to an Access database .......................................................... 45 2.7.1 Creating the application and connecting to the database .................................. 45 2.8 Connecting to a MySQL database ............................................................ 47 2.8.1 Creating the application and connecting to the database .................................. 47 2.9 Text files ................................................................................................. 49 2.10 Applying the concepts covered in this unit ............................................. 50 Self-assessment ................................................................................................. 51

UNIT 3: CONTROL STATEMENTS AND RELATIONAL OPERATORS ............................... 52 Learning objectives ............................................................................................ 52 Prescribed reading ............................................................................................. 52 Introduction ....................................................................................................... 53 3.1 Control structure .................................................................................... 53 3.1.1 Sequence structure ..................................................................................... 53 3.1.2 Selection statements ................................................................................... 53 3.1.3 Repetition statements ................................................................................. 54 3.2 Statements ............................................................................................. 54 3.2.1 If single selection statement ........................................................................ 54 3.2.2 If…else double selection statement ............................................................... 54 3.2.3 Nested if…else statement ............................................................................. 54 3.2.4 Switch Multiple-Selection statement .............................................................. 55 3.3 Counter controlled repetition ........................................................................ 56 3.3.1 For repetition statement .............................................................................. 56 3.3.2 While repetition statement ........................................................................... 57 3.3.3 Nested repetition statement ......................................................................... 57 3.4 String and character manipulations ........................................................ 58 3.5 Applying the concepts covered in this unit ............................................. 58 Self-assessment ................................................................................................. 59

UNIT 4: ARRAYS ....................................................................................................... 60 Learning objectives ............................................................................................ 60 Prescribed reading ............................................................................................. 60 Introduction ....................................................................................................... 61 4.1 Primitive types and reference types ....................................................... 61 4.2 Arrays ..................................................................................................... 61 4.2.1 Declaring an array ...................................................................................... 61 4.2.2 Declaring many arrays in single declaration ................................................... 62 4.2.3 Using an array initialiser .............................................................................. 62 4.3 Enhanced for statement .......................................................................... 62 4.4 Passing arrays to methods...................................................................... 63

Page 5: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

4.5 Multi-dimensional arrays ........................................................................ 64 4.6 Collections and class ArrayLists .............................................................. 65 4.7 Working with ArrayList class .................................................................. 66 4.7.1 Creating an ArrayList .................................................................................. 66 4.7.2 Putting an Item into ArrayList ...................................................................... 66 4.7.3 Checking size of ArrayList ............................................................................ 66 4.7.4 Checking Index of an Item in Java ArrayList ................................................... 66 4.8 Applying the concepts covered in this unit ............................................. 67 Self-assessment ................................................................................................. 67

UNIT 5: EXCEPTION HANDLING ................................................................................ 68 Learning objectives ............................................................................................ 68 Prescribed reading ............................................................................................. 68 Introduction ....................................................................................................... 68 5.1 Java Exception Hierarchy ........................................................................ 69 5.2 Error handling ......................................................................................... 69 5.3 Exception examples ................................................................................ 69 5.4 Example of division by zero .................................................................... 70 5.4.1 Without exception handling .......................................................................... 70 5.5 With exception handling – using the Try block ....................................... 71 5.6 Termination model of exception handling ............................................... 73 5.7 When to use exception handling ............................................................. 73 5.8 Applying the concepts covered in this unit ............................................. 73 Self-assessment ................................................................................................. 74

UNIT 6: APPLETS ...................................................................................................... 75 Learning objectives ............................................................................................ 75 Prescribed reading ............................................................................................. 75 Introduction ....................................................................................................... 76 6.1 Applet lifecycle methods ......................................................................... 76 6.1.1 public void init () ........................................................................................ 76 6.1.2 public void start () ...................................................................................... 76 6.1.3 public void stop () ....................................................................................... 76 6.1.4 public void destroy () .................................................................................. 77 6.1.5 public void paint (Graphics g) ....................................................................... 77 6.2 Other applet methods ............................................................................. 78 6.3 Creating the Applet class ........................................................................ 79 6.3.1 Overriding method paint for drawing ............................................................. 80 6.3.2 Executing in the AppletViewer ...................................................................... 80 6.3.3 Using the init method to initialise Instance variables ....................................... 80 6.4 Applying the concepts covered in this unit ............................................. 81 Self-assessment ................................................................................................. 81

UNIT 7: TESTING AND DOCUMENTATION ................................................................. 82 Learning objectives ............................................................................................ 82 Prescribed reading ............................................................................................. 83 Introduction ....................................................................................................... 83 7.1 Software documentation......................................................................... 83 7.1.1 Technical documentation for technical users ................................................... 83 7.1.2 Writing software documentation for end users ................................................ 84 7.1.3 Monitor and assess the process .................................................................... 85 7.2 Categories of docs .................................................................................. 85 7.2.1 Planning documents .................................................................................... 85 7.2.2 Specification documents .............................................................................. 85 7.2.3 Reporting documents .................................................................................. 85 7.3 Test design specifications ....................................................................... 85 7.3.1 Test case specification document .................................................................. 86 7.3.1.1 Test and analysis reports ............................................................................. 86 7.4 Types of testing techniques .................................................................... 86 7.4.1 Component/Unit testing ............................................................................... 86

Page 6: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

7.4.2 Integration testing ...................................................................................... 86 7.4.3 Validation testing ........................................................................................ 87 7.4.4 Defect testing ............................................................................................. 87 7.4.5 Alpha and beta testing ................................................................................ 87 7.4.6 Acceptance testing ...................................................................................... 88 7.4.7 System testing ........................................................................................... 88 7.4.8 Performance testing .................................................................................... 88 7.4.9 Stress testing ............................................................................................. 88 7.4.10 Interface testing ......................................................................................... 88 7.4.11 White-box/structural testing......................................................................... 89 7.5 Applying the concepts covered in this unit ............................................. 89 Self-assessment ................................................................................................. 89

UNIT 8: UNIFIED MODELLING LANGUAGE FOR OBJECT-ORIENTED DESIGN ............. 90 Learning objectives ............................................................................................ 90 Prescribed reading ............................................................................................. 90 Introduction ....................................................................................................... 91 8.1 Requirements capture ............................................................................ 91 8.1.1 Use case diagram ....................................................................................... 91 8.2 System structure .................................................................................... 92 8.2.1 Class diagrams ........................................................................................... 92 8.3 System behaviour ................................................................................... 93 8.3.1 Sequence diagram ...................................................................................... 93 8.3.2 Activity diagram ......................................................................................... 93 8.3.3 Aggregation ............................................................................................... 94 8.3.4 Composition ............................................................................................... 95 8.3.5 Dependency ............................................................................................... 95 8.4 Applying the concepts covered in this unit ............................................. 96 Self-assessment ................................................................................................. 96

GLOSSARY ................................................................................................................ 97

BIBLIOGRAPHY ...................................................................................................... 101

Page 7: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 1

© CTI Education Group

Introduction

The aim of this module is to provide students with an understanding of the

principles of programming in Java, exploring the object-oriented nature of the language and the multi-platform versatility offered.

The main sources of information for Programming in Java are a prescribed

textbook and a Study Guide. The Study Guide should not be seen as a replacement for the prescribed textbook – you have to use it in conjunction

with the textbook, which contains the actual learning content of the module. You are expected to work through the relevant sections of the textbook

independently. The Study Guide facilitates this process by means of references to relevant page numbers in the prescribed textbook.

In this introductory unit we provide you with the following information on

Programming in Java:

A brief description of the aim of the module

An abstract of the module The learning outcomes and assessment criteria involved in the module

An outline of the module content An outline of the module structure

An explanation of the purpose, design and proper use of the Study Guide and prescribed textbook

Module aim

To provide students with an understanding of the principles of programming in

Java, exploring the object-oriented nature of the language and the multi-platform versatility offered.

Module abstract

Object-oriented programming is an industry-proven method for developing reliable modular programs and is popular in software engineering and systems

development. Consistent use of object-oriented techniques can lead to shorter development lifecycles, increased productivity, adaptable code, reuse of

different technologies, the interaction of different systems using common platforms and, therefore, lower the cost of producing and maintaining systems.

Java is synonymous with the object orient paradigm offering all the features of

the technology in a format that can be used on many differing systems. The development of systems with Java objects simplifies the task of creating and

maintaining complex applications.

Page 8: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 2

© CTI Education Group

Many environments use Java as its ‘underpinning’ framework, with Java

applications found on mobile phones, dedicated systems, web-based multimedia, security and control systems as well as traditional applications and

bespoke operating systems.

The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

applications or web-based solutions.

Learning outcomes and assessment criteria

On successful completion of this module, you will:

1. Explain the principles of programming in Java

2. Design Java solutions

3. Implement Java solutions

4. Test and document Java solutions

The following table outlines the assessment criteria that are aligned to the

learning outcomes.

Summary of learning outcomes and assessment criteria

Learning outcomes Assessment criteria to pass

On successful completion of

this module you will: You can:

1. Explain the principles of

programming in Java

1.1 Discuss the principles, characteristics and features

of programming in Java

1.2 Critically evaluate the environmental flexibility of

programming in Java

2. Design Java solutions

2.1 Design a Java programming solution to a

given problem

2.2 Explain the components and data and file

structures required to implement a given design

Page 9: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 3

© CTI Education Group

3. Implement Java solutions

3.1 Implement a Java programming solution based

on a prepared design

3.2 Define relationships between objects to

implement design requirements

3.3 Implement object behaviours using

control structures to meet the design

algorithms

3.4 Identify and implement opportunities for

error handling and reporting

3.5 Make effective use of an Integrated Development

Environment (IDE) including code and screen

templates

4. Test and document Java

solutions

4.1 Critically review and test a Java

programming solution

4.2 Analyse actual test results against expected

results to identify discrepancies

4.3 Evaluate independent feedback on a developed

Java program solution and make

recommendations for improvements

4.4 Create user documentation for the developed

Java program solution

4.5 Create technical documentation for the support and

maintenance of a Java program solution.

These outcomes are covered in the module content and they are assessed in

the form of written assignments and semester tests. If you comply with and achieve all the pass criteria related to the outcomes, you will pass this module.

Learning and assessment may be performed across modules, at module level or at outcome level. Evidence may be required at outcome level, although

opportunities exist for covering more than one outcome in an assignment.

Module content

1. Explain the principles of programming in Java

Characteristics: Java Virtual Machine (JVM); Java platform; classed-

based; object-oriented; compilers; class libraries; applications; applets; object models; enforced error handling; concurrency;

threads, multi-platform

Reasons for choice of language: organisational policy; suitability of

features and tools; availability of trained staff; reliability; development and maintenance costs; expandability

Object models: inheritance; polymorphism; encapsulation; public classes;

private classes; public methods; private methods

Page 10: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 4

© CTI Education Group

Data structures: public instance variables; private instance variables;

naming conventions; arrays (one-dimensional, two-dimensional); file structures; loops, e.g. conditional (pre-check, post-check, break-

points), fixed; conditional statements; case statements; logical operators; assignment statements; input statements; output

statements

Data types: constants and literals; integer; floating point; byte; date; Boolean; others, e.g. character, string, small int; choice of data types,

e.g. additional validation, efficiency of storage

Environment: features, e.g. interpreted, run time environment, system specific libraries

Programming syntax: features, e.g. command rules, variable

declaration, class/method declaration

Standards: features, e.g. use of comments, code layout, indentation

2. Design Java solutions

Requirements specification: overview, e.g. inputs, outputs,

processing, user interface; constraints, e.g. hardware platforms, timescales for development; delivery environment, e.g. mobile,

hand-held, web based, desktop; interaction, e.g. data exchange, compliance, compatibility, standards

Program design: tools, e.g. structure diagrams, data flow diagrams,

entity relationship models, flow charts, pseudo code, class diagrams, class responsibilities, collaboration cards; inheritance

Technical documentation: requirements specification; others as

appropriate to language, e.g. form design, flowcharts, pseudo code, structured English, action charts, data dictionary, class and instance

diagrams

3. Implement Java solutions

Classes: features, e.g. identification attributes, methods, control of scope of attributes and methods, inheritance, aggregation, association,

polymorphism

Programming: use of conventional language commands; use of library classes; pre-defined, e.g. class libraries, downloaded, imported

Complexity: multiple classes; inheritance; reuse of objects; application of

polymorphism

Page 11: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 5

© CTI Education Group

4. Test and document Java solutions

Mechanisms: methods, e.g. valid declarations, debugging code, checking

naming conventions, checking functionality against requirements, error detection, error messages, compiler errors, runtime errors, in code

response, dry running

Feedback: record feedback, e.g. surveys, questionnaire, interviews; analyse feedback; present results

Supportive documentation: test plan; test results; programmer guidance;

user guidance

Review: design against specification requirements, interim reviews

Lectures

Each week has four compulsory lecture hours for all students. It is recommended that the lecture hours be divided into two sessions of two hours

each, but this may vary depending on the campus.

Each week has a lecture schedule which indicates the approximate time that should be allocated to each activity. The week’s work schedule has also been

divided into two lessons.

Class exercises and activities

Students will be required to complete a number of exercises and activities in class. These activities and exercises may also contribute to obtaining pass; it

is, therefore, important that students are present in class so that they do not forfeit the opportunity to be exposed to such exercises and activities.

Activity sheets that are handed in should be kept by the lecturer so that they

can be used as proof of criteria that were met, if necessary.

Information resources

You should have access to a resource centre or a library with a wide range of relevant resources. Resources can include textbooks and e-books, newspaper

articles, journal articles, organisational publications, databases, etc. You can access a range of academic journals in electronic format via EBSCOhost. You

have to consult the campus librarian to assist you with accessing EBSCOhost.

Page 12: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 6

© CTI Education Group

Prescribed textbook

The prescribed textbook for Programming in Java

Deitel, P., Deitel, H. 2015. Java, How to program: Late Objects, Global Edition.

10th edition. New Jersey: Pearson Education. ISBN: 9781292019369

Recommended information sources

Books

Bloch, J. 2008. Effective Java, Second Edition. New Jersey: Prentice Hall. Goetz, B. 2006. Java Concurrency in Practice. Boston: Addison Wesley.

Niemeyer, P. 2005. Learning Java, Third Edition. Sebastopol: O’Reilly.

Websites

http://java.sun.com/docs/books/tutorial/ http://math.hws.edu/javanotes/

http:// http://www.codecademy.com/ www.idevelopment.info/data/Programming/java/PROGRAMMING_Java_Pr

ogramming.shtml

Note

Web pages provide access to a further range of Internet information sources.

Students must use this resource with care, justifying the use of information gathered.

Using the Study Guide

As we indicated earlier, the prescribed textbook is your main source of information for this module and the Study Guide serves as a guide to the

prescribed textbook.

The purpose of the Study Guide is to facilitate your learning and help you to master the content of the prescribed textbook and other material. It helps you

to structure your learning and manage your time, provides outcomes and activities to help you to master those outcomes, and directs you to the

appropriate sections in the prescribed textbook. It is important that you start

with the Study Guide.

The Study Guide has been carefully designed to optimise your study time and maximise your learning, so that your learning experience is as meaningful and

successful as possible. To deepen your learning and enhance your chances of success, it is important that you read the Study Guide attentively and follow all

the instructions carefully. Pay special attention to the module outcomes at the beginning of the Study Guide and at the beginning of each unit.

Page 13: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 7

© CTI Education Group

It is essential that you complete the exercises and other learning activities in

the Study Guide, because your module assessment (examinations, tests and assignments) will be based on the assumption that you have completed these

activities.

This Study Guide accompanies a prescribed textbook and, therefore, it should be read in conjunction with the prescribed text: it should not be deemed as a

replacement for the prescribed text.

Purpose

The purpose of the Study Guide is to facilitate the learning process and to help you to structure your learning and to master the content of the module. The

textbook covers certain themes in detail.

Where applicable, we give more simplified explanations in the Study Guide. It is important for you to work through both the prescribed textbook and the

Study Guide attentively and to follow all the instructions set out in the Study Guide. In this way, you should be able to deepen your learning and enhance

your chances of success.

Structure

The Study Guide is structured as follows: Introduction

Unit 1: Introduction to the Java environment

Unit 2: GUI components

Unit 3: Control statements and relational operators

Unit 4: Arrays

Unit 5: Exception handling

Unit 6: Applets

Unit 7: Testing and documentation

Unit 8: Unified Modelling Language for object-oriented design

Glossary

Bibliography

Page 14: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 8

© CTI Education Group

Individual units

The individual units in the Study Guide are structured in the same way and each unit contains the following features, which should enhance the learning

process:

Unit title

Each unit title in based on the title and content of the specific

outcome or the assessment criterion (criteria) discussed in the

unit.

Learning outcomes

The unit title is followed by an outline of the learning outcomes

and assessment criteria, which guide the learning process. It is

important for you to become familiar with the learning outcomes

and assessment criteria, because they represent the overall

purpose of the module, as well as the end product of what you

should have learned in the unit.

Learning objectives

Learning objectives, which follow the learning outcomes and

assessment criteria, are statements that define the expected

goal of the unit in terms of the specific knowledge and skills that

you should acquire as a result of mastering the unit content.

Learning objectives clarify, organise and prioritise learning and

they help you to evaluate your own progress, thereby taking

responsibility for your learning.

Introduction The learning objectives are followed by an introduction that

identifies the key concepts of the unit.

Content

The content of each unit contains the theoretical foundation of

the module and is based on the work of experts in the field of

this module. The theory is illustrated by means of relevant

examples.

Concluding remarks

The concluding remarks at the end of each unit provide a brief

summary of the unit, as well as an indication of what you can

expect in the following unit.

Self-assessment

The content is followed by a number of theoretical self-

assessment questions that test your knowledge of the content

of a particular unit.

Glossary

As you can see, we include a glossary at the end of the Study Guide. Please

refer to the glossary as often as necessary, in order to familiarise yourself with the exact meaning of the terms and concepts involved in Programming in Java.

The use of icons

Icons are used to highlight (emphasise) particular sections or points in the

Study Guide, to draw your attention to important aspects of the work, or to highlight activities. The following icons are used in the Study Guide:

Page 15: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 9

© CTI Education Group

Learning outcome alignment

This icon is used to indicate how individual units in the Study Guide are aligned to a specific outcome and its

assessment criteria.

Prescribed reading This icon indicates reference to relevant sections in the

prescribed textbook that you are expected to study.

Test your knowledge This icon appears at the end of each unit in the Study

Guide, indicating that you are required to answer self-assessment questions to test your knowledge of the

content of the foregoing unit.

Alignment to prescribed textbook

The following table reflects the alignment between learning outcomes,

assessment criteria, units in the Study Guide and chapters in the prescribed textbook.

Study Guide/Prescribed textbook alignment

Learning outcome Assessment criteria Study

guide unit

Textbook

chapter

LO1 AC1.1, AC1.2 1, 4, 6 1, 2, 5, 6, 7, 8

LO2 AC2.1, AC2.2 1,2, 3, 4,

6, 8

1, 2, 3, 4, 5, 6, 7,

8, 12, 14, 22

LO3 AC3.1, AC3.2, AC3.3, AC3.4, AC3.5 1,2, 4, 5,

6, 8

2, 3, 4, 5, 6, 7, 8,

11, 12,15, 22

LO4 AC 4.1, AC4.2, AC4.3, AC4.4, AC4.5 7

Page 16: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Introduction Page 10

© CTI Education Group

Concluding remarks

At this point, you should be familiar with the module design and structure as well as with the use of the prescribed textbook in conjunction with the Study

Guide.

Page 17: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 11

© CTI Education Group

Unit 1: Introduction to the Java environment

Unit 1 is aligned with the following learning outcomes and

assessment criteria:

Learning outcomes: LO1: Explain the principles of programming in Java

LO2: Design Java solutions LO3: Implement Java solutions

Assessment criteria:

AC1.1: Discuss the principles, characteristics and features of programming in Java.

AC2.1: Critically evaluate the environmental flexibility of

programming in Java AC2.2: Explain the components and data and file

structures required to implement a given design. AC3.1: Implement a Java programming solution based on

a Prepared design. AC3.2: Define relationships between objects to implement

Design requirements.

Learning objectives

After studying this unit, you should be able to:

Understand the principles of programming in Java

Understand the Java environment Understand the role of Java in distributed networking applications

Understand Java syntax and structure Write simple Java Applications

Use input and output statements

Use operators Understand basic memory concepts

Understand classes, objects and instance variables Declare a class and use it to create an object

Use the keyword this Use static variables and methods

Organise classes in packages to promote reuse Understand relational operators

Page 18: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 12

© CTI Education Group

Prescribed reading

Deitel, P., Deitel, H. 2015. Java, How to program: Late

Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: 9781292019369

Chapter 1, Section 1.5, 1.8 – 1.10

Chapter 2, Section 2.2 – 2.8 Chapter 5, Section 5.1 – 5.5, 5.9 – 5.12

Chapter 7, Section 7.2 – 7.9 Chapter 8, Section 8.2 – 8.15

Introduction

Java is a powerful computer programming language that is used in building substantial enterprise systems. Students should be able to achieve program

clarity through the proven techniques of structured programming and object-

oriented programming.

In this learning unit students will be reminded of several important object-

oriented concepts. In addition to this some new concepts will be covered and it will be required of students to not only know the concepts covered in this

learning unit but also apply them.

1.1 Java development environment

1.1.1 Java Virtual Machine (JVM)

Java is platform independent. Programs written in Java can be compiled just

once and be run on any operating system by making use of the Java Virtual Machine (JVM). JVM is part of the Java Development Kit (JDK) (download link

http://developers.sun.com/downloads/) and the foundation of the Java platform. A virtual machine is a software application that that simulates a

computer but hides the underlying operating system and hardware from the programs that interact with it.

The JVM understands the environment and version of Java in which bytecode

were compiled. The JVM is invoked by the java command. For example to execute a Java application called Mike, using the Command Prompt window

you type javac Mike.java to use the Javac compiler to covert the java file Mike.java to a bytecode file Mike.class. Then you run the compiled file by

typing java Mike, and this then executes the JVM and, therefore, will initiate all necessary steps to execute the program.

Page 19: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 13

© CTI Education Group

Java programs usually go through five phases namely:

Figure 1 – Java application phases

Source: Deitel (2008:12)

Page 20: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 14

© CTI Education Group

1. Edit

This is where you create your program. It consists of editing a file with an editor program (editor). This means you type a Java program using the

editor; you can, therefore, make any changes and save it on any secondary storage device with file extension .java.

For example Mike.java.

2. Compile

In this phase you use the command javac (Java compiler) to compile a program. For example javac Mike.java within the command prompt. This

means that the Java compiler will translate Java source code into byte

codes. Byte codes will be executed by the Java Virtual machine.

3. Load At this stage the JVM places the program in memory to execute it

(loading). This basically means that the JVM’s class loader takes the .class files containing the byte code of the program and puts them into primary

memory.

4. Verify As the classes are loaded, the byte code verifier checks the byte code to

ensure that they are valid and do not violate security restrictions.

5. Execute JVM executes the program’s byte code, i.e. performing actions specified

by the program. Before, JVM was an interpreter for Java byte codes. This

had a problem of causing the programs to execute slowly. Nowadays, they use Just In Time compilation (JIT).

1.2 Java class libraries/API packages

These are the pre-defined classes that are grouped into categories of related classes called packages. All together they form the Java Application

Programming Interface or the Java class libraries.

A package is also defined as a namespace that organises a set of related

classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one

folder, images in another, and scripts or applications in yet another. The table below shows some of the examples of packages and their

descriptions.

Page 21: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 15

© CTI Education Group

Table 1 – Java packages

Package Description

java.applet The Java Applet Package contains a class and several interfaces for

creating Java applets – programs that execute in web browsers.

Java.awt

The Java Abstract Window Toolkit Package contains the classes and

interfaces required to create and manipulate GUIs in early versions of

Java. In current versions of Java, the Swing GUI components of the

javax.swing packages are typically used instead.

Java.awt.event

The Java Abstract Window Toolkit Event Package contains classes

and interfaces that enable event handling for GUI components in

both the java.awt and javax.swing packages.

Java.awt.geom The Java 2D Shapes Package contains classes and interfaces for

working with Java’s advanced two-dimensional graphics capabilities.

Java.io The Java Input/Output Package contains classes and interfaces that

enable programs to input and output data

java.lang

The Java Language Package contains classes and interfaces that are

required by many Java programs. This package is imported by the

compiler into all programs.

Java.net

The Java Networking Package contains classes and interfaces that

enable programs to communicate via computer networks like the

Internet.

Java.text

The Java Text Package contains classes and interfaces that enable

programs to manipulate numbers, dates, characters and strings. The

package provides internationalisation capabilities that enable a

program to be customised to locales.

Java.util

The Java Utilities Package contains utility classes and interfaces that

enable such actions as date and time manipulations, random-number

processing and the storing and processing of large amounts of data.

Javax.swing

The Java Swing GUI Components Package contains classes and

interfaces for Java’s Swing GUI components that provide support for

portable GUIs.

Javax.swing.event

The Java Swing Event Package contains classes and interfaces that

enable event handling (e.g. responding to button clicks) for GUI

components in package javax.swing

Source: Mapundu (2014)

For further reading about Java application packages: Chapter 5, Section 5.8

1.3 Variables

In most programming languages, variables are strongly typed. What this means is that you need a specific type of variable to store a specific type of value. You

cannot, for example, store a name in a variable intended to hold numbers.

Page 22: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 16

© CTI Education Group

Variables should start with a lowercase letter, short, meaningful names, which

sound good to us as programmers. Some examples:

buttonWidth accountBalance

myString

A constant variable is a variable that contains a value which does not change for the entire program; thus, it should be declared with the keyword final.

Constants should be named using uppercase letters with underscore characters as separators. Java constants are created by marking variables static and final.

They should be named using uppercase letters with underscore characters as separators. For example:

MIN_HEIGHT

private final int INCREMENT

//Declares a constant called INCREMENT of type int that cannot be modified

Figure 2 – Declaring constants

Source: Mapundu (2014)

For further reading: Chapter 2, Section 2.3 – 2.6

Chapter 5, Section 5.3 Chapter 8, Section 8.9

//Declaring class called Dog

public class Dog {

//Declaring variables name and colour of type string

String name;

String colour;

public void eat() {

//method called eat

//Eat code in here

}

public void bark() {

//Bark code in here

}

}

Figure 3 – Java code for class Dog

Source: Mapundu (2014)

The following represents the different types of variables in object-oriented

programming:

Page 23: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 17

© CTI Education Group

Instance variables: These are variables that are used to store the state of an

object (for example, colour). Every object created from a class definition would have its own copy of the variable. They are variables within the class but

declared outside any method. The variable is valid for and occupies storage for as long as the corresponding object is in memory. Lines 7 and 8 in the code

below show how instance variables to describe every Car object are declared in a class called Car. Collectively, the values assigned to an instance variables

make up the object’s state.

Figure 4 – Instance variables

Source: Mapundu (2014)

You must always refer to it with the object that you declared, as shown in the

next example:

ClassName myObj = new ClassName();

myObj.theVariable = 90;

Figure 5 – Referring to an initially declared object

Source: Mapundu (2014)

For further reading: Chapter 7, Section 7.2 and 7.3

An object’s state can be changed by making use of Set methods also known as mutator methods. Get methods, also known as accessor methods, can be used

to access the value stored in an instance variable.

For further reading: Chapter 8, Section 8.7

Page 24: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 18

© CTI Education Group

Class variables: These variables are explicitly defined within the class-level scope with a static modifier. Because these variables are defined with

the static modifier, there would always be a single copy of these variables no matter how many times the class has been instantiated. They live as long as

the class is loaded in memory. Line 10 in the code below shows a declaration of a static variable model in a class Car.

Figure 6 – Class variables

Source: Mapundu (2014)

Parameters or Arguments: These are variables passed into a method

signature (for example, maxSpeed). They are not attached to modifiers, i.e.

public, private, protected or static. They can be used everywhere in the method. They are in memory during the execution of the method and cannot

be used after the method returns. Line 12 in the code below shows how an argument maxSpeed is used in a method called accelerate.

Figure 7 – Arguments

Source: Mapundu (2014)

Local variables: These variables are defined and used specifically within

the method-level scope (for example, currentSpeed) but not in the method signature. They do not have any modifiers attached to it. They are destroyed

when method finishes execution completely. Code below shows the method accelerate that has one argument maxSpeed. Line 14 shows a declaration of

a local variable currentSpeed that can only be used inside the method accelerate.

Figure 8 – Local variables

Source: Mapundu (2014)

Page 25: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 19

© CTI Education Group

1.3.1 Data types

During run time, variables and all the information they store are kept in the computer’s memory for access. Think of a computer’s memory as a table of

data — where each cell corresponds to a variable.

Upon creating a variable, we basically create a new address space and give it a unique name. Java goes one step further and lets you define what you can

place within the variable, in other words – the data type of the variable. So,

you essentially have to do two things in order to create a variable:

Create a variable by giving it a unique name; and, Define a data type for the variable.

Line 14 below shows an example of a variable declaration. The name of the

variable is currentSpeed. The variable has been declared as of type int, meaning currentSpeed is a location in the computer memory that is ready to

hold any integer value assigned or placed in it during program execution.

Data types are divided into two – primitive and reference types. Every

variable, whether it is of a primitive type or of a class type, is implemented as a location in computer memory. For a variable of a primitive type, the value of

the variable is stored in the memory location assigned to the variable. So, if an integer variable is declared as “int x = 3″, then when we look at the memory

location of “x”, there will be a “3″ stored there just as expected.

However, a variable of a reference type only stores the memory address of where the object is located – not the values inside the object. So, if we have a

class called “SomeClass”, when we create an object like this: “SomeClass anObject”, then when we look at “anObject” in memory, we will see that it

does not store any of the variables that belong to that object in memory.

Instead, the variable “anObject” just stores an address of another place in memory where all the details of “anObject” reside. This means that the object

named by the variable is stored in some other location in memory and the variable contains only the memory address of where the object is stored. This

memory address is called a reference to the object.

Page 26: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 20

© CTI Education Group

Below is a diagram showing the types of data types in Java.

Figure 9 – Data types

Source: Adapted from: http://img.c4learn.com/2012/03/Data-Types-in-Java-Programming-

Language.png

Below is a description of some of the data types indicated in the diagram above.

Table 2 – Data types description

Type Description Example

string Used to store a sequence of characters, such

as a word or sentence

String name =”Michael”;

int Used to store an integer cannot be used to

store floating point numbers

int passMark = 60;

double Used to store a decimal number double pi = 3.14;

char Used to store a single character char gender=”m”;

bool Used to store a true or false value bool passed = true;

Source: Mapundu (2014)

Page 27: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 21

© CTI Education Group

1.4 Access modifiers

A class can consist of modifiers as well. Access modifiers determine the visibility or accessibility of an object’s attributes and methods to other objects.

Before we can begin implementing our design, we must consider which

attributes and methods of our classes should be public and which should be private. A modifier is a keyword that is added in front of the class and is used

to describe how the class can be accessed or used. Variables or methods declared with access modifier private are accessible only to the methods of the

class to which they are declared.

1.4.1 The three different kinds of modifiers

1.4.1.1 public

A public class may be accessed from anywhere. Classes that are not public can only be accessed from other classes that are within the same directory. Public class Dog {

//Class body

}

Figure 10 – Declaring a public access modifier

Source: Mapundu (2014)

When a class is declared public, it is visible to all other classes. Take note that you may only have one public class in each file. The name of the file must also

be the same as the name of the public class. When using the access modifier public, it means that that classes, methods and data fields can be accessed

from other classes.

1.4.1.2 final

A final class may not be extended. The compiler will return an error if you try

to extend a class with final modifier.

Final class Dog {

//Class body

}

Figure 11 – Declaring a final class using final access modifier

Source: Mapundu (2014)

1.4.1.3 abstract

An abstract class is used to declare one or more abstract methods. A class

cannot be both final and abstract. It can be public and abstract, though.

Page 28: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 22

© CTI Education Group

abstract class Dog {

//Class body

}

Figure 12 – Declaring an abstract class using an abstract modifier

Source: Mapundu (2014)

Abstract classes that are used only as base classes in inheritance hierarchies

are termed abstract superclasses. These classes cannot be instantiated to

create objects as they are incomplete. They are basically created to provide a superclass from which other classes can inherit from. Classes that are used to

instantiate objects are called concrete classes. We have to, therefore, make it abstract by declaring it with keyword abstract. It is the norm that an abstract

class should entail one or more abstract methods, as shown below: public abstract void draw():

Abstract methods do not provide implementation but rather a class that contains an abstract method should explicitly declare an abstract class.

1.4.1.4 default

When you do not specify an access modifier for a class, the class will have

default/package access. This means that the class will only be visible, and can only be used, in the current package or directory.

1.4.2 Types of access modifiers for class members (variables

and methods)

The following sections discuss the various class member access modifiers.

1.4.2.1 Public Public access for members of a class works in the same way as it does with

classes. The members are visible to, and can be used by, any other class.

1.4.2.2 Default Members with default access are only visible to other classes in the same

package. This happens when there is no access modifier declared, then by default the classes, method and data fields are accessible by any class in the

same package. This is known as package-access.

1.4.2.3 Protected

When using the visibility modifier protected, it means there is an intermediate level of access between public and private. A superclass’ protected members

can be accessed by members of that superclass as well as members of its subclass and also any members within the same package. A superclass’ private

members are not accessible outside the class. This means that they are hidden within the subclasses and can only be accessed through public and protected

methods inherited from the superclass, e.g. through the user of the getters and setters.

Page 29: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 23

© CTI Education Group

1.4.2.4 Private

Private members are only visible to the class and cannot be used by any other class. A private data field cannot be accessed by an object from outside the

class that defines the private field. To make a private data field accessible, provide a get method to return its value and provide a set method to set a new

private data field value.

Example code

The following three classes are in the same package called human. Analyse the

code, taking note of the comments.

Figure 13 – Java code demonstrating access modifiers for class members

Source: Mapundu (2014)

Page 30: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 24

© CTI Education Group

For further reading:

Chapter 7, Section 7.2 Chapter 8, Section 8.3 – 8.4

1.5 The this reference

Every object can access a reference to itself by using the keyword this, also

known as the this reference. The this keyword is the name of a reference that refers to a calling object itself. Its common uses are to reference a class's

hidden data fields. A hidden instance variable can be accessed by using the keyword this.

For further reading:

Chapter 8, Section 8.4

1.5.1 Using the super keyword

This is basically used when a subclass method overrides an inherited

superclass method. Therefore, access the superclass method, we have to precede the baseclass method with the keyword super and the (). dot

separator. It can be used in two ways:

• To call a superclass constructor • To call a superclass method

The syntax to call a superclass constructor is:

super(), or super(parameters)

The statement super() invokes the no-argument constructor of its superclass, and the statement super(arguments) invokes the superclass constructor that

matches the argument parameters. The keyword super must appear first of the subclass constructor.

To call Superclass methods, keyword super can also be used to reference a

method other than the constructor in the superclass. The syntax is like:

super.method(parameters);

Page 31: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 25

© CTI Education Group

The following code snippet shows the concept of Inheritance.

Figure 14 – Example code showing inheritance

Source: Mapundu (2014)

1.6 Static class members

The declaration begins with keyword static. This is normally used when every object has its own copy of all the instance variables of the class; therefore, one

copy of a variable will be shared by all objects of a class; thus, we make use of static variables to represent class wide information. A static cannot access non-

static class members, because a static method can be called even when no objects of the class have been instantiated; thus, the this reference cannot be

used in a static method.

For further reading:

Chapter 8, Section 8.4

Page 32: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 26

© CTI Education Group

1.7 Interfaces

An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods. Unlike an

abstract class, all methods in an interface should be abstract. You can declare

classes that implement one or more interfaces.

A class that implements an interface must provide concrete implementations for the abstract methods of that particular interface. Each interface method

must be declared in all the classes that explicitly implement the interface. Once a class implements an interface, all objects of that class have an is-a

relationship with the interface type.

Example code

The following code in Figure 15 shows an interface called Bike and a class HybridBike implementing the interface. It has three abstract methods. A class

that implements this interface Bike must implement all the three methods defined in Bike.

Figure 15 – Bike Interface and class HybridBike implementing the interface Bike

Source: Mapundu (2014)

Page 33: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 27

© CTI Education Group

1.8 Garbage collection through the method finalize

The method finalize is a method of class object under package java.lang. The JVM performs automatic garbage collection to reclaim memory occupied by

redundant objects. This means that when there are no more references to an

object it is eligible to be collected.

The finalize method is called by the garbage collector to terminate an object just before it reclaims memory. This method finalize has no argument list and

always has return type void.

For further reading: Chapter 8, Section 8.10

1.9 Creating packages

Packages are used to ease complexity and be able as programmers to manage

application components. They also aid in software reuse as well as unique naming convention. This basically means that each class in the Java API

belongs to a package that contains a cluster of related classes.

For further reading:

Chapter 8, Section 8.14

1.10 Relational operators

High-level programming like Java provides selection statements that allow choice of action with alternative courses. Java selection statements use

conditions, which are Boolean in expressions. This means that conditions are expressions that can be true or false; thus, a computer program should be able

to make a decision based on a condition’s value.

Examples of relational operators allowed in Java are shown in Table 3:

Page 34: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 28

© CTI Education Group

Table 3 – Relational operators

Operator Name Example (radius = 5) Result

< less than radius < 0 false

<= less than or equal to radius <= 0 false

> greater than radius > 0 true

>= greater than or equal to radius >= 0 true

equal to radius == 0 false

!= not equal to radius != 0 true

Source: Mapundu (2014)

1.11 Characteristics of object-oriented programming

1.11.1 Objects

Everywhere you look in the real world you see objects—people, animals, plants, cars, planes, buildings, and computers and so on. Humans think in

terms of objects. Telephones, houses, traffic lights, microwave ovens and water coolers are just a few more objects. An object has characteristics –

attributes and behaviours. Let us analyse a ball as an object. An attribute is a piece of information about an object; hence the ball has attributes colour, size

and weight. The ball also exhibits behaviours, e.g. a ball can bounce, roll and

inflate.

A computer program consists of a collection of objects interacting with each other by sending messages to achieve certain results. Object-oriented

programming (OOP) involves programming using objects. An object is defined as an instance of a class. When we create a new object, we say that we have

instantiated that object. Another word for instantiated is created. An object-oriented programming language combines many separate self-contained

objects to form a complete program. Each object contains its own program logic which defines what the object is and how it can interact with other

objects. In a nutshell, an object has a unique identity, state and behaviour.

A state of an object, also known as properties or attributes is represented by data fields with their current value. For example, a rectangle object has data

fields width and height, which are the properties that characterise a rectangle.

1.11.2 Attributes

An attribute is a piece of information about an object. Attributes are a property of objects that helps describe an object, giving it state, e.g. a car object can be

described using its colour and year, with values red and 2007 respectively (state of the object) used to describe the car object.

Page 35: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 29

© CTI Education Group

Attributes are also referred to as instance variables. A variable represents a

location in memory that stores a value used during run time. All variables are of a certain data type, e.g. a variable name may contain a value “Mike” which

is of type String.

1.11.3 Classes

A class is a template for creating objects. A class contains characteristics, i.e.

attributes and behaviours that are common amongst all objects created by the

same class. Code below shows an example of a class called Car used to create various car objects.

Figure 16 – Car class

Source: Mapundu (2014)

According to the Car class above, each car object will have the following

characteristics:

Attributes: speed, year and model Methods/behaviours: reverse(), accelerate (int maxSpeed) and brake()

A class can have reference to objects of other classes as members. This is

called ‘composition’ and is usually termed the has-a relationship.

For further reading:

Chapter 8, Section 8.8

Each class you declare can provide a special method called a constructor that

can be used to initialise an object of a class when the object is created. A constructor must have the same name as the class itself (defining class).

Page 36: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 30

© CTI Education Group

Constructors do not have a return type – not even void. Constructors are

invoked using the new operator when an object is created, which plays the role of object initialisation Java requires a constructor call for every object that is

created. A constructor must have the same name as the class and it uses the keyword new which requests memory to store the object, and then calls the

corresponding class’s constructor to initialise the object. A constructor without arguments is referred to as a no-argument constructor. A class that is defined

without a constructor calls a no-argument constructor by default.

Overloading constructors enables objects of a class to be initialised in different ways. To achieve this one should simply provide multiple constructors

with different signatures or parameter/argument list.

GradeBook myGradeBook =

new GradeBook( "CS101 Introduction to Java Programming" );

Figure 17 – Declaring constructors

Source: Mapundu (2014)

public class Dog {

//The constructor that is automatically created with

//no arguments.

public Dog(){}

}

Figure 18 – Default constructor

Source: Mapundu (2014)

For further reading: Chapter 7, Section 7.4

1.11.4 Methods

A method is also known as a ‘function’, ‘behaviour’ or ‘operation’ and assists

with the modularising of a program into self-contained manageable units. We will be using the terms interchangeably throughout the context of the guide.

Behaviour is something which an object does. A behaviour is also known as operation that is defined by methods. When programmers create a class, they

create methods for that class. Methods are where the class’s logic is stored and the real work is done. Methods are used to ask the object to perform an action.

For example, a method called getArea() can be invoked on the rectangle class to return its area.

The main method in an application is called once to begin program execution.

Page 37: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 31

© CTI Education Group

For further reading about Java methods and application packages:

Chapter 5, Section 5.1 – 5.12

1.11.5 Events

Any system or program that is created consists of events. An event is anything

that occurs within the context of the program, for example a button being clicked.

1.11.6 Event handlers

When an event occurs, the program reacts through methods known as ‘event handlers’. For example, if a user clicks on a login button, an event occurs to

log the user into the account. The event handler is the back-end section of the

program which controls the event and logs the user into the account.

1.12 Object-oriented programming principles

1.12.1 Abstraction

An ‘abstraction’ is an idea or concept which is not associated with one specific object. In programming languages, we create abstract templates (classes)

which store the essential attributes and behaviours for a type of object. For example, you could create an abstract Vehicle class which would define all the

attributes and behaviours common to all vehicles.

Because the Vehicle class would be abstract, you would not be able to create objects from it is more of a template from which you can create other classes

through inheritance (which can then be used to create objects).

1.12.2 Encapsulation

Encapsulation, also known as information-hiding, is a principle of object-

oriented programming which states that all the attributes and behaviours of an object should be grouped together in one data type or class. This means

objects may know how to communicate with one another across well-defined interfaces but are not allowed to know how other objects are implemented;

thus, implementation details are hidden within the objects themselves.

Page 38: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 32

© CTI Education Group

1.12.3 Inheritance

Inheritance is a core principle of object-oriented programming which allows one class to inherit all the attributes and behaviours of another class. This

allows you to specialise a class by inheriting from it and providing additional functionality (attributes and behaviours).

Inheritance hierarchy represents relationships between superclasses (base

classes) and subclasses, and are shown in a tree structure in Figure 19 below;

thus, a superclass exists in a hierarchical relationship with its subclasses.

Figure 19 – Inheritance hierarchy

Source: Mapundu (2014)

Inheritance represents an “is-a relationship”. Figure 19 above shows that “a Student is a CommunityMember”, as much as “an Employee is a

CommunityMember”. The CommunityMember class is known as a superclass

or base class while the Student and Employee classes are known as subclasses or derived classes. Inheritance saves us from having to write the

same code out more than once and also allows us to use Polymorphism. It enables us to define a general class (superclass) and later extend it to more

specialised classes (subclasses). The specialised classes inherit accessible data fields and methods from its superclass and may also add new data fields and

methods of its own. CommunityMember is the direct superclass of Employee, Student and Alumnus and is an indirect superclass of all the

other classes in the diagram. Starting from the bottom, you can follow the arrows and apply the is-a relationship up to the topmost superclass.

For example: An Administrator is a Faculty member, is an Employee, is

a CommunityMember and, of course, is an Object.

The following Java code shows how inheritance can be implemented:

Page 39: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 33

© CTI Education Group

Figure 20 – Java code implementing inheritance based on Figure 19 diagram

Source: Mapundu (2014)

The class CommunityMember declares two variables, name and age, and a method move(). Three classes Student, Employee and Alumnus inherit the

variables and the methods declared in the CommunityMember class through the use of the keyword extend on their class definitions.

1.12.4 Polymorphism

The principle of polymorphism allows us to override behaviours inherited from

a parent class such that the derived class (the class which inherits from the parent) has behaviours that work differently to the parent class, but share the

same name. In a nutshell, it allows you to write code that process objects that share the same superclass.

Polymorphism also includes method overloading.

1.12.4.1 Method overloading

Methods of the same name can be declared in the same class having different

set of arguments or parameters. When an overloaded method is called, the Java compiler selects the appropriate method based on the arguments and

their signature.

Page 40: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 34

© CTI Education Group

Figure 21 – Java code demonstrating overloading

Source: Mapundu (2014)

For further reading: Chapter 5, Section 5.12

1.12.4.2 Method overriding

When you define a method in your subclass that has exactly the same

signature as a method in the superclass, the method is overridden and replaces the inherited method. When overriding methods, you are not allowed

to make the methods more private, for example, you cannot define a public method as protected.

Page 41: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 35

© CTI Education Group

Figure 22 – Java code demonstrating overriding

Source: Mapundu (2014)

For further reading:

Chapter 5, p. 167

1.13 Applying the concepts covered in this unit

As stated at the beginning of this learning unit, students need to have a good understanding of the concepts discussed in this learning unit as well as be able

to apply them. In order to ensure that students can apply the concepts discussed, they must be able to demonstrate their ability to do the following:

Chapter 2: Section 2.2 – 2.8

Print a line of text Add comments to programs

Declare a class in a file with the appropriate file name Use End-of-Line comments on right braces for Readability

Compile and execute an application Demonstrate the difference between ‘print’ and ‘println’ statements

Display multiple lines of text with a single statement Demonstrate the use of various escape characters

Displaying text with printf Make use of the Scanner class to obtain input from a user

Perform various arithmetic operations Understand the rules of operator precedence

Demonstrate the use of relational operators

Page 42: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 36

© CTI Education Group

Chapter 5: Section 5.1 – 5.5, 5.9 – 5.12

Create and call methods

Demonstrate and understand the use of the Math class Determine the highest value in a range

Perform string concatenation Generate random numbers

Generate a random number within a particular range Generate a random character

Declare overloaded methods

Chapter 7: Section 7.2 – 7.9

Declare instance variables

Create and use set and get Methods Use the ‘this’ reference appropriately

Use constructors to initialise objects

Chapter 8: Section 8.2 – 8.15

Use the toString() method Overload constructors

Implement compositions Use BigDecimal and the Numberformat package

Self-assessment

Test your knowledge

1. Complete the Self Review exercises from Chapter 1 and 5 of your

prescribed textbook.

2. Complete the Self Review exercises for Chapter 2, 7 and 8 from your textbook.

Page 43: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 1: Introduction to a Java environment Page 37

© CTI Education Group

3. Complete exercises from the Toolbox:

Individual exercise: 2 - 1.2.

Tutorial folder: Tutorial 1 and Configuring the Environment Lab exercise: 1, 2, 3, 7

Research exercise: 2,3 Group work: 1,2,5,10

Tutorial: 2,3

Page 44: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 38

© CTI Education Group

Unit 2: GUI components

Unit 2 is aligned with the following learning outcomes and

assessment criteria:

Learning outcomes: LO2: Design Java solutions

LO3: Implement Java solutions

Assessment criteria: AC2.1: Design a Java programming solution to a given

problem AC3.1: Implement a Java programming solution based

on a prepared design

AC3.5: Make effective use of an Integrated Development Environment (IDE) including code and screen

templates

Learning objectives

After studying this unit, you should be able to:

Understand the concept of graphical user interface Build GUIs and handle events generated by user interactions with GUIs

Understand packages containing GUIs components, event handling classes

and interfaces Create and manipulate buttons, labels, lists, text, fields and panels.

Use layout managers to arrange GUI components Handle mouse and keyboard events

Prescribed reading

Deitel, P., Deitel, H. 2015. Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson

Education. ISBN: 9781292019369

Chapter 12 Section 12.3 – Section 12.13, Section 12.18 – Section 12.20

Chapter 15 Section 15.1 – Section 15.4 Chapter 22 Section 22.4 – Section 22.9

Page 45: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 39

© CTI Education Group

Introduction

A Graphical User Interface (GUI) can be best thought of as a user-friendly mechanism for interacting with an application. This creates an easy to use

environment with a distinctive look and feel. This basically makes it easier for

users to familiarise themselves with an application, thus reducing learning time and improving productivity. GUIs are created from GUI components which are

also known as controls or widgets (window gadgets). Furthermore, GUI components can be seen as objects that permit a user to interact through

input devices such as a mouse, keyboard, etc.

2.1 Simple GUI input/output with JOptionPane

The JOptionPane class is in the javax.swing package. It provides prebuilt dialogue boxes for input and output.

2.2 Input dialogues

JOptionPane is a GUI package that displays an input screen to the user through the JOPtionPane static method, showInputDialog. The JOptionPane static

method showMessageDialog displays a message on the screen.

2.3 Swing components

The swing components offer a customisable and elaborate user interface. They are part of the javax.swing; thus, they are written and can be manipulated in

Java.

Table 4 – Swing components

Component Description Creating the component object

JLabel Displays uneditable text or icons. JLabel lblName = new JLabel(“Name”)

JTextField Enables user to enter data from

the keyboard. Can also be used to

display editable or uneditable text

JTextFIeld txtName = new JTextField(10)

JButton Triggers an event when clicked

with the mouse. JButton btnCancel = new JButton(“Cancel”)

JCheckBox Specifies an option that can be

selected or not selected. JCheckBox chkMale = new JCheckBox(“Male”)

JComboBox Provides a drop-down list of items

from which the user can make a

selection by clicking an item or

possibly by typing into the box.

JComboBox cboOptions = new JComboBox()

Page 46: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 40

© CTI Education Group

JList Provides a list of items from

which the user can make a

selection by clicking on any item

in the list. Multiple elements can

be selected.

JList lstProducts = new JList()

JPanel Provides an area in which

components can be placed and

organised. Can also be used as a

drawing area for graphics

JPanel pane = new JPanel()

Source: Mapundu (2014)

2.3.1 JButton

A button is a component which takes place when a user clicks to trigger an

event for a specific action. Examples of buttons in Java are command buttons, checkboxes, toggle buttons and radio buttons. All button types are derived

classes of the AbstractButton, which declares common features of Swing buttons.

A command button generates an ActionEvent when a user clicks it. The text on the button is called a button label.

2.3.2 JCheckBox

The JCheckBox is also known as a state button. Thus, it takes Boolean values; in other words – either true or false. It is used to select the desired style of the

text that is to be displayed.

2.3.3 JRadioButton

The JRadioButton is more or less like the checkboxes; thus, it also has two states: selected or not selected. They usually appear as a group in which you

can only select one button at a time. They are further said to avail mutually exclusive options.

2.3.4 JTextArea

JTextArea provides an area for manipulating multiple lines of text. It is a subclass of the JTextComponent and it defines common methods for text

based GUI components.

For further reading about Swing components, consult:

Chapter 22

Page 47: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 41

© CTI Education Group

Figure 23 – Hierarchical structure

Source: Mapundu (2014)

Class Component, from the package java.awt, is a subclass of Object that

declares many of the attributes and behaviours common to the GUI components. Most GUI components extend the class Component directly or

indirectly.

Class Container is from the package java.awt and is a subclass of Component. This means that you will be able to have Components attached to Container

such as windows and you can organise them for display. Any object that is a container can be used to organise other components on the GUI. You can also

have containers within other containers.

Class JComponent is of package javax.swing and is a subclass of Container. It declares common attributes and behaviours.

2.4 Using JOptionPane – Addition program

Below is an example of how you can use the JOptionPane syntax. The following

code snippet shows how you can create a simple addition application which accepts input through input dialogues and displays the sum of the two integers

through a message dialogue box.

Page 48: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 42

© CTI Education Group

Figure 24 – Addition program using GUI

Source: Mapundu (2014)

Program output

Table 5 – Addition program output

showInputDialog Created by line 7

The number entered is 12. As soon as

OK is clicked, 12 is assigned to the

string variable firstNum

String firstNum is converted to an

integer and the integer value assigned

to an integer number1 in line 10

showInputDialog Created by line 8

The number entered is 20. As soon as

OK is clicked, 20 is assigned to the

string variable secondNum

String secondNum is converted to an

integer and the integer value assigned

to an integer number2 in line 11

firstNum and secondNum values are

added together and assigned to an

integer variable sum in line 12

showMessageDialog is used to show the

sum of the two numbers. This dialog is

created in line 14 and 15

Source: Mapundu (2014)

Page 49: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 43

© CTI Education Group

For further reading about JOptionPane: Chapter 12, Section 12.3

2.5 Displaying text and images in a window using the JFrame

JFrame is an indirect subclass of class java.awt.Window. It basically avails

attributes and behaviours of a window. Any text stating each component’s purpose is known as a label and is created using the JLabel, which is a subclass

of the JLabel.

Figure 25 – Using GUI to display an image

Source: Mapundu (2014)

Java specifies the layout of the GUI through the FlowLayout in which GUI components are placed on a container from left to right in the order of the

program relative to the container.

Page 50: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 44

© CTI Education Group

It also uses the method setToolTipText to specify the tool tip that is

displayed when a user points a mouse cursor on the JLabel. Icons are specified within an Icon argument through a constructor or the setIcon method.

Method setText is used to set the text displayed on the label. Method getText is used to retrieve the current text displayed on the label. Method setIcon is

used to specify the icon displayed on the label, whilst getIcon is used to extract the current icon displayed on the label. The JLabel methods

setHorizontalTextPosition and SetVerticalTextPosition are used to align and specify the text position on the label.

Note

When testing this program, make sure the path in line 25/26 to the image is correctly

modified to the path where you have the image in your project in your computer.

Program output

Figure 26 – Output of a GUI program displaying an image

Source: Mapundu (2014)

2.6 Event handling

As a user interacts with the GUI, we trigger events in the process whilst trying

to perform certain tasks. GUIs are event driven; thus, any system or program

that is created consists of events. An event is anything that occurs within the context of the program, for example – a button being clicked. Event handling is

when an event occurs; the program reacts through methods known as event handlers. For example, if a user clicks on a login button, an event occurs to log

the user into the account. The event handler is the back-end section of the program which controls the event and logs the user into the account.

2.6.1 GUI components for events

JTextFields extends class JTextComponent from the package javax.swing and has the capability of availing many features of the text components.

JPasswordFields extends JTextField and adds operations that handle password issues.

Page 51: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 45

© CTI Education Group

2.6.1.1 Steps for setting up event handling for GUI

Create a class that represents the event handler Implement appropriate interface (event listener) in the class above

Register the event handler

When a user enters any text through the GUI components for events, an ActionEvent takes place; thus, this event is handled by an object that

implements the interface Action Listener through the Java package

java.awt.event. In general, the application will invoke the operation addActionListener to register the event handler for each component. This

implies that the method will receive arguments through the ActionListener object. The object handler will be an ActionListener as class

TextFieldHandler implements ActionListener.

Every JComponent has an instance variable, called listenerList, that refers to an object of class EventListenerList; thus, each object refers to subclasses to

register them in the listenerList. Event handlers are invoked through mouse events or key events. When an event takes place it is directed only to the

event listeners of the appropriate type. ActionEvents are handled by ActionListeners. MouseEvents are handled by MouseListeners and MouseMotion

Listeners, and KeyEvents are handled by KeyListeners. In general, when an event occurs, the GUI component receives a unique ID from the JVM specifying

the event type. This event ID is then used to decide on the listener type that

corresponds to the event as well as the method to call on each listener.

2.7 Connecting to an Access database

In order to connect to a Microsoft Office Access database, you will need access

to the following files:

ucanaccess-2.0.8.jar

jackcess-2.0.4.jar hsqldb.jar

commons-logging-1.1.3.jar commons-lang-2.6.jar

The steps below should be followed in order to connect to the Access database.

2.7.1 Creating the application and connecting to the database

Create a new project called UCanApp.

Create a Microsoft Access database called Student inside the UCanApp

project folder, which can be found inside the NetBeansProjects directory.

Create a table called student inside the Student database. The table should contain the fields as indicated in the screenshot below:

Page 52: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 46

© CTI Education Group

Figure 27 – Student table inside Student database

Source: Snyman (2015)

Populate the table with at least two records. Then close the database.

Add all five of the JAR files mentioned at the beginning of Section 8 to the

project. In order to do this:

o Expand the tree view for the UCanApp project. o Right-click on the “Libraries” folder in the tree view.

o Select the option “Add JAR/Folder…”.

o Navigate to the folder containing the JAR files. o Select all five JAR files.

o Click on the Open button. o The tree view of the project should now resemble the following

screenshot:

Figure 28 – Tree view after JAR files have been added

Source: Snyman (2015)

Add the following statements below the package statement:

import java.io.File; import java.sql.*;

The code for connecting to a database and querying the database needs to

be enclosed in a Try/Catch block. The code should look like this:

Page 53: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 47

© CTI Education Group

Figure 29 – Database connection established and database queried

Source: Snyman (2015)

Build the application.

Run the application.

2.8 Connecting to a MySQL database

In order to connect to a MySQL database, you will need access to the following files:

Mysql-connector-java-5.1.18-bin.jar

The steps below should be followed in order to connect to a MySQL database.

2.8.1 Creating the application and connecting to the database

Create a new project called MySQLTutorial.

Create a MySQL database called Student.

Create a table called student inside the Student database. The table should

contain the same fields as indicated for the Microsoft Access tutorial indicated in Section 8.7.

Populate the table with at least two records.

Page 54: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 48

© CTI Education Group

Add the JAR files mentioned at the beginning of Section 8.8 to the project.

In order to do this:

o Expand the tree view for the UCanApp project. o Right-click on the “Libraries” folder in the tree view.

o Select the option “Add JAR/Folder…”. o Navigate to the folder containing the JAR files.

o Select all five JAR files. o Click on the Open button.

o The tree view of the project should now resemble the following screenshot:

Figure 30 – Tree view after JAR files have been added

Source: Snyman (2015)

Add the following statements below the package statement:

import java.sql.*;

The code for connecting to a database and querying the database needs to be enclosed in a Try/Catch block. The code should look like this:

Page 55: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 49

© CTI Education Group

Figure 31 – Database connection established and database queried

Source: Snyman (2015)

Build the application. Run the application.

2.9 Text files

The data stored in variables and arrays are lost when a local variable goes out

of scope or when a program is terminated. To ensure that data persists, the data can be written to files. In Java, files are viewed as a sequential stream of

bytes. Stream-based processing in Java takes place by making use of classes and interfaces from the java.io package and the subclasses of the java.nio

package.

Students need to be able to create a text file, write to the textfile and read records from the file. Students, therefore, need to be able to apply the

concepts covered in Chapter 15, Sections 15.1 – 15.4.

Page 56: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 50

© CTI Education Group

2.10 Applying the concepts covered in this unit

Students must be able to demonstrate their ability to do the following:

Chapter 12: Section 12.3 – 12.13, 12.18 – 12.20

Use JOptionPane to obtain input and provide output

Convert String values to integer values Use the various Swing components discussed in this unit

Display text and images in a window Use layout managers

Use icons Use password fields

Employ event handling

Chapter 15: Section 15.1 – 15.4

Create text files Write to text files

Read from text files

Chapter 22: Section 22.4 – 22.9

Create a frame

Use menus with frames Use class UIManager

Use JDesktopPane, JInternalFrame and JTabbedPane

Databases

Connect to a database Use a query to retrieve information from the database

Use a query to add information to the database

Page 57: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 2: GUI components Page 51

© CTI Education Group

Self-assessment

Test your knowledge

1. Attempt the Chapter 12, 14, 22 and 24 Self Review questions and exercises from your textbook.

2. Toolbox

Lab exercises: 4, 5, 6, 9, 10, 11

Tutorial: 4

Page 58: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 3: Control statements and relational operators Page 52

© CTI Education Group

Unit 3: Control statements and relational operators

Unit 3 is aligned with the following learning outcomes and

assessment criteria:

Learning outcomes: LO2: Design Java solutions

LO3: Implement Java solutions

Assessment criteria: AC2.1: Design a Java programming solution to a given

problem AC2.2: Explain the components and data and file

structures required to implement a given design

AC3.3: Implement object behaviours using control structures to meet the design algorithms

Learning objectives

After studying this unit, you should be able to:

Understand the essentials of counter controlled repetition Understand relational operators

Use if and if…else to choose alternative actions

Use while statement to execute statements in a program repeatedly Use the for and do…while statements to execute statements in a program

repeatedly Use the switch statement for multiple selection

Use break and continue statements to alter the flow of control Use logical operators to perform complex conditional expressions

Prescribed reading

Deitel, P., Deitel, H. 2015. Java, How to program: Late

Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: 9781292019369

Chapter 3 Section 3.4 – 3.10

Chapter 4 Section 4.1 – 4.8 Chapter 14 Section 14.2 – 14.7

Page 59: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 3: Control statements and relational operators Page 53

© CTI Education Group

Introduction

In this chapter we introduce control statements to specify the logic required by operations to perform certain tasks. This chapter will basically cover the

procedure for solving problems in terms of the actions to execute as well as

the order in which they are executed.

3.1 Control structure

Control statements allow us to define sequential execution to achieve

structured programming. Our focus will be mainly on sequence, selection and repetition structure.

For further reading: Chapter 3, Section 3.4

3.1.1 Sequence structure

This is built into Java and the computer will execute the statements according

to the predefined order as in the code.

3.1.2 Selection statements

Java has the following types of statements, which are:

The if statement which either selects an action if condition is met/true or

omits if it is false. The if statement is a single selection statement, as it selects or ignores a single action. The if…else is a double statement as it

selects two different actions.

The switch statement is a multiple-selection statement as it selects many different actions.

For further reading:

Chapter 3, Section 3.4 – 3.6 Chapter 4, Section 4.6

Page 60: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 3: Control statements and relational operators Page 54

© CTI Education Group

3.1.3 Repetition statements

These are also known as ‘looping statements’ that allow programs to perform actions repeatedly as long as the condition is met. Examples are the while,

while…do and for statements.

For further reading:

Chapter 3, Section 3.7 – 3.10 Chapter 4, Section 4.2

3.2 Statements

3.2.1 If single selection statement

Figure 32 – If statement

Source: Mapundu (2014)

3.2.2 If…else double selection statement

It is also known as a two way If statement.

Figure 33 – Two way If statement with output

Source: Mapundu (2014)

3.2.3 Nested if…else statement

Multiple cases can be tested by placing if…else statements inside other if…else statements.

Page 61: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 3: Control statements and relational operators Page 55

© CTI Education Group

Figure 34 – Nested if…else statement

Source: Snyman (2015)

3.2.4 Switch Multiple-Selection statement

Figure 35 – Nested if…else statement

Source: Snyman (2015)

Page 62: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 3: Control statements and relational operators Page 56

© CTI Education Group

3.3 Counter controlled repetition

The following are the elements that are needed in order to perform counter

controlled repetition.

A control variable (or loop counter) The initial value of the control variable

The increment (or decrement) by which the control variable is modified each time through the loop (also known as each iteration of the loop)

The loop-continuation condition that determines if looping should continue.

3.3.1 For repetition statement

This specifies the counter controlled repetition details in a single line of code.

General structure:

for ( initialization; loopContinuationCondition; increment ){

//statements

}

Figure 36 – Declaring the for repetition statement

Source: Mapundu (2014)

Example using a counter variable called counter:

Figure 37 – Counter controlled for loop

Source: Mapundu (2014)

Page 63: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 3: Control statements and relational operators Page 57

© CTI Education Group

3.3.2 While repetition statement

initialization; while ( loopContinuationCondition )

{

statement

increment;

}

Figure 38 – Declaring the while repetition statement

Source: Mapundu (2014)

Example

Figure 39 – Counter controlled while loop

Source: Mapundu (2014)

3.3.3 Nested repetition statement

Control statements can be stacked on top of each other or connected to each other by nesting one inside another.

Page 64: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 3: Control statements and relational operators Page 58

© CTI Education Group

Example

Figure 40 – Nested repetition statements

Source: Snyman (2015)

3.4 String and character manipulations

String and character manipulations are made possible through the use of the classes String, StringBuilder and Character from the java.lang package.

3.5 Applying the concepts covered in this unit

Students must be able to demonstrate their ability to do the following:

Chapter 3: Section 3.4 – 3.8, 3.10

Use a single-selection if statement

Use an if…else double-selection statement Use nested if…else statements

Use the while repetition statements Implement counter controlled repetition

Use nested control statements

Chapter 4: Section 4.5 – 4.8

Use a do-while statement

Use a switch multiple-selection statement Use logical operators

Page 65: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 3: Control statements and relational operators Page 59

© CTI Education Group

Chapter 14: Section 14.3 – 14.5, 14.7

Use String constructors

Use the various String methods in Chapter 14 Compare Strings

Locate characters and substrings in Strings Extracting substrings from Strings

Concatenate Strings Use StringBuilder and its associated methods

Use regular expressions as well as Class Pattern and Matcher

Self-assessment

Test your knowledge

1. Attempt the Chapter 3 and 4 Self Review questions and exercises from your textbook.

2. Toolbox

Lab exercises: 13, 14 Tutorial: 5, 6, 7, 8, 9.

Page 66: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 4: Arrays Page 60

© CTI Education Group

Unit 4: Arrays

Unit 4 is aligned with the following learning outcomes and

assessment criteria:

Learning outcomes:

LO1: Explain the principles of programming in Java LO2: Design Java solutions

LO3: Implement Java solutions

Assessment criteria: AC1.1: Discuss the principles, characteristics and features

of programming in Java AC2.1: Design a Java programming solution to a given

problem AC2.2: Explain the components and data and file

structures required to implement a given design AC3.1: Implement a Java programming solution based on

a prepared design AC3.2: Define relationships between objects to implement

design requirements

Learning objectives

After studying this unit, you should be able to:

Understand arrays

Understand Data structures Pass arrays to methods

Declare and manipulate multi-dimensional arrays Use ArrayList collection

Prescribed reading

Deitel, P., Deitel, H. 2015. Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson

Education. ISBN: 9781292019369

Chapter 6, Section 6.1 – 6.5, Section 6.7 – Section 6.14

Page 67: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 4: Arrays Page 61

© CTI Education Group

Introduction

This unit will explore data structures and arrays as being data structures consisting of related data items of the same type. Arrays are appropriate at

processing related group of values. Once declared they remain the same length

even though an array variable can be reassigned. We will further explore ArrayLists which accommodate dynamic resizing to allow additional elements.

4.1 Primitive types and reference types

A primitive type can store exactly one value of its declared type at a time; thus, an int variable can store one whole number at a given point and time.

Examples of primitive types are char, short, byte, Boolean, int, long and float.

All other non-primitive types are reference types; thus, classes which specify these types of objects are reference types. Programs use variables of reference

types to refer to an object in a program within the memory. Scanner input = new Scanner( System.in );

This creates variable input which refers to the Scanner object

4.2 Arrays

An array is a group of variables called components or elements containing

values that all have the same type. They are also objects of reference types.

Elements in array can either be primitive or reference types. Thus, to refer to a specific element in an array, we have to specify the name of the reference to

the array and the position number. This position number is called the element’s index or subscript. A program can then refer to any of the elements

through a process called array-access expression. Note that the first element in an array has index zero.

4.2.1 Declaring an array

Every Array object has space in memory. They are created through the keyword new. One has to specify the type of array elements and the number

of elements; thus, you create an array that returns a reference that will be

stored in an array variable. int[] c = new int[ 12 ];

This creates an array object with 12 elements and stores the array reference in array variable c.

Page 68: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 4: Arrays Page 62

© CTI Education Group

4.2.2 Declaring many arrays in single declaration

String[] b = new String[ 100 ], x = new String[ 27 ];

The above syntax reserves 100 elements for b and 27 elements for x.

4.2.3 Using an array initialiser

This is a list expression separated by commas; thus, the length is determined by the number of elements. Thus, using the example below, we have five

elements with index values 0…4 and n [0] is initialised to 10. The compiler will read and map to the array list.

int[] n = { 10, 20, 30, 40, 50 };

Figure 41 – InitArray class and its output

Source: Mapundu (2014)

4.3 Enhanced for statement

This statement iterates through the elements of an array without using

counter. The syntax is as follows:

for ( parameter : arrayName )

statement

//parameter has a type and identifier

//iteration through arrayName

Figure 42 – Using the enhanced for statement to iterate through array elements

Source: Mapundu (2014)

Page 69: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 4: Arrays Page 63

© CTI Education Group

Figure 43 – Using the enhanced for statement

Source: Mapundu (2014)

4.4 Passing arrays to methods

In order to pass an array argument to a method, specify the name of array

without brackets. Java uses a pass-by-value or pass-by reference to pass arguments to a method. This means if an argument is a passed by value, a

copy of that argument’s value is passed to the called method; thus, the method works with the copy and any modifications won’t affect the original

variable’s value. When an argument is passed by reference, the called method can access the argument’s value in the caller directly and can make changes to

that data.

Figure 44 – Passing an array as an argument

Source: Mapundu (2014)

Page 70: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 4: Arrays Page 64

© CTI Education Group

4.5 Multi-dimensional arrays

These are used basically to define tables of values consisting of information arranged in rows and columns. They use two indices that identify the element’s

row as well as the column. If they require two indices, then ultimately they are

known as two-dimensional arrays. The general rule is an array with x-rows and p columns is termed an x-by-p array.

The syntax for declaring a two-dimensional array is as follows:

int[][] matrix;

You can create a two-dimension array of 3-by-3 int values and assign it to the

matrix using this syntax:

matrix = new int [3][3];

Two subscripts are used in a two-dimensional array, one for the row and the other for the columns, as is with one-dimension arrays the index for each

subscript starts at 0. As illustrated with the figure below, is the:

matrix = new int[3][3];

[0] [1] [2]

[0]

[1]

[2]

Figure 45 – Structure of a two-dimensional array

Source: Mapundu (2014)

To assign value 8 to a specific element at row 2 column 1, the matrix will look as follows;

matrix [2][1] = 8;

[0] [1] [2]

[0]

[1]

[2] 8

Figure 46 – Structure of inserting element in specific cell

Source: Mapundu (2014)

Page 71: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 4: Arrays Page 65

© CTI Education Group

The values of the two-dimensional arrays can be indexed as follows:

int[][] array = new int[3][3];

array[0][0] = 1;

array[0][1] = 2;

array[0][2] = 3;

array[1][0] = 4;

array[1][1] = 5;

array[1][2] = 6;

array[2][0] = 7;

array[2][1] = 8;

array[2][2] = 9;

You can also make use of an array initialiser to declare, create and initialise a two-dimensional array, which would look like the figure below in the matrix:

int[][] array = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

Figure 47 – Creating a two-dimensional array

Source: Mapundu (2014)

[0] [1] [2]

[0] 1 2 3

[1] 4 5 6

[2] 7 8 9

Figure 48 – Structure of a two-dimensional array

Source: Mapundu (2014)

4.6 Collections and class ArrayLists

The Java API provides several predefined data structures called collections

used to store groups of related objects. These methods provide methods that organise, store and retrieve data. The collection class ArrayList<T>from the

java.util. This uses non-primitive types and allows you to dynamically change the size of an array to accommodate more elements. The T is a placeholder

that is used when declaring a new ArrayList. The syntax below means that you have declared a list as an ArrayList collection that can only store strings. The

syntax is as follows: ArrayList< String > list;

Below is a table showing common methods of the class ArrayList<T>

Page 72: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 4: Arrays Page 66

© CTI Education Group

Table 6 – Common methods of the class ArrayList<T>

Method Description

add Adds an element to the end of the ArrayList.

clear Removes all the elements from the ArrayList.

get Returns the element at the specified index.

indexOf Returns the index of the first occurrence of the specified element in the

ArrayList.

remove Removes the element at the specified index.

size Returns the number of elements stored in the ArrayList.

trimToSize Trims the capacity of the ArrayList to current number of elements.

Source: Mapundu (2014)

4.7 Working with ArrayList class

Following sections focus on working with a few methods of the ArrayList class.

4.7.1 Creating an ArrayList

You can use ArrayList in Java with or without Generics both are permitted by generics version is recommended because of enhanced type-safety.

In this example we will create an ArrayList of String in Java. This Java ArrayList will only allow String and will throw compilation error if we try to any

other object than String.

Generic ArrayList to Store only String objects

ArrayList<String> stringList = new ArrayList<String>();

4.7.2 Putting an Item into ArrayList

Second line will result in compilation error because this Java ArrayList will only allow String elements.

stringList.add("Item"); //no error because we are storing String

stringList.add(new Integer(2)); //compilation error

4.7.3 Checking size of ArrayList

Size of an ArrayList in Java is total number of elements currently stored in

ArrayList. int size = stringList.size();

4.7.4 Checking Index of an Item in Java ArrayList

You can use indexOf() method of ArrayList in Java to find out index of a

particular object. int index = stringList.indexOf("Item"); //location of Item object in List

Page 73: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 4: Arrays Page 67

© CTI Education Group

For further reading: Chapter 6, Section 6.14

4.8 Applying the concepts covered in this unit

Students must be able to demonstrate their ability to do the following:

Chapter 6: Section 6.3 – 6.12, 6.14

Create and initialise arrays Summing the elements of an array

Use Bar charts to display array data graphically Use the elements of an array as counters

Use arrays to analyse survey results Use the enhanced for statement

Pass arrays to methods Create and initialise multi-dimensional arrays

Use Class ArrayList and its associated methods

Self-assessment

Test your knowledge

1. Complete the Chapter 6 Self Review questions from your textbook.

2. Complete the following Toolbox exercises:

Group exercises: 9, 11 Tutorials: 11, 12, 13, 14

Lab exercise: 4 Research activity: 4

Page 74: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 5: Exception handling Page 68

© CTI Education Group

Unit 5: Exception handling

Unit 5 is aligned with the following learning outcome and assessment criterion:

Learning outcome:

LO3: Implement Java solutions

Assessment criterion:

AC3.4: Identify and implement opportunities for error handling and reporting

Learning objectives

After studying this unit, you should be able to:

Understand exceptions

Use try, throw and catch to handle exceptions

Use finally block to release resources Understand how it helps with debugging

Prescribed reading

Deitel, P., Deitel, H. 2015. Java, How to program: Late

Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: 9781292019369

Chapter 6, Section 6.6 Chapter 11, Section 11.1 – 11.6

Introduction

Exception handling can be best thought of as an indication of problems that might occur during execution. In its literal sense exception means that a

problem can occur infrequently. The aim behind exception handling is to create a reliable program that can handle any errors. Ideally, not all errors are

captured at compile time; however, the ability of the system or application to

handle any error during run-time makes an application robust. The end product should be a robust and fault tolerant program.

Page 75: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 5: Exception handling Page 69

© CTI Education Group

5.1 Java Exception Hierarchy

All Java exception classes inherit indirectly or directly from class Exception,

forming an inheritance hierarchy. This hierarchy can be extended with your own exception classes. Class Throwable is the superclass of class Exception.

Class Throwable has two subclasses: Exception and Error. Class Exception and its subclasses represent exceptional situations that can occur in a Java

program and that can be caught by the application. Class Error and its subclasses represent abnormal situations that happen in the JVM. Errors

should not be caught by applications due to its infrequent occurrence.

5.2 Error handling

In Java, programs test conditions and define the sequence in which a program

should execute. Exceptions are objects that represent errors in your program.

There are a number of things that can go wrong while a program is executing. Java enables you to handle exceptions so that you may recover from these

problems. This enables your program to display a message or log the error and continue with execution instead of crashing. The basis of this is defined by the

following pseudocode.

Perform a task

If the preceding task did not execute correctly

Perform error processing

Perform next task

If the preceding task did not execute correctly

Perform error processing

Figure 49 – Pseudocode for error handling

Source: Mapundu (2014)

5.3 Exception examples

Just like any Java object, exceptions are thrown when a method detects a problem and is unable to handle it.

In the earlier chapters, few exceptions that you might have noticed include:

ArrayIndexOutOfBoundsException: occurs when an attempt is made to

access an element past either end of an array. Such a problem may occur, for example, if there is an “off-by-one” error in a for statement that

manipulates an array. ClassCastException: occurs when an attempt is made to cast an object

that does not have an is-a relationship with the type specified in the cast operator.

NullPointerException: occurs when a null reference is used where an object is expected, for example, when an attempt is made to use a

reference-type instance variable it is initialised.

Page 76: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 5: Exception handling Page 70

© CTI Education Group

5.4 Example of division by zero

5.4.1 Without exception handling

This section explains what happens when errors arise in an application that

does not use exception handling. The sample code below prompts the user for two integers and passes them to method quotient, which calculates the integer

quotient and returns an int result. When the method detects a problem, which it is unable to handle, it throws an exception

“DivideByZeroNoExceptionHandling”

When an exception is thrown, several lines of information are displayed known

as stack trace, which includes the name of the exception in a descriptive message that indicated the problem that occurred and the method-call stack at

the time it occurred. In our current example, Java throws an ArithmeticException when division by zero in integer arithmetic occurs.

ArithmeticExceptions can arise from a number of different problems in arithmetic, extra data (“/ by zero”) provides more specific information. A

Division by zero with floating-point values returns a NaN, which represents “not-a-number”.

Figure 50 – Java code with no error handling

Source: Mapundu (2014)

Figure 51 below is a compilation of the four different outputs based on the

different inputs to the division program

Page 77: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 5: Exception handling Page 71

© CTI Education Group

Figure 51 – Four different outputs from the code in Figure 50 showing errors

Source: Mapundu (2014)

The program shows exceptions thrown when user tries to divide by zero or if

user enters a value other than the integer, e.g. a string. These exceptions are the ArithmethicException and the InputMismatchException.

5.5 With exception handling – using the Try block

5.5.1 Try block

Try block encloses the code that might throw an exception, in addition with the

code that should not execute if an exception occurs. In essence, if an error occurs, the remaining code in the try block will be skipped. Within try block, a

number of different method calls might generate the same exception, but you need only one handler.

5.5.2 Catch block

A catch block also known as exception handling. It catches and handles an exception. If an exception is thrown, the exception-handling mechanism goes

hunting for the first handler with an argument the matches the type of the exception. Each catch block specifies in parentheses an exception parameter

that identifies the exception type the handler can process. When an exception occurs in a try block, the type in the catch block matches the thrown exception

type exactly or is a superclass of it. At least one catch block or a finally block must immediately follow the try block. An uncaught exception is one for which

there are no matching catch blocks.

Page 78: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 5: Exception handling Page 72

© CTI Education Group

5.5.3 Finally clause

Java guarantees that the finally block will execute whether or not an exception is thrown in the corresponding try block. Java also guarantees that the finally

block will execute is a try block exits by using a return, break or continue

statement or simply by reaching its closing right brace. The only exception to the above conditions is when the application exits early from a try block by

calling method System.exit().

Finally block is optional and always comes after the last catch block. Below is a try-catch statement with a finally block. Finally block is an ideal place to

release resources acquired in a try block (such as opened files), which helps eliminate resource leaks. To avoid resource leaks, programs that obtain certain

types of resources must return them to the system explicitly.

Figure 52 – Structure of the Try-catch block

Source: Mapundu (2014)

Figure 53 – Catching the ArithmeticException

Source: Mapundu (2014)

Page 79: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 5: Exception handling Page 73

© CTI Education Group

Figure 54 – Catching the InputMisMatchException

Source: Mapundu (2014)

5.6 Termination model of exception handling

If an exception occurs in a try block, the try block terminates immediately and

program control transfers to the first of the following catch blocks in which the exception parameter's type matches the thrown exception's type. After the

exception is handled, program control does not return to the throw point, because the try block has expired. Rather, control resumes after the last catch

block. This is known as the termination model of exception handling.

Another termination handling method is called resumption model of exception handling. It means that the exception handler is expected to do something to

rectify the situation, and then the faulting method is retired, presuming success the second time. If you want resumption, it means you still hope to

continue execution after the exception is handled.

5.7 When to use exception handling

Exception handling is designed to process synchronous errors, which occur

when a statement executes. Exception handling is not designed to process

problems associated with asynchronous events (e.g. disk I/O completions, network message arrivals, mouse clicks and keystrokes), which occur in

parallel with, and independent of, the program's flow of control.

5.8 Applying the concepts covered in this unit

Students must be able to demonstrate their ability to do the following:

Chapter 6: Section 6.6

Use an ArrayIndexOutOfBoundsException

Page 80: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 5: Exception handling Page 74

© CTI Education Group

Chapter 11: Section 11.1 – 11.6

Use Try/Catch/Finally clauses appropriately

Self-assessment

Test your knowledge

1. Attempt the Chapter 11 Self Review questions and exercises from your textbook.

2. Toolbox

Group work: 4, 5, 6, 7 Lab exercise: 13

Page 81: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 6: Applets Page 75

© CTI Education Group

Unit 6: Applets

Unit 6 is aligned with the following learning outcomes and

assessment criteria:

Learning outcomes: LO1: Explain the principles of programming in Java

LO2: Design Java solutions

LO3: Implement Java solutions

Assessment criteria: AC1.1: Discuss the principles, characteristics and features

of programming in Java AC1.2: Critically evaluate the environmental flexibility of

programming in Java AC2.1: Design a Java programming solution to a given

problem AC3.1: Implement a Java programming solution based

on a prepared design AC3.5: Make effective use of an Integrated Development

Environment (IDE) including code and screen templates

Learning objectives

After studying this unit, you should be able to:

Understand applets Write simple applets

Five methods called by an applet during its life cycle

Prescribed reading

The study guide contents of this learning unit comprise the

prescribed reading for this learning unit.

Page 82: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 6: Applets Page 76

© CTI Education Group

Introduction

Applets are mini programs that run within the context of large programs. An

applet is a panel that allows interaction with a Java program. An applet is typically embedded in a Web page and can be run from a browser. You need

special HTML in the Web page to tell the browser about the applet. For instance Java programs are embedded in extensible Hyper Text Markup

Language also known as web pages. Therefore, when a Java enabled web browser loads a web page containing an applet, the applet downloads into the

browser and executes. The application in which an applet executes is known as the applet container. The container serves the purpose of creating an instance

of the applet and manages its lifecycle. The Java Development Kit has the applet viewer which is basically used to test any developed applets before

being integrated into web browsers. For security reasons, applets run in a

sandbox: they have no access to the client’s file system

6.1 Applet lifecycle methods

6.1.1 public void init ()

When the applet is loaded, the init() method is called to initialise the applet. This is the first method to execute; it is an ideal place to initialise variables and

define the GUI Components (buttons, text fields, scrollbars, etc.), and lay them out, and add listeners to them. Almost every applet you ever write will have an

init() method.

6.1.2 public void start ()

An applet is started once it has been initialised. It could also have been

stopped, and then started again. You can start an applet more than once with

the start() method, but it is initialised only once. Called each time the page is loaded and restarted and is used mostly in conjunction with stop() function.

Thus, if a user browses to another site and later returns to the applet’s XHTML page the method start is called again.

6.1.3 public void stop ()

An applet is stopped when a user leaves the Web page. This method is called by the applet container when the user leaves the applet’s web page by

browsing to another web page. Actions performed would stop the execution of animations and threads. The stop() method can be called explicitly. Called

when the browser leaves the page and is mostly used in conjunction with

start() method.

Page 83: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 6: Applets Page 77

© CTI Education Group

6.1.4 public void destroy ()

This allows the applet to clean up after itself before memory is freed. It is

called by the applet container when the applet is being removed from memory. This normally takes place when the user exits the browsing session by closing

all the browser windows; thus, it performs tasks that are required to clean up resources allocated to the applet.

6.1.5 public void paint (Graphics g)

This method is called by an applet container after methods init() and start(). This method performs drawing actions and the graphics object g is passed to

the paint method by the applet container. An applet usually displays something on the page. Call repaint( ) when you have changed something and want your

changes to show up on the screen repaint( ) is a request – it might not

happen. When you call repaint( ), Java schedules a call to update(Graphics g).

When you call repaint( ), Java schedules a call to update(Graphics g) Here's what update does:

public void update(Graphics g) {

// Fills applet with background color, then

paint(g);

}

Figure 55 – Drawing in applets using the paint () method

Source: Mapundu (2014)

Page 84: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 6: Applets Page 78

© CTI Education Group

Applet’s method’s calls

Figure 56 – Applet lifecycle methods

Source: Mapundu (2014)

init and destroy are only called once each start and stop are called whenever the browser enters and leaves the page

do some work is code called by your listeners paint is called when the applet needs to be repainted

6.2 Other applet methods

System.out.println(String s)

Works from applet viewer, not from browsers. Automatically opens an output window.

Init()

start ()

Process something

stop()

destroy()

Page 85: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 6: Applets Page 79

© CTI Education Group

showStatus(String)

This displays the String in the applet’s status line. Each call overwrites the previous call. You have to allow time to read the line!

getCodeBase, getDocumentBase Applet file - getCodeBase

HTML file - getDocumentBase

getParameter Retrieves the value from the associated HTML PARAM element

getSize

Returns the Dimension (width, height) of the applet

getGraphics Retrieves the current Graphics object for the applet. The Graphics object does

not persist across paint invocations

6.3 Creating the Applet class

The code snippet in Figure 57 below imports the Graphics class to enable the

applet to draw graphics. Class JApplet is imported from the package javax.swing to create applets. An applet should have at least one public class

declaration; thus, it can create objects of classes that are public and also extend JApplet. Each JApplet class should have applet methods. Any new

applet class can inherit behaviours and attributes from the superclass, the JApplet. However, these methods can also be overridden to perform tasks as

defined by you the programmer. The following code will be loaded by the applet container (WelcomeApplet class).The container will then create an

object which will then call the applet methods in sequence. If you do not define the methods, the Applet container will implement the inherited versions.

Figure 57 – WelcomeApplet code

Source: Mapundu (2014)

Page 86: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 6: Applets Page 80

© CTI Education Group

6.3.1 Overriding method paint for drawing

We have to find a way to enable our applet for drawing; thus, class

WelcomeApplet overrides method paint, indicated by the override notation in line 7. Method paint receives arguments of type Graphics through g which

draws graphics on the applet. Therefore, it is the responsibility of the applet container to call method paint and instruct it when to draw and then passes

the argument Graphics object.

6.3.2 Executing in the AppletViewer

Before you execute an applet you must create an HTML document that

specifies which applet to execute in the applet container. Your HTML should have corresponding opening and closing tags. What you have within these tags

are known as elements. You should also specify the applet element to instruct the applet container to load a specific applet and define its display area. The

code snippet also defines the applet’s attributes “width” and “height” which describes our applet element. Attributes are always enclosed in quotes. The

HTML document should be saved with file extension .html. Therefore, you can view your applet in a default browser by opening the file directory where your

HTML file will be located.

<html>

<body>

<applet code = "WelcomeApplet.class" width = "300" height = "45">

</applet>

</body>

</html>

6.3.3 Using the init method to initialise Instance variables

The following code snippet shows how you can add two numbers when a user enters input through the dialogue boxes and ultimately displays the result by

drawing a String within the rectangular applet. The init method instructs the computer to store the sum as an instance variable of the AdditionApplet class.

<html>

<body>

<applet code = "AdditionApplet.class" width = "300" height = "50">

</applet>

</body>

</html>

Page 87: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 6: Applets Page 81

© CTI Education Group

Figure 58 – AdditionApplet code

Source: Mapundu (2014)

6.4 Applying the concepts covered in this unit

Students need to be able to create Applets.

Self-assessment

Test your knowledge

1. Toolbox

Lab exercise: 12

Page 88: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 7: Testing and documentation Page 82

© CTI Education Group

Unit 7: Testing and documentation

Unit 7 is aligned with the following learning outcome and assessment criteria:

Learning outcome:

LO4: Implement Java solutions

Assessment criteria: AC4.1: Critically review and test a Java

programming solution AC4.2: Analyse actual test results against expected

results to identify discrepancies AC4.3: Evaluate independent feedback on a developed

Java program solution and make

recommendations for improvements AC4.4: Create user documentation for the developed

Java program solution AC4.5: Create technical documentation for the support

and maintenance of a Java program solution.

Learning objectives

After studying this unit, you should be able to:

To discuss the distinctions between validation testing and defect testing

To describe the principles of system and component testing To describe strategies for generating system test cases

Understand the purposes and importance of documentation Identify some key quality documents and their relations

Understand the structure and content of key quality documents Appreciate needs and opportunities for automatically generating and

managing documentation

Understand the purposes and importance of documentation Identify some key quality documents and their relations

Understand types of documentation approaches

Page 89: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 7: Testing and documentation Page 83

© CTI Education Group

Prescribed reading

The study guide contents of this learning unit comprise the prescribed reading for this learning unit.

Introduction

Testing can be defined as the process of executing a program with the

intention of finding errors, thus showing the presence of bugs but never their absence. Software testing is an investigation conducted to provide

stakeholders with information about the quality of the product or service under test. This basically tries to test a given system for bugs and errors and make

sure that it complies with the user requirements. Software testing can also provide an objective, independent view of the software to allow the business to

appreciate and understand the risks of software implementation. This unit will discuss the different approaches that exist relative to software testing as well

as techniques for documenting systems.

7.1 Software documentation

Software documentation should be of high quality; thus, it has to be specific, concise, and relevant, providing all the information important to the person

using the software. Documentation is very vital in that it helps us easily understand a given system. It also makes it easier for new team members to

easily understand the system in question. Developers can come up with internal documentation through the use of commenting within the code. This

makes it easier to easily understand the components of a given code. It also

helps when the initial developer leaves an organisation. Documentation also helps when you have user manuals; this makes it easily understandable when

end users use the system. This, therefore, highlights the need to have proper and detailed user manuals. In brief you can also make use of the UML tools to

serve as supplementary documentation as these tools describe the system structure, requirements as well as system behaviour.

7.1.1 Technical documentation for technical users

Developers should do some research on what information needs to be included. Software specification documents serve as reference manuals for

designers of the user interface, programmers who write the code, and testers

who verify that the software works as intended. Information may include important files within the application.

Page 90: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 7: Testing and documentation Page 84

© CTI Education Group

This may include files created by the development team, databases accessed

during the program's operation, and third-party utility programs. It may also be operations and should entail detailed explanation of what each function

does, including its input and output values.

Program variables and constants, and how they are used in the application.

Decide how much of the documentation should be within the program code and how much should be separate from it. The more technical

documentation is developed within the program's source code to begin with, the easier it will be to update and maintain along with the code, as well as to

document various versions of the original application. At a minimum, documentation within the source code needs to explain the purpose of

functions, subroutines, variables, and constants. If the source code is particularly lengthy, it can be documented in the form

of a help file, which can be indexed or searched with keywords. Choose the appropriate documentation tool. Word-processing programs for

Microsoft Word are adequate for creating separate text files of documentation, as long as the documentation is fairly short and simple. Help

files for documenting source code can be produced with any help-authoring

tool.

7.1.2 Writing software documentation for end users

Determine the business objectives for your documentation. Although the

functional reason for documenting software is to help users understand how to use the application.

Understand the audience you are writing the documentation for. In most cases, software users have little knowledge of computers outside of the

tasks the applications they use enable them to do. Look at the job titles your prospective users hold. A system administrator is likely expert with a

number of software applications, while a data entry clerk is more likely to

know only the application he or she currently uses to enter data. Look at existing documentation. Documentation for previous versions of

software, as well as functional specifications, provides some indication as to what the user will need to know to use the program. Keep in mind, however,

that end users are not as interested in how the program works as they are in what it can do for them.

Determine the appropriate format/s for the documentation. Software documentation can be structured in 1 of 2 formats, the reference manual

and the user guide. Sometimes, a combination of formats is the best approach.

A reference manual format is devoted to explaining the individual features of a software application (button, tab, field, and dialog box) and how they

work. A user guide format explains how to use the software to perform a particular task. User guides are often formatted as printed guides or PDFs,

although some help files include topics on how to perform particular tasks.

Page 91: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 7: Testing and documentation Page 85

© CTI Education Group

Decide what form/s the documentation should take. Software documentation

for end users can take one or several of many forms: printed manuals, PDF documents, help files, or online help. Each form is designed to show the user

how to use each of the program's functions, whether in the form of a

walkthrough or a tutorial; in the case of help files and online help, this may include demonstration videos as well as text and still graphics. Help files and

online help should be indexed and keyword-searchable to allow users to quickly find the information they are looking for.

Choose the appropriate documentation tool. Printed or PDF user manuals can be written with a word-processing program like Word or a sophisticated

text editor like FrameMaker, depending on their length and complexity. Help files can be written with a help authoring tool like RoboHelp, Help and

Manual, Doc-To-Help, Flare, HelpLogix, or HelpServer.

7.1.3 Monitor and assess the process

This describes the process of process visibility as deemed fit for internal use as well as external authorities for certification and auditing purposes. As

developers we should be able to maintain a body of knowledge reused across projects and also summarise and present data for process improvement, thus

increasing reusability of test suites and other artifacts within and across projects.

7.2 Categories of docs

7.2.1 Planning documents

These are used to describe the organisation of the quality process and include

organisation strategies and project plans.

7.2.2 Specification documents

They are best used to describe test suites and test cases, test design

specifications, test case specification, checklists, analysis procedure

specifications.

7.2.3 Reporting documents

This depicts details and summary of analysis and test results

7.3 Test design specifications

They serve the same purpose as other software design documentation. They

are used to guide in further development and prepare for use in maintenance. They include a complete description of test suites and may be divided into unit,

integration, system, acceptance suites (organise by granularity) and functional, structural, performance suites (organised by objectives).

Page 92: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 7: Testing and documentation Page 86

© CTI Education Group

Thus, they entail all the information needed for initial selection of test cases,

maintenance of the test suite over time and they also identify features to be verified (cross-reference to specification or design document. Furthermore,

they include description of testing procedure and pass/fail criteria (references

to scaffolding and oracles) includes (logically) a list of test cases.

7.3.1 Test case specification document

A complete test design for individual test case defines test inputs according to

required environmental conditions, procedures for test execution, expected outputs. It, therefore, indicates item to be tested (reference to design

document), describes dependence on execution of other test cases and is labelled with a unique identifier.

7.3.1.1 Test and analysis reports

These are the reports that are used by developers to identify open faults,

schedule fixes and revisions. Test developers use them to assess and refine their approach, prioritise list of open faults: the core of the fault handling and

repair procedure. Failure reports must be consolidated and categorised to manage repair effort and systematically prioritised to properly allocate effort

and handle all faults.

7.4 Types of testing techniques

7.4.1 Component/Unit testing

This is a technique that is used to test algorithms and logic, data structures (global and local), interfaces, independent paths, boundary conditions and

error handling. This is when the developer tests individual program components. It is the discretion of the developer to use his or her experience

to identify components for testing. Component or unit testing is the process of testing individual components in isolation. It can also be termed defect testing

process. Components may be individual functions or methods within an object

or object classes with several attributes and methods.

7.4.2 Integration testing

This is a process of testing if one module can have an adverse effect on

another. It is building a system from its components and testing it for problems that may arise from component interactions. It involves testing sub

functions; thus, when combined, it may not produce the desired major function. It can also be used to test if individually acceptable imprecision in

calculations may be magnified to unacceptable levels. Furthermore, interfacing errors not detected in unit testing may appear when performing integration

testing. It can also be applied to timing problems (in real-time systems) and

resource contention problems which are not detectable by unit testing.

Page 93: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 7: Testing and documentation Page 87

© CTI Education Group

7.4.2.1 Top down integration

Develop the skeleton of the system and populate it with components .The main control module is used as a driver, and stubs are substituted for all modules

directly subordinate to the main module. Depending on the integration

approach selected (depth or breadth first), subordinate stubs are replaced by modules one at a time. Tests are run as each individual module is integrated.

On the successful completion of a set of tests, another stub is replaced with a real module. Regression testing is performed to ensure that errors have not

developed as result of integrating new modules

7.4.2.2 Bottom up

Integrate infrastructure components then add functional components.

Integration begins with the lowest-level modules, which are combined into clusters, or builds, that perform a specific software sub function. Drivers

(control programs developed as stubs) are written to coordinate test case input and output. The cluster is then tested and drivers are removed and clusters

are combined moving upward in the program structure. Note

To simplify error localisation, systems should be incrementally integrated

7.4.3 Validation testing

Validation testing is done to demonstrate to the developer and the system

customer that the software meets its requirements. It strives to do a successful test that shows that the system operates as intended.

7.4.4 Defect testing

This aims at discovering faults or defects in the software where its behaviour is

incorrect or not in conformance with its specification. A successful test is a test that makes the system perform incorrectly and so exposes a defect in the

system. The goal of defect testing is to show the presence not the absence of defects.

7.4.5 Alpha and beta testing

Beta testing refers to a process where users or clients are presented with an incomplete version of the application or software and the user or client is

asked to provide feedback. It is best to provide customers with an outline of the things that you would like them to focus on and specific test scenarios for

them to execute.

Alpha testing is final testing before the software is released to the general

public. It has two phases which include testing the software by in-house developers.

Page 94: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 7: Testing and documentation Page 88

© CTI Education Group

You can use debugger software, or hardware-assisted debuggers. The goal is

to catch bugs quickly. The second stage is when you hand over the software QA staff, for additional testing in an environment that is similar to the intended

use. It is also a process of simulating the actual operational testing by

potential users/customers; thus, customers who are actively involved can identify defects.

7.4.6 Acceptance testing

This is similar to validation testing except that customers are present or directly involved. Usually the tests are developed by the customer.

7.4.7 System testing

This is the testing of groups of components integrated to create a system or

sub-system. This is usually done by the independent testing team and tests are based on a system specification. System testing may involve testing an

increment to be delivered to the customer. It normally has two stages, which are:

Integration testing: The test team have access to the system source code.

The system is tested as components are integrated. Release testing: The test team tests the complete system to be delivered as

a black-box; thus, testers do not have knowledge of the system implementation.

7.4.8 Performance testing

Performance testing is when part of release testing may involve testing the

emergent properties of a system, such as performance and reliability. Performance tests usually involve planning a series of tests where the load is

steadily increased until the system performance becomes unacceptable

7.4.9 Stress testing

This involves exercising the system beyond its maximum design load.

Stressing the system often causes defects to come to light. Systems should not fail catastrophically. Stress testing checks for unacceptable loss of service or

data. Stress testing is particularly relevant to distributed systems that can

exhibit severe degradation as a network becomes overloaded.

7.4.10 Interface testing

The objectives are to detect faults due to interface errors or invalid

assumptions about interfaces. This is an important part in object-oriented development as objects are defined by their interfaces.

Page 95: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 7: Testing and documentation Page 89

© CTI Education Group

7.4.11 White-box/structural testing

This is a technique of testing software’s internal structures or workings of an

application, as opposed to its functionality (i.e. black-box testing).This is when derivation of test cases is done according to program structure. The knowledge

of the program is used to identify additional test cases. The main objective is to exercise all program statements (not all path combinations).

7.5 Applying the concepts covered in this unit

Students need to be able to create test methods.

Self-assessment

Test your knowledge

1. Discuss the difference between black-box and white-box testing.

2. Discuss in groups the types of testing approaches.

3. Carry out research on types of documentation.

Page 96: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 8: Unified Modelling Language for object-oriented design Page 90

© CTI Education Group

Unit 8: Unified Modelling Language for object-

oriented design

Unit 8 is aligned with the following learning outcomes and

assessment criteria:

Learning outcomes:

LO2: Design Java solutions LO3: Implement Java solutions

Assessment criteria:

AC2.1: Design a Java programming solution to a given problem

AC3.1: Implement a Java programming solution based on a prepared design

AC3.2: Define relationships between objects to implement design requirements

Learning objectives

After studying this unit, you should be able to:

Create a requirements model using UML notations based on user requirements, and to analyse requirements models for correctness and

quality. Create various UML diagrams using specialised applications/software to

model an object–oriented system. Comprehend enough Java to see how to create software that implements the

object-oriented designs modelled using UML. Comprehend the nature of design patterns by understanding a small number

of examples from different pattern categories, and to be able to apply these patterns in creating an object-oriented design.

Determine the collaborations among objects in a system.

Prescribed reading

Deitel, P., Deitel, H. 2015. Java, How to program: Late

Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: 9781292019369

Page 97: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 8: Unified Modelling Language for object-oriented design Page 91

© CTI Education Group

Introduction

The Unified Modelling Language (UML) is an industry standard for object-

oriented design notation, supported by the Object Management Group (OMG).

It is becoming widely adopted in many areas of the software and computer systems development community. This technique also helps in managing

software complexity. The basic idea of UML is to improve association of systems analysis and design, and try solve problems through modelling. We

should, therefore, be able to use object-oriented notation to visualise, construct and document the artifacts of software engineering.

8.1 Requirements capture

This describes the UML tools that are to be used to specify clearly how the

system should be constructed to satisfy these requirements. The output of the design stage is the design specification.

8.1.1 Use case diagram

This model shows the interaction between system clients and its use cases. As

developers we should be able to use use cases to capture what a proposed system should do. An actor indicates an external person or system which is

involved in a use case shown by the stick figure. The same person or system may play the role of more than one actor, depending on the context. An actor

may be a set of roles, which are related. An actor may be involved in more than one use case and an actor is normally the initiator of each use case.

The use case symbol indicates an activity which will supply value to an actor

Within each use case there must be a description of what this activity does for the actor. Use cases can be described by English descriptions – active voice,

present tense.

Page 98: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 8: Unified Modelling Language for object-oriented design Page 92

© CTI Education Group

Figure 59 – Possible Use case diagram for Bank System

Source: Mapundu (2014)

8.2 System structure

This part will cover the UML tools that are used to describe the system’s

objects and their interrelationships.

8.2.1 Class diagrams

Class diagrams model classes used in a system. All objects identified in the requirements analysis become possible candidates of being classes in the

system. In a nutshell, they specify the structural relationship between parts of the system. Class diagrams show the relationship between classes of the

system. It is divided into three parts namely: class name, attributes and lastly the operations.

Figure 60 – Possible class diagram for Account object

Source: Mapundu (2014)

Page 99: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 8: Unified Modelling Language for object-oriented design Page 93

© CTI Education Group

8.3 System behaviour

This part will explore the system dynamics and basically describe how the

system changes as its objects interact with one another.

8.3.1 Sequence diagram

Sequence diagrams basically depict the sequence of interactions among

objects in a system focusing on when interactions occur.

Figure 61 – Sequence Diagram showing sequence of interactions

Source: Mapundu (2014)

8.3.2 Activity diagram

This models aspects of system behaviour, object’s sequence of events during

program execution. This means that it models the actions the object will perform and in what order.

Page 100: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 8: Unified Modelling Language for object-oriented design Page 94

© CTI Education Group

Figure 62 – Activity diagram

Source: Mapundu (2014)

8.3.3 Aggregation

Aggregation “is part of" relationship and is symbolised by a clear white

diamond. It is used to indicate that, as well as having attributes of its own; an instance of one class may consist of, or include, instances of another class.

This is also associations in which one class belongs to a collection.

Figure 63 – Aggregation relationship

Source: Mapundu (2014)

Page 101: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 8: Unified Modelling Language for object-oriented design Page 95

© CTI Education Group

8.3.4 Composition

Composition “is entirely made of" relationship and is a stronger version of

aggregation. The parts live and die with the whole symbolised by a black diamond. Compositions imply coincident lifetime. A coincident lifetime means

that when the whole end of the association is created (deleted), the part components are created (deleted).

Figure 64 – Composition relationship

Source: Mapundu (2014)

8.3.5 Dependency

Dependency "uses temporarily" symbolised by dotted line often is an implementation detail, not an intrinsic part of that object's state. A dependency

exists between two elements if changes to the definition of one element (the supplier or target) may cause changes to the other (the client or source). A

dependency between two classes means that one class uses, or has knowledge of, another class (i.e. a transient relationship). Dependency relationships show

that a model element requires another model element for some purpose. Dependencies can also indicate relationships between model elements at

different level of abstraction.

Page 102: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Unit 8: Unified Modelling Language for object-oriented design Page 96

© CTI Education Group

Figure 65 – Dependency relationship

Source: Mapundu (2014)

8.4 Applying the concepts covered in this unit

Students need to be able to create and interpret the diagrams described in this

learning unit.

Self-assessment

Test your knowledge

1. Toolbox

Individual exercise: 1, 2 Group work: 3, 8

Research activity: 1

Page 103: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Glossary Page 97

© CTI Education Group

Glossary

Abstract class

A class that contains one or more abstract methods and, therefore,

can never be instantiated. Abstract classes are defined so that

other classes can extend them and make them concrete by

implementing the abstract methods.

Abstract method A method that has no implementation.

Access modifier

A Java keyword that describes whether/how some class member

can be referred to (accessed). Common access modifiers are public,

private, protected, static, and final.

Actual parameter list The arguments specified in a particular method call

Array A collection of data items, all the same type, in which each item's

position is uniquely designated by an integer.

Block In the Java(TM) programming language, any code between

matching braces. Example: { x = 1; }.

Boolean

Refers to an expression or variable that can have only a true or

false value. The Java(TM) programming language provides the

Boolean type and the literal values true and false.

Break

A Java(TM) programming language keyword used to resume

program execution at the statement immediately following the

current statement. If followed by a label, the program resumes

execution at the labelled statement.

Casting Explicit conversion from one data type to another.

Catch

A Java(TM) programming language keyword used to declare a block

of statements to be executed in the event that a Java exception, or

run time error, occurs in a preceding "try" block.

Char A Java(TM) programming language keyword used to declare a

variable of type character.

Checked exception

A checked exception is a subclass of Throwable but not of

RunTimeException. Such exceptions generally indicate an extra-

logical failure (one not related to programming errors; e.g.

EndOfFileException). They are required either to be caught, or

appear in a method that specifies in its prototype that it throws

that kind of exception. Contrast to Unchecked Exception.

Class

In the Java (TM) programming language, a type that defines the

implementation of a particular kind of object. A class definition

defines instance and class variables and methods, as well as

specifying the interfaces the class implements and the immediate

superclass of the class. If the superclass is not explicitly specified,

the superclass will implicitly be Object.

Class constant A variable defined as both final and static.

Class method

A method that is invoked without reference to a particular object.

Class methods affect the class as a whole, not a particular instance

of the class. Also called a static method.

Class scope

Private variables defined outside the methods within a class have

class scope. They are accessible from all methods within the class,

regardless of the order in which they are defined. Private methods

also have class scope. Variables and methods may have a wider

scope if they do not use the private access modifier.

Class variable

A data item associated with a particular class as a whole--not with

particular instances of the class. Class variables are defined in class

definitions. Also called static field.

Constructor A class member whose purpose is to help initialise all the fields of a

class. Constructors can be overloaded.

Components A GUI is built by arranging components on screen. Components are

represented by objects.

Debugging Debugging is the attempt to pinpoint and fix the source of an error.

Page 104: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Glossary Page 98

© CTI Education Group

Encapsulation

The localisation of knowledge within a module. Because objects

encapsulate data and implementation, the user of an object can

view the object as a black box that provides services. Instance

variables and methods can be added, deleted, or changed, but as

long as the services provided by the object remain the same, code

that uses the object can continue to use it without being rewritten.

Event handling The term event handling refers to the task of reacting to user

events, such as mouse button clicks or keyboard input.

Exception

If a built-in Java operator or programmer supplied Java method

cannot correctly compute its result (e.g. the user has specified the

bad arguments) it throws an exception to indicate a problem.

Exceptions are classified as either checked or not-checked. When

such operators/methods occur in try/catch blocks, the programmer

can indicate how to proceed if an exception is thrown.

Exception handler

A block of code that reacts to a specific type of exception. If the

exception is for an error that the program can recover from, the

program can resume executing after the exception handler has

executed.

Extends

Class X extends class Y to add functionality, either by adding fields

or methods to class Y, or by overriding methods of class Y. An

interface extends another interface by adding methods. Class X is

said to be a subclass of class Y.

Final

A Java(TM) programming language keyword. You define an entity

once and cannot change it or derive from it later. More specifically:

a final class cannot be sub-classed, a final method cannot be

overridden and a final variable cannot change from its initialised

value.

Finally

A Java(TM) programming language keyword that executes a block

of statements regardless of whether a Java Exception, or run time

error, occurred in a block defined previously by the "try" keyword.

For

A Java(TM) programming language keyword used to declare a loop

that reiterates statements. The programmer can specify the

statements to be executed, exit conditions, and initialisation

variables for the loop.

Garbage collection

The automatic detection and freeing of memory that is no longer in

use. The Java(TM) runtime system performs garbage collection so

that programmers never explicitly free objects.

Identifier

A kind of token, used for names: variable names, method names,

class names, etc. Identifiers always start with letters; a dollar sign

is allowed, but this character should be reserved for special

identifiers created by the Java compiler.

If

A Java(TM) programming language keyword used to conduct a

conditional test and execute a block of statements if the test

evaluates to true.

Immu7

A class is immutable if is defines no mutator methods. This means

that once the state of an object is initialised by a constructor, it will

never change. String and the wrapper classes are all immutable.

Implements

A Java(TM) programming language keyword optionally included in

the class declaration to specify any interfaces that are implemented

by the current class

Import

A Java(TM) programming language keyword used at the beginning

of a source file that can specify classes or entire packages to be

referred to later without including their package names in the

reference.

Inheritance The concept of classes automatically containing the variables and

methods defined in their superTypes. See also super, subclass

Page 105: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Glossary Page 99

© CTI Education Group

Inheritance Inheritance allows us to define one class as an extension of

another.

Inheritance hierarchy Classes that are linked through inheritance relationships from an

inheritance hierarchy.

Instance

An object of a particular class. In programs written in the Java(TM)

programming language, an instance of a class is created using the

new operator followed by the class name.

Instance method Any method that is invoked with respect to an instance of a class.

Also called simply a method. See class method.

Instance variable

Any item of data that is associated with a particular object. Each

instance of a class has its own copy of the instance variables

defined in the class. Also called field. See also class variable.

Instanceof

A two-argument Java(TM) programming language keyword that

tests whether the run-time type of its first argument is assignment

compatible with its second argument.

Interface

A Java(TM) programming language keyword used to define a

collection of method definitions and constant values. It can later be

implemented by classes that define this interface with the

"implements" keyword.

Keyword A kind of token, used for names/identifiers reserved by Java with

immutable meanings.

Layout Arranging the layout of components is achieved by using layout

managers.

Main The starting point for program execution (public static void

main(String[] args)

Member A field or method of a class. Unless specified otherwise, a member

is not static.

Members

Java classes define and document three kinds of members:

constructors, methods, and fields. Almost everything that we can

say about a class is said about one of these members.

Menu bar, content

pane

Components are placed in a frame by adding them to a menu bar

or content pane.

Method A function defined in a class. See also instance method, class

method. Unless specified otherwise, a method is not static.

Multithread Describes a program that is designed to have parts of its code

execute concurrently. See also thread.

Mutator

A Java method that changes the state of an object is called a

mutator. Mutators typically do not return a result (are declared to

return void), although some mutators both change state and return

a result (e.g. nextToken in StringTokenizer). Mutators just change

state, without looking at current values, are often call "setters",

and their names often start with set.

New

New is a unary prefix operator, which takes as an operand the

name of any class. Following the class name is a pair of open/close

parentheses; inside these parentheses, separated by commas, is

any information that the class requires to specify the initial state of

the object being constructed. The new operator constructs a new

object from this class, initialises it, and then returns as a result (all

operators return results) a reference to this object.

Null reference A value used to mean, `no object'. Used when an object reference

variable is not referring to an object.

Operator

A kind of token mostly used for arithmetic, relational, logical, or

textual operations (operating on primitive types or references -but

not on the state of the objects that they refer to).

Overloaded

An operator or method is overloaded if it has more than one

prototype. Java determines which actual operator/method to use

based on its signature.

Page 106: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Glossary Page 100

© CTI Education Group

Overriding Providing a different implementation of a method in a subclass of

the class that originally defined the method.

Primitive type

A type built in to the Java language (as a keyword). The main

primitive types are int, double, Boolean, and char; less often used

primitive types are short, long, and float.

Protected

A Java(TM) programming language keyword used in a method or

variable declaration. It signifies that the method or variable can

only be accessed by elements residing in its class, subclasses, or

classes in the same package.

Protected access

Protected access is available to a class member prefixed with the

protected access modifier. Such a member is accessible to all

classes defined within the enclosing package, and any subclasses

extending the enclosing class.

Polymorphism The ability to take many forms. This is when you use the same

method but with different argument.

Public

A Java(TM) programming language keyword used in a method or

variable declaration. It signifies that the method or variable can be

accessed by elements residing in other classes.

Reference A data element whose value is an address.

Reference type A reference type includes the names of interfaces and classes

(either declared in the standard Java library or by a programmer).

Static

A Java(TM) programming language keyword used to define a

variable as a class variable. Classes maintain one copy of class

variables regardless of how many instances exist of that class.

"Static" can also be used to define a method as a class method.

Class methods are invoked by the class instead of a specific

instance, and can only operate on class variables.

Testing Testing is the activity of finding out whether a piece of code (a

method, class, or program) produces the intended behaviour.

UML Unified modelling language is a tool to model object-oriented-

programming

Page 107: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

Bibliography Page 101

© CTI Education Group

Bibliography

Deitel, P. 2010. Java How to Program: Late Objects. 8th edition. Pearson Education.

Deitel, P., Deitel, H. 2010. Java, How to Program: Late Objects. New Jersey:

Pearson Education.

How to write good software documentation. [Online] Available at: http://www.softwaredocumentation.info/DocumentingSoftware.aspx

[Accessed: 19 November 2014].

How to write user documentation. [Online] Available at:

http://www.techscribe.co.uk/ta/how-to-write-user-documentation.htm [Accessed: 19 November 2014].

Mapundu, M. 2014. Programming in Java C_ITJA211. CTI Education Group.

Pooley, R., Wilcox, P. 2004. Applying UML: Advanced Application. Oxford:

British Library.

Page 108: Programming in Java - WordPress.com · The unit is not specific to one instance of the Java programming language and may be used to deploy, among others, mobile applications, bespoke

© CTI Education Group

Contact details

Bedfordview Campus

9 Concorde Road East, Bedfordview P.O. Box 1389, Bedfordview, 2008 Tel: +27 (0)10 595 2999, Fax: +27 (0)86 686 4950 Email: [email protected]

Bloemfontein Campus

Tourist Centre, 60 Park Avenue, Willows, Bloemfontein P.O. Box 1015, Bloemfontein, 9300 Tel: +27 (0)51 430 2701, Fax: +27 (0)51 430 2708 Email: [email protected]

Cape Town Campus

The Brookside Building, 11 Imam Haron Str (old Lansdowne Road), Claremont P.O. Box 2325, Clareinch, 7740 Tel: +27 (0)21 674 6567, Fax: +27 (0)21 674 6599 Email: [email protected]

Durban Campus

1 Lunar Row, Umhlanga Ridge, Durban

P.O. Box 20251, Durban North, 4016 Tel: +27 (0)31 564 0570/5, Fax: +27 (0)31 564 8978 Email: [email protected]

Durbanville Campus

Kaapzicht, 9 Rogers Street, Tyger Valley P.O. Box 284, Private Bag X7

Tyger Valley, 7536 Tel: +27 (0)21 914 8000, Fax: +27 (0)21 914 8004 Email: [email protected]

East London Campus

12 Stewart Drive, Berea, East London PostNet Suite 373

Private Bag X9063, East London, 5200 Tel: +27 (0)43 721 2564, Fax: +27 (0)43 721 2597 Email: [email protected]

Nelspruit Campus 50 Murray Street, Nelspruit P.O. Box 9497, Sonpark, Nelspruit, 1206 Tel: +27 (0)13 755 3918, Fax: +27 (0)13 755 3918 Email: [email protected]

Port Elizabeth Campus

Building 4, Ascot Office Park Cnr Ascot & Conyngham Roads, Greenacres P.O. Box 40049, Walmer, 6065 Tel: +27 (0)41 374 7978, Fax: +27 (0)41 374 3190 Email: [email protected]

Potchefstroom Campus

12 Esselen Street, Cnr Esselen Street & Steve Biko Avenue, Die Bult, Potchefstroom P.O. Box 19900, Noordbrug, 2522 Tel: +27 (0)18 297 7760, Fax: +27 (0)18 297 7783 Email: [email protected]

Pretoria Campus

22 Umgazi Street, Menlo Park, Pretoria PostNet Suite A147, Private Bag X18, Lynnwood Ridge, 0040 Tel: +27 (0)12 348 3060, Fax: +27 (0)12 348 3063 Email: [email protected]

Randburg Campus

6 Hunter Avenue, Cnr Bram Fischer Drive Ferndale, Randburg P.O. Box 920, Randburg, 2125 Tel: +27 (0)11 789 3178, Fax: +27 (0)11 789 4606 Email: [email protected]

Vanderbijlpark Campus

Building 2, Cnr Rutherford & Frikkie Meyer Boulevards Vanderbijlpark P.O. Box 6371, Vanderbijlpark, 1900 Tel: +27 (0)16 931 1180, Fax: +27 (0)16 933 1055 Email: [email protected]

Group Head Office

Management Services Building 44 Alsatian Road, Glen Austin Extension 3, Midrand P.O. Box 1398, Randburg, 2125 Tel: +27 (0)11 467 8422, Fax: +27 (0)86 583 6660 Website: www.cti.ac.za

CTI is part of Pearson, the world’s leading learning company. Pearson is the corporate owner, not a registered

provider nor conferrer of qualifications in South Africa. CTI Education Group (Pty) Ltd. is registered with the Department of Higher Education and Training as a private higher education institution under the

Higher Education Act, 101, of 1997. Registration Certificate number: 2004/HE07/004. www.cti.ac.za.