1. 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
2. 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 Education
Department of National Education
2008
3.
4. 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
5.
6. 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
7. vii Software Engineering
Table of Contents
FOREWORD....................................................................................................iv
EDITORIAL......................................................................................................vi
HOW TO USE THIS BOOK...............................................................................x
CHAPTER 6 ADVANCED PROGRAMMING ALGORITHM ..............................1
6. 1. MULTIDIMENSIONAL ARRAY..............................................................2
6.1.1. Concept of multidimensional array.................................................2
6.1.2. Matrix operation with Multidimensional Array ................................3
6.2. PROCEDURE AND FUNCTION............................................................6
6.3. SUMMARY.........................................................................................8
6.4. EXERCISE..........................................................................................8
CHAPTER 7 APPLICATION PROGRAMMIN USING VB & VB.NET ................9
7.1. Foundation of Visual Basic .................................................................10
7.1.1. Main GUI based programming principles.....................................14
7.1.2. Data type, Variable and Constant ................................................16
7.1.3. Operator ......................................................................................17
7.1.4. Control Program Structure...........................................................19
7.1.5. Procedure and Function...............................................................29
7.2. Access and Database Manipulation with Visual Basic.........................31
7.2.1. Create and Manipulate Database using ADO ..............................33
7.3. COM Technology.................................................................................35
7.3.1. COM Concept..............................................................................35
7.4. SUMMARY.......................................................................................36
7.5. EXERCISE........................................................................................37
CHAPTER 8 JAVA OBJECT ORIENTED PROGRAMMING ...........................39
8.1. OBJECT ORIENTED PROGRAMMING CONCEPT............................40
8.1.1. Abstraction...................................................................................41
8.1.2. Encapsulation..............................................................................41
8.1.3. Inheritance ..................................................................................41
8.1.4. Polymorphism .............................................................................42
8.2. INTRODUCTION TO JAVA..................................................................42
8.2.1. Software Requirement.................................................................42
8.2.2. Source Code Compilation............................................................43
8.3. DATA TYPE, VARIABEL, DAN INPUT/OUTPUT (I/O) STATEMENT...46
8.3.1. Data Type.....................................................................................46
8.3.2. Variable and Constant. ................................................................47
8.3.3. Input / Output ..............................................................................48
8.4. OPERATOR.........................................................................................49
8.4.1. Arithmetic Operator......................................................................49
8.4.2. Relational Operator......................................................................51
8.4.3. Logical Operator ..........................................................................52
Directorate Technical Vocational Education
8. viii Software Engineering
8.5. PROGRAM CONTROL STRUCTURE ................................................52
8.5.1. Selection Structure ......................................................................52
8.5.2. Looping Structure.........................................................................54
8.5.3. The use break and continue.........................................................55
8.6. EXCEPTION HANDLING....................................................................56
8.6.1. The understanding of Exception Handling ...................................56
8.6.2. Try and Catch ..............................................................................58
8.6.3. Throw ..........................................................................................59
8.6.4. Finally ..........................................................................................60
8.7. MULTI-THREADING............................................................................61
8.7.1. Concept of Thread ......................................................................61
8.7.2. Thread Creation and Usage ........................................................62
8.7.3. Multi-Thread ................................................................................63
8.8. OBJECT ORIENTED PROGRAMMING APPLICATION USING JAVA 65
8.8.1. Class Creation .............................................................................65
8.8.2. Application of Inheritance ............................................................71
8.8.3. Implementation of Overriding and Overloading ...........................74
8.8.4. Application of Polymorphism .......................................................77
8.8.5. How to use Package and Interface ..............................................79
8.9. SUMMARY..........................................................................................83
8.10. EXERCISES......................................................................................83
CHAPTER 9 APLICATION PROGRAM C++ ................................................85
9.1. BASIC C++ PROGRAMMING.............................................................86
9.1.1. Structure of C++ Program...........................................................87
9.1.2. Header File (.h) ...........................................................................88
9.1.3. Comment, Identifier and Data Type..............................................88
9.1.4. Operator ......................................................................................91
9.1.5. Control Program Structure...........................................................93
9.1.6. Input / Output ..............................................................................98
9.2. FUNCTIONS IN C++..........................................................................99
9.2.1. Function Types.............................................................................99
9.2.2. Using Parameter in Function .....................................................100
9.3. POINTER AND ARRAY .....................................................................102
9.3.1. Concept and Understand Pointer ..............................................102
9.3.2. Using New and Delete in Pointer................................................104
9.3.3. Array ..........................................................................................105
9.4. CLASS ..............................................................................................108
9.4.1. Class Declaration ......................................................................108
9.4.2. Inheritance .................................................................................110
9.4.3. Polymorphism ............................................................................112
9.5. OBJECT ORIENTED APPLICATION DESIGN ..................................117
9.6. SUMMARY.........................................................................................119
Directorate Technical Vocational Education
9. ix Software Engineering
9.7. EXERCISE........................................................................................120
CHAPTER 10 BASIC SYSTEM DATA BASE .............................................122
10. 1. DATA, DATA BASE AND DATABASE MANAGEMENT SYSTEM....123
10.1.1. Database .................................................................................123
10.1.2. Database Management System...............................................125
10.2. ENTITY-RELATIONSHIP DIAGRAM ...............................................130
10.2.1. Entity .......................................................................................131
10.2.2. Attribute ...................................................................................132
10.2.3. Relationship ............................................................................134
10.3. RELATIONAL DATA BASE..............................................................136
10.3.1. RELATIONAL DATA BASE MODEL........................................136
10.3.2. Relational Database Structure.................................................138
10.3.3. Inter Table Relationship............................................................140
10.4. SUMMARY.....................................................................................146
10.5. EXERCISES....................................................................................146
REFERENCES..............................................................................................147
APPENDIX 1 GLOSARY..............................................................................149
APPENDIX 2 SITE LIST................................................................................154
APPENDIX 3 FUNCTIONS BUILD-IN ON VISUAL BASE.............................156
Directorate Technical Vocational Education
10. x Software Engineering
HOW TO USE THIS BOOK
A. Global Description
This book is given the title quot;Software Engineeringquot;, 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
11. 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 3
and Computer
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- 4
based
HDW.OPR.104.(1).A Operate the computer operating system based 4
GUI
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 13
static web
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 - 12
SQL Query Language) basic level
TIK.PR03.002.01 Operates programming data description language 12
Directorate Technical Vocational Education
12. 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 8
programming language
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
14. 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.
Figure 6.1. Matrix notation.
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
15. 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
16. 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
Figure 6.3. Matrix 4 x 3.
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
17. 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
18. 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
19. 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
20. 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
21. 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
22. 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
23. 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
24. 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
25. 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
26. 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.
Figure 7.5. Toolbox in VB
6.
Directorate Technical Vocational Education
27. 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
28. 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
29. 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
30. 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
31. 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) = 25
4 ^ (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
32. 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
33. 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 = quot;Menangquot;
Case 2
txtOutcome.Text = quot;Kalahquot;
Case 3
txtOutcome.Text = quot;Seriquot;
Case Else
txtOutcome.Text = quot;Tidak bertanding.quot;
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
34. 21 Software Engineering
Open code windows and using the code editor write the source code as follows.
Private Sub Command1_Click()
If Text1.Text = quot;nusantaraquot; 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 = quot;nusantaraquot; Then
Image1.Visible = True
Text1.Enabled = False
Command1.Enabled = False
Else
Directorate Technical Vocational Education
35. 22 Software Engineering
MsgBox quot;Passwordnya Salah !quot;
Text1.Text = quot;quot;
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) = quot;nusantaraquot; 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
36. 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 quot;Disketquot;
List1.AddItem quot;Bukuquot;
List1.AddItem quot;Kertasquot;
List1.AddItem quot;Pulpenquot;
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 = quot;quot; Then
MsgBox quot;Anda belum memilih barang !!quot;
Directorate Technical Vocational Education
37. 24 Software Engineering
List1.ListIndex = 0
Exit Sub
End If
If Text1.Text = quot;quot; Then
MsgBox quot;Anda belum mengisi jumlah barang !!quot;
Text1.SetFocus
Exit Sub
End If
Select Case List1.Text
Case quot;Disketquot;
harga = 35000
satuan = quot;Boxquot;
Case quot;Bukuquot;
harga = 20000
satuan = quot;Lusinquot;
Case quot;Kertasquot;
harga = 25000
satuan = quot;Rimquot;
Case quot;Pulpenquot;
harga = 10000
satuan = quot;Pakquot;
End Select
lblBarang.Caption = quot;Barang : quot; & List1.Text
lblHarga.Caption = quot;Harga : quot; & Format(harga,
quot;Currencyquot;) & quot;/quot; & satuan
lblJumlah.Caption = quot;Jumlah : quot; & Text1.Text & quot; quot; &
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 = quot;Diskon : quot; & Format(diskon, quot;0
%quot;)
lblTotal.Caption = quot;Total Bayar : quot; & Format(total,
quot;Currencyquot;)
End Sub
Click on menu Project > Project1 Properties then click General tab. Change Startup
Object into Form6.
Directorate Technical Vocational Education
38. 25 Software Engineering
Please run Project1:
List1 will be filled by name of items.
●
Click OK, will be shown message box quot;Anda belum memilih barang!!quot;
●
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
39. 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 quot;Isi jumlah barang harus angka !!quot;
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
40. 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=x2
Loop
Do
y=y+1
x=x2
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
41. 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
42. 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 quot;Angka quot; & i
Next i
End Sub
Private Sub Command2_Click()
List1.Clear
For i = 100 To 1 Step -2
List1.AddItem quot;Angka quot; & i
Next i
End Sub
Private Sub Command3_Click()
List1.Clear
i = Asc(quot;Aquot;)
Do Until i > Asc(quot;Zquot;)
List1.AddItem quot;Huruf quot; & Chr(i)
i=i+1
Loop
End Sub
Private Sub Command4_Click()
List1.Clear
i = Asc(quot;Zquot;)
Do While i >= Asc(quot;Aquot;)
List1.AddItem quot;Huruf quot; & 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
43. 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
44. 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 = quot;Januariquot;
Case 2: sRet = quot;Februariquot;
Case 3: sRet = quot;Maretquot;
Case 4: sRet = quot;Aprilquot;
Case 5: sRet = quot;Meiquot;
Case 6: sRet = quot;Juniquot;
Case 7: sRet = quot;Juliquot;
Case 8: sRet = quot;Agustusquot;
Case 9: sRet = quot;Septemberquot;
Case 10: sRet = quot;Oktoberquot;
Case 11: sRet = quot;Nopemberquot;
Case 12: sRet = quot;Desemberquot;
Case Else
sRet = quot;tidak sahquot;
End Select
Bulan = sRet
End Function
7.2. Access and Database Manipulation with Visual Basic
Directorate Technical Vocational Education
45. 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
46. 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 = quot;Provider=Microsoft.Jet.OLEDB.3.51;quot;
_
& quot;Data Source=C:Microsoft Visual
StudioVb98Biblio.mdbquot;
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 = quot;C:Program FilesMicrosoft Visual
StudioVb98NWind.mdbquot;
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
Directorate Technical Vocational Education
47. 34 Software Engineering
cn.Open quot;Provider=Microsoft.Jet.OLEDB.3.51;Data Source=quot; &
DBPATH
rs.Source = quot;Employeesquot;
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 & quot; = quot; & 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 & quot; = quot; & fld
Next
Data manipulation in recordset.
●
Data update on recordset may be done as follows.
rs.Update Array(quot;FirstNamequot;, quot;LastNamequot;, quot;BirthDatequot;, quot;HireDatequot;), _
Array(quot;Johnquot;, quot;Smithquot;, #1/1/1961#, #12/3/1994#)
While to add a recordset, the following statement may be used.
rs.AddNew
rs(quot;FirstNamequot;) = quot;Robertquot;
rs(quot;LastNamequot;) = quot;Doe
rs(quot;BirthDatequot;) = #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
48. 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
49. 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 quot;(correct)quot;
Else
Set colSuggestions =
MSWord.GetSpellingSuggestions(text)
If colSuggestions.Count = 0 Then
lstSuggestions.AddItem quot;(no suggestions)quot;
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
50. 37 Software Engineering
7.5. EXERCISE
1. What is the result of the following Visual Basic expression:
a. 3*4
b. 7^2
c. 1/ (2^3)
d. 3 + (4*5)
e. (5 - 3) *4
f. 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
51. 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
52. 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
Figure 8.1. Logo Java.
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
53. 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
54. 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
55. 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
56. 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:TestCodeJava, 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
57. 44 Software Engineering
Open command-prompt in Windows then type:
●
set PATH=C:progra~1javajdk1.5.0bin;%PATH%
set CLASSPATH= . ;D:TestCodeJava
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(quot;Hallo ini Java lhoquot;);
}
}
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
58. 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
59. 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 Representing two (2) conditions: true and false.
(boolean)
Text (char) Must be between quotes (' ')
Integer (byte, Integer data type, default type is int.
byte = 8 bits ranging from -27 – 27-1
short, int &
short 16 bits ranging from -215 – 215-1
long)
int = 32 bits ranging from -231 – 231-1
long = 64 bits ranging from -263 - 263-1
Floating point Numbers data type, may be fractional. Default data type is double.
Float = 32 bits ranging from -231 – 231-1
(float and
Double = 64 bits ranging from -263 - 263-1
double)
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
60. 47 Software Engineering
System.out.println(quot;Hasil penjumlahan = quot; + d);
System.out.println(quot;Hasil perkalian = quot; + 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(quot;Luas Lingkaran = quot; + 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(quot;ch = quot; + ch);
ch++;
System.out.println(quot;ch = quot; + 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
61. 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 = quot;quot;;
System.out.print(quot;Ketikkan nama anda:quot;);
try{
name = dataIn.readLine();
}catch( IOException e ){
System.out.println(quot;Error!quot;);
}
System.out.println(quot;Hai quot; + name +quot;!quot;);
}
}
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
62. 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(quot;Error!quot;);
}
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
63. 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(quot;Nilai Variabel...quot;);
System.out.println(quot; i = quot; + i);
System.out.println(quot; j = quot; + j);
System.out.println(quot; x = quot; + x);
System.out.println(quot; y = quot; + y);
//penjumlahan
System.out.println(quot;Penjumlahan...quot;);
System.out.println(quot; i + j = quot; + (i + j));
System.out.println(quot; x + y = quot; + (x + y));
//pengurangan
System.out.println(quot;Pengurangan...quot;);
System.out.println(quot; i - j = quot; + (i - j));
System.out.println(quot; x - y = quot; + (x - y));
//perkalian
System.out.println(quot;Perkalian...quot;);
System.out.println(quot; i * j = quot; + (i * j));
System.out.println(quot; x * y = quot; + (x * y));
//pembagian
System.out.println(quot;Pembagian...quot;);
System.out.println(quot; i / j = quot; + (i / j));
System.out.println(quot; x / y = quot; + (x / y));
//modulus
System.out.println(quot;Sisa Hasil Bagi...quot;);
System.out.println(quot; i % j = quot; + (i % j));
System.out.println(quot; x % y = quot; + (x % y));
//increment
System.out.println(quot;Increment...quot;);
System.out.println(quot; i++ = quot; + (i++));
System.out.println(quot; ++i = quot; + (++i));
System.out.println(quot; j++ + i = quot; + (j++ + i));
System.out.println(quot; ++j + i = quot; + (++j + i));
}
}
Directorate Technical Vocational Education
64. 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(quot;Nilai variabel...quot;);
System.out.println(quot; i = quot; + i);
System.out.println(quot; j = quot; + j);
System.out.println(quot; k = quot; + k);
//lebih besar dari
System.out.println(quot;Lebih besar dari...quot;);
System.out.println(quot; i > j = quot; + (i > j));
System.out.println(quot; j > i = quot; + (j > i));
System.out.println(quot; k > j = quot; + (k > j));
//lebih besar atau sama dengan
System.out.println(quot;Lebih besar atau sama
dengan...quot;);
System.out.println(quot; i >= j = quot; + (i >= j));
System.out.println(quot; j >= i = quot; + (j >= i));
System.out.println(quot; k >= j = quot; + (k >= j));
//lebih kecil dari
System.out.println(quot;Lebih kecil dari...quot;);
System.out.println(quot; i < j = quot; + (i < j));
System.out.println(quot; j < i = quot; + (j < i));
System.out.println(quot; k < j = quot; + (k < j));
//lebih kecil atau sama dengan
System.out.println(quot;Lebih kecil atau sama
dengan...quot;);
System.out.println(quot; i <= j = quot; + (i <= j));
System.out.println(quot; j <= i = quot; + (j <= i));
System.out.println(quot; k <= j = quot; + (k <= j));
//sama dengan
System.out.println(quot;Sama dengan...quot;);
System.out.println(quot; i == j = quot; + (i == j));
Directorate Technical Vocational Education
65. 52 Software Engineering
System.out.println(quot; k == j = quot; + (k == j));
//tidak sama dengan
System.out.println(quot;Tidak sama dengan...quot;);
System.out.println(quot; i != j = quot; + (i != j));
System.out.println(quot; k != j = quot; + (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(quot;Selamat anda lulus!quot;);
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(quot;Selamat anda lulus!quot;);
else System.out.println(quot;Anda tidak lulus!quot;);
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
66. 53 Software Engineering
int nilai = 68;
if( nilai > 90 ){
System.out.println(quot;Your mark is very good!quot;);
}
else if( nilai > 60 ){
System.out.println(quot;Your mark is good!quot;);
}
else{
System.out.println(quot;You are not passedquot;);
}
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(quot;Nilai b: quot; + b);
}
}
What is the results of the above source code in Example 8.9. If your answer is 4
Directorate Technical Vocational Education
67. 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(quot;Nilai x: quot; + x);
System.out.println(quot;Nilai j: quot; + 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