Programming in Java C_ITJA211

Size: px
Start display at page:

Download "Programming in Java C_ITJA211"

Transcription

1 Programming in Java C_ITJA211

2 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

3 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 UNIT 1: INTRODUCTION TO THE JAVA ENVIRONMENT Learning objectives Prescribed reading Introduction Java development environment Java Virtual Machine (JVM) Java class libraries/api packages Variables Data types Access modifiers The three different kinds of modifiers Types of access modifiers for class members (variables and methods) The this reference Using the super keyword Static class members Interfaces Garbage collection through the method finalize Creating packages Relational operators Characteristics of object-oriented programming Objects Attributes Classes Methods Events Event handlers Object-oriented programming principles Abstraction Encapsulation Inheritance Polymorphism Method overloading... 33

4 Method overriding Applying the concepts covered in this unit Self-assessment UNIT 2: GUI COMPONENTS Learning objectives Prescribed reading Introduction Simple GUI input/output with JOptionPane Input dialogues Swing components JButton JCheckBox JRadioButton JTextArea Using JOptionPane Addition program Displaying text and images in a window using the JFrame Event handling GUI components for events Steps for setting up event handling for GUI Connecting to an Access database Creating the application and connecting to the database Connecting to a MySQL database Creating the application and connecting to the database Text files Applying the concepts covered in this unit Self-assessment UNIT 3: CONTROL STATEMENTS AND RELATIONAL OPERATORS Learning objectives Prescribed reading Introduction Control structure Sequence structure Selection statements Repetition statements Statements If single selection statement If else double selection statement Nested if else statement Switch Multiple-Selection statement Counter controlled repetition For repetition statement While repetition statement Nested repetition statement String and character manipulations Applying the concepts covered in this unit Self-assessment UNIT 4: ARRAYS Learning objectives Prescribed reading Introduction Primitive types and reference types Arrays Declaring an array Declaring many arrays in single declaration Using an array initialiser Enhanced for statement Passing arrays to methods... 63

5 4.5 Multi-dimensional arrays Collections and class ArrayLists Working with ArrayList class Creating an ArrayList Putting an Item into ArrayList Checking size of ArrayList Checking Index of an Item in Java ArrayList Applying the concepts covered in this unit Self-assessment UNIT 5: EXCEPTION HANDLING Learning objectives Prescribed reading Introduction Java Exception Hierarchy Error handling Exception examples Example of division by zero Without exception handling With exception handling using the Try block Termination model of exception handling When to use exception handling Applying the concepts covered in this unit Self-assessment UNIT 6: APPLETS Learning objectives Prescribed reading Introduction Applet lifecycle methods public void init () public void start () public void stop () public void destroy () public void paint (Graphics g) Other applet methods Creating the Applet class Overriding method paint for drawing Executing in the AppletViewer Using the init method to initialise Instance variables Applying the concepts covered in this unit Self-assessment UNIT 7: TESTING AND DOCUMENTATION Learning objectives Prescribed reading Introduction Software documentation Technical documentation for technical users Writing software documentation for end users Monitor and assess the process Categories of docs Planning documents Specification documents Reporting documents Test design specifications Test case specification document Test and analysis reports Types of testing techniques Component/Unit testing... 86

6 7.4.2 Integration testing Validation testing Defect testing Alpha and beta testing Acceptance testing System testing Performance testing Stress testing Interface testing White-box/structural testing Applying the concepts covered in this unit Self-assessment UNIT 8: UNIFIED MODELLING LANGUAGE FOR OBJECT-ORIENTED DESIGN Learning objectives Prescribed reading Introduction Requirements capture Use case diagram System structure Class diagrams System behaviour Sequence diagram Activity diagram Aggregation Composition Dependency Applying the concepts covered in this unit Self-assessment GLOSSARY BIBLIOGRAPHY

7 Introduction Page 1 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 multiplatform 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.

8 Introduction Page 2 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 On successful completion of this module you will: 1. Explain the principles of programming in Java 2. Design Java solutions Assessment criteria to pass You can: 1.1 Discuss the principles, characteristics and features of programming in Java 1.2 Critically evaluate the environmental flexibility of programming in Java 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

9 Introduction Page 3 3. Implement Java solutions 4. Test and document 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.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; classedbased; 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

10 Introduction Page 4 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, breakpoints), 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

11 Introduction Page 5 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.

12 Introduction Page 6 Prescribed textbook The prescribed textbook for Programming in Java Deitel, P., Deitel, H Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: Recommended information sources Books Bloch, J Effective Java, Second Edition. New Jersey: Prentice Hall. Goetz, B Java Concurrency in Practice. Boston: Addison Wesley. Niemeyer, P Learning Java, Third Edition. Sebastopol: O Reilly. Websites 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.

13 Introduction Page 7 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

14 Introduction Page 8 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 Learning outcomes Learning objectives Introduction Content Concluding remarks Self-assessment Each unit title in based on the title and content of the specific outcome or the assessment criterion (criteria) discussed in the unit. 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, 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. The learning objectives are followed by an introduction that identifies the key concepts of the unit. 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. 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. The content is followed by a number of theoretical selfassessment 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:

15 Introduction Page 9 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 selfassessment 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

16 Introduction Page 10 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.

17 Unit 1: Introduction to a Java environment Page 11 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

18 Unit 1: Introduction to a Java environment Page 12 Prescribed reading Deitel, P., Deitel, H Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: Chapter 1, Section 1.5, Chapter 2, Section Chapter 5, Section , Chapter 7, Section Chapter 8, Section 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 objectoriented programming. In this learning unit students will be reminded of several important objectoriented 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 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 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.

19 Unit 1: Introduction to a Java environment Page 13 Java programs usually go through five phases namely: Figure 1 Java application phases Source: Deitel (2008:12)

20 Unit 1: Introduction to a Java environment Page 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.

21 Unit 1: Introduction to a Java environment Page 15 Table 1 Java packages Package java.applet Java.awt Java.awt.event Java.awt.geom Java.io java.lang Java.net Java.text Java.util Javax.swing Javax.swing.event Description The Java Applet Package contains a class and several interfaces for creating Java applets programs that execute in web browsers. 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. 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. The Java 2D Shapes Package contains classes and interfaces for working with Java s advanced two-dimensional graphics capabilities. The Java Input/Output Package contains classes and interfaces that enable programs to input and output data 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. The Java Networking Package contains classes and interfaces that enable programs to communicate via computer networks like the Internet. 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. 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. The Java Swing GUI Components Package contains classes and interfaces for Java s Swing GUI components that provide support for portable GUIs. 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 For further reading about Java application packages: Chapter 5, Section 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.

22 Unit 1: Introduction to a Java environment Page 16 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 For further reading: Chapter 2, Section 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 The following represents the different types of variables in object-oriented programming:

23 Unit 1: Introduction to a Java environment Page 17 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 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 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

24 Unit 1: Introduction to a Java environment Page 18 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 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 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

25 Unit 1: Introduction to a Java environment Page 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.

26 Unit 1: Introduction to a Java environment Page 20 Below is a diagram showing the types of data types in Java. Figure 9 Data types Source: Adapted from: 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 String name = Michael ; as a word or sentence int Used to store an integer cannot be used to int passmark = 60; store floating point numbers 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;

27 Unit 1: Introduction to a Java environment Page 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 The three different kinds of modifiers 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 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 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 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.

28 Unit 1: Introduction to a Java environment Page 22 abstract class Dog { //Class body } Figure 12 Declaring an abstract class using an abstract modifier 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 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 Types of access modifiers for class members (variables and methods) The following sections discuss the various class member access modifiers 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 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 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.

29 Unit 1: Introduction to a Java environment Page 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

30 Unit 1: Introduction to a Java environment Page 24 For further reading: Chapter 7, Section 7.2 Chapter 8, Section 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 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);

31 Unit 1: Introduction to a Java environment Page 25 The following code snippet shows the concept of Inheritance. Figure 14 Example code showing inheritance 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 nonstatic 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

32 Unit 1: Introduction to a Java environment Page 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

33 Unit 1: Introduction to a Java environment Page 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 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 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:

34 Unit 1: Introduction to a Java environment Page 28 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 1.11 Characteristics of object-oriented programming 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 objectoriented 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 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.

35 Unit 1: Introduction to a Java environment Page 29 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 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 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).

36 Unit 1: Introduction to a Java environment Page 30 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 public class Dog { //The constructor that is automatically created with //no arguments. public Dog(){} } Figure 18 Default constructor For further reading: Chapter 7, Section 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.

37 Unit 1: Introduction to a Java environment Page 31 For further reading about Java methods and application packages: Chapter 5, Section 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 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 Object-oriented programming principles 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) Encapsulation Encapsulation, also known as information-hiding, is a principle of objectoriented 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.

38 Unit 1: Introduction to a Java environment Page 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 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:

39 Unit 1: Introduction to a Java environment Page 33 Figure 20 Java code implementing inheritance based on Figure 19 diagram 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 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 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.

40 Unit 1: Introduction to a Java environment Page 34 Figure 21 Java code demonstrating overloading For further reading: Chapter 5, Section 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.

41 Unit 1: Introduction to a Java environment Page 35 Figure 22 Java code demonstrating overriding For further reading: Chapter 5, p 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 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

42 Unit 1: Introduction to a Java environment Page 36 Chapter 5: Section , 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 Declare instance variables Create and use set and get Methods Use the this reference appropriately Use constructors to initialise objects Chapter 8: Section 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.

43 Unit 1: Introduction to a Java environment Page Complete exercises from the Toolbox: Individual exercise: 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

44 Unit 2: GUI components Page 38 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 Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: Chapter 12 Section 12.3 Section 12.13, Section Section Chapter 15 Section 15.1 Section 15.4 Chapter 22 Section 22.4 Section 22.9

45 Unit 2: GUI components Page 39 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 JComboBox cbooptions = new JComboBox() possibly by typing into the box.

46 Unit 2: GUI components Page 40 JList JPanel 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. Provides an area in which components can be placed and organised. Can also be used as a drawing area for graphics JList lstproducts = new JList() JPanel pane = new JPanel() 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 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 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 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

47 Unit 2: GUI components Page 41 Figure 23 Hierarchical structure 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.

48 Unit 2: GUI components Page 42 Figure 24 Addition program using GUI 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

49 Unit 2: GUI components Page 43 For further reading about JOptionPane: Chapter 12, Section 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 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.

50 Unit 2: GUI components Page 44 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 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 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.

51 Unit 2: GUI components Page 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 jar jackcess jar hsqldb.jar commons-logging jar commons-lang-2.6.jar The steps below should be followed in order to connect to the Access database 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:

52 Unit 2: GUI components Page 46 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:

53 Unit 2: GUI components Page 47 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 bin.jar The steps below should be followed in order to connect to a MySQL database 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.

54 Unit 2: GUI components Page 48 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:

55 Unit 2: GUI components Page 49 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

56 Unit 2: GUI components Page Applying the concepts covered in this unit Students must be able to demonstrate their ability to do the following: Chapter 12: Section , 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 Create text files Write to text files Read from text files Chapter 22: Section 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

57 Unit 2: GUI components Page 51 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

58 Unit 3: Control statements and relational operators Page 52 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 Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: Chapter 3 Section Chapter 4 Section Chapter 14 Section

59 Unit 3: Control statements and relational operators Page 53 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 Sequence structure This is built into Java and the computer will execute the statements according to the predefined order as in the code 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 Chapter 4, Section 4.6

60 Unit 3: Control statements and relational operators Page 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 Chapter 4, Section Statements If single selection statement Figure 32 If statement If else double selection statement It is also known as a two way If statement. Figure 33 Two way If statement with output Nested if else statement Multiple cases can be tested by placing if else statements inside other if else statements.

61 Unit 3: Control statements and relational operators Page 55 Figure 34 Nested if else statement Source: Snyman (2015) Switch Multiple-Selection statement Figure 35 Nested if else statement Source: Snyman (2015)

62 Unit 3: Control statements and relational operators Page 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 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 Example using a counter variable called counter: Figure 37 Counter controlled for loop

63 Unit 3: Control statements and relational operators Page While repetition statement initialization; while ( loopcontinuationcondition ) { statement increment; } Figure 38 Declaring the while repetition statement Example Figure 39 Counter controlled while loop Nested repetition statement Control statements can be stacked on top of each other or connected to each other by nesting one inside another.

64 Unit 3: Control statements and relational operators Page 58 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.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 Use a do-while statement Use a switch multiple-selection statement Use logical operators

65 Unit 3: Control statements and relational operators Page 59 Chapter 14: Section , 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.

66 Unit 4: Arrays Page 60 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 Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: Chapter 6, Section , Section 6.7 Section 6.14

67 Unit 4: Arrays Page 61 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 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.

68 Unit 4: Arrays Page 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 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 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

69 Unit 4: Arrays Page 63 Figure 43 Using the enhanced for statement 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

70 Unit 4: Arrays Page 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 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

71 Unit 4: Arrays Page 65 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 [0] [1] [2] [0] [1] [2] Figure 48 Structure of a two-dimensional array 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>

72 Unit 4: Arrays Page 66 Table 6 Common methods of the class ArrayList<T> Method add clear get indexof remove size trimtosize Description Adds an element to the end of the ArrayList. Removes all the elements from the ArrayList. Returns the element at the specified index. Returns the index of the first occurrence of the specified element in the ArrayList. Removes the element at the specified index. Returns the number of elements stored in the ArrayList. Trims the capacity of the ArrayList to current number of elements. 4.7 Working with ArrayList class Following sections focus on working with a few methods of the ArrayList class 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>(); 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 Checking size of ArrayList Size of an ArrayList in Java is total number of elements currently stored in ArrayList. int size = stringlist.size(); 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

73 Unit 4: Arrays Page 67 For further reading: Chapter 6, Section Applying the concepts covered in this unit Students must be able to demonstrate their ability to do the following: Chapter 6: Section , 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

74 Unit 5: Exception handling Page 68 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 Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN: Chapter 6, Section 6.6 Chapter 11, Section 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.

75 Unit 5: Exception handling Page 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 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.

76 Unit 5: Exception handling Page Example of division by zero 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 Figure 51 below is a compilation of the four different outputs based on the different inputs to the division program

77 Unit 5: Exception handling Page 71 Figure 51 Four different outputs from the code in Figure 50 showing errors 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 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 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.

78 Unit 5: Exception handling Page 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 Figure 53 Catching the ArithmeticException

79 Unit 5: Exception handling Page 73 Figure 54 Catching the InputMisMatchException 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

80 Unit 5: Exception handling Page 74 Chapter 11: Section 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

81 Unit 6: Applets Page 75 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.

82 Unit 6: Applets Page 76 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 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 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 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.

83 Unit 6: Applets Page 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 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

84 Unit 6: Applets Page 78 Applet s method s calls Init() start () Process something stop() destroy() Figure 56 Applet lifecycle methods 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.

85 Unit 6: Applets Page 79 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

86 Unit 6: Applets Page 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 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> 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>

87 Unit 6: Applets Page 81 Figure 58 AdditionApplet code 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

88 Unit 7: Testing and documentation Page 82 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

89 Unit 7: Testing and documentation Page 83 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 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.

90 Unit 7: Testing and documentation Page 84 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 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.

91 Unit 7: Testing and documentation Page 85 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 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 Planning documents These are used to describe the organisation of the quality process and include organisation strategies and project plans Specification documents They are best used to describe test suites and test cases, test design specifications, test case specification, checklists, analysis procedure specifications 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).

92 Unit 7: Testing and documentation Page 86 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 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 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 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 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.

93 Unit 7: Testing and documentation Page 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 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 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 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 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.

94 Unit 7: Testing and documentation Page 88 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 Acceptance testing This is similar to validation testing except that customers are present or directly involved. Usually the tests are developed by the customer 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 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 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 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.

95 Unit 7: Testing and documentation Page 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.

96 Unit 8: Unified Modelling Language for object-oriented design Page 90 Unit 8: Unified Modelling Language for objectoriented 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 Java, How to program: Late Objects, Global Edition. 10th edition. New Jersey: Pearson Education. ISBN:

97 Unit 8: Unified Modelling Language for object-oriented design Page 91 Introduction The Unified Modelling Language (UML) is an industry standard for objectoriented 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 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.

98 Unit 8: Unified Modelling Language for object-oriented design Page 92 Figure 59 Possible Use case diagram for Bank System 8.2 System structure This part will cover the UML tools that are used to describe the system s objects and their interrelationships 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

99 Unit 8: Unified Modelling Language for object-oriented design Page System behaviour This part will explore the system dynamics and basically describe how the system changes as its objects interact with one another 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 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.

100 Unit 8: Unified Modelling Language for object-oriented design Page 94 Figure 62 Activity diagram 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

101 Unit 8: Unified Modelling Language for object-oriented design Page 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 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.

102 Unit 8: Unified Modelling Language for object-oriented design Page 96 Figure 65 Dependency relationship 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

103 Glossary Page 97 Glossary Abstract class Abstract method Access modifier Actual parameter list Array Block Boolean Break Casting Catch Char Checked exception Class Class constant Class method Class scope Class variable Constructor Components Debugging 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. A method that has no implementation. 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. The arguments specified in a particular method call A collection of data items, all the same type, in which each item's position is uniquely designated by an integer. In the Java(TM) programming language, any code between matching braces. Example: { x = 1; }. 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. 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. Explicit conversion from one data type to another. 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. A Java(TM) programming language keyword used to declare a variable of type character. A checked exception is a subclass of Throwable but not of RunTimeException. Such exceptions generally indicate an extralogical 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. 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. A variable defined as both final and static. 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. 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. 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. A class member whose purpose is to help initialise all the fields of a class. Constructors can be overloaded. A GUI is built by arranging components on screen. Components are represented by objects. Debugging is the attempt to pinpoint and fix the source of an error.

104 Glossary Page 98 Encapsulation Event handling Exception Exception handler Extends Final Finally For Garbage collection Identifier If Immu7 Implements Import Inheritance 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. The term event handling refers to the task of reacting to user events, such as mouse button clicks or keyboard input. 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. 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. 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. 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. 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. 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. 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. 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. A Java(TM) programming language keyword used to conduct a conditional test and execute a block of statements if the test evaluates to true. 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. A Java(TM) programming language keyword optionally included in the class declaration to specify any interfaces that are implemented by the current class 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. The concept of classes automatically containing the variables and methods defined in their supertypes. See also super, subclass

105 Glossary Page 99 Inheritance Inheritance hierarchy Instance Instance method Instance variable Instanceof Interface Keyword Layout Main Member Members Menu bar, content pane Method Multithread Mutator New Null reference Operator Overloaded Inheritance allows us to define one class as an extension of another. Classes that are linked through inheritance relationships from an inheritance hierarchy. 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. Any method that is invoked with respect to an instance of a class. Also called simply a method. See class method. 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. 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. 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. A kind of token, used for names/identifiers reserved by Java with immutable meanings. Arranging the layout of components is achieved by using layout managers. The starting point for program execution (public static void main(string[] args) A field or method of a class. Unless specified otherwise, a member is not static. 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. Components are placed in a frame by adding them to a menu bar or content pane. A function defined in a class. See also instance method, class method. Unless specified otherwise, a method is not static. Describes a program that is designed to have parts of its code execute concurrently. See also thread. 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 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. A value used to mean, `no object'. Used when an object reference variable is not referring to an object. 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). 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.

106 Glossary Page 100 Overriding Primitive type Protected Protected access Polymorphism Public Reference Reference type Static Testing UML Providing a different implementation of a method in a subclass of the class that originally defined the method. 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. 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 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. The ability to take many forms. This is when you use the same method but with different argument. 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. A data element whose value is an address. A reference type includes the names of interfaces and classes (either declared in the standard Java library or by a programmer). 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 is the activity of finding out whether a piece of code (a method, class, or program) produces the intended behaviour. Unified modelling language is a tool to model object-orientedprogramming

107 Bibliography Page 101 Bibliography Deitel, P Java How to Program: Late Objects. 8th edition. Pearson Education. Deitel, P., Deitel, H Java, How to Program: Late Objects. New Jersey: Pearson Education. How to write good software documentation. [Online] Available at: [Accessed: 19 November 2014]. How to write user documentation. [Online] Available at: [Accessed: 19 November 2014]. Mapundu, M Programming in Java C_ITJA211. CTI Education Group. Pooley, R., Wilcox, P Applying UML: Advanced Application. Oxford: British Library.

108 Contact details Bedfordview Campus 9 Concorde Road East, Bedfordview P.O. Box 1389, Bedfordview, 2008 Tel: +27 (0) , Fax: +27 (0) bedfordview@cti.ac.za Cape Town Campus The Brookside Building, 11 Imam Haron Str (old Lansdowne Road), Claremont P.O. Box 2325, Clareinch, 7740 Tel: +27 (0) , Fax: +27 (0) capetown@cti.ac.za Durbanville Campus Kaapzicht, 9 Rogers Street, Tyger Valley P.O. Box 284, Private Bag X7 Tyger Valley, 7536 Tel: +27 (0) , Fax: +27 (0) durbanville@cti.ac.za Nelspruit Campus 50 Murray Street, Nelspruit P.O. Box 9497, Sonpark, Nelspruit, 1206 Tel: +27 (0) , Fax: +27 (0) nelspruit@cti.ac.za Potchefstroom Campus 12 Esselen Street, Cnr Esselen Street & Steve Biko Avenue, Die Bult, Potchefstroom P.O. Box 19900, Noordbrug, 2522 Tel: +27 (0) , Fax: +27 (0) potchefstroom@cti.ac.za Randburg Campus 6 Hunter Avenue, Cnr Bram Fischer Drive Ferndale, Randburg P.O. Box 920, Randburg, 2125 Tel: +27 (0) , Fax: +27 (0) randburg@cti.ac.za Group Head Office Management Services Building 44 Alsatian Road, Glen Austin Extension 3, Midrand P.O. Box 1398, Randburg, 2125 Tel: +27 (0) , Fax: +27 (0) Website: Bloemfontein Campus Tourist Centre, 60 Park Avenue, Willows, Bloemfontein P.O. Box 1015, Bloemfontein, 9300 Tel: +27 (0) , Fax: +27 (0) bloemfontein@cti.ac.za Durban Campus 1 Lunar Row, Umhlanga Ridge, Durban P.O. Box 20251, Durban North, 4016 Tel: +27 (0) /5, Fax: +27 (0) durban@cti.ac.za East London Campus 12 Stewart Drive, Berea, East London PostNet Suite 373 Private Bag X9063, East London, 5200 Tel: +27 (0) , Fax: +27 (0) eastlondon@cti.ac.za Port Elizabeth Campus Building 4, Ascot Office Park Cnr Ascot & Conyngham Roads, Greenacres P.O. Box 40049, Walmer, 6065 Tel: +27 (0) , Fax: +27 (0) port_elizabeth@cti.ac.za Pretoria Campus 22 Umgazi Street, Menlo Park, Pretoria PostNet Suite A147, Private Bag X18, Lynnwood Ridge, 0040 Tel: +27 (0) , Fax: +27 (0) pretoria@cti.ac.za Vanderbijlpark Campus Building 2, Cnr Rutherford & Frikkie Meyer Boulevards Vanderbijlpark P.O. Box 6371, Vanderbijlpark, 1900 Tel: +27 (0) , Fax: +27 (0) vanderbijlpark@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 Registration Certificate number: 2004/HE07/004.

Procedural Programming

Procedural Programming Unit 18: Procedural Unit code: D/601/1293 QCF Level 4: BTEC Higher National Credit value: 15 Aim To provide learners with an understanding of the principles of procedural programming and to enable them

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Object Oriented Programming

Object Oriented Programming Unit 19: Object Oriented Unit code: K/601/1295 QCF Level 4: BTEC Higher National Credit value: 15 Aim To provide learners with an understanding of the principles of object oriented programming as an underpinning

More information

CS Exam 1 Review Suggestions

CS Exam 1 Review Suggestions CS 235 - Fall 2015 - Exam 1 Review Suggestions p. 1 last modified: 2015-09-30 CS 235 - Exam 1 Review Suggestions You are responsible for material covered in class sessions, lab exercises, and homeworks;

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Mathematics/Science Department Kirkwood Community College. Course Syllabus. Computer Science CSC142 1/10

Mathematics/Science Department Kirkwood Community College. Course Syllabus. Computer Science CSC142 1/10 Mathematics/Science Department Kirkwood Community College Course Syllabus Computer Science CSC142 Bob Driggs Dean Cate Sheller Instructor 1/10 Computer Science (CSC142) Course Description Introduces computer

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING Wednesady 23 rd March 2016 Afternoon Answer any FOUR questions out of SIX. All

More information

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl...

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl... Page 1 of 13 Units: - All - Teacher: ProgIIIJavaI, CORE Course: ProgIIIJavaI Year: 2012-13 Intro to Java How is data stored by a computer system? What does a compiler do? What are the advantages of using

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

Curriculum Map Grade(s): Subject: AP Computer Science

Curriculum Map Grade(s): Subject: AP Computer Science Curriculum Map Grade(s): 11-12 Subject: AP Computer Science (Semester 1 - Weeks 1-18) Unit / Weeks Content Skills Assessments Standards Lesson 1 - Background Chapter 1 of Textbook (Weeks 1-3) - 1.1 History

More information

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application Last Time v We created our first Java application v What are the components of a basic Java application? v What GUI component did we use in the examples? v How do we write to the standard output? v An

More information

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units. This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units. Introduction Overview Advancements in technology are

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Chapter 2: Java OOP I

Chapter 2: Java OOP I Chapter 2: Java OOP I Yang Wang wyang AT njnet.edu.cn Outline OO Concepts Class and Objects Package Field Method Construct and Initialization Access Control OO Concepts Object Oriented Methods Object An

More information

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) COE318 Lecture Notes: Week 3 1 of 8 COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) Announcements Quiz (5% of total mark) on Wednesday, September 26, 2012. Covers weeks 1 3. This includes both the

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Introduction Welcome! Before you start Course Assessments The course at a glance How to pass M257

Introduction Welcome! Before you start Course Assessments The course at a glance How to pass M257 Introduction Unit 1: Java Everywhere Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 Introduction Welcome! Before you start Course Assessments The course at a glance How to pass M257 1. Java background 2.

More information

Standard. Number of Correlations

Standard. Number of Correlations Computer Science 2016 This assessment contains 80 items, but only 80 are used at one time. Programming and Software Development Number of Correlations Standard Type Standard 2 Duty 1) CONTENT STANDARD

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

SELF-STUDY. Glossary

SELF-STUDY. Glossary SELF-STUDY 231 Glossary HTML (Hyper Text Markup Language - the language used to code web pages) tags used to embed an applet. abstract A class or method that is incompletely defined,

More information

System.out.print(); Scanner.nextLine(); String.compareTo();

System.out.print(); Scanner.nextLine(); String.compareTo(); System.out.print(); Scanner.nextLine(); String.compareTo(); Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 6 A First Look at Classes Chapter Topics 6.1 Objects and

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

COWLEY COLLEGE & Area Vocational Technical School

COWLEY COLLEGE & Area Vocational Technical School COWLEY COLLEGE & Area Vocational Technical School COURSE PROCEDURE FOR JAVA PROGRAMMING CIS1868 3 Credit Hours Student Level: This course is open to students on the college level in either freshman or

More information

Review sheet for Final Exam (List of objectives for this course)

Review sheet for Final Exam (List of objectives for this course) Review sheet for Final Exam (List of objectives for this course) Please be sure to see other review sheets for this semester Please be sure to review tests from this semester Week 1 Introduction Chapter

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

CO Java SE 8: Fundamentals

CO Java SE 8: Fundamentals CO-83527 Java SE 8: Fundamentals Summary Duration 5 Days Audience Application Developer, Developer, Project Manager, Systems Administrator, Technical Administrator, Technical Consultant and Web Administrator

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Week 7 - More Java! this stands for the calling object:

Week 7 - More Java! this stands for the calling object: Week 7 - More Java! Variable Scoping, Revisited this Parameter Encapsulation & Principles of Information Hiding: Use of public and private within class API, ADT javadoc Variables of class Type Wrapper

More information

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

S.E. Sem. III [CMPN] Object Oriented Programming Methodology S.E. Sem. III [CMPN] Object Oriented Programming Methodology Time : 3 Hrs.] Prelim Question Paper Solution [Marks : 80 Q.1(a) Write a program to calculate GCD of two numbers in java. [5] (A) import java.util.*;

More information

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Course Overview This course teaches programmers the skills necessary to create Java programming system applications and satisfies the

More information

Basics of Object Oriented Programming. Visit for more.

Basics of Object Oriented Programming. Visit   for more. Chapter 4: Basics of Object Oriented Programming Informatics Practices Class XII (CBSE Board) Revised as per CBSE Curriculum 2015 Visit www.ip4you.blogspot.com for more. Authored By:- Rajesh Kumar Mishra,

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System?

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System? Page 1 of 21 Page 2 of 21 and identity. Objects are members of a class, and the attributes and behavior of an object are defined by the class definition. The Essence of Object Oriented Programming with

More information

Introduction to Java

Introduction to Java Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus PESIT Bangalore South Campus 15CS45 : OBJECT ORIENTED CONCEPTS Faculty : Prof. Sajeevan K, Prof. Hanumanth Pujar Course Description: No of Sessions: 56 This course introduces computer programming using

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Distributed Software Applications

Distributed Software Applications Unit 40: Distributed Software Applications Unit code: M/601/1525 QCF Level 5: BTEC Higher National Credit value: 15 Aim To provide learners with an understanding of the principles of distributed computing,

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes CS111: PROGRAMMING LANGUAGE II Lecture 1: Introduction to classes Lecture Contents 2 What is a class? Encapsulation Class basics: Data Methods Objects Defining and using a class In Java 3 Java is an object-oriented

More information

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points. Java for Non Majors Final Study Guide April 26, 2017 The test consists of 1. Multiple choice questions 2. Given code, find the output 3. Code writing questions 4. Code debugging question 5. Short answer

More information

Module 10 Inheritance, Virtual Functions, and Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:

More information

CHAPTER 1: A GENERAL INTRODUCTION TO PROGRAMMING 1

CHAPTER 1: A GENERAL INTRODUCTION TO PROGRAMMING 1 INTRODUCTION xxii CHAPTER 1: A GENERAL INTRODUCTION TO PROGRAMMING 1 The Programming Process 2 Object-Oriented Programming: A Sneak Preview 5 Programming Errors 6 Syntax/Compilation Errors 6 Runtime Errors

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java.

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java. [Course Overview] The Core Java technologies and application programming interfaces (APIs) are the foundation of the Java Platform, Standard Edition (Java SE). They are used in all classes of Java programming,

More information

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on

More information

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.asp...

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.asp... 1 of 8 8/27/2014 2:15 PM Units: Teacher: ProgIIIAPCompSci, CORE Course: ProgIIIAPCompSci Year: 2012-13 Computer Systems This unit provides an introduction to the field of computer science, and covers the

More information

CT 229. CT229 Lecture Notes. Labs. Tutorials. Lecture Notes. Programming II CT229. Objectives for CT229. IT Department NUI Galway

CT 229. CT229 Lecture Notes. Labs. Tutorials. Lecture Notes. Programming II CT229. Objectives for CT229. IT Department NUI Galway Lecture Notes CT 229 Programming II Lecture notes, Sample Programs, Lab Assignments and Tutorials will be available for download at: http://www.nuigalway.ie/staff/ted_scully/ct229/ Lecturer: Dr Ted Scully

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

MARS AREA SCHOOL DISTRICT Curriculum TECHNOLOGY EDUCATION

MARS AREA SCHOOL DISTRICT Curriculum TECHNOLOGY EDUCATION Course Title: Java Technologies Grades: 10-12 Prepared by: Rob Case Course Unit: What is Java? Learn about the history of Java. Learn about compilation & Syntax. Discuss the principles of Java. Discuss

More information

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

CS112 Lecture: Defining Instantiable Classes

CS112 Lecture: Defining Instantiable Classes CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

College Board. AP CS A Labs Magpie, Elevens, and Picture Lab. New York: College Entrance Examination Board, 2013.

College Board. AP CS A Labs Magpie, Elevens, and Picture Lab. New York: College Entrance Examination Board, 2013. AP Computer Science August 2014 June 2015 Class Description AP Computer Science is the second class after Pre-AP Computer Science that together teach the fundamentals of object-oriented programming and

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 P a g e 1 CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 Q1 Describe some Characteristics/Advantages of Java Language? (P#12, 13, 14) 1. Java

More information

Java 1.8 Programming

Java 1.8 Programming One Introduction to Java 2 Usage of Java 3 Structure of Java 4 Flexibility of Java Programming 5 Two Running Java in Dos 6 Using the DOS Window 7 DOS Operating System Commands 8 Compiling and Executing

More information

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2) Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu

More information

CS 11 java track: lecture 1

CS 11 java track: lecture 1 CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Lecture Notes on Programming Languages

Lecture Notes on Programming Languages Lecture Notes on Programming Languages 85 Lecture 09: Support for Object-Oriented Programming This lecture discusses how programming languages support object-oriented programming. Topics to be covered

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

NEW YORK CITY COLLEGE OF TECHNOLOGY/CUNY Computer Systems Technology Department

NEW YORK CITY COLLEGE OF TECHNOLOGY/CUNY Computer Systems Technology Department NEW YORK CITY COLLEGE OF TECHNOLOGY/CUNY Computer Systems Technology Department COURSE: CST1201 Programming Fundamentals (2 class hours, 2 lab hours, 3 credits) Course Description: This course is an intensive

More information

Systems and Principles Unit Syllabus

Systems and Principles Unit Syllabus Systems and Principles Unit Syllabus Level 2 Creating an event driven computer program using Java 7540-007 www.cityandguilds.com October 2010 Version 2.0 About City & Guilds City & Guilds is the UK s leading

More information

CLASSES AND OBJECTS IN JAVA

CLASSES AND OBJECTS IN JAVA Lesson 8 CLASSES AND OBJECTS IN JAVA (1) Which of the following defines attributes and methods? (a) Class (b) Object (c) Function (d) Variable (2) Which of the following keyword is used to declare Class

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Internet Application Developer

Internet Application Developer Internet Application Developer SUN-Java Programmer Certification Building a Web Presence with XHTML & XML 5 days or 12 evenings $2,199 CBIT 081 J A V A P R O G R A M M E R Fundamentals of Java and Object

More information

Software Architecture (Lesson 2) Object-Oriented Paradigm (1)

Software Architecture (Lesson 2) Object-Oriented Paradigm (1) Software Architecture (Lesson 2) Object-Oriented Paradigm (1) Table of Contents Introduction... 2 1.1 Basic Concepts... 2 1.1.1 Objects... 2 1.1.2 Messages... 3 1.1.3 Encapsulation... 4 1.1.4 Classes...

More information

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

Scheme of work Cambridge International AS & A Level Computing (9691)

Scheme of work Cambridge International AS & A Level Computing (9691) Scheme of work Cambridge International AS & A Level Computing (9691) Unit 2: Practical programming techniques Recommended prior knowledge Students beginning this course are not expected to have studied

More information

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Object Oriented Concepts and Programming (CSC244) By Dr. Tabbasum Naz

Object Oriented Concepts and Programming (CSC244) By Dr. Tabbasum Naz Object Oriented Concepts and Programming (CSC244) By Dr. Tabbasum Naz tabbasum.naz@ciitlahore.edu.pk Course Outline Course Title Object Oriented Concepts and Course Code Credit Hours 4(3,1) Programming

More information

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

(800) Toll Free (804) Fax   Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days Course Description This course introduces the Java programming language and how to develop Java applications using Eclipse 3.0. Students learn the syntax of the Java programming language, object-oriented

More information

Core JAVA Training Syllabus FEE: RS. 8000/-

Core JAVA Training Syllabus FEE: RS. 8000/- About JAVA Java is a high-level programming language, developed by James Gosling at Sun Microsystems as a core component of the Java platform. Java follows the "write once, run anywhere" concept, as it

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information