Top Banner
Aunur R. Mulyanto SOFTWARE ENGINEERING Book 1 Vocational Education Directorate Technical and Vocational Education Directorate General of Management Education Basic and Middle Department of National Education Copy Right @Department of National Education All right reserve
171

Rekayasa perangkat lunak(Jilid2)

Dec 18, 2014

Download

Education

sekolah maya

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Rekayasa perangkat lunak(Jilid2)

Aunur R. Mulyanto

SOFTWARE ENGINEERING

Book 1

Vocational Education

Directorate Technical and Vocational Education Directorate General of Management Education Basic and MiddleDepartment of National EducationCopy Right @Department of National Education All right reserve

Page 2: Rekayasa perangkat lunak(Jilid2)

SOFTWARE ENGINEERING

Book 2

For Vocational Education

Author : Aunur R. Mulyanto Cover Design : Team Book Size : 17,6 x 25 cm

MUL MULYANTO,Aunur R. Software Engineering Book1 For SMK / by Aunur

R. Mulyanto ---- Jakarta : Directorate Technical and Vocational Education Directorate General for Basic and Middle Education Department of National Education, 2008. xiii. 158 pages Libraries : A1-A2 Glosarium : B1-B6 ISBN : 978-979-060-007-2 ISBN : 978-979-060-008-9

Published by: Directorate Technical and Vocational Education Directorate General Primary and Secondary EducationDepartment of National Education 2008

Page 3: Rekayasa perangkat lunak(Jilid2)
Page 4: Rekayasa perangkat lunak(Jilid2)

FOREWORD

We thank to Allah SWT, blessing and gift of His mercy, the Government, in this case, the Directorate of Development of Vocational High School of Directorate General of Primary and Secondary Education Management, Ministry of Education, has conducted the activities of the book trade as a form of purchase of copyright books text for students learning vocational SMK. Because textbooks vocational very difficult to get in on the market. Text book lesson this has been through the process of assessment by the National Education Standards as a text book lesson to SMK and have been declared eligible to be used in the feasibility of the learning process through the Ministry of National Education Regulation No. 45 Year 2008 on 15 August 2008.

We delivered the award at a high level to all the writers who have been well switch copyright works to the Ministry of National Education to be used widely by teachers and students SMK. Text book lessons that have been transferred the copyright to the Ministry of National Education is, can be downloaded , duplicated, printed, media transfer, or photocopy by the community. But for the multiplication of commercial sales price must meet conditions set by the Government. With the soft copy of this show will be easier for the public especially teachers and students of vocational school (SMK) in Indonesia as well as abroad to access and utilize as a reference.

We hope all parties can support this policy. To the students good luck in your study and hopefully can use this book as well as possible. We realize that this book still needs to be improved quality. Therefore, suggestions and criticisms are we expected.

Jakarta, 17 Agustus 2008

Director of Technical and Vocational Education

Page 5: Rekayasa perangkat lunak(Jilid2)
Page 6: Rekayasa perangkat lunak(Jilid2)

vi Software Engineering

EDITORIAL

With all humility, we give thanks to Allah SWT. Because only with patronage, blessing and gift of His mercy , then this book can be completed.

Book entitled 'Software Engineering' is organized to meet the needs handbook for students Vocational Education. Especially on the program expertise Software Engineering. This book includes a description refers to the standard of competence and basic competencies for Software Engineering students from SMK class X, XI to class XII.

Each chapter contains a theory must be understood correctly by students and accompanied by examples of problems that are relevant to the theory. In addition there is also a matter that is based on the concept and discussed the theory test as a tool to measure the ability of students in the control of these materials.

In developing this book, the author seeks to be the material that is presented in accordance with the needs of competency to be achieved. Therefore, apart from the result of thought and experience as writers and practitioners of Software Engineering, which developed the material with other appropriate reference

In this moment I wish to thank to all parties that support this book can be published. Hopefully this book can be useful for students in developing capabilities. The author realized that this book still needs to be developed continuously, so that the suggestions from various parties, this book is useful.

The Author,

Directorate Technical Vocational Education

Page 7: Rekayasa perangkat lunak(Jilid2)

vii Software Engineering

Table of ContentsFOREWORD....................................................................................................ivEDITORIAL......................................................................................................viHOW TO USE THIS BOOK...............................................................................xCHAPTER 6 ADVANCED PROGRAMMING ALGORITHM ..............................1

6. 1. MULTIDIMENSIONAL ARRAY..............................................................26.1.1. Concept of multidimensional array.................................................26.1.2. Matrix operation with Multidimensional Array ................................3

6.2. PROCEDURE AND FUNCTION............................................................66.3. SUMMARY.........................................................................................86.4. EXERCISE..........................................................................................8

CHAPTER 7 APPLICATION PROGRAMMIN USING VB & VB.NET ................97.1. Foundation of Visual Basic .................................................................10

7.1.1. Main GUI based programming principles.....................................147.1.2. Data type, Variable and Constant ................................................167.1.3. Operator ......................................................................................177.1.4. Control Program Structure...........................................................197.1.5. Procedure and Function...............................................................29

7.2. Access and Database Manipulation with Visual Basic.........................317.2.1. Create and Manipulate Database using ADO ..............................33

7.3. COM Technology.................................................................................357.3.1. COM Concept..............................................................................35

7.4. SUMMARY.......................................................................................367.5. EXERCISE........................................................................................37

CHAPTER 8 JAVA OBJECT ORIENTED PROGRAMMING ...........................398.1. OBJECT ORIENTED PROGRAMMING CONCEPT............................40

8.1.1. Abstraction...................................................................................418.1.2. Encapsulation..............................................................................418.1.3. Inheritance ..................................................................................418.1.4. Polymorphism .............................................................................42

8.2. INTRODUCTION TO JAVA..................................................................428.2.1. Software Requirement.................................................................428.2.2. Source Code Compilation............................................................43

8.3. DATA TYPE, VARIABEL, DAN INPUT/OUTPUT (I/O) STATEMENT...468.3.1. Data Type.....................................................................................468.3.2. Variable and Constant. ................................................................478.3.3. Input / Output ..............................................................................48

8.4. OPERATOR.........................................................................................498.4.1. Arithmetic Operator......................................................................498.4.2. Relational Operator......................................................................518.4.3. Logical Operator ..........................................................................52

Directorate Technical Vocational Education

Page 8: Rekayasa perangkat lunak(Jilid2)

viii Software Engineering

8.5. PROGRAM CONTROL STRUCTURE ................................................528.5.1. Selection Structure ......................................................................528.5.2. Looping Structure.........................................................................548.5.3. The use break and continue.........................................................55

8.6. EXCEPTION HANDLING....................................................................568.6.1. The understanding of Exception Handling ...................................568.6.2. Try and Catch ..............................................................................588.6.3. Throw ..........................................................................................598.6.4. Finally ..........................................................................................60

8.7. MULTI-THREADING............................................................................618.7.1. Concept of Thread ......................................................................618.7.2. Thread Creation and Usage ........................................................628.7.3. Multi-Thread ................................................................................63

8.8. OBJECT ORIENTED PROGRAMMING APPLICATION USING JAVA 658.8.1. Class Creation .............................................................................658.8.2. Application of Inheritance ............................................................718.8.3. Implementation of Overriding and Overloading ...........................748.8.4. Application of Polymorphism .......................................................778.8.5. How to use Package and Interface ..............................................79

8.9. SUMMARY..........................................................................................838.10. EXERCISES......................................................................................83

CHAPTER 9 APLICATION PROGRAM C++ ................................................859.1. BASIC C++ PROGRAMMING.............................................................86

9.1.1. Structure of C++ Program...........................................................879.1.2. Header File (.h) ...........................................................................889.1.3. Comment, Identifier and Data Type..............................................889.1.4. Operator ......................................................................................919.1.5. Control Program Structure...........................................................939.1.6. Input / Output ..............................................................................98

9.2. FUNCTIONS IN C++..........................................................................999.2.1. Function Types.............................................................................999.2.2. Using Parameter in Function .....................................................100

9.3. POINTER AND ARRAY .....................................................................1029.3.1. Concept and Understand Pointer ..............................................1029.3.2. Using New and Delete in Pointer................................................1049.3.3. Array ..........................................................................................105

9.4. CLASS ..............................................................................................1089.4.1. Class Declaration ......................................................................1089.4.2. Inheritance .................................................................................1109.4.3. Polymorphism ............................................................................112

9.5. OBJECT ORIENTED APPLICATION DESIGN ..................................1179.6. SUMMARY.........................................................................................119

Directorate Technical Vocational Education

Page 9: Rekayasa perangkat lunak(Jilid2)

ix Software Engineering

9.7. EXERCISE........................................................................................120CHAPTER 10 BASIC SYSTEM DATA BASE .............................................122

10. 1. DATA, DATA BASE AND DATABASE MANAGEMENT SYSTEM....12310.1.1. Database .................................................................................12310.1.2. Database Management System...............................................125

10.2. ENTITY-RELATIONSHIP DIAGRAM ...............................................13010.2.1. Entity .......................................................................................13110.2.2. Attribute ...................................................................................13210.2.3. Relationship ............................................................................134

10.3. RELATIONAL DATA BASE..............................................................13610.3.1. RELATIONAL DATA BASE MODEL........................................13610.3.2. Relational Database Structure.................................................13810.3.3. Inter Table Relationship............................................................140

10.4. SUMMARY.....................................................................................14610.5. EXERCISES....................................................................................146

REFERENCES..............................................................................................147APPENDIX 1 GLOSARY..............................................................................149APPENDIX 2 SITE LIST................................................................................154APPENDIX 3 FUNCTIONS BUILD-IN ON VISUAL BASE.............................156

Directorate Technical Vocational Education

Page 10: Rekayasa perangkat lunak(Jilid2)

x Software Engineering

HOW TO USE THIS BOOK

A. Global Description

This book is given the title "Software Engineering", together with one of the program expertise in the Vocational School (SMK). However, the actual contents of this book is not specifically discuss on Software Engineering. From the perspective of Computer Science field of five sub-areas covered in this book, the sub-field of Engineering Software, Operating System, Algorithm and Data Structure, Programming Languages and Database. This curriculum tailored to the level of expertise SMK Program for Software Engineering.

Main subject of Engineering Software in general, describe the basics of Software Engineering, and solving problems, and methods of software development. The discussion about the sub-field of Operating System contains a computer system, the system operating and working in the computer network. The scope of the material basic algorithms include algorithms and advance algorithms. Sub field Programming Languages take a big portion, including GUI programming with VB & VB.Net, Java programming, C + + programming, Programming of object-oriented and web-based. Sub-sector which is the last part of this book is a data base with the scope of the system databases, conceptual modeling, relasional database, Microsoft Access and SQL.

B. Competency Map

In general, this book refers to the Standard and Competence Basic Competency (SKKD) for Vocational School (SMK) as follows :

1. Using a basic level of programming algorithm 2. Using advanced programming algorithm 3. Operate the database application 4. Create an application-based Microsoft Access 5. Mastering the basic techniques electronics 6. Mastering the digital electronics technology 7. Create file with HTML according to specifications 8. Applying the basics of creating a basic level of static web 9. Make the application using VB and VB.NET 10. Make the software application package 11. Doing programming data description (Structured-SQL Query Language) basic level 12. Operates programming data description language (SQL) advanced 13. Create a web page dynamic basic levels 14. Create a web page more dynamic level

Directorate Technical Vocational Education

Page 11: Rekayasa perangkat lunak(Jilid2)

xi Software Engineering

15. Create a web application program using JSP Software Engineering 16. Make the application database using XML 17. Make a database program using Microsoft (SQL Server) 18. Make a database program using PL / SQL (Oracle) 19. Make the application using C + + 20. Explaining the system peripherals 21. Make the program in object-oriented programming language 22. Make the application using Java 23. Operate the computer operating system and text-based GUI

In this book, chapters not compiled based on SKKD, but the materials are developed based on the sequence of basic subject. So that in some chapters contain a mix of several standards of competence. Or a basic competency may not be on the competency standards groups such as SKKD on the list, but is on the other sub-chapters.

SKKD suitability and content of the chapter can be seen in the table below :

Competency Code Competency Relation

ELKA-MR.UM.001.A Mastering the basic techniques electronics 3

ELKA.MR.UM.004.A Mastering the digital electronics technology and Computer

3

TIK.PR02.001.01 Using a basic level of programming algorithm 5

TIK.PR02.002.01 Using advanced programming algorithm 6

HDW.OPR.103.(1).A Operate the computer operating system and text-based

4

HDW.OPR.104.(1).A Operate the computer operating system based GUI

4

TIK.PR02.020.01 Operate the database application 10 and 11

TIK.PR08.004.01 Create an application-based Microsoft Access 11

TIK.PR08.024.01 Create file with HTML according to specifications 13

TIK.PR08.027.01 Applying the basics of creating a basic level of static web

13

TIK.PR08.003.01 Make the application using VB and VB.NET 7

TIK.PR02.016.01 Make the software application package 7

TIK.PR03.001.01 Doing programming data description (Structured -SQL Query Language) basic level

12

TIK.PR03.002.01 Operates programming data description language 12

Directorate Technical Vocational Education

Page 12: Rekayasa perangkat lunak(Jilid2)

xii Software Engineering

(SQL) advanced

TIK.PR04.002.01 Create a web page dynamic basic levels 13

TIK.PR04.003.01 Create a web page dynamic advance levels 13

Competency Code Competency Relation

TIK.PR02.009.01 Operate the program in object-oriented programming language

8

TIK.PR08.012.01 Make application program using Java 8

TIK.PR08.001.01 Make application program using C++ 9

TIK.PR06.003.01 Describe Peripheral system 3

TIK.PR08.005.01 Make database using PL/SQL 10 and 12

TIK.PR08.006.01 Make database program using SQL server 12

TIK.PR08.008.01 Make JSP based we application web program 14

C. How to use this book

This book is specifically aimed at students and teachers for the vocational school (SMK) expertise in RPL. However, this book is also open for general readers who are interested in the RPL, Algorithm and Programming, Database and the Internet. For students, this book can be a handbook, because this book is to provide learning materials that are complete enough for the subjects for three years at the school. Some parts of this book may need books to help enrich more insight and capacity building. Whereas for teachers, this book can be used as reference books to prepare teaching modules for the students. This book is structured in such a way so that students can independently learn and encourage to try. Therefore, in this book, many will be found either in the form of illustration image, the scheme and program listings. This is so that students can easily understand the explanation or the application of a particular concept. The chapter will be ended with exercise of the subject.

Directorate Technical Vocational Education

Page 13: Rekayasa perangkat lunak(Jilid2)

xiii Software Engineering

Directorate Technical Vocational Education

Page 14: Rekayasa perangkat lunak(Jilid2)

1 Software Engineering

CHAPTER 6 ADVANCED PROGRAMMING ALGORITHM

I am sure most of you have seen the notation in Figure 6.1. Yes, it is an general mathematical notation used in Matrix. Matrix operation is an operation that used in many calculation activities. Please review your mathematical course / book that discuss matrix, you'll see a lot of things may be calculated by using matrix.

Have you ever heard MATLAB software? This software is based on mathematical operation and very popular among scientist, engineer and those who do lots of calculation. By using array, ypu can create a program to carry out matrix operation as in MATLAB.

The standard of competence in advanced programming algorithm consists of four (4) basic competences, namely, the use of array multidimensional, the use of procedure and function. In this book, each basic competence contains the material and exercise. The summary is at the end of each chapter. Before studying this competence, please review the principle of problem solution, the foundation of programming algorithm and supporting materials such as mathematics.

At the end the chapter has been included exercises compiled from the easiest to difficult level. These exercises is used to measure the capacity in this basic competence. Thus, after studying this basic competence either through teacher's guidance as well as self-study, one may evaluate one's capacity by completing the exercise.

OBJECTIVES

After studying this chapter, it is hoped you could:

● Use multidimensional array.● Use procedure and function

Directorate Technical Vocational Education

Figure 6.1. Matrix notation.

Page 15: Rekayasa perangkat lunak(Jilid2)

2 Software Engineering

6. 1. MULTIDIMENSIONAL ARRAY

6.1.1. Concept of multidimensional array

One dimensional array as described in Chapter 5 is good to store similar sequential data, but how can we simultaneously keep list of cities with its respective temperature , or student's name and their respective final exam mark? In this case, we may use two one dimensional arrays, one array to store student's name, and one array to store student's mark. However, it is not a good choice as it makes more difficult to create a efficient program. The better choice would be using a multidimensional array. In such problem, we may store the data in two dimensional array. Examine figure to see the difference between two one dimensional arrays and two dimensional array.

Nama(4) Nilai(4) NilaiSiswa (4,1) Joni 70 0 Joni 70 Rudi 80 1 Rudi 80 Sari 45 2 Sari 45 Dono 56 3 Dono 56 Indro 77 4 Indro 77 Dua array satu dimensi Array dua dimensi

Figure 6.2. The difference between one dimensional array and two dimensional.

Two dimensional array has two indexes. The first index indicates the row whereas the second index indicates the column. In Figure 6.2, variable array NilaiSiswa has two indexes, namely, the first index with 4 indicates the maximum index value for the row is 4 (or there will be 5 row as row index starts at 0), while the second index with 1 indicates that the maximum number of column is 1(or there will be 2 column as the first column index is 0). To declare a two dimensional array may be use the following

Dim NilaiSiswa(4,1)

Whereas to access the value in array two dimensions could be used the following example.

Example 6.1. Read value from a multidimentional array

Print NilaiSiswa (3.0)Print NilaiSiswa (3.1)

The first statement in Example 6.1 will produce “Dono” (the 4th row and the first column) whereas the second statement produced output 56 (the 4th row and second column).

Directorate Technical Vocational Education

Page 16: Rekayasa perangkat lunak(Jilid2)

3 Software Engineering

One of the main advantage in using multidimensional array is a conceptually easier to managed. For example, if we want to create a game program and want to locate a place on a game board. Each square may be identified by using two numbers, as vertical and horizontal coordinate (or row and column). Such structure is a typical two dimensional array. Horizontal coordinate is the row index, while vertical coordinate is the column index. Multidimensional array may be expanded to more than two dimensional. In statement Dim Matrix (9,9,9) will create multidimensional arrays with 1000 elements (10x10x10).

6.1.2. Matrix operation with Multidimensional Array As being described in the beginning of this chapter, we could use an array to carry out matrix operations. Examine the following Figure 6.3.

Figure 6.3 shows a two two dimensional matrix consists of 4 row and 3 column, normally noted as A4x3. This is a multidimensional array multidimensional defined as A (3, 2). Note that the array indexes is one number smaller than the actual array as index starts with 0. Whereas the matrix's index starts at 1. To create an array or matrix such as in Figure 63, we need a repetition structure. For structure may be used as we know exactly how many row and column of the array. The following picture in Figure 6.3 shows the flowchart to create a matrix.

In Figure 6.4, there are two (2) counter variables namely I and J. I is used to index the row with 4 rows (1 to 4), whereas J is used to index the column that is 3 columns (1 to 3). Data reading will be as follows:

A(1,1) = .... A(1,2) = .... A(1,3) = .... A(2,1) = .... A(2,2) = .... A(2,3) = .... etc.

Directorate Technical Vocational Education

Figure 6.3. Matrix 4 x 3.

Page 17: Rekayasa perangkat lunak(Jilid2)

4 Software Engineering

Figure 6.4. Algorithm to create matrix 4 x 3.

Example 6.2. Add matrix operation.

Note the following matrix operation:

The above matrix operation is an adding operation of two matrix with the same dimension 3 x 3. How is the algorithm?

The solution:

Directorate Technical Vocational Education

Page 18: Rekayasa perangkat lunak(Jilid2)

5 Software Engineering

In the example, there are two matrices, namely, matrix A and matrix B. In addition, we need the third matrix C to store the sum of matrix A and matrix B. Figure 6.5 shows the algorithm to add two matrices.

Figure 6.5. Algorithm to add two (2) matrices

Directorate Technical Vocational Education

Page 19: Rekayasa perangkat lunak(Jilid2)

6 Software Engineering

6.2. PROCEDURE AND FUNCTION

Each programming language always provides built-in functions that have been defined by the programming language. However sometimes we need a certain procedures that will be used repeatedly and not available in built-in function.

Procedure is a collection statements as part of a larger program that does a certain task. The procedure also known as subroutine / subprogram is relatively independent on other part of the program. The advantages of using procedure are:

● Reduce code duplication.● Provide possibility to re-use the code for other program.● Breakdown a big problem into smaller parts and, thus, easier to solve. Please

see problem reduction principles in Chapter 2.● Make a code easier to read.● Hide program details.

In flowchart, procedure is written using Predefined Process notation (see Chapter 5 for flowchart notation). The use of procedure is schematically shown in Figure 6.6.

The picture 6,6. showed had the main process that happened and had the actual procedure was part of this main process. When the main process needs a certain task then it calls certain procedure to complete the task. Examine the following example:

Figure 6.6. Schematics in procedure usage. Example 6.3. Procedure.

Create an algorithm to calculate the area of triangle, square and circle.

The solution:

To create this algorithm we should look into the area calculation process of the triangle, square and circle as an independent program part. We could create procedure for respective processes and call it from the main process as shown in Figure 6.7.

Directorate Technical Vocational Education

Page 20: Rekayasa perangkat lunak(Jilid2)

7 Software Engineering

Figure 6.7. Solution for Example 6.3

Process sequence of Figure 6.7 is as follows.

● Read data.● Main process to check input data.● If input data is for triangle, then main process will call triangle area calculation

procedure with the needed input variable for the procedure.● Area calculation of triangle is performed within the procedure.● As the area calculation completed, the final result is passed back into the main

process to be print.

Similar process sequence is the same for square and circle.

Directorate Technical Vocational Education

Page 21: Rekayasa perangkat lunak(Jilid2)

8 Software Engineering

A good procedure has the followings characteristics.

● logically inherent – has only one function – a good procedure has only one aim and not mixed with other functions. Thus, the procedure can be more focused and able easily to reach the aim.

● Independent – does not depend on the other procedure - a procedure must be able to run and tested without having to wait for other part of the program to be finished. Moreover variables used in this procedure are not influencing other variables in the whole program.

● Small size – the code size is short. Short code is easier to read and to fix. A long module should be considered to be broken into smaller modules.

6.3. SUMMARY

● Two dimensional arrays has two indexes. The first index indicates the row whereas the second index indicates column.

● Data reading and writing in multidimensional array is directly carried out by pointing to the index number.

● Procedure is a collection statements as part of a larger program that only does a certain task.

6.4. EXERCISE

1. Examine Example 6.1. Create an algorithm to do subtraction on two matrices.2. Create an algorithm to multiply two matrices.3. Using procedure create an algorithm to read matrix data then select the

operation whether addition, subtraction or multiplication of two matrices.

Directorate Technical Vocational Education

Page 22: Rekayasa perangkat lunak(Jilid2)

9 Software Engineering

CHAPTER 7 APPLICATION PROGRAMMIN USING VB & VB.NET

Figure 7.1. Application made by Visual Basic.

Examine Figure 7.1, it an application to show a table of collection of data. Someday you may find such application. The above application may be quickly made by using Visual Basic, without any difficulties in handling table, menu, button etc. All we need to do is click, drag, placed, arrange position then do a little bit of coding, an application may be made.

The standard of competence in programming with VB and basic VB.Net consists of three (3) basic competences. In this book, each basic competence contains the material, and the exercise. The summary is written at the end of each chapter and followed by exercise. In this chapter, the basic competence covers Visual Basic foundations, data access and manipulation in Visually Basic, and applying COM technology. Prior to study this competence, please review the operation system, the principle of problem solving, the programming algorithm as well as supporting materials especially mathematics.

THE OBJECTIVES

After studying this chapter, the reader is hoped to be able to:

● Explain on the foundation of Visual Basic.● Data access and manipulation using Visual Basic.● Applying COM technology.

Directorate Technical Vocational Education

Page 23: Rekayasa perangkat lunak(Jilid2)

10 Software Engineering

7.1. Foundation of Visual Basic Visually Basic (VB) is one of the computer's programming. The VB programming language, that was developed by Microsoft since 1991, is the development from its predecessor namely BASIC programming language (Beginner’s All-purpose Symbolic Instruction Code) that was developed in the 1950 's. VB is one of the development tool in Windows environment. In developing application, Visual Basic uses Visual approach to design the form of user interface, whereas the coding uses Basic language that is very easy to study. Visually Basic is becoming a famous tool for both beginners and developers. However, the major drawback of VB is in its slow performance as compared to other programming language. Although, using current fast processors and large memory, such problem is no longer important.

Visually Basic is run on Microsoft Windows operation system. To start Visual Basic, we need to select Start -> Programs -> Microsoft Visual Studio 6 -> Microsoft Visual Basic. The starting early Visual Basic will appear like the Picture 7,2.

Figure 7.2. Starting Page of Visual Basic.

In Figure 7.2, we are asked to select the type of project that will be built. For a beginner, standard project .EXE is a good choice. After selecting Standard .EXE, we will see the following page.

Directorate Technical Vocational Education

Page 24: Rekayasa perangkat lunak(Jilid2)

11 Software Engineering

Figure 7.3. Starting page for Standard.EXE.

Prior to work with Visual Basic, it would be a good idea to know the working environment (IDE) of Visual Basic. The Visual Basic IDE (Integrated Development Environment) is the integrated environment within which a programmer is developing their application. Using IDE, a programmer may create interface, do coding, carry out testing and debugging as well as compile the program into executable. A good understanding of IDE will help the programmer to make their job more efficient. Figure 7.4 shows the Visual Basic IDE.

Directorate Technical Vocational Education

Page 25: Rekayasa perangkat lunak(Jilid2)

12 Software Engineering

Figure 7.4. Visual Basic IDE

● Menu Bar, used to select certain task such as save project, open project etc.

● Main Toolbar, used quickly invoke certain task.

● Project Window, shows all modules in your application. You may use icon Toggle Folders to show modules in the windows in a group or sort based on

Directorate Technical Vocational Education

Page 26: Rekayasa perangkat lunak(Jilid2)

13 Software Engineering

name. You may use Ctrl+R to show project windows, or use icon Project Explorer.

● Form Designer Window is where you may design the user interface of your application. The windows is like canvas for a painter.

● Toolbox Window contains the components that could be used to develop user interface.

● Windows Code is where you write your code. You may active the windows using Shift-F7.

● Properties Window lists object properties that being used. For example, you may change the foreground color and the background color. You may invoke the Properties Windows using F4 button.

● Color Palette window is a short cut facility to change object color.

● Form Layout window shows particular form during run-time.

Toolbox Window is an important windows. From Toolbox Windows, you may select the objects in form to built the user interface.

● Pointer is not a control tool; use Pointer icon to select existing control in the form.

● PictureBox is a control to show image using format: BMP, DIB (bitmap), ICO (icon), CUR (cursor), WMF (metafile), EMF (enhanced metafile), GIF, and JPEG.

● Label is a control to show fixed texts.

● TextBox is a control that contains string that could be changed by the user. It can be single or multiple lines.

● Frame is a control that used as container for other control.

Directorate Technical Vocational Education

Figure 7.5. Toolbox in VB 6.

Page 27: Rekayasa perangkat lunak(Jilid2)

14 Software Engineering

● CommandButton is a control that can be found in almost every form, and may be used to trigger an certain process event as clicked by the user.

● CheckBox is used to provide selection process, such as, yes / no, true / falses.

● OptionButton is often used to provide options on certain selection.

● ListBox contains user selectable items. More than one item may be selected depending on the property of MultiSelect.

● ComboBox is a combination between TextBox and ListBox where input data may be carried out using typing or selection.

● HScrollBar and VScrollBar is used to create a stand alone scrollbar.

● Timer is to active background process in a specific interval. It is non-visual control.

● DriveListBox, DirListBox, and FileListBox is often used to create dialog box related to files.

● Shape and Line is present form, such as, line, square, circles, oval.

● Image function similar to image box, but could not be used as container for other control. It is interesting to know that control image uses much lower resource than PictureBox.

● Data is used for data binding.

● OLE may be used to link to external programs, such as, Microsoft Excel, Word, etc.

7.1.1. Main GUI based programming principles. In principle there are two main parts in the application development using VB, that is: visual design and event-driven programming.

Visual Design

In Windows environment, user-interface plays an important role, as the application will have to interact with users via user-interface without realizing that it is supported by instruction program to support the visual interface and the process. In Visual programming, application development starts with user interface creation. To design user interface, the most needed knowledge is only the understanding of type and usage of control and basic knowledge on how to draw an object.

Directorate Technical Vocational Education

Page 28: Rekayasa perangkat lunak(Jilid2)

15 Software Engineering

Form and control is the basic user interface elements of Windows based applications. In VB, these elements are known as object as it may be manipulated similar to an object. An object is a combination of code and data that could be treated as one entity. An object has a certain properties and methods, and will react to some external events such as physical objects.

As shown in Figure 7.6, a car is a physical object that has property, method and event. One of its property is color. Car's color property is usually determined prior to its fabrication. If we don't like the color of our car, we can always change it by re-painting the car. Similarly in VB, property of a control is usually determined when object was made (when put in one form), but we may change the property by giving new value. We may change property's value during design process via Properties windows or during run time through program code. Some properties are only available during design time, some available during runtime.

Figure 7.6. Object, Property, Method and Event

Directorate Technical Vocational Education

Page 29: Rekayasa perangkat lunak(Jilid2)

16 Software Engineering

Event-Driven Programming

Application programming is not easy, we should follow a methodology. The application program made with VB is not a monolithic program that has only one sequential pass. When we create a program using VB, we must first determine the user interaction of the application. Or in other words, we must define the reaction of every action taken by te user, such as, mouse click, mouse double-click, keyboard button, and so on. This concept is known as Event-Dri ven Programming, because program flow is decided by an event triggered by the user. Our application program must react to the external condition / event, and user action defines the program flow.

7.1.2. Data type, Variable and Constant In general, data type, variable, and constant in Visual Basic is not different than that described in Chapter 5. Please review Chapter 5 to provide some idea on this topics. The main different is in the declaration syntax. Examine the following example.

Example 7.1. Declaration example of variable, constant, and data type.Dim speed As Double Dim timeElapsed As Double Dim NumberStudent as Integer = 10 Dim velocity as Single Dim Nama as String Const phi as Single = 3.14

In Example 7.1, variable is declared using Dim while constant is declared Const. We can also set the initial value of a variable right after its data type declaration.

One of benefit if using GUI based programming such as Visual Basic is the availability of objects that could be treated as data type. Examine the following example.

Example 7.2. Example object data type usage.Dim frm As Form Dim midfrm As MDIForm Dim ctrl As Control Dim obj As Object Dim inv As frmInvoice Dim txtSalary As TextBox Dim wrk As Excel.Worksheet In the above Example 7.2, the Form statement, MDIForm, Control and Object are the controls owned by Visual Basic. Whereas frmInvoice is the form made by us the programmer and named frmInvoice. Visual Basic enables us to use object from outside Visual Basic. Examine the above last line. We use Excel worksheet in our program.

Directorate Technical Vocational Education

Page 30: Rekayasa perangkat lunak(Jilid2)

17 Software Engineering

7.1.3. Operator

Operator is a symbol used in programming language to carry out an operation against data. Operator's symbol may be a character or certain word. In Visual Basic, there are three (3) main operator groups, namely, arithmetics operator, comparative operator and logic operator.

● Arithmetics Operator

Arithmetics operator is used to perform mathematical operation on data. Arithmetics operator notation is shown in the following table.

Tabel 7.1. Arithmetics Operator

Symbol Mathematical operation Example

^ power 5 ^ 2 result 25

* multiplication 5 * 2 result 10

/ divide 5 / 2 result 2.5

\ divide 5 \ 2 result 2

Mod Remains of division 5 Mod 2 result 1

+ addition 5 + 2 result 7

- subtraction 5 – 2 result 3

& string combining 5 & 2 result 52

Notation / symbol for this operator has a hierarchical level, meaning that if two or more operator are used together, then the operator with higher hierarchy would be executed first before the lower hierarchy. The hierarchical level from the highet is as follows ^, * and/,\, mod, + and -. The operator * and / is equal level. Likewise the operator + and -. Examine the following example.

Example 7,3. Example of the hierarchical of Arithmetics operator.

5 * 2 + 3 = 13 4 ^ 2 - 5 = 11

In the first example, the sign * (multiplication) has a higher level than + sign (addition) so that multplication operation is carried out before the adding. The result is 10 plus 3, not 5 times 5. While in the second example, sign ^ (power) has a higher level than – (subtraction) so that the result would be 11 (from 16 minus 5). To change the

Directorate Technical Vocational Education

Page 31: Rekayasa perangkat lunak(Jilid2)

18 Software Engineering

arithmetic sequence, it may be done by using parentheses. Examine the following example.

Example 7.4. The example of parentheses usage to arrange hierarchical operator.

5 * (2 + 3) = 254 ^ (2 – 5) = 0,015625

In this example, we use the same numbers and operators as the previous example, but using parentheses to change calculation sequence. In the first example, the first process is adding 2 and 3, then multiply by 5. The final result is 25, as compared with the previous example, that is 13. In Example two, the first process is 2 minus 5 then used as power of 4, i.e., 4 ^ 3. The result is 0,015625, big different from the previous result that is 11. From the two examples, it could be seen that parentheses have a higher level than arithmetics operator. If there is more then one parenthesis then the most inner parentheses will be processed first. Examine the following example.

5 * ((2 + 2) / 8 ) = 2,5

● Comparative Operator

Comparative Operator is used to do data comparison operation. Symbol used are as follows.

Table 7.2 Comparative Operator

Symbol Comparative Operator Example

< Less then 5 < 2 results FALSE

> Larger than 5 > 2 results TRUE

<= Less then or equal 5 <= 2 results FALSE

>= Larger then or equal 5 >=2 results TRUE

= equal 5 =2 results FALSE

<> Not equal 5 <> 2 results TRUE

● Logical Operator

Logical operator is used to compare two comparisons. Symbol used are as follows.

Table 7.3. Logical operator

Directorate Technical Vocational Education

Page 32: Rekayasa perangkat lunak(Jilid2)

19 Software Engineering

Symbol Logical Operator Example

Or Atau (5<2) Or (5>2) results TRUE

And Dan (5<2) And (5>2) results FALSE

Not Tidak Not (5<2) results TRUE

7.1.4. Control Program Structure Control program structure also known as control structure is an implementation of algorithm for branching structure and looping structure. Please review Chapter 5 for algorithm structure.

● Branching Structure

Branching Structure in Visual Basic may be done by using If... Then and Select... Case. When there is not too many branches, If... then may used. Whereas Select... Case is used in the case of many branching. Please examine the following example of using If ... Then.

Example 7.5. If .. Then.

' Single line branching without Else If x > 0 Then y = x

' Single line branching with Else If x > 0 Then y = x Else y = 0

' Single line branching with : and Else If x > 0 Then y = x: x = 0 Else y = 0

' Branching written in more than one line If x > 0 Then y = x x = 0 Else y = 0 End If

' Using Block IF If x > 0 Then y = x ElseIf x < 0 Then y = x * x Else

Directorate Technical Vocational Education

Page 33: Rekayasa perangkat lunak(Jilid2)

20 Software Engineering

x = -1 End If

Example 7.6. Select ... Case.

Dim position As Integer 'Pilihan position = CInt(txtPosition.Text) Select Case position Case 1 txtOutcome.Text = "Menang" Case 2 txtOutcome.Text = "Kalah" Case 3 txtOutcome.Text = "Seri" Case Else txtOutcome.Text = "Tidak bertanding." End Select

Examine the following application of using If... Then and Select... Case.

Example 7.7. Application program with if... then.

Activate VB 6 then create a form as follows.

Arrange properties for the following respective objects.

Directorate Technical Vocational Education

Page 34: Rekayasa perangkat lunak(Jilid2)

21 Software Engineering

Open code windows and using the code editor write the source code as follows.

Private Sub Command1_Click() If Text1.Text = "nusantara" Then Image1.Visible = True End Sub

Click on menu Project > Project1 Properties then click General tab. Change the Startup Object to Form 5. Try to run Project1:

● Type any text in the TextBox then click OK or press Enter, there will be nothing.● Type “nusantara” in TextBox then click OK or press Enter, a computer picture

will emerge.

Code explanation:

Modified the source code as follows

Private Sub Command1_Click() If Text1.Text = "nusantara" Then Image1.Visible = True Text1.Enabled = False Command1.Enabled = False Else

Directorate Technical Vocational Education

Page 35: Rekayasa perangkat lunak(Jilid2)

22 Software Engineering

MsgBox "Passwordnya Salah !" Text1.Text = "" Text1.SetFocus End If End Sub

Try re-run Project1:

● Type any text in TextBox then click OK or press Enter, shown a box with text “Passwordnya salah! ”.

● Type “nusantara” in TextBox then the click OK or press Enter, a computer picture will emerge. TextBox and OK switch is disabled and cannot be used.

Source code explanation:

Additional notes:

● The text “nusantara” must be in lower case. Remember: data string is case sensitive!

● To make password not case sensitive, modify the following statement using.

If LCase (Text1.Text) = "nusantara" Then

LCase fuction is to convert all string in Text1.Text to lower case, although user may input it in capital letters.

Example 7.8. Application program with Select... Case.

Activate VB 6 through Start button, then create the following Form.

Directorate Technical Vocational Education

Page 36: Rekayasa perangkat lunak(Jilid2)

23 Software Engineering

Set properties for each object as follows.

Open code windows and in the code editor type the source code as follows.

Private Sub Form_Load() List1.AddItem "Disket" List1.AddItem "Buku" List1.AddItem "Kertas" List1.AddItem "Pulpen" End Sub Private Sub Command1_Click() Dim harga As Currency, total As Currency Dim jumlah As Integer Dim diskon As Single Dim satuan As String If List1.Text = "" Then MsgBox "Anda belum memilih barang !!"

Directorate Technical Vocational Education

Page 37: Rekayasa perangkat lunak(Jilid2)

24 Software Engineering

List1.ListIndex = 0 Exit Sub End If If Text1.Text = "" Then MsgBox "Anda belum mengisi jumlah barang !!" Text1.SetFocus Exit Sub End If Select Case List1.Text Case "Disket" harga = 35000 satuan = "Box" Case "Buku" harga = 20000 satuan = "Lusin" Case "Kertas" harga = 25000 satuan = "Rim" Case "Pulpen" harga = 10000 satuan = "Pak" End Select lblBarang.Caption = "Barang : " & List1.Text lblHarga.Caption = "Harga : " & Format(harga, "Currency") & "/" & satuan lblJumlah.Caption = "Jumlah : " & Text1.Text & " " & satuan jumlah = Text1.Text Select Case jumlah Case Is < 10 diskon = 0 Case 10 To 20 diskon = 0.15 Case Else diskon = 0.2 End Select total = jumlah * (harga * (1 - diskon)) lblDiskon.Caption = "Diskon : " & Format(diskon, "0 %") lblTotal.Caption = "Total Bayar : " & Format(total, "Currency") End Sub

Click on menu Project > Project1 Properties then click General tab. Change Startup Object into Form6.

Directorate Technical Vocational Education

Page 38: Rekayasa perangkat lunak(Jilid2)

25 Software Engineering

Please run Project1:

● List1 will be filled by name of items.● Click OK, will be shown message box "Anda belum memilih barang!!"● Click OK, the first item will be automatically selected. You may select other

items.● Click OK, will be shown message box “Anda belum mengisi jumlah barang!!!”● Click OK, text1 will be the focus. Fill in the number of goods, for example: 10● Clok OK, will shows item name, item price per unit, total item with its unit,

discount and total price.● Please change the name of items (in List 1) and total item (in Text1) then click

OK.

Source code explanation:

Directorate Technical Vocational Education

Page 39: Rekayasa perangkat lunak(Jilid2)

26 Software Engineering

Note:

● If the total item fills with other than numbers, an error message will be shown.● To check whether Text1 is number only, add the following code:

If Not IsNumeric(Text1.Text) Then MsgBox "Isi jumlah barang harus angka !!" Text1.SetFocus Exit Sub End If

● Loop Structure.

The mainly used loop structure in Visual Basic is For structure. In Visual Basic, the structure for this is known as For... Next. In general, the code is For... Next is as follows.

Directorate Technical Vocational Education

Page 40: Rekayasa perangkat lunak(Jilid2)

27 Software Engineering

For counter = nilaiAwal To nilaiAkhir [Step increment] ' pernyataan yang akan diulang... Next

The Step and increment statement may be reviewed in Chapter 5 and will not be discussed here. Examine the use of For .. Next in the following application.

Please examine the following For... Next

Example 7.9. Repetition using For ... Next.

Dim d As Single, count As Long For d = 0 To 10 Step 2 count = count + 1 Next Print count

In Example 7,9, d is counter and we declare as single. We may use increment as 2. Increment value may be integer or floating point. However, floating point value sometimes give error results. How is the output from the program above? At the end the program, count value will be 5.

More flexible Loop structure then For .. Next is Do... Loop. Do... Loop could have different form. Examine the following example.

In Example 7.10. loop using For... Next.

Do While x > 0 y = y + 1 x = x \ 2 Loop

Do y = y + 1 x = x \ 2 Loop Until x <= 0

In the first part of the Example 7.10 we use Do While... Loop. This is the same as While structure discussed in Chapter 5. The statement within Do While, will be executed if the condition to Do While is true.

The second part of Example 7,10, we use Do... Loop Until to do the looping. In this form to carry out the loop. In this form, looping is carried out until the Loop Until condition is true. Thus, as long as the Loop Until condition is false, loop will always be carried out. In other word, Do .. Loop is the opposite of Do While. Examine these two

Directorate Technical Vocational Education

Page 41: Rekayasa perangkat lunak(Jilid2)

28 Software Engineering

sections, if we initialize x = -4 and Y = 5, how is the result? In Do While, it will not give result as X less than 0 and looping is not carried out. Whereas in Do... Loop Until, the statement under Do will be executed. So that X value will be -2 and Y is 6.

The following is the application program example using a loop structure.

Example 7.11. Application program with loop structure.

Open VB and create the following form.

Set properties as shown in the following table.

Directorate Technical Vocational Education

Page 42: Rekayasa perangkat lunak(Jilid2)

29 Software Engineering

Open windows code and in the Code Editor, type the following source code.

Dim i As Integer Private Sub Command1_Click() List1.Clear For i = 1 To 100 List1.AddItem "Angka " & i Next i End Sub Private Sub Command2_Click() List1.Clear For i = 100 To 1 Step -2 List1.AddItem "Angka " & i Next i End Sub Private Sub Command3_Click() List1.Clear i = Asc("A") Do Until i > Asc("Z") List1.AddItem "Huruf " & Chr(i) i = i + 1 Loop End Sub Private Sub Command4_Click() List1.Clear i = Asc("Z") Do While i >= Asc("A") List1.AddItem "Huruf " & Chr(i) i = i - 1 Loop End Sub

Run the program Press the four buttons in the form one at a time. Examine the output of the program.

7.1.5. Procedure and Function

There are several type of procedures used in Visual Basic:

● Sub procedure with no return value.● Function procedure that returns value.● Property procedure that could return the value and that refers to an object.● Sub procedure

Directorate Technical Vocational Education

Page 43: Rekayasa perangkat lunak(Jilid2)

30 Software Engineering

Syntax of sub procedure

[Private|Public][Static]Sub procedurename (argumen-argumen) statements End Sub

Every time procedure is called, then statements between Sub and End Sub will be executed. The procedure's argument is a value passed during calling the procedure.

In Visual Basic, Sub Procedure can be split into two, namely,

● General Procedure, activated by the application.● Event Procedure, activated by the system as to the response to event.

Example 7.12. Example of Sub procedure

In this example, we will create a sub procedure called CenterForm to show a half screen form, where x is the parameter in form of a form in the middle of the screen.

Sub CenterForm(x As Form) x.Top = (Screen.Height - x.Height) \ 2 x.Left = (Screen.Width - x.Width) \ 2 End Sub

‘memanggil sub prosedur CenterForm Private Sub Form_Load() Call CenterForm(Me) End Sub

In Example 7.12, the sub procedure CenterForm needs the argument form. So that to call the sub procedure, one needs to include the argument. Examine the line that call CenterForm (Me). Me is the argument from sub procedure. In Visual Basic, Me refers to form where the source code is made.

• Function procedure

There are two kind of functions in Visual Basic, namely, Built-in Function and Function Procedure. In Visual Basic, many Built-in Functions are available for many purposes, such as, mathematical calculation, string manipulation, data type manipulation etc. In this section, we will discuss more detail on the built-in function. In the appendix, some frequently used built-in function is listed.

Although there are quite large collection of built-in functions, these functions are fairly general and may not suite programmer specific needs. Thus, for specific needs, we may create our own Procedure Function or we may create our own function.

Directorate Technical Vocational Education

Page 44: Rekayasa perangkat lunak(Jilid2)

31 Software Engineering

Syntax of procedure function is

[Private|Public][Static]Function procedurename (argumen-argumen) [As type] statements End Function

There are were three differences between function and procedure:

● In general, you could call a function by using function name on the right hand side in a statement of expression (returnvalue = function ()).

● Function has same data type as a variable. It sets the return data type.● The return value is put into its function name, and some function may be part

of a long expression.

Please examine the following function.

Example 7.13. Function Example.

The following function is to show the name of month in Indonesian from the input date. The needed input argument is x with data type as date.

Function Bulan(x As Date) Dim sRet As String Select Case Month(x) Case 1: sRet = "Januari" Case 2: sRet = "Februari" Case 3: sRet = "Maret" Case 4: sRet = "April" Case 5: sRet = "Mei" Case 6: sRet = "Juni" Case 7: sRet = "Juli" Case 8: sRet = "Agustus" Case 9: sRet = "September" Case 10: sRet = "Oktober" Case 11: sRet = "Nopember" Case 12: sRet = "Desember" Case Else sRet = "tidak sah" End Select Bulan = sRet End Function

7.2. Access and Database Manipulation with Visual Basic

Directorate Technical Vocational Education

Page 45: Rekayasa perangkat lunak(Jilid2)

32 Software Engineering

One of the advantage of Visual Basic is in its ability to access and manipulate database since Visual Basic is developed by Microsoft that also made the Windows operating system. Thus, it has a quite complete set of support for database functionality.

Visually Basic provides many ways to access and to manipulate data. Examine the following figure.

Figure 7.7. Many ways to access database in Visual Basic.

● ODBC

ODBC, short for Open Data Base Connectivity, is a collection of functions that permit us to connect local or network database. ODBC is usually used to access various types of the database including, Ms FoxPro, Ms Access, Ms SQL Serve, Oracle or even data in raw data file format.

● DAO

DAO, short for Data Access Object, is the interface for Microsoft Jet, the main driver behind MS Access. We could easily create a database with Ms Access

Directorate Technical Vocational Education

Page 46: Rekayasa perangkat lunak(Jilid2)

33 Software Engineering

then manipulate it using Visual Basic via DAO. Since DAO has a direct connection to Ms Access, we could use DBMS functions from Visual Basic.

● OLE DB

OLE DB is a technology to access low level database and is meant to replace the ODBC function. However, in its development, ODBC and OLE DB have some differences, namely, OLE DB based on COM technology and could be used to access non-relational database..

● ADO

ADO (ActiveX Data Object) is a high level interface of OLE DB. ADO is developed on top of OLE DB to equip functions that is not available in OLE DB and facilitate programmer in making the application.

7.2.1. Create and Manipulate Database using ADO

The working method with database in Visual Basic is principally the same not depends on its access method. There are several stages needed to be able to work with database. In this section, we will use ADO as Needed by several stages to be able to work with the database. In this part we will use ADO as its technology is more flexible than other technology. It may always developed using other technology.

● Connection using database.

Connection using database means we connect to open the database and access the data in it. The following is an example of connecting to database biblio.mdb.

Dim cn As New ADODB.Connection cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" _ & "Data Source=C:\Microsoft Visual Studio\Vb98\Biblio.mdb"

● Access record data in database.

A collection of data record in database, in ADO, is known as recordset. To work with recordset, we need access to table or view / query to see what is available in the database. Exampine the following example.

Const DBPATH = "C:\Program Files\Microsoft Visual Studio\Vb98\NWind.mdb" Dim cn As New ADODB.Connection, rs As New ADODB.Recordset

Directorate Technical Vocational Education

Page 47: Rekayasa perangkat lunak(Jilid2)

34 Software Engineering

cn.Open "Provider=Microsoft.Jet.OLEDB.3.51;Data Source=" & DBPATH rs.Source = "Employees" rs.Open , cn

In the above code, we use database Nwind.mdb as data source. Then as source recordset, we call “Employees” table. Variable rs is the recordset. After determining the source table, we may open the table using open statement.

After open the source table, we may access the data in it. The following is the source code example to access data in a table.

Dim i As Integer For i = 0 To rs.Fields.Count Print rs.Fields(i).Name & " = " & rs.Fields(i).Value Next

The above statement will print all row and column Name in the Employees table that is previously opened. The fastest method is by using For Each statement as follows,

Dim fld As ADODB.Field For Each fld In rs.Fields Print fld.Name & " = " & fld Next

● Data manipulation in recordset.

Data update on recordset may be done as follows.

rs.Update Array("FirstName", "LastName", "BirthDate", "HireDate"), _ Array("John", "Smith", #1/1/1961#, #12/3/1994#)

While to add a recordset, the following statement may be used.

rs.AddNew rs("FirstName") = "Robert" rs("LastName") = "Doe rs("BirthDate") = #2/5/1955# rs.Update

To erase a record, it may be done by the following statement.

rs.Delete rs.MoveNext If rs.EOF Then rs.MoveLast

Directorate Technical Vocational Education

Page 48: Rekayasa perangkat lunak(Jilid2)

35 Software Engineering

7.3. COM Technology

7.3.1. COM Concept COM or Component Object Model is an infrastructure provided by Visual Basic to access objects or controls as long as it has interface accessible by Visual Basic.

To be able to use COM in Visual Basic, we may open Reference Dialog from Project menu select add Reference. The following windows as Figure 7,8 will be opened.

Figure 7.8. Reference Windows.

In Figure 7.8 select COM or other object that we'll like to use. In this example, we select “Microsoft Word 8,0 Object Library”. After click OK, we could use the choosen object in our program. The following is the example of object usage.

Example 7.14. Example of COM usage.

Directorate Technical Vocational Education

Page 49: Rekayasa perangkat lunak(Jilid2)

36 Software Engineering

Private Sub cmdCheck_Click() Dim text As String Dim suggestion As Word.SpellingSuggestion Dim colSuggestions As Word.SpellingSuggestions ' menambahkan dokumen bila belum ada dokumen yang terbuka. If MSWord.Documents.Count = 0 Then MSWord.Documents.Add text = Trim$(txtWord.text) lstSuggestions.Clear If MSWord.CheckSpelling(text) Then lstSuggestions.AddItem "(correct)" Else Set colSuggestions = MSWord.GetSpellingSuggestions(text) If colSuggestions.Count = 0 Then lstSuggestions.AddItem "(no suggestions)" Else For Each suggestion In colSuggestions lstSuggestions.AddItem suggestion.Name Next End If End If End Sub

In the above code, we use one of the method from the previously opened object (“Microsoft Word 8,0 Object Library”). The method that we like to use is Spelling Suggestion. Please see the code in the variable declaration section. Using the same way, we may use method or function that we like to use from COM object that has been loaded.

In the Reference windows in Figure 7.8, there are a large number of COM that can be used. Please try to open it and examine its function one by one.

7.4. SUMMARY In this chapter, you have studied the Visual Basic programming language. Start with variable, constant, data type and operator. Then continue with control structure, namely, branching and looping. Procedure and function usage is also provided to complete the foundation of Visual Basic programming.

In other section, we also studied access and data manipulation technique using ADO. This chapter is closed by studying how to open and use COM technology provided by Visual Basic.

Directorate Technical Vocational Education

Page 50: Rekayasa perangkat lunak(Jilid2)

37 Software Engineering

7.5. EXERCISE

1. What is the result of the following Visual Basic expression:

a. 3*4b. 7^2c. 1/ (2^3)d. 3 + (4*5)e. (5 - 3) *4f. 3* ((-2) ^5)

2. What is the result using the following mod expression. a. 6 Mod 2 b. 14 Mod 4 c. 7 Mod 3 d. 5 Mod 5

3. Check the naming of variable in Visual Basic. Determine whether it is true or false.

a. sales.2006 b. room&Board c. fOrM_1040 d. 1040B e. expenses? f. INCOME 2006

4. If a = 2, b = 3, and c = 4, what is the result of the following expression.

a. (a*b) + c b. a*(b + c) c. (1 + b)*c d. a^c e. b^(c - a) f. (c - a)^b

5. Create a program to calculate the following expression. a. 7•8 + 5 b. (1 + 2•9)3 c. 5.5% of 20

d. 15 - 3(2 + 34) e. 17(3 + 162) f. 4 1/2 - 3 5/8

Directorate Technical Vocational Education

Page 51: Rekayasa perangkat lunak(Jilid2)

38 Software Engineering

6. Open Figure 5.6 and 5.7 in Chapter 5. Create the program in Visual Basic. Use

Text Box control and Command Button in this exercise.

7. Open Figure 5.9 and 5.10 in Chapter 5. Create the program in Visual Basic.

8. Open Figure 5.15 and 5.17 in Chapter 5. Create the program in Visual Basic.

Directorate Technical Vocational Education

Page 52: Rekayasa perangkat lunak(Jilid2)

39 Software Engineering

CHAPTER 8 JAVA OBJECT ORIENTED PROGRAMMING

You may have seen a picture of a mug with a vapor billowed with Java written on it such as in Figure 8.1. Yes, it is the logo of Java programming language that increases its popularity in recent years. Many games and applications that used in mobile equipment such as cellular phone and PDA is made using Java. Java is well known due to its portability and the support of object oriented programming.

This chapter covers two standard of competences, namely, create a program in object oriented programming language and create an application program in Java. This is due to the similarities between Java and object oriented programming. The standard of competence in creating a program in object oriented programming consists of four (4) basic competence, namely, data type and control of the program, class creation, inheritance usage, polymorphism, and overloading, and the usage of interface and package. Whereas the standard of competence in creating application program with Java consists of five (5) basic competences, namely, explaining I/O file, data type and variable, applying operator, explaining exception handling, applying multi- threading and explaining network programming.

In this book, a section is indirectly referred to a basic competence. The summary is at the end of each chapter followed by exercise. Before studying this competence please review the operation system, the problem solving principles, the programming algorithm, the programming with VB and VB.Net and supporting materials from the other subjects.

OBJECTIVE

After studying this chapter, the reader is hoped to be able to:

● Understand the concept of object oriented programming.● Explain I/O File, data type and variable in Java● Use of operator.● Implement program control.

Directorate Technical Vocational Education

Figure 8.1. Logo Java.

Page 53: Rekayasa perangkat lunak(Jilid2)

40 Software Engineering

● Explain Exception Handling.● Implement Multi-Threading● Explain Network Programming● Create object oriented program using class● Use inheritance principle, polymorphism and overloading● Create object oriented program with interface and package.

8.1. OBJECT ORIENTED PROGRAMMING CONCEPT Object Oriented Programming (OOP) is a programming paradigm that uses object and interaction to design an application and computer program. OOP is uncommon in the early 1990's. However, today it is commonly used. Programming languages such as Microsoft dotNet family (Visual Basic.Net, Visual C#, and Visual J), Borland Delphi, Java, Phyton, PHP version 5 and above, C++ and many others are OOP supported programming language.

What is an object? All objects in the world may be used as object. Even your Software Engineering teacher is an object. This software engineering handbook is also an object. Even the software engineering course is an object. Every object has certain characteristics and behavior. Characteristics is known as attribute, and behavior is known as behavior or method.

In object oriented, it is known to have class and object. Class defines the abstract characteristics of an object including attribute or characteristics or it tasks (method). For example, a car is a class as it has attributes, such as, color, maker, type etc. Car has also method, such as, forward, reverse, and stop etc. Please see Figure 8.2.

Figure 8.2. Class, Attribute and Method.

An object is an example of well define class. Attribute and method of a class is automatically inherent in an object with some certainties. As an illustration, please see Figure 8.2. In the Figure, we may easily identify that the class is a car with its attribute and method. The object may be a sedan, from Toyota, and red color. The sedan may have method to go forward, reverse, and stop. In this case, the sedan is known as instance or decedent from car class.

Directorate Technical Vocational Education

Page 54: Rekayasa perangkat lunak(Jilid2)

41 Software Engineering

There are several important concepts that you must understand in object oriented programming, namely, abstraction, encapsulation, inheritance and polymorphism.

8.1.1. Abstraction Abstraction is also known as composition is a simplification principle by modeling a complex using class in accordance to the problem. Please examine Figure 8.3, a car may be broken down into parts, such as, wheel, engine,frame, window glass, etc. as well as the other way around. In an object oriented programming, we may have several classes or object that may have many similar attributes and methods that may be merge into a super class.

Figure 8.3. Abstraction Example.

8.1.2. Encapsulation Encapsulation principle is to hide the detail of a class on object that interact with it. For example when we drive a car, we interact with the car and ask it to do its method, such as, forward, reverse, or stop. We interact only through some if car interface, such as, gears, throttle, break and several other parts. The detail process how to gp forward, backward, and stop, we don't need to know and understand.

8.1.3. Inheritance Inheritance is an inheritance principles of the characteristics inheritance from its parents to the child or its descendants that is applied in the class. Parents has a more general attribute and method as compared with the child or its descendants. In Figure 8.4., it is shown that a car has its own attribute and method that are more general then that of sedan, truck, or bus. The car as the class that is inherited is known as super class, whereas sedan, truck and bus as the inherited class is known as sub class.

Directorate Technical Vocational Education

Page 55: Rekayasa perangkat lunak(Jilid2)

42 Software Engineering

Figure 8.4. Inheritance.

8.1.4. Polymorphism Polymorphism is possibly the most difficult concept to understand in object oriented programming. The meaning of polymorphism is the ability of an object to have more than one form. In other words, we may implement different things using the same way. For example, suppose we have four (4) different animals, such as, bird, snake, frog, and lion, if we ask them to move forward, then bird will fly, snake will crawl, frog will jump and lion will possibly run. So the same method may be implemented differently by different object.

8.2. INTRODUCTION TO JAVA The Java programming language was born from The Green Project, that was 18 months, from early 1991 to summer 1992. This particular project used version named Oak. The name Oak is never used the name of Java release version as another software has been registered to use it as trade mark, this the replacement name is “Java”.The name taken from coffee seeds. Today, Java is under the license from Sun Microsystems.

Based on Sun's definition, Java is a name for a collection of technology to create and to run software on a standalone computer or in a network environment. While people who work in programming world tend to see Java as a technology rather than a conventional programming language.

8.2.1. Software Requirement To create a Java program, we need at least two (2) software, namely,

● Java 2 SDK Standard Edition (J2SE).

Directorate Technical Vocational Education

Page 56: Rekayasa perangkat lunak(Jilid2)

43 Software Engineering

This software is used to compile the Java source code. More over, it has classes that may be used to build desktop application, graphics, security, database connectivity and networking. The software may be freely downloaded from Sun Microsystems site. After that, the software must be installed in our operating system.

● Text Editor.

This software helps us in writing the source code. Notepad, vi, Gedit, are the example of text editor. However, there is help facilities to write Java source code in such text editor. Today, there are several free IDE available on the Internet. These IDE provide many facilities, such as, syntax colorig, auto completion, and template to make easier for one to write code in Java. NetBeans (www.netbeans.org) and Eclipse (www.eclipse.org) are the two (2) famous and powerful IDE. Figure 8.5. shows NetBeans IDE.

Figure 8.5. NetBeans IDE.

8.2.2. Source Code Compilation Before create and compile a program, we need to set ClassPath. ClassPath is a system variable to let Java knows various location needed for running it. For example, we may put the source code in directory d:\TestCode\Java, then we must set the path so that we may use Java compiler from this directory. The following is the step by step process to set classpath:

Directorate Technical Vocational Education

Page 57: Rekayasa perangkat lunak(Jilid2)

44 Software Engineering

● Open command-prompt in Windows then type:

set PATH=C:\progra~1\java\jdk1.5.0\bin;%PATH%set CLASSPATH= . ;D:\TestCode\Java

The above Path is typically used in JDK 1.5. We need to change slightly for other version.

● Check for correct setting by type Java command in any directory from the command prompt.

After classpath is set, try open notepad and type the following code.

public class Main { //isi blok public static void main(String[] args) { System.out.println("Hallo ini Java lho"); } }

Then save the source code file using the same name as the class in the code, namely, main and add the extension .java. Save the code in the appointed directory, as shown in Figure 8.6. Java has a very tight writing rule of file name. If the filename of the member is not the same as the class name, the program will not be able to be executed.

In the above source code, the first line shows the class name, namely, Main. In Java all code must be placed in class declaration. We use keyword class. In addition, class with public access indicates that this class may have free access to other class in other package. A package is a collection of classes.

After class declaration follow by { sign as the beginning of the code block. It must be closed by } sign to end the block.

Line starts with // is a comment. The next line is the method. In our case the method is main (main method). We may create other methods other than main. After declaration followed by the block code. In the example block code, I t contains the System.out.println(“Hallo ini Java lho”); statement. The statement System.out.println() will print the text between dual quotation marks (“ ”) into the screen.

Directorate Technical Vocational Education

Page 58: Rekayasa perangkat lunak(Jilid2)

45 Software Engineering

Figure 8.6. File name and file location.

Now open the command prompt and select the directory where the file is and type the command as shown in Figure 8.7. Examine how to write it and the result.

Figure 8.7. Execute Java Program.

Directorate Technical Vocational Education

Page 59: Rekayasa perangkat lunak(Jilid2)

46 Software Engineering

Prior to run, the source code (Main.java) must be compiled by using javac as shown in Figure 8.7. After a successful compilation, the program may be executed by using Java. The compilation process will produce Main.class file. Check your directory using dir command, look for the file with extension .class. The Java command calls the .class file, not the source code with extension .java.

8.3. DATA TYPE, VARIABEL, DAN INPUT/OUTPUT (I/O) STATEMENT

8.3.1. Data Type There are 8 basic data types in Java, namely, boolean (for logic form), char (for text form), byte, short, int, long (integer), double and float (floating point). The table 8.1 shows the details of these data types.

Tabel 8.1. Data type in Java.

Data type Comment

Logic (boolean)

Representing two (2) conditions: true and false.

Text (char) Must be between quotes (' ')

Integer (byte, short, int & long)

Integer data type, default type is int.byte = 8 bits ranging from -27 – 27-1short 16 bits ranging from -215 – 215-1int = 32 bits ranging from -231 – 231-1long = 64 bits ranging from -263 - 263-1

Floating point (float and double)

Numbers data type, may be fractional. Default data type is double.Float = 32 bits ranging from -231 – 231-1Double = 64 bits ranging from -263 - 263-1

In Java, String is not a data primitive, but a Class. String represents data type consisted of several characters. String is written by using dual quotation marks (“”).

The following examples shows how to use the above data type. Type the following codes, then compile and run it.

Example 8.1. The use of integer data type. public class ContohPerhitungan { public static void main(String[] args) { byte a = 1; short b = 12; int c = 300, d, e; d = a + b + c; e = a * b * c;

Directorate Technical Vocational Education

Page 60: Rekayasa perangkat lunak(Jilid2)

47 Software Engineering

System.out.println("Hasil penjumlahan = " + d); System.out.println("Hasil perkalian = " + e); } }

Example 8.2. The use of float data type.

public class LuasLingkaran { public static void main(String[] args) { double pi = 3.1416; double r = 2.12; double luas; luas = pi * r * r; System.out.println("Luas Lingkaran = " + luas); } }

Example 8.3. The use of char data type.

public class tipeChar { public static void main(String[] args) { char ch = 'A'; System.out.println("ch = " + ch); ch++; System.out.println("ch = " + ch); } }

8.3.2. Variable and Constant. The naming (identifier) rule of variable and constant as written in Chapter 5 also apply for Java. Moreover the identifier in Java is case-sensitive. Similar variable with different upper case and lower case character is a different variable. Unlike Visual Basic, Java requires us to firstly declare variable and constant. If not then the source code would not be compiled.

Method to declare a variable is as follows.

<data type> <variable name> [= initial value];

The initial value is optional. Examine the example 8.1. The variable a, b, and c are initialized by the initial value. Whereas the variable d and e are initialized. Please examine example 8.2 and 8.3 on variable declaration.

Directorate Technical Vocational Education

Page 61: Rekayasa perangkat lunak(Jilid2)

48 Software Engineering

8.3.3. Input / Output In the above example, we have used one of the method to sent output to the screen, it uses the statement System out printing. We have not use command to get input. In the followings, we will study how use input and output statement in Java.

To catch input from keyboard, we must use the class Buffered Reader that is in java.io package. Thus, in the beginning of our program, we must include this class in the source code. Please examine the following example.

Example 8.4. Input statement in Java.

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class InputKeyboard { public static void main( String[] args ){ BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) ); String name = ""; System.out.print("Ketikkan nama anda:"); try{ name = dataIn.readLine(); }catch( IOException e ){ System.out.println("Error!"); } System.out.println("Hai " + name +"!"); } }

The three (3) lines started with import shows that we will use the class BufferedReader, InputStreamReader and IOException in java.io package. Mode detailed explanation on package will be discussed in other section of this chapter.

In the following statements,

BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );

We declare a variable named dataIn with type class BufferedReader. Then, we declare a String variable with identifier name. Those statements are used to keep user input. The variable name is initialized by using en empty String. The following line will print the string using System.out.print statement.

Directorate Technical Vocational Education

Page 62: Rekayasa perangkat lunak(Jilid2)

49 Software Engineering

The following block code is a try-catch block. We will discuss on this in exception section.

try{ name = dataIn.readLine(); }catch( IOException e ){ System.out.println("Error!"); }

This will catch possible error in name = dataIn.readLine (); If mistake occurs that text “Error” will be printed. If no error, variable name will be the user input data via keyboard. It will be printed in the last statement.

To print the output, we may use the following statement.

System.out.println() System.out.print()

System.out.println ()will create a new line, whereas System.out.print () will not make a new line.

8.4. OPERATOR

8.4.1. Arithmetic Operator Arithmetics operator in Java is almost the same as VB. The only difference is in the notation of modulus operator. VB uses mod whereas Java uses % sign. Table 8.2 shows the list of arithmetics operator in Java.

Table 8.2. Arithmetics Operator in Java

Operator Function Example

+ Adding 3 + 5 = 8

- Subtracting 7 – 2 = 5

* Multiplying 5 * 2 = 10

/ Dividing 6 / 3 = 2

% Remaining of a Dividing (modulus) 5 / 2 = 1

++ Increment by 1 C++ = C + 1

-- Decrement by 1 C-- = C - 1

The following example shows how to use the arithmetics operator. Type the following

Directorate Technical Vocational Education

Page 63: Rekayasa perangkat lunak(Jilid2)

50 Software Engineering

source code, compile and run. Examine the output of the program

Example 8.4. The use of Arithmetics Operator.

public class DemoAritmatika { public static void main(String[] args) { int i = 21; int j = 38; double x = 9.123; double y = 12.78; //Cetak nilai variabel System.out.println("Nilai Variabel..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y); //penjumlahan System.out.println("Penjumlahan..."); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); //pengurangan System.out.println("Pengurangan..."); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); //perkalian System.out.println("Perkalian..."); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y)); //pembagian System.out.println("Pembagian..."); System.out.println(" i / j = " + (i / j)); System.out.println(" x / y = " + (x / y)); //modulus System.out.println("Sisa Hasil Bagi..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); //increment System.out.println("Increment..."); System.out.println(" i++ = " + (i++)); System.out.println(" ++i = " + (++i)); System.out.println(" j++ + i = " + (j++ + i)); System.out.println(" ++j + i = " + (++j + i)); } }

Directorate Technical Vocational Education

Page 64: Rekayasa perangkat lunak(Jilid2)

51 Software Engineering

8.4.2. Relational Operator Relational or comparison operator in Java is also similar to VB. The only different in symbol same or not the same. In VB to compare two operand whether the same or not the same uses the operator = for the same, and < > for not the same. Whereas in java uses == for the same, and ! = for not the same. Type in the following example source code, compile and run it. Examine the output of the program.

Example 8.5. The use of Relational Operator.

public class DemoRelasional { public static void main(String[] args) { int i = 20; int j = 16; int k = 16; //Cetak nilai variabel System.out.println("Nilai variabel..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" k = " + k); //lebih besar dari System.out.println("Lebih besar dari..."); System.out.println(" i > j = " + (i > j)); System.out.println(" j > i = " + (j > i)); System.out.println(" k > j = " + (k > j)); //lebih besar atau sama dengan System.out.println("Lebih besar atau sama dengan..."); System.out.println(" i >= j = " + (i >= j)); System.out.println(" j >= i = " + (j >= i)); System.out.println(" k >= j = " + (k >= j)); //lebih kecil dari System.out.println("Lebih kecil dari..."); System.out.println(" i < j = " + (i < j)); System.out.println(" j < i = " + (j < i)); System.out.println(" k < j = " + (k < j)); //lebih kecil atau sama dengan System.out.println("Lebih kecil atau sama dengan..."); System.out.println(" i <= j = " + (i <= j)); System.out.println(" j <= i = " + (j <= i)); System.out.println(" k <= j = " + (k <= j)); //sama dengan System.out.println("Sama dengan..."); System.out.println(" i == j = " + (i == j));

Directorate Technical Vocational Education

Page 65: Rekayasa perangkat lunak(Jilid2)

52 Software Engineering

System.out.println(" k == j = " + (k == j)); //tidak sama dengan System.out.println("Tidak sama dengan..."); System.out.println(" i != j = " + (i != j)); System.out.println(" k != j = " + (k != j)); } }

8.4.3. Logical Operator There are three (3) logical operators in Java, namely, && (AND), || (OR), | and! (NOT). The use of these operators are the same as VB, only different in notation.

8.5. PROGRAM CONTROL STRUCTURE

As in VB, Java provides the control program structure for selection and looping. The statements is also fairly similar.

8.5.1. Selection Structure

The selection structure may use if, if... else, and if... else... if. It is fairly similar to Chapter 5 and Chapter 7. Please examine the following program snapshots.

Example 8.6. The use of if.

int nilai = 68; if( nilai > 60 ) System.out.println("Selamat anda lulus!");

Example 8.6 uses if as selection structure. If the mark is more than 60 then the program will print “Selamat anda lulus!”

Example 8.7. The use of if ... else.

int nilai = 68; if( nilai > 60 ) System.out.println("Selamat anda lulus!"); else System.out.println("Anda tidak lulus!");

In Example 8.7, we use the structure if... else. If the mark is more than 60 then the output will be “Selamat you passed! ” but if not (else) then the program will print “You are not pass! ”.

Example 8.8. The use of if ... else ... if.

Directorate Technical Vocational Education

Page 66: Rekayasa perangkat lunak(Jilid2)

53 Software Engineering

int nilai = 68; if( nilai > 90 ){ System.out.println("Your mark is very good!"); } else if( nilai > 60 ){ System.out.println("Your mark is good!"); } else{ System.out.println("You are not passed"); }

Example 8.8 is the evolution from example 8.7. If the mark is more than 90 then the program will print “Your mark is very good! ”, but if less than 90 and more than 60 (else if) then the program will print “Your mark is good! ” and if not both of them (else) then the program will print “Your are not pass”

The selection structure provides many alternatives. However, the if structure may be quite complex. Java provides switch command. It is similar to Select .. case in VB. Examine the following example.

Example 8.9. The use of switch.

public class SwitchControl { public static void main(String[] args) { int a=2; int b; switch(a) { case 1: b = a + 1; break; case 2: b = a + 2; break; case 3: b = a + 3; break; case 4: b = a + 4; break; default: b = 0; } System.out.println("Nilai b: " + b); } }

What is the results of the above source code in Example 8.9. If your answer is 4

Directorate Technical Vocational Education

Page 67: Rekayasa perangkat lunak(Jilid2)

54 Software Engineering

means you have understand how the switch command works. Switch will check whether a value is the same as case, namely, 2. Inspection starts at the first case, I,e, 1. Break statement is used to stop matching to other cases. Try to eliminate break statement and run the source code again. How is the result?

8.5.2. Looping Structure There are three (3) looping structure in Java, namely, for, while and do- while. In principle, the looping structure is similar to the one described in Chapter 5 and 7. The following is example of looping structure.

Example 8.10. The use of for in Java.

public class ForLoop { public static void main(String[] args) { int j=4; for (int x=0; x < 5; x++) { System.out.println("Nilai x: " + x); System.out.println("Nilai j: " + j); System.out.println(); j--; } } }

General syntax of for is: for (start value; condition; increment) follows by the block to be repeated. Examine how to use for structure as in Example 8.10. Initial value of x=0. Whereas x < 5 is the condition for looping.. Statement x++ is to increment by 1. Remembered that x++ is the same as x = x + 1. Please run the above program. What do you think the output would be?

Example 8.11. The use of While in Java.

public class WhileLoop { public static void main(String[] args) { int y = 4; while ( y > 0 ){ System.out.print(y); y--; } } }

Directorate Technical Vocational Education

Page 68: Rekayasa perangkat lunak(Jilid2)

55 Software Engineering

In the example 8,11 we use while statement to do looping. In while structure, we need to initialize the variable before entering the while structure. In this case, the variable y is initialized to 4. The while condition to be met is y>0. In this example, decrement counter is used, examine the y --. Thus, the program will print 4321 on screen. What happen if the counter y – is removed? How many times looping will be performed?

Example 8.12. The of do-while in Java.

public class ContohDoWhile { public static void main(String[] args) { int z=3; do { System.out.println("Java"); z++; } while (z < 6); } }

Example 8.12 shows how to use do-while to repeatedly print “Java” on screen. Examine the syntax of do-while in this example. Do-while needs initialization and counter to do the looping. Try to run the program. How many times “Java” will appear? Now substitute the condition in while with z < 1. Is the program printing “Java”? Why? Read Chapter 7 in the section of control structure to understand this issue.

8.5.3. The use break and continue. The break statement has three (3) functions, namely,

● Stopped selection process in switch statement.● Stopped looping process or exit the loop body.● Exit from certain labeled block.

The break statement may be used to break selection process in switch structure. We will study how to break a loop. Examine the following example.

Example 8.13. The use of break in a loop.

class BreakPengulangan { public static void main(String[] args) { for (int i=0; i<10; i++) { if (i == 5) { break; }

Directorate Technical Vocational Education

Page 69: Rekayasa perangkat lunak(Jilid2)

56 Software Engineering

System.out.println("baris ke-" + i); } System.out.println("Ini setelah break pengulangan”); } }

In Example 8.13, the looping will be totaling 10 times, and is begin from 0 to 9. However, due to statement if (1 == 5) {break;} then the loop will stop when i =5. The program will exit the loop body and continue with statements after the ending sign of the loop.

The statement continue is used to force the program to continue the looping process. Examine the following example.

Example 8.14. The use of continue.

String nama[] = {"Joni", "Riko", "Denis", "Riko"}; int hitung = 0; for( int i=0; i<names.length; i++ ){ if( !nama[i].equals("Riko") ){ continue; } hitung++; } System.out.println("Ada " + hitung + " Riko dalam daftar");

Example 8.14 is a program to count the number of Riko in the collection of name. The statement if (! Names [i] .equals (“Riko”) means that if the variable name is not “Riko” then follows continue statement. Continue statement forces the program to directly looping without executing the below statements. Thus, the line hitung++ will not be executed. So that the final result is 2.

8.6. EXCEPTION HANDLING

8.6.1. The understanding of Exception Handling

Mistakes in a program is fairly normal, even if it is written by a professional programmer. To reduce time in finding the mistakes, Java provides the mechanism for exception handling. Exception shorts for Exceptional Events. Its general definition, Exception is an abnormal condition that occurs during runtime. Runtime error during program execution will be trapped by exception. Exception may be automatically

Directorate Technical Vocational Education

Page 70: Rekayasa perangkat lunak(Jilid2)

57 Software Engineering

generated by Java runtime or deliberately generated by certain code for exception handling.

Examine the following code.

public class DivByZero { public static void main(String args[]) { int a = 5, b = 0, c; c = a/b; System.out.println("c = " + c); } }

In the above source code, there is nothing wrong with the syntax. However, there is a fatal mistake, namely, divide by zero mistake. As a = 5 is divided b = 0. This type of mistake often happens as it is quite invisible or we are not conscientious. In this type of error / mistake, we may successfully compile the program. However, it will stop running and shows the message of the occurrence exception or the abnormal condition as shown in Figure 8.8 and the program will stop.

Figure 8.8. Warning of Runtime Error.

As shown in Figure 8.8, it informs the exception type and the exception location at which line. This is the default action when an exception is nor handled. If there is no code to handle an exception, default action will be automatically used.

There are several general exception type, namely,

● ArithmeticException. Exception due to arithmetic related error, such as, divide by zero.

● ArrayIndexOutOfBoundException. Exception due to read Array index outside its limit.

● NullPointerException. Mistakes due to no value / null in the pointer.● Etc.

Directorate Technical Vocational Education

Page 71: Rekayasa perangkat lunak(Jilid2)

58 Software Engineering

8.6.2. Try and Catch Try is used to check on the block that may contain exception. If during runtime there is exception in this block it will be redirected to block that catch the exception that written using catch statement. Examine the following example.

Example 8.15. Exception with Try-Catch.

public class DivByZero { public static void main(String args[]) { int a = 5, b = 0, c; try { c = a/b; } catch (ArithmeticException exc) { //Reaksi jika terjadi exception System.out.println(exc); } System.out.println("Setelah exception"); } }

The source code in Example 8.15 is an expansion from the previous source code. The statement c = a/b is the statement to be tested whether contains exception or not. When exception occurs it will be thrown to the catch code. Exception is checked by ArithmeticException. The reaction occurs when an exception happens while running the following System.out.println(exc); statement. Using the above mechanism, the program will not be forced to terminate, in fact, after the try-catch block, it will continue running. Figure 8.9. shows the program execution result. Compare it to the Figure 8.8.

Figure 8.9. Output from Try-Catch.

In general, there may be more than one exception in one problem. In Example 8.16, we may use several exception type to check possible exception. Type the following source code, run and examine what happen.

Example 8.16. Exception with Try-Catch.

Directorate Technical Vocational Education

Page 72: Rekayasa perangkat lunak(Jilid2)

59 Software Engineering

class BanyakEksepsi { public static void test(int a, int b) { try { int c = a / b; System.out.println("Hasil bagi: " + c); int[] Arr = {1,2,3,4,5}; // array dengan 5 elemen Arr[10] = 11; // mengakses indeks ke-10 } catch (ArithmeticException ae) { System.out.println("Terdapat pembagian dengan 0"); System.out.println(ae); } catch (ArrayIndexOutOfBoundsException oobe) { System.out.println("Indeks di luar rentang"); System.out.println(oobe); } public static void main(String[] args) { test(4, 0); // menimbulkan ArithmeticException System.out.println(); test(12, 4); // menimbulkan ArrayIndexOutOfBoundsException } }

8.6.3. Throw

In addition to catch an exception, Java permits one to throw an exception. Examine the following Example 8.17.

Example 8.17. Exception with Try-Catch and Throw.

class ThrowDemo { public static void main(String args[]){ String input = "Salah input"; try { if (input.equals("Salah input")) { throw new RuntimeException("Demonstrasi Throw"); } else { System.out.println(input); } System.out.println("Setelah throw"); } catch (RuntimeException e) { System.out.println("Exception ditangkap di sini."); System.out.println(e); } } }

Directorate Technical Vocational Education

Page 73: Rekayasa perangkat lunak(Jilid2)

60 Software Engineering

Examine the statement starts with if statement. As shown clearly, if the input is the same as “Salah input” then threw exception and print “Demonstrasi Throw”. Output from this program is shown in Figure 8.10.

Figure 8.10. Output program using throw.

8.6.4. Finally The finally block contains the handling code to be used after try and catch. This code block always executed after block Try. This code block will return value true although it may executed return, continue or break. Examine the following program.

Example 8.18. Exception with try-catch-finally.

class DemoFinally { private static int i = 0; public static void main(String[] args) { while (true) { try { System.out.print("Pada saat i = " + i + ": "); if (i++ == 0) { throw new Exception(); // melempar exception } System.out.println("Tidak terjadi exception"); } catch (Exception e) { System.out.println("Terdapat exception"); } finally { System.out.println("Pernyataan dalam blok finally\n"); if (i == 2) { break; // pada saat i==2, pengulangan akan berhenti } } } } }

Directorate Technical Vocational Education

Page 74: Rekayasa perangkat lunak(Jilid2)

61 Software Engineering

When the program runs, the output appears as Figure 8.11. Please note that statements in block finally will always be executed.

Figure 8.11. Output of program with Try-Catch-Finally. 8.7.1. Concept of Thread

8.7. MULTI-THREADING

8.7.1. Concept of Thread A thread is a control of program flow. Let us imagine, a threat as a process to be executed by a certain program. Thread is an independent program, not depends on other section of the program and may be simultaneously run. It means a threat may stop, or paused without stopping other thread. In Java, every threat is controlled by unique object of the Thread, is defined in java.lang package.

When a Java program is run, it, in fact, automatically runs a thread. This particular thread is normally called main thread. The main thread is the mother of all other thread. Despite the main thread is automatically run, it may be controlled through the object thread by using currentThread() method. Please examine the following example.

Example 8.19. Main Thread.

class ThreadUtama { public static void main(String[] args) throws InterruptedException { // mendapatkan thread yang sedang aktif Thread tUtama = Thread.currentThread(); // menampilkan informasi tentang thread System.out.print("Informasi thread: "); System.out.println(tUtama.toString()); for (int i=0; i<5; i++) { System.out.println("Detik ke-" + (i+1)); Thread.sleep(1000); // membuat delay selama 1 detik }

Directorate Technical Vocational Education

Page 75: Rekayasa perangkat lunak(Jilid2)

62 Software Engineering

} }

In the example above, we name the thread as tUtama. This variable is used to catch the running main thread using Thread.currentThread (). Then the information about this thread is printed on the screen. In the next line starts with for, we will use command to control running thread. We use sleep method to control thread to postpone a job for 1 second for each repetition time. Please type the code, then run it. Then try to remove the Thread.sleep line (1000);. Run the program again. What is the different?

8.7.2. Thread Creation and Usage Thread may be created in two methods, namely, create a new class that apply interface Runnable or create a new class as a decedent of Thread class. These two (2) methods need java.lang package. By default this package has been automatically imported when we made a program in Java.

In this section, we will only discuss the first method. Whereas the second method will be studied in the multi-thread section. Please examine the following example.

Example 8.20. Create thread using interface Runnable.

class TestRunnable implements Runnable { // mengimplementasikan method run() yang dideklarasikan // di dalam interface Runnable public void run() { System.out.println("Thread anak dieksekusi"); } } class PenerapanRunnable { public static void main(String[] args) { // (LANGKAH KE-1): membuat objek Runnable TestRunnable obj = new TestRunnable(); // (LANGKAH KE-2): membuat objek Thread dengan melewatkan objek Runnable Thread t = new Thread(obj); // (LANGKAH KE-3) : menjalankan thread t.start(); System.out.println("Thread utama dieksekusi"); } }

In the above example, we create class TestRunnable that appliy Runnable. Please note the line class TestRunnable implements Runnable and its block code beneath it.

Directorate Technical Vocational Education

Page 76: Rekayasa perangkat lunak(Jilid2)

63 Software Engineering

Then, we create object TestRunnable from this class, see the line TestRunnable obj = new TestRunnable (). This object is used to create new thread using constructor class thread, see the line Thread t = new Thread (obj). After created then could run the thread, examine the line t.start ().

8.7.3. Multi-Thread In Example 8.19 and 8.20, we are using one and two threads. However, Java allows us to create more than two (2) threads. This is known as Multi- thread. Examine the following example.

Example 8.21. Create a multi-thread.

class MyThread1 extends Thread { public void run() { try { for (int i=0; i<10; i++) { System.out.println("Thread pertama: detik ke-" + (i+1)); if (i != 9) { sleep(1000); } else { System.out.println("Thread pertama selesai...\n"); } } } catch (InterruptedException ie) { System.out.println(ie.getMessage()); } } } class MyThread2 extends Thread { public void run() { try { for (int i=0; i<5; i++) { System.out.println("Thread kedua: detik ke-" + (i+1)); if (i != 4) { System.out.println(); sleep(1000); } else { System.out.println("Thread kedua selesai...\n"); } } } catch (InterruptedException ie) { System.out.println(ie.getMessage()); } }

Directorate Technical Vocational Education

Page 77: Rekayasa perangkat lunak(Jilid2)

64 Software Engineering

} class DemoMultipleThread { public static void main(String[] args) { MyThread1 t1 = new MyThread1(); t1.start(); MyThread2 t2 = new MyThread2(); t2.start(); } }

The above source code shows how to create two (2) threads. The first thread is created in class MyThread1 by deriving from class Thread. This method is the second method as describe in the previous section. The second Thread using class MyThread2 is also created using the same method. Then in class DemoMultipleThread, we create object t1 from class MyThread1 and object t2 from class MyThread2. As we run the program, the following results will be presented as shown in Figure 8.12.

Figure 8.12. Execution result of multi-thread.

Directorate Technical Vocational Education

Page 78: Rekayasa perangkat lunak(Jilid2)

65 Software Engineering

8.8. OBJECT ORIENTED PROGRAMMING APPLICATION USING JAVA In the previous examples as well as the explanations, we have touched on class and object. In this section, we will study more detailed on class and object to implement object oriented programming principles.

Class may be defined as the framework that defines variables, general methods of a certain object. In object oriented programming, class is not that different from data type primitive. The difference is data type is used to declare normal variable, while class is used to declare object variable. Class is more abstract.

8.8.1. Class Creation In Java, class is defined by keyword class. The general form in defining class is as follows.

class NamaKelas tipe data1; tipe data2; ... tipe dataN; tipe method1 (daftar parameter) { //blok kode untuk method1 } tipe method2 (daftar parameter) { //blok kode untuk method2 } ... tipe methodN (daftar parameter) { //blok kode untuk methodN } }

Data or variable defined in a class is often known as instance variable. The values of these variable may be read through available methods. Therefore method is used as interface between the class user and the data in the class. Remember the encapsulation principle in the beginning of the chapter. Examine the following class example.

Example 8.22. Create a simple class.

class Siswa {

Directorate Technical Vocational Education

Page 79: Rekayasa perangkat lunak(Jilid2)

66 Software Engineering

String name; String alamat; int usia; }

In the above code, we create a class named Student. There are three (3) data in the class, namely, name, address and age. We have not add any method yet. In the above code, we have defined a new data called Student. The above source code is only a template. Thus, nothing will happen if we run the above program. We need to create the actual object using the above class. Please see the following.

Example 8.23. The use of class. class Siswa { String nama; String alamat; int usia; }

public class DataSiswa { public static void main(String[] args) { Siswa siswa1 = new Siswa(); siswa1.nama = "Roni"; siswa1.alamat = "Mergosono Gg. 1 No. 34"; siswa1.usia = 23; System.out.println("Nama :" + siswa1.nama); System.out.println("Alamat :" + siswa1.alamat); System.out.println("Usia :" + siswa1.usia); } }

The source code must be saved in DataSiswa.java file, and will open Siswa.java. This is because the main method is in class DataSiswa. In the above code, the class Siswa is in class DataSiswa. We made the actual object from class Student by typing

Siswa siswa1 = new Siswa();

Siswa1 is the name of the actual object in class Siswa. Then, we may use variable or data in class Siswa. If we run it, the above source code will show the following output as shown in Figure 8.13.

After that just we could use the variable or the available data in the student's class. If being undertaken, the program code above will produce output like to the Picture 8,13.

Directorate Technical Vocational Education

Page 80: Rekayasa perangkat lunak(Jilid2)

67 Software Engineering

Figure 8.13. Output result of class class DataSiswa.

We will create a little bit complex class by including method into the class. Please examine the following example.

Example 8.23. Creating class with method. class Siswa { String nama; String alamat; int usia; double nilaiMatematika; double nilaiBhsInggris; double nilaiBhsIndonesia; double rerata; // Menghasilkan nama dari Siswa public String getNama(){ return nama; } // Mengubah nama siswa public void setNama( String temp ){ nama = temp; } // Menghitung rata – rata nilai public double getRerata(){ rerata = ( nilaiMatematika+nilaiBhsInggris+nilaiBhsIndonesia )/3; return rerata; } } public class DataSiswa { public static void main(String[] args) { Siswa siswa1 = new Siswa(); siswa1.setNama("Rony"); siswa1.nilaiMatematika = 67;

Directorate Technical Vocational Education

Page 81: Rekayasa perangkat lunak(Jilid2)

68 Software Engineering

siswa1.nilaiBhsInggris = 87; siswa1.nilaiBhsIndonesia = 59; System.out.println("Nama :" + siswa1.getNama()); System.out.println("Nilai Matematika :" + siswa1.nilaiMatematika); System.out.println("Nilai Bahasa Inggris :" + siswa1.nilaiBhsInggris); System.out.println("Nilai Bahasa Indonesia :" + siswa1.nilaiBhsIndonesia); System.out.println("Rerata :" + siswa1.getRerata()); } }

In the above code, we expand class Siswa by adding four (4) more variables, namely, nilaiMatematika, nilaiBhsInggris, nilaiBhsIndonesia and rerata. We also added three (3) more methods, namely, getNama, setNama and getRerata. getNama is a method to show value of variable nama. setNama is a method to set value to variable nams. GetRerata is a method to calculate the avarage value of the three (3) lessons and show the calculation result. Examine how these methods are used in class DataSiswa. The output result of the source code may be seen in Figure 8.14.

Figure 8.14. Execution result of class with method.

There are several types of method in a class, namely, method that return no value, method that returns value and special method namely constructor. In general, method is similar to procedure or the function. Please review Chapter 6 and 7. Examine the following example.

Example 8.24. Method creation with no value in return.

Class Bangun { double panjang; double lebar; // Mendefinisikan method void (tidak mengembalikan nilai) void cetakLuas() { System.out.println(“Luas bangun = “ + (panjang * lebar)); }

Directorate Technical Vocational Education

Page 82: Rekayasa perangkat lunak(Jilid2)

69 Software Engineering

} class pakaiBangun { public static void main(String[] args) { Bangun b1, b2; // instansiasi objek b1 = new Bangun(); b2 = new Bangun(); // mengisi data untuk objek b1 b1.panjang = 4; b1.lebar = 3; // mengisi data untuk objek b2 b2.panjang = 6; b2.lebar = 5; // memanggil method cetakLuas() untuk masing-masing objek b1.cetakLuas(); b2.cetakLuas(); } }

In the above source code, class Bangun has one method, namely, cetak Luas. This method is not returning any value. The final result of the method will be stored in the method. Examine the following exanple.

Example 8.25. Method creation that returns value.

Class Bangun { double panjang; double lebar; // Mendefinisikan method yang mengembalikan nilai double hitungLuas() { double luas = panjang * lebar; return luas; } } class pakaiBangun { public static void main(String[] args) { Bangun b1, b2; // instansiasi objek b1 = new Bangun(); b2 = new Bangun(); // mengisi data untuk objek b1 b1.panjang = 4; b1.lebar = 3; // mengisi data untuk objek b2 b2.panjang = 6; b2.lebar = 5;

Directorate Technical Vocational Education

Page 83: Rekayasa perangkat lunak(Jilid2)

70 Software Engineering

// memanggil method hitungLuas() untuk masing-masing objek System.out.println(“Luas b1 = “ + b1.hitungLuas()); System.out.println(“Luas b2 = “ + b2.hitungLuas()); } }

In Example 8.25, we create a method hitungLuas that returns value. Please note that method declaration is not using void, but double as the returns value data type. To return a value, a keyword “return” is used. Compare calling method in Example 8.24 and 8.25, what is the difference?

Method may have argument similar to function or procedure. Examine the following example.

Example 8.26. Method creation with argument.

class Bangun { double panjang; double lebar; // method dengan argumen void isiData(double p, double l) { panjang = p; lebar = l; } // method yang mengembalikan nilai double hitungLuas() { double luas = panjang * lebar; return luas; } } class pakaiBangun { public static void main(String[] args) { Bangun b; // instansiasi obyek b = new Bangun(); // memanggil method isiData dan mengisi argumennya b.isiData(6,8); // memanggil method hitungLuas() untuk objek b System.out.println("Luas b = " + b.hitungLuas()); } }

In Example 8.26, we add one (1) more method to class Bangun, namely, isiData. Since, it returns no value, we use void. This method has two (2) arguments, namely, p

Directorate Technical Vocational Education

Page 84: Rekayasa perangkat lunak(Jilid2)

71 Software Engineering

and l that is used to collect the input value. Examine how to use this methid, see the part of b.isiData (6, 8).

Constructor is a special method, it is defined in time and automatically called when defining an object. Constructor is usually used to initialize the data value in a particular class. The name of method constructor must be the same as its class. Constructor has no return value and not void. Examine the following example.

Example 8.27. Constructor creation with class..

class Bangun { double panjang; double lebar; // constructor dengan argumen Bangun(double p, double l) { panjang = p; lebar = l; } // method yang mengembalikan nilai double hitungLuas() { double luas = panjang * lebar; return luas; } } class pakaiBangun { public static void main(String[] args) { Bangun b; // instansiasi obyek b = new Bangun(); // memanggil method isiData dan mengisi argumennya b.isiData(6,8); // memanggil method hitungLuas() untuk objek b System.out.println("Luas b = " + b.hitungLuas()); } }

The above code is nearly similar to Example 8.26, but in fact different. In this code, there is a constructor named Bangun same as its class. Constructor is similar to other method may or may not have argument. In the above example, the constructor Bangun has argument p and l.

8.8.2. Application of Inheritance Inheritance principle in general has been studied in the beginning of the chapter. An

Directorate Technical Vocational Education

Page 85: Rekayasa perangkat lunak(Jilid2)

72 Software Engineering

inheritance is a big advantage in an object oriented programming as a characteristic or a method defined in superclass, will be automatically bequeathed to all subclasses. So we may have to define a method once in superclass and may be used in subclasses. Examine the following exampile.

Example 8.28. Application of Inheritance.

class SuperA { private int a; public void setSuperA(int nilai) { a = nilai; } public int getSuperA() { return a; } } // membuat kelas turunan (subclass) dari kelas A class SubB extends SuperA { private int b; public void setSubB(int nilai) { b = nilai; } public int getSubB() { return b; } } class DemoKelasTurunan1 { public static void main(String[] args) { // melakukan instansiasi terhadap kelas B SubB ObyekB = new SubB(); // mengeset nilai objek dari kelas B ObyekB.setSuperA(50); ObyekB.setSubB(200); // mendapatkan nilai yang terdapat dalam objek dari kelas B System.out.println("Nilai a : " + Obyek.getSuperA()); System.out.println("Nilai b : " + Obyek.getSubB()); } }

In the above source code, class SuperA is a super class with one data, namely, a and two (2) methods, namely, setSuperA and getSuperA. Class SubB is the descendant from the class SuperA. Please note the declaration class SubB extends SuperA. Data and method available in class SuperA will be automatically brought to class SubB. Thus, class SubB will have two (2) data, namely, a and b. Data a is inheritance from class SuperA while data b is the property of class SubB. Method in class SubB

Directorate Technical Vocational Education

Page 86: Rekayasa perangkat lunak(Jilid2)

73 Software Engineering

consists of four (4) methods, namely, setSuperA and getSuperA that is the inheritance from class SuperA and class setSubB and getSubB that property of class SubB. Please type the program above source code and run, please examine the result.

Examine the following example.

Example 8.29. Implementation of inheritance to calculate area and volume.

class Bangun { protected double panjang; protected double lebar; // constructor default Bangun() { panjang = lebar = 0; } Bangun(double p, double l) { panjang = p; lebar = l; } // method yang mengembalikan nilai public double hitungLuas() { double luas = panjang * lebar; return luas; } } class Box extends Bangun { private double tinggi; // constructor class Box Box (int p, int l, int t) { panjang = p; lebar = l; tinggi = t; } public double getTinggi() { return tinggi; } public double hitungVolume() { double volume = panjang * lebar * tinggi; return volume; } } class inheritBangun { public static void main(String[] args) { Box kotak; // instansiasi obyek kotak = new Box(6, 8, 3);

Directorate Technical Vocational Education

Page 87: Rekayasa perangkat lunak(Jilid2)

74 Software Engineering

// memanggil method hitungLuas(), getTinggi() dan hitung volume() System.out.println("Luas salah satu sisi = " + kotak.hitungLuas()); System.out.println("Tinggi kotak = " + kotak.getTinggi()); System.out.println("Volume kotak = " + kotak.hitungVolume()); } }

The class Bangun is a superclass whereas Box is a subclass. In the default constructor Bangun, the length and wide value is initialized by 0. Examine in front of the declaration of the length and wide variable in the class Bangun includes key word protected means a decendants's class from Bangun may be able to access the value of the variable but not for those with no descendant relationship.

In Box, which is a subclass, we add one more variable, namely, tinggi, with added keyword private and its data type. Private means that variable tinggi may only be access internally in class Box. The opposite of private is public, that means to allow access by anyone from anywhere. In class Box, we also add one more method, namely, hitungVolume (). In Example 8.29, an object kotak is created based on class Box. Thus, Box is the decedent from class Bangun, and may access method hitungLuas () that is the inheritance from class Bangun. Of course, we could also access method getTinggi () and hitungVolume () that are the method in the class Box. When the program is executed, the followings will be shown.

Figure 8.15. Execution result from class Bangun dan class Box.

8.8.3. Implementation of Overriding and Overloading Sometimes, when we make a method inside a subclass, we want to make the method by using the same name as a method in the superclass but with the different application. For example, in class Bangun in Example 8.29, it is available method hitungLuas (). For example, we want to make a subclass Segitiga which is the descendant from the class Bangun. Then, we want to make method hitungLuas () that is no longer area = length x wide rather area = 0,5 x base length x high. In this condition, method hitungLuas () from superclass will be override by method in subclass. It is normally called overriding. Examine the following example.

Directorate Technical Vocational Education

Page 88: Rekayasa perangkat lunak(Jilid2)

75 Software Engineering

Example 8.30. Implementation of overriding.

class Bangun { // method umum public double hitungLuas() { System.out.println("Method belum terdefinisi"); Return 0; } } class Segitiga extends Bangun { private double alas; private double tinggi; Segitiga (int a, int t) { alas = a; tinggi = t; } // overriding method hitungLuas() public double hitungLuas() { double luas = 0.5 * alas * tinggi; return luas; } } class overridingBangun { public static void main(String[] args) { Segitiga s; // instansiasi obyek s = new Segitiga(6, 8); // memanggil method hitungLuas() dari subclass Segitiga System.out.println("Luas segitiga = " + s.hitungLuas()); } }

In the above example, class Bangun as superclass has a method hitungLuas(), but not yet defined. In the class Segitiga, method hitungLuas () is overriding to get the value of the area of the triangle. During program execution, the one that has been run is the method hitungLuas () is subclass Segitiga. Results of the program execution is shown in Figure 8.16. If we want to continue to run method hitungLuas () in class Bangun, it may be called by using keyword super. Change the method hitungLuas () in the class Segitiga by using the following code.

public double hitungLuas() { super.hitungLuas(); System.out.println(); double luas = 0.5 * alas * tinggi;

Directorate Technical Vocational Education

Page 89: Rekayasa perangkat lunak(Jilid2)

76 Software Engineering

return luas; }

Run the program, you will get the result as shown in Figure 8.17. Compare it with the previous result in Figure 8.16.

Figure 8.16. Result of overriding in method hitungLuas().

Figure 8.17. Result of overriding dan uses super statement.

Overloading is similar to overriding in terms hiding a method from a superclass. However, it has some differences, namely, in overloading, a method has the same name as the method in the parent class, but has different argument list and implementation. Whereas in overriding, method has the same name and same argument list as the parent class, only different in its implementation. Examine the following example.

Example 8.31. Example of overloading.

class Bangun { // method umum public double hitungLuas() { System.out.println("Method belum terdefinisi"); return 0; } } class BujurSangkar extends Bangun { private double sisi; // overload method hitungLuas()

Directorate Technical Vocational Education

Page 90: Rekayasa perangkat lunak(Jilid2)

77 Software Engineering

public double hitungLuas(double sisi) { double luas = sisi * sisi; return luas; } } class overloadBangun { public static void main(String[] args) { BujurSangkar b; // instansiasi obyek b = new BujurSangkar(); // memanggil method hitungLuas() dari subclass BujurSangkar System.out.println("Luas BujurSangkar = " + b.hitungLuas(6)); } }

Examine the above code, method hitungLuas () in the class Bangun has no argument. Whereas in the class BujurSangkar, it has argument, namely, sisi.. This is known as overloading. Please compare overriding example in Example 8.29 and 8.30.

8.8.4. Application of Polymorphism

As explain in the beginning of the chapter, polymorphism is the capacity to translate a method into various actions. In fact, when you study overriding and overloading, it is indirectly the foundation of the polymorphism. Polymorphism permitts the parent class (superclass) to define general methods for its descendants. Its descendant classes may implement method in accordance to each class characteristics.

In the Example 8.30 and 8.31, we make class Bangun that is the parent class that has a method hitungLuas (). This is a general method. In Example 8.30, we implement the method to calculate triangle's area in the class Segitiga. Whereas in Example 8.31, the method is implemented to calculate the area of BujurSangkar in class BujurSangkar. Please examine the followings example.

Example 8.32. Application polymorphism.

class Bangun { public double hitungLuas() { System.out.println("Method umum"); return 0; } } class BujurSangkar extends Bangun { private double sisi; BujurSangkar(int s) { sisi = s;

Directorate Technical Vocational Education

Page 91: Rekayasa perangkat lunak(Jilid2)

78 Software Engineering

} //overriding method hitungLuas() public double hitungLuas() { double luas = sisi * sisi; return luas; } } class Segitiga extends Bangun { private double alas; private double tinggi; Segitiga (int a, int t) { alas = a; tinggi = t; } // overriding method hitungLuas() public double hitungLuas() { double luas = 0.5 * alas * tinggi; return luas; } } class Lingkaran extends Bangun { private double jarijari; private final double PI = 3.1416; Lingkaran(int r) { jarijari = r; } //overriding method hitungLuas() public double hitungLuas() { double luas = PI * jarijari * jarijari; return luas; } } class DemoPolimorfisme2 { public static void main(String[] args) { Bentuk obyek; BujurSangkar b = new BujurSangkar(12); Segitiga s = new Segitiga(5, 6); Lingkaran l = new Lingkaran(4); // obyek mengacu pada objek BujurSangkar obyek = b; // akan memanggil method yang terdapat pada BujurSangkar System.out.println(“Luas bujursangkar : “ + obyek.hitungLuas()); System.out.println(); // obyek mengacu pada objek Segitiga obyek = s; // akan memanggil method yang terdapat pada Segitiga

Directorate Technical Vocational Education

Page 92: Rekayasa perangkat lunak(Jilid2)

79 Software Engineering

System.out.println(“Luas segitiga : “ + obyek.hitungLuas()); System.out.println(); // obyek mengacu pada objek Lingkaran obyek = l; // akan memanggil method yang terdapat pada Lingkaran System.out.println(“Luas lingkaran: “ + obyek.hitungLuas()); System.out.println(); } }

In Example 8.32, we combine the previous examples to show how polymorphism is formed. The parent class is Bangun and with subclass is BujurSangkar, Segitiga and Lingkaran. All of the subclasses have method hitungLuas () that is decendent from class Bangun. Please note that despite the name method hitungLuas () is in all subclasses, its implementation is different and depends on its subclass respectively.

8.8.5. How to use Package and Interface In some section, we have touched on package. Packages in JAVA means grouping of several classes and interface into one unit. This feature provides way to manage a large number class and interface and to avoide disorder in class and file naming.

Examine closely Example 8.4 in previous section, we have indirectly used package concept. In the Example, we use import statement to use classes in Java.IO package. Java provides many packages that has been written by java developer team. These packages are to make the programming easier.

To create a package is fairly easy. Use keyword follow by package name.

package NamaPaket;

NamaPaket is the package name to store the program code and compiled file. Java uses system directory to store package. If we made the package named PaketBangun, then we must create a directory using the exact name as PaketBangun. File and class in one package must be stored in the same directory. Please examine the following example.

Example 8.33. Package Creation.

In this section, we will create a package that is modified from Example 8.32. The package name is PaketBangun with three (3) class members, namely, class BujurSangkar, class Segitiga and class Lingkaran. As an initial stage, create a directory named PaketBangun. In this example, the directory is located in D:\TestCode\Java\PaketBangun. Then, write the following source code, store and

Directorate Technical Vocational Education

Page 93: Rekayasa perangkat lunak(Jilid2)

80 Software Engineering

named according to the class in directory PaketBangun. Please note that in the beginning of a class must be started by statement package PaketBangun;. It shows that the class is a member of PaketBangun.

File : BujurSangkar.java package PaketBangun; class BujurSangkar extends Bangun { private double sisi; public BujurSangkar(int s) { sisi = s; } public double hitungLuas() { double luas = sisi * sisi; return luas; } }

File : Segitiga.java package PaketBangun; class Segitiga extends Bangun { private double alas; private double tinggi; public Segitiga (int a, int t) { alas = a; tinggi = t; } public double hitungLuas() { double luas = 0.5 * alas * tinggi; return luas; } }

File : Lingkaran.java package PaketBangun; class Lingkaran extends Bangun { private double jarijari; private final double PI = 3.1416; public Lingkaran(int r) { jarijari = r; } public double hitungLuas() { double luas = PI * jarijari * jarijari; return luas; } }

Directorate Technical Vocational Education

Page 94: Rekayasa perangkat lunak(Jilid2)

81 Software Engineering

Do classpath management as shown in the beginning of the chapter. Compile these three (3) files to get the result as shown in Figure 8.18.

Figure 8.18. Compile the three (3) files as part of the package.

After a successful compilation, create new file in directory D:\TestCode\Java, for example PakaiPaketBangun.java. Type the following code in the file. Compile and run the source code.

//import seluruh kelas pada PaketBangun import PaketBangun.*; class PakaiPaketBangun { public static void main(String[] args) { BujurSangkar b = new BujurSangkar(12); Segitiga s = new Segitiga(5, 6); Lingkaran l = new Lingkaran(4); System.out.println("Luas bujursangkar : " + b.hitungLuas()); System.out.println(); System.out.println("Luas segitiga : " + s.hitungLuas()); System.out.println(); System.out.println("Luas lingkaran: " + l.hitungLuas()); System.out.println(); } }

Directorate Technical Vocational Education

Page 95: Rekayasa perangkat lunak(Jilid2)

82 Software Engineering

Please examine how to write and call package. If we need only class Lingkaran, we must write import PaketBangun.Lingkaran;. but if we need all the classes then we use import PaketBangun. *;. If we run the result is the same as Example 8.33. The main difference is that in Example 8.32 collect all class in a single file. While in Example 8.33, classes are in respective file and grouped in package.

Interface in Java programming language is similar to class, but without class attribute and with declared method without content. Declaration method of an interface may be implemented in other class. A class may be implemented in more than one interface. Method in interface may be implemented in a class must be the same as the one in interface. Interface is used if we want unrelated class implement the same method. Please examine the following example.

Example 8.34. Create interface. interface Bentuk { public double luas(); public double volume(); }

In the above example, we make an interface named Bangun with two (2) methods, namely, area() and the volume(). Examine how to write interface. Both methods is declared without content. We may use the interface to create new class and implement the interface in the new class. Examine the following example.

Example 8.34. The use of Interface.

class Kubus implements Bentuk { int x = 10; public double luas( ) { return (6 * x * x); } public double volume() { return (x * x * x); } } class Lingkaran implements Bentuk { int radius = 10; public double luas() { return (Math.PI * radius * radius); } public double volume() { return 0; } }

Directorate Technical Vocational Education

Page 96: Rekayasa perangkat lunak(Jilid2)

83 Software Engineering

8.9. SUMMARY

● Important concepts in object oriented programming are class, object, abstraction, encapsulation, inheritance and polymorphism.

● There are eight (8) basic data types in Java, namely, boolean (for logic form), Char (for textual form), byte, short, int, long (integer), double and float (floating point).

● Operators in Java are arithmetic operator, relational, logic and bitwise.● Control program structure for branching may be done by statements if, if...

else, and if... else... if, whereas the looping may be done with for, while and do-while.

● Exception is an abnormal condition during runtime. Java provides mechanisms, such as, try, throw, catch and finally to handle exception.

● Thread is a program section that is not depend on other part of the main program and may be run simultaneously together.

● Java fully supports the concept of class, inheritance, overriding, overloading, and polymorphism.

● Package is a collection of classes. Whereas interface is a class without the attribute and has method declare without the contents.

8.10. EXERCISES

1. Create a program to print the value of the following variables with different data type and initial value, namely.a. Data type float, initial value = 3.45.b. Data type char, initial value = B.c. Data type int, initial value = 23.

2. Create a program to calculate the average value of the following three (3) variables, namely, number1 = 56,3, number2 = 12 and number3 = 2,78.

3. Using variables in problem no. 2, create a program to seek for the smallest value from these three (3) variables.

4. Get three (3) Exam values from user and calculate its average value. Print “Congratulation” if the average value is larger than 60, in addition of print the average value. Use BufferedReader to get input from user, and System.out to print results.

5. Create a program to print your name a hundred times. Create three (3) version of the program using while loop, do while and for-loop.

6. Using class, create a program on class of school staff. This is a superclass

Directorate Technical Vocational Education

Page 97: Rekayasa perangkat lunak(Jilid2)

84 Software Engineering

which has subclass teacher and subclass administrative staff.

● The class school staff has variables, namely, name, address, children,start working date, and rank. Moreover, it has method work period, calculated from start working date and current date, and method to calculate basic salary. The basic salary is calculated from basic payment plus work period allowance, rank allowance and children allowance. Moreover, method to calculate total payment is not defined yet.

● Class teacher, in addition to variables and methods in superclass, it has additional variables, namely, field of expertise and method to calculate teaching allowance based on the hours time the allowance per hour. Define method to calculate total payment as main salary plus teaching allowance.

● Class administrative staff, in addition to variables and methods in superclass, it has additional variables, namely, weekly working hours and method to calculate overtime. Overtime allowance is calculated as the additional hours from 40 hours per week working hour. Overtime allowance is overtime hours times overtime charges per hour. Define method to calculate total payment as main salary plus overtime allowance.

Directorate Technical Vocational Education

Page 98: Rekayasa perangkat lunak(Jilid2)

85 Software Engineering

CHAPTER 9 APLICATION PROGRAM C++

Figure 9.1 may raise question. What is its relation with the above chapter title? Do you know that the space shuttle in Figure 9.1 is controlled by a sophisticated computer with most of its applications written in C++ programming language.

The standard competence in application programming using C++ consists of five (5) basic competences. In this book, each basic competence contains the objectives, material, and exercise. The summary is at end of each chapter. Basic competence of this chapter is the foundation of C++ programming, applying function, pointer, class concept, and designing an object oriented programming. Please review chapter on operating system, algorithm and concept of object oriented programming in previous chapters.

In the final section, exercise is compiled from the easiest to the more difficult exercise. These exercises are used to measure the capacity on basic competence in this chapter. It is suggested to do these exercises at school under your teacher's guidance or at home.

THE OBJECTIVES

After studying this chapter, the reader is hoped to be able to,

● Explain the basic of C++ programming.● Applying function.● Applying pointer.● Applying class concept.● Designing an object oriented application.

Directorate Technical Vocational Education

Figure 9.1. Space Shuttle.

Page 99: Rekayasa perangkat lunak(Jilid2)

86 Software Engineering

9.1. BASIC C++ PROGRAMMING C++ is a popular language in the software developing world. Like its predecessor the C Language, C++ is a middle level language. The main objective of C++ is to increase the programmer productivity in application creation. C++ is of interest as it supports object oriented programming. Moreover, there are many books / library that could be used to speed up the application creation. Some of these libraries are freely available on the Internet.

Source code in C++ may not be directly used. We have to compile it using approriate C++ compiler. Compilation and execution concept of C++ program is shown in Figure 9.2. The source code is a text file with extension .cpp. The source code is put into PreProcessor. The PreProcessor output file is for the Compiler. Compiler will translate the PreProcessor output file into assembly language. This code is then processed by the Assembler into object code. If no library is used, the object code may be directly executed into a file. If library is used, Link Editor will combine the object code and the library to create the EXE file.

We may type the C++ code in any text editor, such as, Notepad, vi, etc. However, it would be much easier if we could use IDE (Integrated Development Environment) tool that integrates text editor and C++ compiler. Some of the famous C++ are Microsoft Visual the Studio, Borland C++, MingGW Developer Studio, etc.In this book, most of the code is written using MinGW Developer the Studio as shown in Figure 9.3. The licence of MinGW IDE is free. Thus, we could use it without worrying about the software license. MinGW may be downloaded from http://visual-mingw.sourceforge.net/.

Figure 9.2. Compilation processes in C++

Directorate Technical Vocational Education

Page 100: Rekayasa perangkat lunak(Jilid2)

87 Software Engineering

Figure 9.3. MingGW Developer Studio

9.1.1. Structure of C++ Program.

Please examine the above source code. The code consists of several sections, namely,

● Section to include libraries or setting a certain condition. It uses a statement starts with #.

● Section to define a function. A function starts with void and follows by function name. This section may or may not be used to create a function.

● Section main(). The main program code starts with int main(). This section must be available in all program as it is the main program.

● Section starts with { and end with }, in

Directorate Technical Vocational Education

Page 101: Rekayasa perangkat lunak(Jilid2)

88 Software Engineering

void as well as in main, is called block code.

9.1.2. Header File (.h) Header file is a file with extension. h that contains certain functions that has been previously compiled. This file is usually contained files / library to be included in our source code / program. For example file iostream.h has some functions to show output and capture input such as cout and cin.

There are two writing file header models, namely, write complete with extension and not. First model is for older C++ compiler as Example 9.1. The Second model is a standard C++ compiler as in Example 9.2.

Example 9.1. Writing file header for older C++ Compiler.

#include <iostream.h> Int main() { ... return 0; }

Example 9.2. Writing file header for standard C++ Compiler.

#include <iostream> using namespace std; Int main() { ... return 0; }

9.1.3. Comment, Identifier and Data Type

● Comment

Comment in C++ may be written in two format, namely, starts with // sign or put the comments start with /* and close with */. First method is used if comment only one line, whereas second method if comment more than one line.

Example 9.3. Comment with sign //.

// first program #include <iostream> int main( ){

Directorate Technical Vocational Education

Page 102: Rekayasa perangkat lunak(Jilid2)

89 Software Engineering

cout << "Hello World"; // print “Hello World” on screen }

Example 9.4. Comment with sign /* .. */..

/* first program Written by ARM Date 17-11-2007 */

#include <iostream> int main( ){ std::cout << "Hello World"; // print “Hello World” on screen }

● Identifier

Identifier or variable name or constant in C++ is generally followed the naming rules as described in Chapter 5. There is one important note that C++ identifier is case sensitive. Thus, varible techername and TeacherName is different.

There are two ways to declare a constant. Firstly, we use preprocessor directive #define. Secondly, we use the key word const. Type the following program and check execution result.

Example 9.5. Constant Declaration

#include <iostream> #define cut 0.1; using namespace std; int main() { const float pricePerUnit = 2500; int totalUnit; float priceTotal, priceDiscount, discount; cout << "Input total purchasing unit : "; cin >> totalUnit; priceTotal = totalUnit * pricePerUnit; discount = priceTotal * cut; priceDiscount = priceTotal - discount; cout << "Total price purchasing = " << priceTotal << endl; cout << "Discount = " << discount << endl; cout << "Price Discount = " << priceDiscount; return 0; }

Directorate Technical Vocational Education

Page 103: Rekayasa perangkat lunak(Jilid2)

90 Software Engineering

In the above example, there are two constants, namely, cut and pricePerUnit which are differently declared.

Variable declaration is firstly done by setting the data type followed by variable name as in Figure 9.5. There are some defined variables, namely, totalUnit, priceTotal, priceDiscount and discount. For variable with the same data type, it may be declare in one line separated by comma. Examine the above example, priceTotal, priceDiscount and discount have same float data type.

You should completely declare all variables or constants prior to use. If not then the program will not be executed.

● Data type

As explain in Chapter 5, data type depends on the programming language. The basic data type in C++ is in the following table. The data type is fairly similar to Java. This is due to Java takes some elements programming language from C++.

Table 9.1. Data type in C++

Data Type Describes

Intlongfloatdoublechar

boolshort

Integer data type with 4 bytes widthInteger type but larger than intData type in fraction Data type in fraction but larger than floatData type in character with letter, numeric, symbols (alphanumeric) as long as within sign “ “ or ' '.Data type booleanData type in integer with 2 bytes width

Data structure in C++ are array, struct and enum. Array will explain an other section in this chapter. While struct and enum has been described in Chapter 5. In this chapter, we will describe the syntax to write these structure. Please type the following source code and see the execution result.

Example 9.6. Using struct data type

#include <iostream> using namespace std; int main() {

struct Teacher { char* NIP;

Directorate Technical Vocational Education

Page 104: Rekayasa perangkat lunak(Jilid2)

91 Software Engineering

char* Name; char* Address; };

Teacher A; A.NIP = "132 232 477"; A.Name = "Syafiq"; A.Address = "Perum. Dirgantara Permai";

// Showing score – fill in to screen cout<<A.NIP<<endl; cout<<A.Name<<endl; cout<<A.Alamat<<endl; return 0; }

Example 9.6. Using enum data type

#include <iostream> using namespace std; enum SEX { Man, Woman }; int main() {

struct Teacher { char* NIP; char* Name; SEX JK; } A;

A.NIP = "132 232 477"; A.Name = "Syafiq"; A.JK = Man;

cout<<"NIP : "<<A.NIS<<endl; cout<<"Name : "<<A.Name<<endl; cout<<"Sex : "<<A.JK<<endl;

return 0; }

9.1.4. Operator

Directorate Technical Vocational Education

Page 105: Rekayasa perangkat lunak(Jilid2)

92 Software Engineering

Similar to VB and Java, C++ also provides operators to help solving problems. There are fairly similar operators between Java and C++. The available operator in C++ is shown in Table 9.2.

Table 9.2. Operator in C++

Operator Type Function Example

Operator Assignment

'= Assign value into a variable C = 5

Unary Operator

+ Make positive value X = + 10

- Make negative value Y = - 12

++ Increase variable one value ++C (pre-increment)C++ (post-increment)

- - Decrease variable one value --C (pre-increment)C-- (post-increment)

Binary Operator

+ Adding 3 + 5 = 8

- Substitute 7 – 2 = 5

* Multiplying 5 * 2 = 10

/ Dividing 6 / 3 = 2

% Modulus 5 % 2 = 1

Logical Operator

&& AND 1 && 1 = 1

II OR 1 II 0 = 1

! NOT 10 = 1

Relational Operator

> Bigger (5 > 4) = 1

< Smaller (5 < 4) = 0

>= Bigger or equals (4 > = 4) = 1

<= Smaller or equals (5 < = 4) = 0

'== Equals (5 == 4) = 0

Directorate Technical Vocational Education

Page 106: Rekayasa perangkat lunak(Jilid2)

93 Software Engineering

!= Unequals (5 ! = 4) = 1

Bitwise Operator

& AND 1 & 0 = 0

I OR 1 I 0 = 1

^ XOR 1 ^ 1 = 0

~ NOT ~0 = 1

Ternary Operator

?: Use if it involves 3 operators

9.1.5. Control Program Structure C++ control program structure is fairly the same as VB and Java. The difference is only in its syntax. For branching, C++ provides if (without then) and switch ... case. For repetition, C++ provides for, while, do-while. In addition, C++ provides break and continue facilities for loop. Below is some example in applying control program structure. Type in the code, and observed the execution result.

Example 9.7. The use of simple if branching

#include <iostream> using namespace std; int main() { int bil;

cout<<"input an integer : "; cin>>bil;

// To check variable by operator modulus if (bil % 2 == 0) { cout<<bil<<" is even number" << endl; } else { cout<<bil<<" is odd number" << endl; } return 0; } In the above example, we use if to check whether a number is even or odd. Modulus (%) operator is used. Examine how to write the structure if and else.

Directorate Technical Vocational Education

Page 107: Rekayasa perangkat lunak(Jilid2)

94 Software Engineering

Example 9.8. Using if branch structure for three (3) conditions

#include <iostream> using namespace std; int main() { int bil;

cout<<"Input an integer : "; cin>>bil;

if (bil > 0) { cout<<bil<<" is POSITIF number"; } else if (bil < 0) { cout<<bil<<" is NEGATIF number"; } else { cout<<"is ZERO number"; } return 0; }

Example 9,8. is a development from Example 9.7. Branching structure is developed for three (3) conditions by adding else. For more than three (3) or many conditions, C++ provides switch ... case command to facilitate the selection process. Examine the following example.

Example 9.9. Using branch structure switch ... case.

#include <iostream> using namespace std; int main() { int bil;

cout<<"Input a number (1 - 5) : "; cin>>bil;

switch (bil) { case 1 : cout<<"Your number is : ONE"; break; case 2 : cout<<"Your number is : TWO"; break; case 3 : cout<<"Your number is : TIGA"; break; case 4 : cout<<"Your number is : FOUR";

Directorate Technical Vocational Education

Page 108: Rekayasa perangkat lunak(Jilid2)

95 Software Engineering

break; case 5 : cout<<"Your number is : FIVE"; break; default : cout<<"Your input over capacity"; } return 0; }

Example 9,9. uses switch for branching and convert number into text. Examine how to write switch and case.

As in Java, looping with for may be used if we know exactly how many repetition will be done. The following is a loop example with for.

Example 9.10. Loop structure with for.

#include <iostream> using namespace std; int main() { int C, J;

cout<<"Print number from small to big :"<<endl; for (C=0; C<10; C+3) { cout<<C+1<<endl; }

cout<<endl; cout<<"Print number from big to small"<<endl; for (J=10; J>0; J--) { cout<<J<<endl; } return 0; }

Example 9.10. is a simple case on using for. There are two (2) for loop, one is to print 1 to 10 and from 10 to 1. Note the use of increment ++ and decrement --. The syntax / written method is fairly similar to Java. In Example 9.11 the loop using for is expanded by using nested for,.

Example 9.11. Loop structure using nested for.

#include <iostream> using namespace std;

Directorate Technical Vocational Education

Page 109: Rekayasa perangkat lunak(Jilid2)

96 Software Engineering

int main() { for (int j=1; j<=4; j++) { for (int k=1; k<=3; k++) { cout<<k+j<<' '; } cout<<endl; } return 0; }

There are two loops in Example 9.11. The first loop uses j as variable counter, the second loop uses variable counter k that nested to loop j. What should be the output of the program?

Use while in a loop, is not that different from Java and VB. Please examine Example 9.12 and 9.13.

Example 9.12. Loop structure using while command.

#include <iostream> using namespace std;

int main() { int C; C = 1; // initialization value C

while (C<10) { cout<<"I am not naughty anymore"<<endl; C++; // increment } return 0; }

Example 9.13. Loop structure using nested while.

#include <iostream> using namespace std;

int main() { int x, y; x = 1; //initialization variabel x

while (x<=4){ y = 1; //initialization variabel y

Directorate Technical Vocational Education

Page 110: Rekayasa perangkat lunak(Jilid2)

97 Software Engineering

while (y<=3){ cout<<y+x<<' '; y++; } cout<<endl; x++; } return 0; }

Examine the above Example 9.12, what do you think output from the program? Compare it with Example 9.11. Try to change initialization for variable y. Put it after after initialization of variable x. How is the results?

Another from of loop in C++ is the do-while. A little bit different from while, condition check in do-while is at the end of the loop body. Example 9.14 gives explanation how to use a do-while in in C++.

Example 9.14. The use of do-while structure.

#include <iostream> using namespace std;

int main() { int J = 5; int K; do { K = 1; do { cout<<K*J<<' '; K++; } while (K <= J); cout<<endl; J--; } while (J >= 1); return 0; }

Example 9.14 shows a quite complicated source code. As we examine more closely, it is basically a loop with nested do while. Examine how to write and logical flow of the program. The outer do-while uses variable counter J and will loop from the large number to small as we can see J is initialized with 10 while J > =1. While the inner do-while uses variable counter K and loop from the small to big. How is the execution results of the source code? Examine the following output. Please examine the source code to really understand why the output program becomes like this.

Directorate Technical Vocational Education

Page 111: Rekayasa perangkat lunak(Jilid2)

98 Software Engineering

5 10 15 20 25 4 8 12 16 3 6 9 2 4 1

9.1.6. Input / Output So far, we have done a significant amount of programming exercises using C++. However, we have not yet learn the input / output statement in C++. Although, if you noticed the input / output statement has been indirectly studied. cout and cin command are the mostly used input/output statement.

cout and cin commands are classified as stream and included in iostream class. Thus, we need to include header file iostream in the beginning of a program to use these two (2) commands. Stream is a logical device to get or to put data. Stream connects with hardware such as keyboard, screen monitor, printer via I/O system. Command cin is stream for input standard. This command will get anything we type on keyboard. Examine how to write it in Example 9.15.

Example 9.15. The use of cin and cout.

#include <iostream> using namespace std;

int main() { int bil1, bil2; //cin part one cout<<"In put first number : "; cin>>bil1; cout<<"In put second number : "; cin>>bil2; cout<<"Result multiply both number = "<<bil1*bil2<<endl; //cin part two cout<<"In put two numbers : "; cin>>bil1>>bil2; cout<<"Result multiply both number = "<<bil1*bil2<<endl; return 0; }

cin command may be used to get character one by one as in Example 9.15, please

Directorate Technical Vocational Education

Page 112: Rekayasa perangkat lunak(Jilid2)

99 Software Engineering

examine section below //cin part one, or get directly the data in sequence as shown in section below //cin part two. Command cin must be followed by operator >>.

cout command will do a standard output to monitor screen. cout command must be followed by operator <<. Examine the above Example 9.15. cout command may be used to directly print character in between two (2) marked “ “ or content variable. As in cin, cout command may be used to display character one by one or at the same time. In the above Example, the endl statement is used to print new line.

9.2. FUNCTIONS IN C++

Functions in C++ has an important role. As C++ code is basically a collection of functions. All available functions as well as the one we make, may be called from the main() function. As all programming languages, C++ provides built-in function and may be accessed by including the header file in the beginning of the C++ Program. C++ also provides facilities to create user-defined functions. This section will explain how to create a user-defined function.

9.2.1. Function Types

There are two (2) types of function, namely, function without return value and function that returns value.

● Function without return value.

This function is a void type. In VB or Pascal, this function is known as procedure. Examine the Example 9.16.

Example 9.16. Function without return value.

#include <iostream> using namespace std;

// Making function print-out number void Print-outNumber() { for (int C=0; C<10; C++) { cout<<C+1<<endl; } } // Main function in program C++ int main() {

Directorate Technical Vocational Education

Page 113: Rekayasa perangkat lunak(Jilid2)

100 Software Engineering

// Calling funcion Print-outNumber Print-outNumber(); return 0; }

In the above example, we create a function, namely, Print-outNumber with type void so no return value. Examine how to declare the function. The function will run up to end of function code.

● Function with return value.

This function will return a value to be used by other program. To define this function, we don't use void, use data type of the returned value. Examine Example 9.17.

Example 9.17. Function with return value

#include <iostream> using namespace std;

// Making function with return value by char type char* CharValue() { return "Value to be return"; } // Main function

int main() { // Calling and viewing result function cout<< CharValue(); return 0; }

In type of function, we need a return statement to show section that returns value. In the above Example, the return value data type is char. The mark * in data type char means that variable CharValue may contain more than one letter and will keep/print as we input data.

9.2.2. Using Parameter in Function

As VB and Java, function C++ also allows the use of parameter or argument to pass input or collect output from this function. Examine the example below.

Directorate Technical Vocational Education

Page 114: Rekayasa perangkat lunak(Jilid2)

101 Software Engineering

Example 9.18. Function by parameter input.

#include <iostream> using namespace std;

// Making function by parameter input int Quadratic(int X) { int result; result = X * X; return value; }

int main() { int Val, Result; cout<<"Input an integer : "; cin>>Val; RESULT = Quadratic(Val); //calling quadrant function cout<<"Quadratic from number “<<Val<<”is : "<<RESULT; return 0; }

Function in example 9,18 are a simple quadratic. This function needs one input variable input, namely, X. In function main(), variable Val is used to keep value to pass the parameter for calling quadratic function.

Example 9.19. Function with input and output parameter.

#include <iostream> using namespace std;

// Making function with parameter input int Quadrant(int X, int *result) { *result = X * X; return *result; } int main() { int NUMBER, RESULT; cout<<"Input an integer : "; cin>>Bil; // Showing value after process in function cout<<"Quadrant from number"<<Number<<" is : "<<Quadrant(Number, &RESULT); return 0; }

Directorate Technical Vocational Education

Page 115: Rekayasa perangkat lunak(Jilid2)

102 Software Engineering

Example 9.19 is a development from Example 9.18. In the Quadratic function, we add parameter output, namely, result. Output parameter must be passed base on memory address (namely result), pointer (mark *). In calling the function, input and output parameter must be called. The output parameter to store the calculation results must be given prefix &.

9.3. POINTER AND ARRAY C++ language allows us to manipulate memory by using pointer. This feature is not provided in other programming language. It is very beneficial if it is correctly used. However, it may crashing the operating system if wrongly used.

9.3.1. Concept and Understand Pointer Pointer is variable. However, it is different with normal variable, pointer keeps the address in memory, but not the input value. Examine the following example.

Example 9.20. Pointer declaration.

#include <iostream> using namespace std;

int main() { long *Address; long X;

Address = &X; X = 5; // Input value 5 into variabel X

cout<<"Value X : "<<X<<endl; cout<<"Value *Address : "<<*Address<<endl; cout<<"Value Address : "<<Address<<endl; cout<<"Value &X : "<<&X<<endl;

*Address = 20; // Input value 20 into *Address

cout<<"Value X : "<<X<<endl; cout<<"Value *Address : "<<*Address<<endl; cout<<"Value Address : "<<Address<<endl; cout<<"Value &X : "<<&X<<endl; return 0; }

In the above example, we declare variable Address as pointer by adding mark * in front

Directorate Technical Vocational Education

Page 116: Rekayasa perangkat lunak(Jilid2)

103 Software Engineering

of variable name. If we do not use * , then variable will function as normal variable. Variably X is declared as normal variable with data type long. Please note the statement Address = &X. This statement means that variable Address (not pointer) will fill in with value address from X. Mark & in front of variable name means we want use the value of memory address but not the actual value. The execution result is shown in Figure 9.4.

Figure 9.4. Execution result from pointer declaration.

Examine the output values in Figure 9,4. Value 0x22ff88 is a hexadecimal number from variable address. If you observe, when we put the value 5 into variable X then variable *Address will contain the value 5. And if we put the value 20 into variable *Address, value X is changed to 20. This because variable *Address and X occupy same address memory.

Every time we declare a pointer, it will point to random address in memory. To avoid this, we must set the variable pointer with adding value NULL. Please see the execution result in Figure 9.5.

Example 9.21. Pointer declaration with NULL.

#include <iostream> using namespace std; int main() { long *Address; long *Address1; Address = NULL; cout<<"Address memory pointer with NULL : "<<Address<<endl;

Directorate Technical Vocational Education

Page 117: Rekayasa perangkat lunak(Jilid2)

104 Software Engineering

cout<<"Address memory pointer without NULL : "<<Address1<<endl; return 0; }

Figure 9.5. Execution result with NULL pointer.

9.3.2. Using New and Delete in Pointer

Keyword New may be used to allocate memory in empty space. This keyword should be followed by the data type used to let the compiler knows the memory to be allocated. While keyword Delete is the opposite of New. Delete will release memory from our variable. Delete is very important, as undelete memory will consume / waste the memory and make the system uncontrollable. Examine the following example in using New and Delete.

Example 9.22. Using new and delete.

#include <iostream> using namespace std;

int main() { int *Address; // To allocation memory Address = new int;

// Using memory which allocated *Address = 100;

cout<<"Value *Address : "<<*Address<<endl;

// free the memory delete Address; return 0;

Directorate Technical Vocational Education

Page 118: Rekayasa perangkat lunak(Jilid2)

105 Software Engineering

} 9.3.3. Array As mention earlier, array is used to keep many data with same type in one variable name. Array definition in C++ almost the same as VB or Java. The only different is the syntax. Examine the example below.

Example 9.23. Simple Array.

#include <iostream> using namespace std;

int main() { // declaration array A with 5 type elements int int A[5];

cout<<"A[C]"<<" "<<"B"<<endl; // Input value to array element for (int C=0; C<5; C++) { double B = 5; A[C] = C; B = A[C]/B; cout<<A[C]<<" "<<B<<endl; } return 0; }

In the above example, we declare array named A with data type int. C is the variable counter. To put value in an array, examine the statement A [C] = C. C is the index for variable A. Same as VB or Java, the starting default of the array index is 0. The execution result is shown in Figure 9.6.

Directorate Technical Vocational Education

Page 119: Rekayasa perangkat lunak(Jilid2)

106 Software Engineering

Figure 9.6. Execution result of a simple array program

In the above Example 9.23, we declare array without initialization value. But in fact we can direct give value together with declaration array variable. We may later change the value in other program or when program is in process. Examine the Example 9.24 .

Example 9.24. Array declaration and initialization.

#include <iostream> using namespace std;

int main() { // Declaration and array initiation char X[3] = { 'A', 'B', 'C' }; // Showing early value array element cout<<"Value array early"<<endl; cout<<"X[0] = "<<X[0]<<endl; cout<<"X[1] = "<<X[1]<<endl; cout<<"X[2] = "<<X[2]<<endl; // Change element to-1 and to-2 X[0] = 'G'; X[1] = 'H'; // Showing change value array element cout<<"Array value after change"<<endl; cout<<"X[0] = "<<X[0]<<endl; cout<<"X[1] = "<<X[1]<<endl; cout<<"X[2] = "<<X[2]<<endl; return 0; } The execution result is shown in Figure 9.7.

Directorate Technical Vocational Education

Page 120: Rekayasa perangkat lunak(Jilid2)

107 Software Engineering

Figure 9.7. Execution result from array declaration and initialization.

C++ also provides feature for multidimensional array. Multidimensional array declaration is shown in Example 9.25.

Example 9.25. Multidimensional array declaration.

#include <iostream> using namespace std;

int main() { // Declaration and initialization array multidimensional int Matrix_A[3][2] = { {1,2}, {3,4}, {5,6} }; int Matrix_B[2][3] = { {1,2,3}, {4,5,6} };

// Declaration variable for repetition index int j, k;

// Showing value by keeping array A element cout<<"CONTENTS MATRIX A"<<endl; for (j=0; j<3; j++) { for (k=0; k<2; k++) { cout<<"Matrix A["<<j<<"]["<<k<<"] = "<<Matrix_A[j][k]<<endl; } cout<<endl; }

// Showing value by keeping array B element cout<<"CONTENTS MATRIX B"<<endl; for (j=0; j<2; j++) { for (k=0; k<3; k++) { cout<<"Matrix B["<<j<<"]["<<k<<"] = "<<Matrix_B[j][k]<<endl; } cout<<endl; } return 0; }

In the above example, there are two (2) multidimensional arrays, namely, Matrix A and Matrix B. Both are two dimensional matrix. Matrix A has 3 rows and 2 columns whereas Matrix B has 2 rows and 3 columns. Value fills in is done during declaration. However, we may fill it using keyboard via cin cmmand. The execution result is shown in Figure 9.8.

Directorate Technical Vocational Education

Page 121: Rekayasa perangkat lunak(Jilid2)

108 Software Engineering

Figure 9.8. Result execution of multidimensional array.

9.4. CLASS Class concept in C++ is the same as described in Chapter 8. This concept is derived from the object oriented programming paradigm. If you understand well the object oriented programming and Java class programming, then class in C++ concept is not a problem. You much understand, Java adopt most of the C++ programming concepts, including class. The main difference perhaps only in the syntax. In the section, we will not explain the object oriented programming, but the actual implementation in C++.

9.4.1. Class Declaration Same as Java, C++ class creation uses class as keyword. In a class, there is data and method that will be used by an object (instance). Data and method is usually called class member. Method in C++ has same form as function.

Example 9.26. Declaration and using class

#include <iostream>

Directorate Technical Vocational Education

Page 122: Rekayasa perangkat lunak(Jilid2)

109 Software Engineering

using namespace std;

class Rectangle { int x, y; public: void set_value (int,int); int wide() {return (x*y);} };

void Rectangle::set_value (int a, int b) { x = a; y = b; }

int main () { Rectangle pp1, pp2; pp1.set_value(3,4); pp2.set_value(7,12); cout << “Wide pp1 : “ << pp1.wide()<<endl; cout << “Wide pp2 : “ << pp2.wide()<<endl; return 0; }

Example above example, the class declared named Rectangle and has two class data member, namely, x and y and two methods, namely, set_value and wide (). The two (2) methods has public access. Same as java, there are three (3) access rights for data or method in class, namely, public, private and protected. Public means class member can access from outside class. Private means class member can only be accessed in class. Protected means class member can be accessed by subclass from class, but not from outside class.

Method set_value has two (2) arguments / parameters with data type int but does not have return value, so we use key word void. Method wide() does not have argument but returns value. To return value on a Method we use data type in front of method name.

In C++ we can implement method in or outside the class , but method declaration must be in side the class. We generally put method implementation outside the class (outside sign {}). Examine the above example. Declaration of method set_value is inside class Rectangle but the implementation is outside the class. Whereas method wide(), both the declaration and the implementation are inside the class. Implementation method outside the class uses sign::, also to define outside class member, (Examine the statement void Rectangle::set value (int a, int b)).

After class is formed, we can use and make object which is an instance of the class.

Directorate Technical Vocational Education

Page 123: Rekayasa perangkat lunak(Jilid2)

110 Software Engineering

Examine the beginning part is starts with int main (). In this part, we create two (2) objects, namely, pp1 and pp2 as instance from Rectangle class. Then we use these objects to call method set_value and wide() from Rectangle class. Type above program and run it. How is results?

Similar to Java, a class have generally a constructor that use to initiate variable or allocate memory. Constructor has same name as the class. In a class, it would be better to add method destructor. Destructor is the opposite from constructor. The main goal is to return variable value to the original form and release memory to be free from variable usage. Method destructor has same name as the name class, with prefix ~. Examine how to use constructor and destructor.

Example 9.27. Constructor and destructor.

#include <iostream> using namespace std; class Rectangle { int *length, *wide; public: Rectangle (int,int); ~Rectangle (); int wide () {return (*length * *wide);} }; Rectangle::Rectangle (int a, int b) { length = new int; wide= new int; *length = a; *wide = b; } Rectangle::~Rectangle () { delete length; delete wide; } int main () { Rectangle pp1 (3,4), pp2 (5,6); cout << "Wide pp1: " << pp1.wide() << endl; cout << "wide pp2: " << pp2.wide() << endl; return 0; }

9.4.2. Inheritance C++ provides facilities inheritance in class. Inheritance process in C++ is more complicated compare with Java. This is because C++ gives possibility inheritance with

Directorate Technical Vocational Education

Page 124: Rekayasa perangkat lunak(Jilid2)

111 Software Engineering

access right consideration. There are two (2) access rights in inheritance superclass to subclass, namely, public and private.

If the inheritance class is public from superclass, the requirements are as follow:

● Part of public in superclass will stay on as public in subclass.● Part of protect in superclass will stay on as protect in subclass.● Part of private in superclass can not access by subclass.

If the inheritance class is private from superclass, the requirements are as follow:

● Part public in superclass will become private in subclass. ● Part protect in superclass will become private in subclass.● Part private in superclass can not access by subclass. See example:

Example 9.28. Inheritance

#include <iostream> using namespace std;

class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class CRectangle: public CPolygon { public: int area () { return (width * height); } }; class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; }

Directorate Technical Vocational Education

Page 125: Rekayasa perangkat lunak(Jilid2)

112 Software Engineering

In above program, CPolygon is superclass, while CRectangle and CTriangle are subclass. In Cpolygon class, variable width and height are declared as protected, and may only be accessed by the subclass. In addition, this class has method set_values. Both two variables and method will be inheritance to the subclass such as CRectangle and CTriangle. Please note how CRectangle and CTriangle is declared as the descendant class from CPolygon by using keyword public. Please change public in the declaration of Ctriangle class to Ctriangle class: private CPolygon. You will see the following error in compiling,

Compiling source file(s)... oo-test.cpp oo-test.cpp: In function `int main()': oo-test.cpp:9: error: `void CPolygon::set_values(int, int)' is inaccessible oo-test.cpp:28: error: within this context oo-test.cpp:28: error: `CPolygon' is not an accessible base of `CTriangle'

Why there is an error in compilation? This is because the above rule. Method set_values in class CPolygon declare as public, but inheritance to class CTriangle as private. It will change method from public to private in class CTriangle. As you may understand, if class member has private access right then it can not be accessed from outside.

9.4.3. Polymorphism In C++, to apply polymorphism, we must use special function named virtual. Put the virtual function in superclass, so we can re-define it in subclass. Examine the following example:

Example 9.29. Using virtual function.

#include <iostream> using namespace std; class MemberSchool { char* name; char* address; public: void SetName(char* N) { name = N; }

Directorate Technical Vocational Education

Page 126: Rekayasa perangkat lunak(Jilid2)

113 Software Engineering

void SetAddress(char* A) { address = A; } char* GetName() { return name; } char* GetAddress() { return address; } // Create virtual function virtual void Working() { cout<<"Working"<<endl; } virtual void Dressing() { cout<<"Dressing"<<endl; } };

class Student: public MemberSchool { char* Faculty; char* Program; int semester; public: void SetJurusan(char* J) { Jurusan = J; } void SetProgram(char* P) { Program = P; } void SetSemester(int smt) { semester = smt; } char* GetFaculty() { return Faculty; } char* GetProgram() { return Program; } int GetSemester() { return semester; } // override on function Working void Working() { cout<<"Work demanding knowledge"<<endl; } // override on function Dressing

Directorate Technical Vocational Education

Page 127: Rekayasa perangkat lunak(Jilid2)

114 Software Engineering

void Dressing() { cout<<"Dressing uniform white gray"<<endl; } };

class Teacher: public Member School { char* position; char* expertise; public: void SetPosition(char* jbt) { position = jbt; } void SetExpertise(char* khl) { expertise = khl; } char* GetPosition() { return position; } char* GetExpertise() { return expertise; } // override on function Working void Working() { cout<<"Work teaching knowledge"<<endl; } // override on function Dressing void Dressing() { cout<<"Dressing formal uniform"<<endl; } };

// Main functionint main() { // instantion on class MemberSchool, Student and Teacher MemberSchool As; Student Sw; Teacher Gr;

// Calling function Working from each class cout<<"Member school in "; As.Working(); cout<<"Student in "; Sw.Working(); cout<<"Teacher in "; Gr.Working(); cout<<'\n';

Directorate Technical Vocational Education

Page 128: Rekayasa perangkat lunak(Jilid2)

115 Software Engineering

// Calling function Dressing from each class cout<<"Member much be "; As.Dressing(); cout<<"Student must be "; Sw.Dressing(); cout<<"Teacher much be "; Gr.Dressing(); return 0; }

In the above source code, there are two (2) virtual methods, namely, Working and Dressing. These methods will be used in subclass in different applications. Please examine the content of each method in each subclass. This is normally called as overriding. The review overiding concept in Chapter 8. Compare overriding concept between Java and C++. As we execute the above program, the result is shown in Figure 9.9. Overloading may also be done using virtual function. Please review the difference between overriding and overloading as described iin Chapter 8.

Figure 9.9. Execution results of virtual function and overriding.

In the above Example 9.29, virtual function is completed with the content of the function. C++ also provides pure virtual function that only declared as a function with empty content. This concept is similar to interface in Java. The pure virtual function will be inheritance into classes. The advantage in using pure virtual function is in the freedom in defining functions in the descendant class. The pure virtual function is usually used in abstract class. An abstract class has at least one pure virtual function. We should not create an object directly from an abstract class.

Polymorphism concept in C++ is based on the virtual function, pure virtual function, overriding, overloading, and abstract class. Examine the following polymorphism example.

Example 9.30. Applying polymorphism.

Directorate Technical Vocational Education

Page 129: Rekayasa perangkat lunak(Jilid2)

116 Software Engineering

#include <iostream> using namespace std; class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; // pure virtual function void printarea (void) { cout << this->area() << endl; } }; class CRectangle: public CPolygon { public: // overriding function area int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: // overriding function area int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon *ppoly1 = &rect; // defining object pointer CPolygon *ppoly2 = &trgl; // defining object pointer ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly1->printarea(); ppoly2->printarea(); return 0; }

In the above example, CPolygon class is an abstract class and has pure virtual function, namely, area. Examine how to declare pure virtual function with a beginning statement virtual. This function does not have any contents but only mark = 0. We can not make an object directly from Cpolygon class. But we can make object pointer to allocate memory base on CPolygon class. In Cpolygon class a keyword this is used. The this keyword is used as a pointer to the class. Statement this->area() is the same as CPolygon->area (). Thus, same as calling the virtual function are in the class.

In the above code, we create two (2) pointer variables *ppoly1 and *ppoly2 that has the

Directorate Technical Vocational Education

Page 130: Rekayasa perangkat lunak(Jilid2)

117 Software Engineering

same value as the address of variable rect and trgl. Note the mark * and & to point to memory address. Execute the program and examine the result.

9.5. OBJECT ORIENTED APPLICATION DESIGN Basic concept of object oriented programming has been studied in Chapter 8. Its application in Java is also described in Chapter 8. While its implementation in C++ is in this Chapter. In this section, we will discuss the application design in object oriented.

In this example, we will solve one of the problem in book store, namely, supply / stock, If we closely examine, a book store will sell many things, including, novel, books, magazines, office stationery, etc.. Each has its own brand, price, and other characteristics. Moreover each materials also has relations with pricing, discount, number of purchases and storage. Availability of supplies in book store determine by incoming materials from ordering and outgoing as being sold. Each out going materials should automatically decrease the supply.

The beginning of the step in object oriented application is to create the abstraction of the problem. Examine closely the problem, we can create the main class of all available things. This is due to the special characteristics of the materials, as well as the general characteristic for all materials. For example, price is general characteristic for all materials. However, certain brand is specific to a certain materials, especially stationery. Moreover, title is a characteristic belongs to books. Confined by this condition we can make problem abstraction as follow.

Directorate Technical Vocational Education

Page 131: Rekayasa perangkat lunak(Jilid2)

118 Software Engineering

Figure 9.10. Case abstraction in book store supply materials.

In Figure 9.10, we create six (6) classes to facilitate the above case. There are two (2) relations described in the Figure, namely, relations inheritance with arrow mark and association (relations between two or more class) with line without arrow. Material is superclass and described in abstract class. Bahan Bacaan and Alat Tulis is a subclass of Barang, whereas Buku and Majalah are subclass from Bahan Bacaan. Location is a class to refer the storage. In the above case, we may apply the inheritance and polymorphism concept as well as use of pure virtual function in class Barang. These functions may be inheritance to be implemented in the subclasses. The code design is shown in Table 9.3.

Examining the diagram and table 9.3, we may write the source code. There are six (6) classes in the code. Each class may be written in a separate file or collected in a singe file. Then the implementation from these class may be written in a single file. To link these files and call class from different file, we may use preprocessor #include follows by the file name.

Directorate Technical Vocational Education

Page 132: Rekayasa perangkat lunak(Jilid2)

119 Software Engineering

Table 9.3. Class, Function and Parameter on bookstore stock application.

Class Name Variable Function Parameter Comments

Barang KodeBrg

HargaSediaanAwalBrgKeluarBrgMasuk

-SisaBarang

-Simpan

pAwal, bKeluar,bMasukkodeLok

KelasAbstrak

BahanBacaan Penerbit Subclass danmewarisianggotakelas Barang

Buku ISBNJudulPengarangTahunJumlahHalamanDiskon

-setDiskon-getDiskon-HrgDiskon

Hrg, Potongan Subclass dariBahanBacaandan mewarisianggotakelastersebut

Majalah NamaNoEdisiTglTerbit

Subclass dariBahanBacaan dan mewarisianggootakelastersebut

AlatTulis Supplier

NamaMerek

Lokasi KodeLokasiDescripsi

9.6. SUMMARY

● The general program structure in C++ includes file registration, function definition, main() section, and code block.

● Data type primitive in C++ consists of int, long, float, double, char, boolean, and short. The available composite data type is struct, enum and array.

Directorate Technical Vocational Education

Page 133: Rekayasa perangkat lunak(Jilid2)

120 Software Engineering

● The operator type are assignment operator, unary operator, binary operator, relational operator, bitwise operator and ternary operator.

● Selection Control structure may be done with if (without then) and switch... case. While in looping, C++ provides several commands, namely, for, while, and do-while.

● The input and output statements is done with commands cout and cin as stream that includes in class iostream.

● Function may or may not returns value. Parameter in function may be input parameter, output parameter or both of them.

● Pointer is a variable. However, different from normal variable, Pointer keep the memory address but not the actual value.

● C++ supports object oriented programing with class, inheritance, virtual function, overriding, overloading and polymorphism.

9.7. EXERCISE

1. Create a C++ program to calculate the average value of 34, 56, 91, 11, and 22.

2. Create a C++ program to determine the rice after discount for the followings.

Input Price / unit : Rp. 20.000 Number Of things buy : 5------------------------------------------------ ---------------------------------------------- Total cost before discount :Rp.100000 discounts (10%) :Rp. 10000 Net price :Rp. 90000

3. Someone has a saving account in bank and starting balance at Rp. 10,000.-. He allows to store or withdraw money from his saving account. Create a C++ program for Banking transaction. The main menu should be as follows:

Directorate Technical Vocational Education

Page 134: Rekayasa perangkat lunak(Jilid2)

121 Software Engineering

--------------------------------------PT. BANK ABC -------------------------------------- Balance:.... Transaction Menu 1. Deposit savings 2. Take savings 3. Exit Menus (1/2/3)? ...Requirement: Bank made policy that minimum balance in account is Rp 10,000.-

If the customer chooses option 1 then the customer will be asked to enter the amount of Rupiah to be stored. If customer chooses option 2 then customer will be asked to enter the amount of Rupiah to be withdraw. However, if the balance is less than Rp. 10000, the program will refuse. (Note: please use cin command to get input from keyboard)

4. Create a program use function to calculate the final mark in a class. There are two (2) arguments in the function, namely, mid test mark and final exam mark. The program output should gives A if the average mark is the same or larger than 80, and B if it less then 80 and same or larger than 70, and C if it is less then 70.

5. Examine problem no 5 in Chapter 8. Create abstraction diagram as well as the program in C++.

Directorate Technical Vocational Education

Page 135: Rekayasa perangkat lunak(Jilid2)

122 Software Engineering

CHAPTER 10 BASIC SYSTEM DATA BASE

The figure is a picture of cellular telephone which is also known as hand phone with Contact List application. The application is fairly familiar for those who has used a hand phone. The application keeps friend's name, parents as well as other information such as name and telephone number. Even sometimes complete with email address, office address, fax number and other data.

Examine the Contact List application, when you input someone name telephone number then the entered name and telephone number should not be switched with name or telephone number other people. All should be well sorted and arranged. You may find someone's name by only typing some letters part of the name. Please note that the name will always be alphabetically sorted in sequence, although your input may not be in sequence or sorted.

Data name, telephone number and others data in application Contact List are stored in a database. In this chapter, we will study basic database concepts. The basic competence in database management system (DBMS) is part of standard competence that make application based on Microsoft Access and will be explain ed in detail in Chapter 11. The end of this chapter will be closed with summary and exercises.

THE OBJECTIVES

After studying this chapter, the reader is hoped to be able to,

● Explain the concept of data, database and database management system (DBMS).

● Explain Entity-Relationship Diagram.● Explain database relational

Directorate Technical Vocational Education

 Figure 10.1. Contact list facility on a handphone.

Page 136: Rekayasa perangkat lunak(Jilid2)

123 Software Engineering

10. 1. DATA, DATA BASE AND DATABASE MANAGEMENT SYSTEM

10.1.1. Database

Database is a collection of data that relates to each other, it is stored in computer hardware and use software to do the manipulation. Database is one of the main component in information system, as the base of information system for the users. (Fathansyah, 1999; Post, 1999).

Imagine a database as a cupboard in administrative school which keep various archives. Each type archives in group, arrange and keep in certain place. So there will some archives such as teacher's archives, subject archives,financial archives, student's archives, and others. Difference is only storage media. If filing cabinet use cupboard from wood, iron or plastic, but database use saving media electronics like disks (hard disc, CD, or tape). Figure 10,2 give illustration similarity filing cabinet and database.

Important is, database not only as electronically data storage. And not all electronically data storage called database. If archives do not use rules of arrange, separate or good organize, then we can not say storage data as data base. Figure 10.2 showing apply principles, illustration, organize or separately, for filing cabinet or and database.

Figure 10.2. Archive and data base cupboard.

Main principle in database is independence data concept such as separation data from application program (Lewis et al., 2002; Post, 1999). While main goal of a

Directorate Technical Vocational Education

Page 137: Rekayasa perangkat lunak(Jilid2)

124 Software Engineering

database is to help user in abstraction of a system. There are three (3) levels abstraction that usually use: physical level, conceptual level and view level (Figure 10.3). Physical level shows how data will be kept. Conceptual level relates type of data and the relation between data. View level is the highest level, it explains section of database for certain usage. (Ramakrishnan and Gehrke, 2000).

Figure 10.3. Abstraction at data level (Lewis et al., 2002).

Database have several important criteria, such as:

1. Should be data oriented and not program oriented.2. Can be used by any application programs without changing the database. 3. Can be easily developed, both volume and structure.4. Can easily satisfy new system requirements. 5. Can be used in many ways.

The structure of basic database operation is shown in Figure 10.4. These operations include.

● Create database. It is similar to the creation or purchase of new filing cabinet.● Drop database. It is similar to the destruction filing cabinet. ● Create table. It is similar to add new archives group. This operation can only

be used if the database is available.● Drop table. It is similar to the destruct old archives group. This operation can

only be used if table is available at database.

Directorate Technical Vocational Education

Page 138: Rekayasa perangkat lunak(Jilid2)

125 Software Engineering

Figure 10..4. Database basic operations

● Insert data into table. This Operation is similar to add new sheet archives in archives group. Operation will be permitted if table is available.

● Retrieve data. This operation is similar to search sheet archives in archives group storage.

● Update data. This operation is similar to contents update of sheet archives in group archives.

● Delete data. This operation is similar to removal of sheet archives in archives group.

Database is build for certain data management goals, such as,

1. Efficiency covers speed, storage/space and accuracy2. Handled data in large quantities. 3. Shareability. 4. Remove duplication and data inconsistency.

10.1.2. Database Management System Database management may not be directly done by the users, handled by a special/ specific Software or DBMS that will determine how to organize data, keep, change and retrieve. It also applies security data mechanism, sharing, forced data accuracy &

Directorate Technical Vocational Education

Page 139: Rekayasa perangkat lunak(Jilid2)

126 Software Engineering

accountability, etc. In summary, structure some DBMS may be seen in Figure 10.5.

Figure 10.5. DBMS Structures

The additional applications are optional and usually available in DBMS as additional function. For example, application to make report, application to design form, application to make diagram or chart, application to monitoring system, and other applications.

There may be tens or hundreds DBMS software available. Each with different specification. From very simple to most complex. In this part we will explain five (5) kinds DBMS familiar to DMBS users, such as, Microsoft Access, MySQL, Microsoft SQL Server, PosgreSQL, and Oracle.

● Microsoft Access

Microsoft Access, is also known as Microsoft Office Access, is a relational DBMS produced by Microsoft in Microsoft Office package. Microsoft Access make combination engine relational Microsoft Jet Database, Graphical User Interface (GUI) and software developer.

Directorate Technical Vocational Education

Figure 10.6. Logo MS Access

Page 140: Rekayasa perangkat lunak(Jilid2)

127 Software Engineering

Microsoft Access can use data stored in Microsoft Jet Database, Microsoft SQL Server, Oracle or other ODBC (Open Database Connectivity) compatible.

Microsoft Access is often used in Rapid Application Development, especially to build prototype and application stand-alone. Microsoft Access can use as database for simple web based application. However in more complex application, for web or not, Microsoft Access is not a good choice. Especially, to handle multi-user. This because Microsoft Access is a personal single user database. Microsoft Access is also incomplete in database triggers and stored procedures.

Figure 10.7. View Microsoft Access.

One of the advantage of Microsoft Access for the programmer is that compatibility to SQL (structured query language) is relatively high. In Microsoft Access, we can make query based on text or GUI, and execute to get results easily.

● MyQSL

MySQL is a multi-user and multi-threaded SQL-DBMS. MySQL may be run as a server to serve many users to access many databases. MySQL is very popular in the web based application as database component. MySQL is available for free. In addition,

Directorate Technical Vocational Education

Figure 10.8. Logo MySQL

Page 141: Rekayasa perangkat lunak(Jilid2)

128 Software Engineering

MySQL is influenced by popular web server Apache and programming language PHP. All technical term such as LAMP (Linux- Apache-MySQL-PHP/Perl/Python), MAMP (Mac-Apache-MySQL-PHP/Perl/Python) and WAMP (Windows-Apache-MySQL-PHP/Perl/Python) become very famous. Plenty web base applications are build by using these software combinations, such as, WordPress, Drupal, Mambo, Wikipedia, PHP-Nuke.

Unlike Microsoft Access, the MySQL default installation provides no GUI interface for users to interact with the MySQL database. User interact with commands line interface. However, there are many GUI developed to facilitate interaction with the MySQL database, either for application stand-alone (for example MySQL-Front, MySQL-GUI, etc) or for web based (for example, phpMyAdmin). Moreover by the use of MyODBC component, MySQL may access Microsoft Access database similar to other ODBC compatible.

Figure 10.9. Opening view of phpMyAdmin.

● Microsoft SQL Server

Microsoft SQL Server is a relational DBMS produced by Microsoft same Microsoft Access. The main query language is used a variant ANSI SQL known as T-SQL (Transact-SQL). User can access this language to create stored procedure to increase efficiency access to the database. DBMS also facilities clustering and mirroring. Cluster is a collection of servers with identical configuration to enable distribution of work between server. Whereas mirroring facility allows DBMS to make a complete replica of the contents database to be use in another server.

Directorate Technical Vocational Education

Figure 10.10. Logo Microsoft SQL Server

Page 142: Rekayasa perangkat lunak(Jilid2)

129 Software Engineering

Microsoft SQL Server is available in several distribution versions. Joint distribution between Microsoft SQL Server - Microsoft Office or Microsoft Visual Studio, normally call as MSDE (Microsoft SQL Server Database Engine), but no GUI provided. User may use text based client interface. Similar to MySQL. While the higher version as personal or professional version are available with GUI facilities as shown in Figure 10.11.

Figure 10.11. GUI on Microsoft SQL Server

● PostgreSQL

PostgreSQL, also known as Postgres, is an Object-Relational Database Management System (ORDBMS). An ORDBMS is a DBMS that uses not only principles relational database but also object oriented approach in the database models. Postgres is a free software and open-source, and, thus, not controlled by one or two companies.

Figure 10.12. PostgreSQL Logo

Directorate Technical Vocational Education

Page 143: Rekayasa perangkat lunak(Jilid2)

130 Software Engineering

The advantage of Postgres as compared with other DBMS is in its characteristics as open source and free, supported by an extraordinary documentation. Its flexibility and feature is not different from commercial DBMS. In addition to support for object-relational data model, Postgres also supports spatial database usually for Geographic Information System. Postgres also supports multi-user and multi-threaded operation. In fac, it is better than MySQL from security side.

Similar to MySQL and Microsoft SQL Server, we can interact with Postgres by using commands client side with tool, such as, psql. GUI interface has also been developed, such as, phpPgAdmin, PgAdmin, etc.

● Oracle Database

Name of Oracle Database or Oracle RDBMS is well known in the DBMS world. Oracle is developed by Oracle Corporation.

Oracle keep data in logically in tablespaces form and physically in data files form. Tablespaces can contain various memory, such as, data part, index part etc. These parts contain one or more area. The areas contain collection block data. Oracle can automatically keep and store procedure and function stand alone.

10.2. ENTITY-RELATIONSHIP DIAGRAM E-R Model is normally shown in diagram and called Entity-Relationship Diagram (ERD). ERD is a graphic notation of conceptual data model that is used to make structural data and relations between data models. With ERD we can test model by ignoring further process. With ERD we try to answer questions, such as; what data we need? How one data connect with others? ERD use notations and symbol to show structure and relations between data. It has basically three (3) symbols, such as.

1. Entity: Entity is shown in a rectangle form.

2. Attribute: Attribute is shown in form of ellipse and connect with entity where attribute is.

Figure 10.14. Notation entity on ER-Diagram

Directorate Technical Vocational Education

Figure 10.13. Oracle Logo

Page 144: Rekayasa perangkat lunak(Jilid2)

131 Software Engineering

Figure 10.15. The use of attribute notation to ER-Diagram.

3. Relationship: Relationship is shown in diamonds form.

Figure 10,16. Use notation relationship to ER-Diagram.

10.2.1. Entity Entity is an individual to represent a real matter / thing and may be differentiate to one another. Could be an element from an environment, a resources or a transaction that very important in the built model.

Example of Entity set:

● All Teacher or A Teacher.This association has member: Mr Fahri, Ms Fitri, Mr Joko and other teachers.

● All Student or A Student.

Directorate Technical Vocational Education

Page 145: Rekayasa perangkat lunak(Jilid2)

132 Software Engineering

This association has member: Joni, Ridho, Fanny, Donny and other students.

● All Cars or A Car.This association has member: Daihatsu car, Toyota car, Suzuki car, and other cars.

Its not easy to Identify the existence of an entity. The existence of noun words in a problem is usually an entity candidate. For example when we will develop the database in school library, then we will find book, student, teacher, library officer as strong candidate entity.

10.2.2. Attribute Each entity has attributes. An attribute has characteristic to be distinguished between one entity and other entity.

Example of Attribute:

● Student Entity.

Has attribute, such as, : Student ID number, name, address, telephone number, birthplace, date birth etc.

Figure 10.17. Student's entity and attributes.

● Teacher entity.

Has attribute such as: NIP, name, address, rank, telephone number, birthplace, date of birth, expertise field, etc.

Directorate Technical Vocational Education

Page 146: Rekayasa perangkat lunak(Jilid2)

133 Software Engineering

Figure 10.18. Teacher's entity and attribute.

● Car entity.

Has attributes, such as, machine number, framework number, color, year produced, machine type, fuel, etc.

Figure 10.19. Car entity and attribute.

Directorate Technical Vocational Education

Page 147: Rekayasa perangkat lunak(Jilid2)

134 Software Engineering

Not all entity characteristics is important for a scope problem. For example problem in library's database, student's shoe number is not an important characteristics to be used as an attribute. But if the scope of problem is in database for ordering student's uniform and student's shoes, then shoes number is an important attribute.

In addition to the most important entity, we must choose one of the attribute as the primary key.

In the above attribute example, we can easily decide the primary key from available entity.

Example Primary key:

● Student Entity.

The available attributes are Student ID number, name, address, telephone number, birth place, and date birth. From these six (6) attributes the most appropriate attribute to become the primary key is Student ID number as it is a unique attribute. No student has same Student ID Number. Student name may be the same, but not in Student ID Number.

● Teacher entity.

The available attributes are NIP, name, address, rank, tel number, birthplace, date birth, and expertise field. The most appropriate attribute to become the primary key is the NIP because it is unique. There is no teacher with the same NIP. So NIP can use identify teacher's entity.

● Car entity.

The available attributes are machine number, frame number, color, year produced, machine type, and fuel. There are two unique attributes, namely, machine number and frame number. In this case we can choose one of them as primary key.

As guidance, here are some attribute characteristics that is considered as identifier (candidate key):

● Value does not change.● Impossible contain null value (empty not zero)● Not contain data name or location that possibly change

10.2.3. Relationship

Directorate Technical Vocational Education

Page 148: Rekayasa perangkat lunak(Jilid2)

135 Software Engineering

Relationship or relations is the connectivity between entity. For example from student's entity there is a student who has entity NIS = “GHI007” and student name = “Donny” has relations with entity program subject = “RPL” and program name = “Software Engineering”. Relations between these two (2) entities means student is currently taking the program subject in certain school.

Figure 10.20. Relationship.

Ramakrishnan and Gehrke (2000) describe that the relationship concept in E-R model is different from the relational concept in data relational model. Relationship is mechanism that connect between entity. In implementation into DBMS both entity and relationship will be represented in relational table form.

Each relationship must have a cardinality. Cardinality or Relations Level shows the maximum number of entity that may be relate to other entity in other entity association.

In Figure 10.20, we can see cardinality between association student's entity and association entity of program subject. Student can make a relation with only one entity at association entity of program subject. On the other hand one entity in program subject may have relation with many students. See in the figure that Donny can only connect with Software Engineering, whereas Software Engineering can connect with Donny and Joni.

There are several level relations (cardinality) between one entity and other entity. Cardinality show the maximum number entity in association of entity and can relate with entity in other association entity. Generally there three (3) forms of cardinality between association entity, such as:

● One to one. Relations with cardinality one-to-one means that one member of entity set may only be connected with one member of other entity set. Relations between entity husband and wife can be group in relations one-to-one.

Directorate Technical Vocational Education

Page 149: Rekayasa perangkat lunak(Jilid2)

136 Software Engineering

Figure 10.21. Relations one-to-one husband and wife.

● One to many/many to one. Cardinality one to many and many to one are the same because the analysis cardinality always see from both sides. For example in school has rule that one class consist many students but not the other way, one student can not learn in different class.

Figure 10.22. Relations one-to-many class with student.

● Many to many. Cardinality is complicated enough to explain but we often see this problem. For example , student's relations with subject has many-to-many cardinality. Student has right to study more than one subject and each subject may take study more than one student.

10.3. RELATIONAL DATA BASE

10.3.1. RELATIONAL DATA BASE MODEL

Relational database is introduced for the first time by E.F. Codd during 1970”s. This model data is based on mathematical structure to be easy and natural, namely is relation table. Data operation manipulation is originated from logical mathematics. Thus, it makes the expressions in table may be analyzed and optimized (Lewis et.al., 2002).

The main form in relational data model is the relation table. Relation consists of two (2) important matters, namely, schema and instance. Relation instance is a table not

Directorate Technical Vocational Education

Page 150: Rekayasa perangkat lunak(Jilid2)

137 Software Engineering

more than two dimensions, with row and column. Row is normally called tuple, it has the same meaning as record in file. But different from file record, all tuple have the same number of columns and there is no tuple in same relation instance. Column in relation instance is also populer as attribute or column (Ramakrishnan and Gehrke, 2000; Lewis et.al., 2002). Figure 10.23 show the relation between table / file / relation, row / record / tuple and column / field / attribute. This Figure also shows the composition of the relations.

Table Row Column

File or Date File Record Field

Relations Tuple Attributes

Figure 10.23. Relation between table/file/relation, row/record/tuple and column/field/attribute.

Relation schema consists of relation name, attribute name in the relation with its domain, and integrity constrains. Relation name must be unique in a database, and no other same relation name. Attribute name is a column name from relation and no same attribute name in a relation. Domain name from an attribute relates to the data type used in the attribute. Integrity constraints are the constrains to relational instances to a schema (Ramakrishnan and Gehrke, 2000; Lewis et.al., 2002)

Directorate Technical Vocational Education

Page 151: Rekayasa perangkat lunak(Jilid2)

138 Software Engineering

10.3.2. Relational Database Structure As explained, a table consists of row and column.

● Row / Lines / Tuple.

Row / Lines / Tuple is a collection of attributes that were connected with each other in one row as shown in Figure 10.23. Row is always repeated in the same structure but different in its content. For example, in Figure 10.23 the first row has the same structure as row to 2 and to 3. However, the data in each row is different. We could identify for buyer with id_buyer = 1 must have name of = Cristiano Ronaldo and id_buyer = 2 must have name of = Ryan Giggs, and so on.

● Field / Column / Attributes

Field / Column / Attributes shows the data structure from repeated rows. In Figure 10.23 it has four (4) columns, namely, id_buyer, name, address, and telephone. For example, the data in id_buyer column will have the same structure as in form of number and is sorted for id_buyer. Also for column name with only contain buyer name so as to not mixing with other data.

A column must have column name and data type for data in the column as shown in Figure 10.24. In addition, there are sometimes constraint and domain for data in the column. Data type depends on used attribute and the operations on the database. Domain data has similar understanding with used data type function. However, data type refer to data storage capacity which is more physical meaning. Meanwhile domain data is more stressed in value constraints of an attributes, as seen in real usage.

Figure 10.24. Column, constrain and data type (Powell, 2006).

Directorate Technical Vocational Education

Page 152: Rekayasa perangkat lunak(Jilid2)

139 Software Engineering

Figure 10,24 shows the column names in a complete table with data type and its constrain. For example, ISBN column is an integer data type, means the column may only be filled by integer number. In addition, the column has no null constrain and, thus, the column may not be emptied during data entry. Pages column with data type date means only contain date data. Pages column does not have constrain null. It means the column can be emptied or not.

The data type depends on the DBMS. For example, MySQL provides more data type options than Microsoft Access. For example, MySQL provides enum data type that is not available in Microsoft Access. An accurate data type selection is very important and may influence data consistency and database performance.

Example of a domain, if use attribute / column on class in Elementary School. This column may be filled by data type number from 1 up to 6, as there is no class no class 7 or 4.5 . It means domain class column is an integer number only between 1 up to 6. Another example, the exam score is a floating point number between 0 up to 100.

There are several types of attribute, namely,

● Simple Attribute is atomic attribute cannot be divided anymore.

Figure 10,25. Simple attribute

● Composite Attribute is an attribute that can be divided into sub attributes and each has meaning.

Directorate Technical Vocational Education

Page 153: Rekayasa perangkat lunak(Jilid2)

140 Software Engineering

Figure 10.26. Composite attribute

● Single-Valued Attribute, is an attribute that has a maximum one value for each data line.

● Multi-Valued Attribute, is an attribute that contains more than one value in same type.

Figure 10.27. Single valuable attribute and multi-value attribute.

● Derived Attribute is attribute that receive value from data processing or from attribute or connect other table.

10.3.3. Inter Table Relationship The advantage of relational database as compared to other database model is in the inter table relationship to be easy to understand and logical. Inter table relation may be directly or indirectly derived from ER-Diagram. Entity in ER-Diagram is usually a candidate from table in relational database. Relationship between table is usually may be identified from relationship between entity in ER-Diagram.

Directorate Technical Vocational Education

Page 154: Rekayasa perangkat lunak(Jilid2)

141 Software Engineering

To clarify how relational database handled relations between tables, we will use the following tables. The First table is the Author. This table consists of three (3) columns: id_ author, author and birth_year as shown in Figure 10.28. In this table, id_author is primary key.

Figure 10.28. Table Author.

The Second table is the Publisher. This table has six (6) columns, namely, id_publisher, name, company_name, address, city and telephone as shown in Figure 10,29. The Primary key of this table is the id_publisher.

Figure 10.29. Table Publisher.

The Third table is Book. This table has six (6) columns, namely, title, year_issued, ISBN, id_publisher, description, and group as shown in Figure 10,30. The Primary key to this table is the ISBN. There is something strange in this table as column id_publisher whih is one of the column in Table Publisher is added in Table Book. This

Directorate Technical Vocational Education

Page 155: Rekayasa perangkat lunak(Jilid2)

142 Software Engineering

is not a mistake, but one of the way for a relational database to handle relations between tables.

Figure 10.30 Table Book

In the real world, we will find that a publisher is not only produce a single book title, but hundreds even possibly millions of book titles. Thus, publisher and book relations may be formally called as cardinality one-to-many. Its ER-Diagram is shown in Figure 10.31. One publisher may publish many book titles and one book title may only published by one publisher. Please examine Figure 10.31, the publisher with id_publisher= 13 (McGraw Hill) publishes 6 books. On the other hand, book with ISBN = 0-0702063-1-7 (Guide To Oracle) is only published by a publisher with id publisher= 13 (McGraw Hill). So that column id_publisher in table book means to presentation Publisher relations to Book. Column id_publisher to table book is usually called as foreign key.

Figure 10.31. ER-Diagram for Publisher and Book

Directorate Technical Vocational Education

Page 156: Rekayasa perangkat lunak(Jilid2)

143 Software Engineering

Figure 10.32. Relations Table Publisher and Book.

In the above tables, we don't see the boot title of each Author. To make table contains author and book title, we relates table author and table book. Prior to it, we must see the relations between writer and book in the real world. A author perhaps only write one title book, but possibly more. Whereas one book is possibly written by one or more author. So we can see the cardinality author's relation with book is many-to-many. Figure 10.33 shows the ER-Diagram.

Directorate Technical Vocational Education

Page 157: Rekayasa perangkat lunak(Jilid2)

144 Software Engineering

Figure 10.33. ER-Diagram for Author - Book

In case with cardinality many-to-many we can not directly insert a foreign key to other table. We must make new table so that cardinality between table involved may be changed to one-to-many. Table Author_Book is table that perform handle relations Book table with Author table. This table only contains two attributes, namely, ISBN column that originates from table Book and id_author that originates from table Author. Figure 10.34 shows table Author_Book that shows several books may be written by more than one author.

Directorate Technical Vocational Education

Page 158: Rekayasa perangkat lunak(Jilid2)

145 Software Engineering

Figure 10.34. Table Relations Author and Book

Directorate Technical Vocational Education

Page 159: Rekayasa perangkat lunak(Jilid2)

146 Software Engineering

Figure 10.35. Relation between table.

10.4. SUMMARY

● A database is collection of data that connect to each other, stored in a computer hardware and uses a software to manipulate data.

● The basic operation of database consists of creation of new database, drop of database, creation of new table, drop of table, add new data, retrieve data, modify data, remove on data.

● Database Management System is a software especially work to handle database

● Entity-Relationship Diagram is a graphic notation to conceptualized data model and use to make structural data model and relations between data. Element from ERD are entity, attribute, relationship and cardinality.

● The main form of model data relational is a relation (table). Relation instance is a two dimensional table with row / record / tuple and column / field / attribute.

● In relational database, exact identification in attribute relationship in a table and relationship among tables is the key to make a good database.

10.5. EXERCISES

1. Visit your school library, then do a short observation. Make notes to determine who and what involves in the activity in the library school . Pay attention on the entity and attribute. And how the relationship between entity.

2. From no. 1 activity, make tables that shows entity and its relationship. Make attributes from each table.

3. Pay close attention to attribute types.

Directorate Technical Vocational Education

Page 160: Rekayasa perangkat lunak(Jilid2)

147 Software Engineering

REFERENCES

Anonymous. 2004. Guide to the Software Engineering Body of Knowledge (SWEBOK). The Institute of Electrical and Electronics Engineers, Inc.

Balter, A. 2006. Sams Teach Yourself Microsoft® SQL ServerTM 2005 Express in 24 Hours. Sams.

Bass, L., P. Clements, and R. Kazman. 2003. Software Architecture in Practice. 2nd Edition. Addison-Wesley.

Cormen, T.H. 2001. Introduction to Algorithm: Second Edition. The MIT Press.

Deek, FP., J.A.M. McHugh, and O.M. Eljabiri. 2005. Strategic software engineering : An Interdisciplinary Approach. Auerbach Publications.

den Haan, P., L. Lavandowska, S.N. Panduranga, and K. Perrumal. 2004. Beginning JSP 2: From Novice to Professional. Apress.

Dobson, R. 1999. Programming Microsoft Access 2000: The Developer’s Guide to Harnessing the Power of Access. Microsoft Press.

Felleisen, M, R.B. Findler, M. Flatt, and S. Krishnamurthi. 2001. How to Design Programs; An Introduction to Computing and Programming. The MIT Press.

Kak, A.C. 2003. Programming With Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java. John Wiley & Sons, Inc.

Kaisler, S.H. 2005. Software Paradigm. John Wiley & Sons, Inc.

Kennedy, B. and C. Musciano. 2006. HTML & XHTML: The Definitive Guide, 6th Edition. O'Reilly.

Lafore, R. 1998. Data Structures & Algorithm in Java. Waite Group Press. 2nd Edition. Laurie, B and P. Laurie. 2001. Apache: The Definition Guide. O’Reilly and Associates, Inc.

Leffingwell, D. and D. Widrig. 2003. Managing Software Requirements: A Use Case Approach. 2nd Edition. Addison-Wesley.

Lischner, R. 2000. Delphi in a Nutshell. O’Reilly and Associates, Inc. Rekayasa Perangkat Lunak A1

Directorate Technical Vocational Education

Page 161: Rekayasa perangkat lunak(Jilid2)

148 Software Engineering

Luckey, T. and J. Phillips. 2006. Software Project Management for Dummies. Wiley Publishing, Inc.

McConnel, S. 2003. Professional Software Development: Shorter Schedules, Higher Quality Products, More Successful Projects, Enhanced Careers. Addison-Wesley.

Meyer, B. 2000. Object Oriented Software Construction. 2nd Edition. ISE, Inc.

Musciano, C. and B. Kennedy. 2002. HTML and XHTML: The Definition Guide. 4th Edition. O’Reilly and Associates, Inc.

Navarro, A. 2001. Effective Web Design. 2nd Edition. SYBEX, Inc.

Powell, G. 2006. Beginning Database Design. Wiley Publishing, Inc.

Riordan, R.M. 2005. Designing Effective Database Systems. Addison Wesley Professional.

Robbins, J. N. 2006. Web Design in a Nutshell, 3rd Edition. O'Reilly.

Suehring, S. 2002. MySQL Bible. Wiley Publishing, Inc.

Taylor, D.A. 1998. Object Technology: A Manager’s Guide. Addison-Wesley.

Van Roy, P and S. Haridi. 2004. Concepts, Techniques, and Models of Computer Programming. The MIT Press.

Directorate Technical Vocational Education

Page 162: Rekayasa perangkat lunak(Jilid2)

149 Software Engineering

APPENDIX 1 GLOSARY

Abstraction Is simply cause from something complex by modeling class depends on problems.

Algorithm Step sort logical of solve problems in sort systematically.

Array Data structure save some same elements.

Attribute Characteristic to difference one entity to other entity.

Authentication Process check legality someone as user in a system (such as DBMS)

Basic Input/Output System (BIOS) Codes program run first time when computer on (booting)

DatabaseData collection in connect each else other, store in hardware computer and use software to manipulation.

Command Line Interface (CLI) Between face user with command text model.

Compiler Translation language program in top level to machine language for all code program. Process called compilation.

Component Object Model (COM) Infrastructure available by Visual Basic to access objects or other controls as long has between face. Constraint Restriction/limitation problem

Control Activities monitoring and evaluating and feedback to make sure whether system in good work or not.

Counter Variable number that use in algorithm structure for repetition.

Directorate Technical Vocational Education

Page 163: Rekayasa perangkat lunak(Jilid2)

150 Software Engineering

Database Management System (DBMS) Special software use for management database.

Disk Operating System (DOS) One of old operation system in CLI base.

Electronic That science about low-tension electric current with operation by electric current control or particle ion electric in an equipment.

Entity Individual for representative extension that make different from other.

Extensible Hypertext Markup Language (XHTML) HTML lat version (4.01) that rewrite by rule strict and tight with term XML

Extensible Markup Language (XML) Rules to make markup language.

Feedback Data about system kinerja

Flowchart Scheme/chart which show flow in a logical program.

IndicationSignal for a problem.

Logical gate Blocks formation from electronic hardware.

Graphical User Interface (GUI) Between user face by graphics model.

Identifier Name of variable or constanta.

Computer scienceA systematic study in algorithm process, explain and transfer information.

Inheritance Principe from characteristic parents to children or generation which apply in classes.

InitializationFirst instruction to variable or expression program.

Directorate Technical Vocational Education

Page 164: Rekayasa perangkat lunak(Jilid2)

151 Software Engineering

Input Elements into system.

Integrated Development Environment (IDE) Software to help easily make computer application.

Interpreter Translate language program at top level to machine language one by one lines, read and direct translatability.

Cardinality Total max entity in an association entity and can relation with others entity association.

Constanta Variable with constant value data and can not change.

Loop Repletion process command.

ProblemDifference between actual situation and hopeful situation or difference between present condition with target or aim wish.

Model Make a simple system or Imitation a simple system.

Multi-tasking Task operation system to run duties/application with the same time.

Multi-user Task operation system to run by different user with the same time.

Output Move elements result from change process to aim wish.

Solve ProblemA process where situation analyze then make solutions if has problem by define, less or remove or cut problem.

Object Oriented Programming – OOP

Paradigm program where use object and integrate to make application and computer program.

Web program

Directorate Technical Vocational Education

Page 165: Rekayasa perangkat lunak(Jilid2)

152 Software Engineering

A way to make web page by language web program (script)

SoftwareAll instruction where use to process information.

Permissions A proses to determine what user can do to a system.

Pointer Variable that keep address in memory computer.

Polymorphism Ability objects to has more than one form.

Programmer A person who work to make computer program.

Procedure • Instruction that user need to process information. • Commands that a part of big program and has function to certain job.

ProcessChange or transformation input to output Prototyping Approach software development in directly to demonstrate how software or components software work in environment before construction actual steps do.

Pseudocode The way write of algorithm with codes similar language program.

Query Request or search certain data in database.

Record Data line from table.

Software Engineering A discipline science that explain all aspect software production, start from first step that analyse user need, to make sure specification user need, design, codes, test until maintain system after use.

RelationshipConnect in between entities.

System

Directorate Technical Vocational Education

Page 166: Rekayasa perangkat lunak(Jilid2)

153 Software Engineering

Elements which interaction to get certain goals.

Database SystemElements such as database, software, hardware, and user which interaction each other to get certain goals that is data organization.

SolutionEnd part or output from solve problem process.

Stored procedure Cut of Code program which can receive parameter input and has result one or more parameter output and use for operation database.

Structured Query Language (SQL) Query language structure to manage database.

Strategic solve problem Method or approach which use by someone when get problem.

Structure algorithm The way or steps to make an algorithm.

Data type Data type which can manage by computer to facility need in computer program.

Trigger Specific type from stored procedure which will execute when get problem.

Variable Place where we can fill-in or make empty value and re-call if need in a program.

View Table virtual which contain base on query and do in database.

Web browser Software that function to translate HTML codes become view as we want.

Web dynamism Web pages which contain and information change as want by user.

Web server Software which do to serve question client to certain web pages.

Web statics Web pages which contain and information not change.

Directorate Technical Vocational Education

Page 167: Rekayasa perangkat lunak(Jilid2)

154 Software Engineering

APPENDIX 2 SITE LIST

Following is the list of important Internet sites used as references for the book.

Address Comments

http://www.apache.org Official site of Apache Web server. This site provides the source code of Apache for various operating systems as well as a complete documentation.

http://www.borland.com Official site of Borland. Borland is a software house that produces Borland Delphi, Borland Jbuilder, Turbo Pascal, Turbo Delphi, Borland C++ etc.

http://www.debian.org Official site of Debian Linux.

http://www.eclipse.org Official site of Eclipse Project, an integrated development software that supports many programming language.

http://www.google.com Google search engine.

http://www.ilmukomputer.com

Indonesian site the provides documentation on various section of computer science.

http://www.javasoft.com Official documentation and online information on Java programming supported by Sun Microsystem.

http://www.kambing.vlsm.org

Indonesian site that provides iso of various linux distribution to be freely downloaded. In addition, this site is mirroring various linux distribution and application runs on linux.

http://www.linuxdoc.org This site provides Linux documentations that can be freely downloaded.

http://www.microsoft.com Official site of Microsoft. A company that produce Windows operating systems, IDE Microsoft Visual Studio, Microsoft Office, Microsoft SQL Server, etc.

http://www.mysql.com Official site of MySQL Database Software. This site provides the installation file for MySQL for various platform. In addition, it provides a complete documentation of MySQL.

http://www.netbeans.org Official site of IDE NetBeans, a Java development software.

http://www.php.net Official site for PHP programming language and interpreter. This site provides the source code and

Directorate Technical Vocational Education

Page 168: Rekayasa perangkat lunak(Jilid2)

155 Software Engineering

installtion file of PHP for various operating systems. In addition, it provides a complete documentation of PHP.

http://www.w3.org Official site of The World Wide Web Consortium (W3C). W3C is a consortium that sets the standard and Web related technology, especially, on HTML, XML, CSS, XHTML etc. The documentations on the technology may be downloaded from this site.

Directorate Technical Vocational Education

Page 169: Rekayasa perangkat lunak(Jilid2)

156 Software Engineering

APPENDIX 3 FUNCTIONS BUILD-IN ON VISUAL BASE

IsNumeric(expression) This function use to test whether an expression get numeric result or not. The value return is Boolean.

IsEmpty(expression) Function to check whether an expression already fill-in value or not. The value return is Boolean.

IsNull (expression) Function to check whether an expression has not valid data, usually use to check contain field recordset.

IsArray (varname) Function to check whether a variable is an array.

IsDate (expression) Function to check whether an expression can conversion to date.

IsError(expression) Function to check whether an expression is error value.

IsObject(expression) Function to check whether an expression use to an OLE Automation object.. IsMissing(argname) Function to check whether an argument optional to procedure, it pass or not.

CBool(expression) Conversion an expression to Boolean.

CByte(expression) Conversion an expression) to Byte.

CCur(expression) Conversion an expression to Currency.

CDate(date) Conversion an expression to date.

CDbl(expression) Conversion an expression to Double.

Directorate Technical Vocational Education

Page 170: Rekayasa perangkat lunak(Jilid2)

157 Software Engineering

CInt(expression) Conversion an expression to Integer.

CLng(expression) Conversion an expression to Long.

CSng(expression) Conversion an expression) to single.

CStr(expression) Conversion an expression to string.

CVar(expression) Conversion an expression to Variant.

Asc(string) Function to show code character from first letter to string.

Chr(charcode) Function to show character from one code to character code.

Format(expression)[, format[, firstDayFromSunday[,sundayFirstFromYear]]]) Formating an expression base on expression format/

Hex(number) and Oct(number) Show string which represent Octal or Hexa from number.

Str(number) Show string which represent number.

Val(string) Show number from string.

Now Return a Variant (Date) which show date and time base on computer system.

Time Return time the present system.

Timer Return number which show total second since midnight.

Date Return date the present system.

Directorate Technical Vocational Education

Page 171: Rekayasa perangkat lunak(Jilid2)

158 Software Engineering

Time = Time and Date = Date Arrange time or date system: Run system by Microsoft Windows 95, date need from 1 Jan 1998 until 31 Dec 2099. Run system by Microsoft Windows NT, date need from 1 Jan 1980 until 31 Dec 2079.

Hour(time), Minute(time) and Second(time) Return a Variant (Integer) such as number 0 s/d 23 for jam, 0 s/d 59 for minutes, and 0 s/d 59 for second.

Day(date), Month(date), and Year(date)

Return a Variant (Integer) such as number 1 s/d 31 for month, 1 up to12 for month, and year.

Directorate Technical Vocational Education