117
COMPETENCY - BASED LEARNING MATERIAL Sector : INFORMATION AND COMMUNICATIONS TECHNOLOGY Qualification : Programming NC IV Unit of Competency : Apply Programming Skills in a Second Language Module Title : Applying Programming Skills in a Second Language SICAT QA SYSTEM COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV Date Developed: JUNE 4, 2011 Document No. Issued by: Page Developed by: Revision # 00

CBLM LO1 LO2.docx

Embed Size (px)

Citation preview

Page 1: CBLM LO1 LO2.docx

COMPETENCY - BASED LEARNING MATERIAL

Sector :

INFORMATION AND COMMUNICATIONS TECHNOLOGY

Qualification :

Programming NC IV

Unit of Competency : Apply Programming Skills in a Second Language

Module Title :

Applying Programming Skills in a Second Language

Technical Education and Skills Development Authority

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 2: CBLM LO1 LO2.docx

How to use this Competency – Based Learning Material

Welcome to the module APPLYING PROGRAMMING SKILLS IN A SECOND LANGUAGE. This module contains training materials and activities for you to complete.

The unit of competency Apply Programming Skills in a Second Language contains the knowledge and skills and attitudes required for Programming. It is one of the specialized modules at National Certificate level IV (NC IV).

You are required to go through a series of learning activities in order to complete each learning outcomes of the module. In each learning outcome there are Information Sheets to help you better understand the required activities. Follow these activities on your own and answer the self –check at the end of each learning outcome. You may remove a blank answer sheet at the end of each module (or get from your facilitator/ trainer) to write your answers for each self-check. If you have questions, don’t hesitate to ask your facilitator for assistance.

Instruction sheets:

Information Sheet – This will provide you with information (Concepts, principles and other relevant information) needed in performing certain activities.

Operation Sheet – This will guide you in performing single task, operation process in a job.

Job Sheet – This is designed to guide you how to do the job that will contribute to the attainment of the learning outcome.

Assignment Sheet – The assignment sheet is a guide used to enhance (follow up) what you have learned in the information sheet or job sheet.

Worksheet – are the different forms that you need to fill up certain activities that you performed.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 3: CBLM LO1 LO2.docx

LIST OF COMPETENCIES

NO UNIT OF COMPETENCIES MODULE TITLE CODE

1 Design Program Logic Designing Program Logic ICT313328

2Apply Program Development Approach

Applying Program Development Approach

ICT313329

3Apply Object-Oriented Program Language Skills

Applying Object-Oriented Program Language Skills

ICT313330

4Apply Programming Skills in a Second Langauge

Applying Programming Skills in a Second Language

ICT313331

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 4: CBLM LO1 LO2.docx

MODULES OF INSTRUCTION

Unit of Competency : Apply Programming Skills in a Second Language

Module Title: Applying Programming Skills in a Second Language

MODULE DESCRIPTOR: This module defines the competency required to undertake introductory programming tasks using a procedural approach to programming. (An object oriented language may be used in this approach)

NOMINAL DURATION: 42 hours

LEARNING OUTCOMES: NC IV

Upon completion of this module, the trainee/student must be able to:

LO1. Apply basic language syntax and layout

LO2. Code using standard algorithms

LO3. Debug code

LO4. Document activities

LO5. Test code

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 5: CBLM LO1 LO2.docx

ASSESSMENT CRITERIA:

LO1

1. Observed basic language syntax rules and best practice based on the standard of specific programming language.

2. Used language data types, operators and expressions based on the standard of specific programming language.

3. Used appropriate language syntax for sequence, selection and iteration constructs based on the standard of specific programming language.

LO2

1. Used basic programming constructs algorithms based on the standard of specific programming language

2. Demonstrated ability to create sequential search, insertion and deletion algorithms to operate on one dimensional array based on the specific programming standard

3. Coded and used standard sequential access algorithms for text and binary files

4. Used of SQL language facilities to access databases based on the standard of specific programming language

LO3

1. Reviewed the code visually and / or used of debugging tools provided by the system or the organization

2. Used a debugger to trace code execution and examine variable contents to detect and correct errors based on the program requirements.

LO4

1. Followed guidelines for developing maintainable code adhering to a set of coding standard

2. Followed and used internal documentation standards and tools.

LO5

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 6: CBLM LO1 LO2.docx

1. Developed and conducted simple tests to confirm the coding process to meet design specification

2. Documented the tests performed 3. Made corrections to the code and the documentation as needed.

CONDITION:

The students/trainees must be provided with the following:

PC Package with OOPL Reference Books Handouts/Modules/Printed Materials

ASSESSMENT METHODS:

1. Written/Oral Examination

2. Observation

3. Practical Demonstration

4. Case Study (Defense)

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 7: CBLM LO1 LO2.docx

LEARNING EXPERIENCESLearning Outcome 1Apply basic language syntax rules and layout

Learning Activities Special Instructions1. Read information sheet

4.1-1 ”Semantics and Syntax”

If you have some problem on the content of the information sheet don’t hesitate to approach your instructor/teacher.If you feel that you are now knowledgeable on the content of the information sheet, you can now answer self-check provided in the module.

2. Answer self-check 4.1-1 Compare your answer to the answer key 4.1-1. If you got 100% correct answer in this self-check, you can now perform the operation sheet 4.1-1. If not review the information sheet and go over the self-check again.

3. Perform operation sheet 4.1-1

Evaluate your work if is performed properly using performance criteria checklist. If it is made properly you can move to the next procedural sheet. If not go over the operation sheet again.

4. Perform procedural checklist 4.1-1

Evaluate your work it is done correctly using procedural criteria checklist. If it is done properly, can move to the new information sheet.

5. Read information sheet 4.1-2 “Elements of programming.

If you have some problem on the content of the information sheet don’t hesitate to approach your facilitator.If you feel that you are now knowledgeable on the content of the information sheet, you can now answer self-check provided in the module.

6. Answer self-check 4.1-2 Compare your answer to the answer key 4.1-2. If you got 100% correct answer in this self-check, you can now move to the next operation sheet 4.1-2. If not review the information sheet and go over the self-check again.

7. Perform operation sheet 4.1-2

Evaluate your work if you it performs properly. If it is made appropriately you

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 8: CBLM LO1 LO2.docx

can move to the next procedural sheet. If not go over the operation sheet again.

8. Perform procedural checklist 4.1-2

Evaluate your work it is done correctly using procedural criteria checklist. If it is made properly, can move to the new information sheet.

9. Read information sheet 4.1-3 “Program control structure”

If you have some problems on the content of the information sheet don’t hesitate to approach your facilitator.If you feel that you are now knowledgeable on the content of the information sheet, you can now answer self-check provided in the module.

10. Answer self-check 4.1-3 Compare your answer to the answer key 4.1-3. If you got 100% correct answer in this self-check, you can now move to the next operation sheet 4.1-3. If not review the information sheet and go over the self-check again.

11. Perform operation sheet 4.1-3

Evaluate your work if it performed properly. If it is made appropriately you can move to the job sheet. If not go over the operation sheet again.

12. Perform the Written test 4.1-3

Compare your answer to the key-answer sheet. If you got 100% correct answer in this written test, you can now move to the next information sheet. If not review the information sheet and go over the written test again.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 9: CBLM LO1 LO2.docx

Information Sheet 4.1-1

Topic: Semantics and Syntax

Objectives

At the end of the lesson, the student should be able to:

Identify the basic parts of a Java program

Create a Java program using text editor and console in the Linux (Ubuntu Dapper) environment

Differentiate between syntax-errors and runtime errors

Create a Java program using NetBeans

Lesson Proper:

Dissecting my first Java programWe will try to dissect your first Java program:

public class Hello{/*** My first java program*/public static void main(String[] args) {//prints the string "Hello world" on screenSystem.out.println("Hello world!");}}

The first line of the code, public class Hello indicates the name of the class which is Hello. In Java, all code should be placed inside a class declaration. We do this by using the class keyword. In addition, the class uses an access specifier public, which indicates that our class in accessible to other classes from other packages (packages are a collection of classes). We will be covering packages and access specifier later.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 10: CBLM LO1 LO2.docx

The next line which contains a curly brace “{“ indicates the start of a block. In this code, we placed the curly brace at the next line after the class declaration; however, we can also place this next to the first line of our code.

So, we could actually write our code as:public class Hello{orpublic class Hello {

The next three lines indicate a Java comment. A comment is something used to document part of the code. It is not part of the program itself, but used for documentation purposes. It is good programming practice to add comments to your code.

/*** My first java program*/

A comment is indicated by the delimiters “/*” and “*/”. Anything within these delimiters are ignored by the Java compiler, and are treated as comments.

The next line,public static void main(String[] args) {or can also be written as,public static void main(String[] args){

indicates the name of one method in Hello which is the main method. The main method is the starting point of a Java program. All programs except Applets written in Java start with the main method. Make sure to follow the exact signature.

The next line is also a Java comment,//prints the string "Hello world" on screen

Now, we learned two ways of creating comments. The first one is by placing the comment inside /* and */, and the other one is by writing // at the start of thecomment.

The next line, System.out.println("Hello world!");prints the text “Hello World!” on screen. The command

System.out.println(), prints the text enclosed by quotation on the screen.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 11: CBLM LO1 LO2.docx

The last two lines which contains the two curly braces is used to close the main method and class respectively.

Coding Guidelines:1. Your Java programs should always end with the .java extension.2. Filenames should match the name of your public class. So for example,

if the name of your public class is Hello, you should save it in a file called Hello.java.

3. You should write comments in your code explaining what a certain class does, or what a certain method do.

Java CommentsComments are notes written to a code for documentation purposes. Those text are not part of the program and does not affect the flow of the program.

Java supports three types of comments: C++-style single line comments, C-style multiline comments and special javadoc comments.

C++-Style CommentsC++ Style comments starts with //. All the text after // are treated

as comments. For example,// This is a C++ style or single line comments

C-Style CommentsC-style comments or also called multiline comments starts with a /*

and ends with a */.All text in between the two delimeters are treated as comments.

Unlike C++ style comments, it can span multiple lines. For example, /* this is an exmaple of aC style or multiline comments */

Special Javadoc CommentsSpecial Javadoc comments are used for generating an HTML

documentation for your Java programs. You can create javadoc comments by starting the line with /** and ending it with */. Like C-style comments, it can also span lines. It can also contain certain tags to add more information to your comments. For example,/**This is an example of special java doc comments used for \ngenerating an html documentation. It uses tags like:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 12: CBLM LO1 LO2.docx

@author Florence Balagtas@version 1.2*/

Java Statements and blocksA statement is one or more lines of code terminated by a semicolon. An example of a single statement is, System.out.println(“Hello world”);

A block is one or more statements bounded by an opening and closing curly braces that groups the statements as one unit. Block statements can be nested indefinitely. Any amount of white space is allowed. An example of a block is,

public static void main( String[] args ){System.out.println("Hello");System.out.println("world");}

Coding Guidelines:1. In creating blocks, you can place the opening curly brace in line with

the statement, like for example,public static void main( String[] args ){or you can place the curly brace on the next line, like,public static void main( String[] args ){

2. You should indent the next statements after the start of a block,for example,

public static void main( String[] args ){System.out.println("Hello");System.out.println("world");}

Java IdentifiersIdentifiers are tokens that represent names of variables, methods, classes, etc. Examples of identifiers are: Hello, main, System, out.

Java identifiers are case-sensitive. This means that the identifier: Hello is not the same as hello. Identifiers must begin with either a letter, an underscore “_”, or a dollar sign “$”. Letters may be lower or upper case. Subsequent characters may use numbers 0 to 9.

Identifiers cannot use Java keywords like class, public, void, etc. We will discuss more about Java keywords later.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 13: CBLM LO1 LO2.docx

Coding Guidelines:1. For names of classes, capitalize the first letter of the class name. For

names of methods and variables, the first letter of the word should start with a small letter.For example:

ThisIsAnExampleOfClassNamethisIsAnExampleOfMethodName

2. In case of multi-word identifiers, use capital letters to indicate the start of the word except the first word. For example, charArray, fileNumber, ClassName.

3.Avoid using underscores at the start of the identifier such as _read or _write.

Java KeywordsKeywords are predefined identifiers reserved by Java for a specific purpose. You cannot use keywords as names for your variables, classes, methods …etc. Here is a list of the Java Keywords.

We will try to discuss all the meanings of these keywords and how they are used in our Java programs as we go along the way.

Note: true, false, and null are not keywords but they are reserved words, so you cannot use them as names in your programs either

Java LiteralsLiterals are tokens that do not change or are constant. The different types of literals in Java are: Integer Literals, Floating-Point Literals, Boolean Literals, Character Literals and String Literals.

Integer LiteralsInteger literals come in different formats: decimal (base 10), hexadecimal (base 16), and octal (base 8). In using integer literals in our program, we have to follow some special notations.

For decimal numbers, we have no special notations. We just write a decimal number as it is. For hexadecimal numbers, it should be preceeded by “0x” or “0X”. For octals, they are preceeded by “0”.

For example, consider the number 12. It's decimal representation is 12, while in hexadecimal, it is 0xC, and in octal, it is equivalent to 014.Integer literals default to the data type int. An int is a signed 32-bit value. In some cases, you may wish to force integer literal to the data type long by appending the “l” or “L” character. A long is a signed 64-bit value. We will cover more on data types later.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 14: CBLM LO1 LO2.docx

Floating-Point LiteralsFloating point literals represent decimals with fractional parts. An example is 3.1415. Floating point literals can be expressed in standard or scientific notations. For example, 583.45 is in standard notation, while 5.8345e2 is in scientific notation.

Floating point literals default to the data type double which is a 64-bit value. To use a smaller precision (32-bit) float, just append the “f” or “F” character.

Boolean LiteralsBoolean literals have only two values, true or false.

Character LiteralsCharacter Literals represent single Unicode characters. A Unicode character is a 16-bit character set that replaces the 8-bit ASCII character set. Unicode allows the inclusion of symbols and special characters from other languages.

To use a character literal, enclose the character in single quote delimiters. For example, the letter a, is represented as ‘a’.

To use special characters such as a newline character, a backslash is used followed by the character code. For example, ‘\n’ for the newline character, ‘\r’ for the carriage return, ‘\b’ for backspace.

String LiteralsString literals represent multiple characters and are enclosed by double quotes. An example of a string literal is, “Hello World”.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 15: CBLM LO1 LO2.docx

SELF – CHECK 4.1-1

Direction: Answer the following questions to the best of your knowledge.

Question Answer1. What is the first line of code in a

simple Java program?2. What is the difference between

the C++ and the C Style Comment?

3. Differentiate keyword from literal.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 16: CBLM LO1 LO2.docx

SELF – CHECK 4.1-1 Answer Key

Question Answer1. What is the first line of code in a

simple Java program?public class hello

2. What is the difference between the C++ and the C Style Comment?

C++ Style uses // as one line comment

C Style uses /** */ as a multi-line comment

3. Differentiate keyword from literal.

Keywords are predefined identifiers reserved by Java for a specific purpose.

Literals are tokens that do not change or are constant.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 17: CBLM LO1 LO2.docx

OPERATION SHEET 4.1-1

OPERATION TITLE

: Apply basic language syntax and layout

PERFORMANCE OBJECTIVE

At the end of the lesson, the student should be able to:• Create a Java program using text editor and console in the Linux (Ubuntu Dapper) environment• Differentiate between syntax-errors and runtime errors• Create a Java program using NetBeans

SUPPLIES Reference Manual

EQUIPMENT : 1 complete computer set installed with Java SDK or Netbeans

PROCEDUREMy First Java Program

public class Hello {/** * My first Java program */public static void main( String[] args ){

//prints the string “Hello world” on screenSystem.out.println(“Hello world”);

}}

Using Text Editor and ConsoleNOTE:

This will be demonstrated by the teacherEnvironment used: Ubuntu DapperFor Windows Environment: Refer to Appendix B in your

student Manual

Step 1: Start the Text EditorTo start the Text Editor in Linux, click on Menu-> Accessories-

> Text EditorStep 2: Open Terminal

To open Terminal in Linux, click on Menu-> System Tools-> Terminal

Step 3: Write your the source code of your Java program in the Text Editor

Step 4: Save your Java ProgramSICAT

QASYSTEM

COMPETENCY BASED LEARNING

MATERIAL IN PROGRAMMING

NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 18: CBLM LO1 LO2.docx

Filename: Hello.javaFolder name: MYJAVAPROGRAMSTo open the Save dialog box, click on the File menu found on

the menubar and then click on Save.If the folder MYJAVAPROGRAMS does not exist yet, create the

folderStep 5: Compiling your program

Go to the Terminal windowGo to the folder MYJAVAPROGRAMS where you saved the

programTo compile a Java program, we type in the command:

javac [filename]So in this case, type in: javac Hello.java

During compilation, javac adds a file to the disk called [filename].class, or in this case, Hello.class, which is the actual bytecode.

Step 6: Running the ProgramTo run your Java program, type in the command: java

[filename without the extension]so in the case of our example, type in: java HelloYou can see on the screen after running the program:

"Hello world!"Syntax Errors Syntax

errors are usually typing errorsCommon Syntax Errors:

misspelled a command in Javaforgot to write a semi-colon at the end of a statement

Run-time Errorserrors that will not display until you run or execute your

programEven programs that compile successfully may display wrong

answers if the programmer has not thought through the logical processes and structures of the program.

Examples:You want your program to print 100 strings of “Hello

world”, but it only printed 99.Your program gets an input from the user, but the user

inputted a character, and so your program crashes/terminates

Using NetBeansNOTE:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 19: CBLM LO1 LO2.docx

This will be demonstrated by the teacherEnvironment used: Ubuntu DapperFor Windows Environment: Refer to Appendix B in your

student ManualStep 1: Run NetBeans

Two ways to run NetBeans:Through command-line using terminalBy just clicking on the shortcut button found on the

menuTo run NetBeans using command-line

Open terminal (see steps on how to run terminal in the previous discussion), and type: netbeans

The second way to run NetBeansClick on shortcut on the desktop

Step 2: Make a projectTo make a project, click on File-> New ProjectAfter doing this, a New Project dialog will appearOn the right pane of the project dialog, click on Java

Application and click on the NEXT buttonA New Application dialog will appear. Edit the Project Name

part and type in "HelloApplication"Step 2: Make a project (continuation)

Now try to change the Application Location, by clicking on the BROWSE button

A Select Project Location dialog will then appear. Double-click on the root folder.

The contents of the root folder are then displayed. Now double-click on the MYJAVAPROGRAMS folder and click on the OPEN button

Finally, on the Create Main Class textfield, type in Hello as the main class' name, and then click on the FINISH button

Step 3: Type in your program

Now, try to modify the code generated by NetBeans.Ignore the other parts of the program for now, as we will

explain the details of the code later.Insert the code System.out.println("Hello world!"); after the

statement, //TODO code application logic here.Step 4: Compile your program

To compile your program, just click on Build -> Build Main Project

If there are no errors in your program, you will see a build successful message on the output window

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 20: CBLM LO1 LO2.docx

Step 5: Run your programTo run your program, click on Run-> Run Main ProjectThe output of your program is displayed in the output window

PRECAUTIONS : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and variable names are however accepted.

ASSESSMENT METHOD

Performance Check

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 21: CBLM LO1 LO2.docx

PROCEDURAL CHECKLIST 4.1-1

4.1-3 Name:

Date

CRITERIASatisfactory Response

YES NO

Did the student follow the proper indention and coding spacing?

Hello World appeared on the screen observing case format (Capital H and W).

No syntax error during runtime was observed.

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 22: CBLM LO1 LO2.docx

Information Sheet 4.1-2

Topic: Elements of Programming

Objectives

At the end of the lesson, the student should be able to:

Differentiate among, primitive data types, variable types, identifiers and operators

Develop a simple valid Java program using the concepts of primitive data types, variable types, identifiers and operators

Lesson Proper:

Primitive data typesThe Java programming language defines eight primitive data types. The following are, boolean (for logical), char (for textual), byte, short, int, long (integral), double and float (floating point).Logical - booleanA boolean data type represents two states: true and false. An example is,

boolean result = true;The example shown above, declares a variable named result as boolean type and assigns it a value of true.Textual – charA character data type (char), represents a single Unicode character. It must have itsliteral enclosed in single quotes(’ ’). For example,

‘a’ //The letter a‘\t’ //A tab

To represent special characters like ' (single quotes) or " (double quotes), use the escapecharacter \. For example,

'\'' //for single quotes'\"' //for double quotes

Although, String is not a primitive data type (it is a Class), we will just introduce String in this section. A String represents a data type that contains multiple characters. It is not a primitive data type, it is a class. It has it’s literal enclosed in double quotes(“”).For example,

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 23: CBLM LO1 LO2.docx

String message=“Hello world!”

Integral – byte, short, int & longIntegral data types in Java uses three forms – decimal, octal or hexadecimal. Examples are,

2 //The decimal value 2077 //The leading 0 indicates an octal value0xBACC //The leading 0x indicates a hexadecimal value

Integral types has int as default data type. You can define its long value by appending the letter l or L. Integral data type have the following ranges:

Floating Point – float and doubleFloating point types has double as default data type. Floating-point literal includes either a decimal point or one of the following,

E or e //(add exponential value)F or f //(float)D or d //(double)

Examples are,3.14 //A simple floating-point value (a double)6.02E23 //A large floating-point value2.718F //A simple float size value123.4E+306D //A large double value with redundant D

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 24: CBLM LO1 LO2.docx

In the example shown above, the 23 after the E in the second example is implicitly positive. That example is equivalent to 6.02E+23. Floating-point data types have the following ranges:

VariablesA variable is an item of data used to store state of objects.A variable has a data type and a name. The data type indicates the type of value that the variable can hold. The variable name must follow rules for identifiers.Declaring and Initializing VariablesTo declare a variable is as follows,

<data type> <name> [=initial value];Note: Values enclosed in <> are required values, while those values enclosed in [] are optional.

Outputting Variable DataIn order to output the value of a certain variable, we can use the following commands,

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

Here's a sample program,public class OutputVariable{public static void main( String[] args ){int value = 10;char x;x = ‘A’;

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 25: CBLM LO1 LO2.docx

System.out.println( value );System.out.println( “The value of x=“ + x );}}

The program will output the following text on screen,10The value of x=A

System.out.println() vs. System.out.print()What is the difference between the commands System.out.println() andSystem.out.print()? The first one appends a newline at the end of the data to output,while the latter doesn't.Consider the statements,

System.out.print("Hello ");System.out.print("world!");

These statements will output the following on the screen,Hello world!

Now consider the following statements,System.out.println("Hello ");System.out.println("world!");

These statements will output the following on the screen,Helloworld!

4.9.4 Reference Variables vs. Primitive VariablesWe will now differentiate the two types of variables that Java programs have. These are reference variables and primitive variables. Primitive variables are variables with primitive data types. They store data in the actual memory location of where the variable is. Reference variables are variables that stores the address in the memory location. It points to another memory location of where the actual data is. When you declare a variable of a certain class, you are actually declaring a reference variable to the object with that certain class.

For example, suppose we have two variables with data types int and String.

int num = 10;String name = "Hello"

Suppose, the illustration shown below is the actual memory of your computer, wherein you have the address of the memory cells, the variable name and the data they hold.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 26: CBLM LO1 LO2.docx

As you can see, for the primitive variable num, the data is on the actual location of where the variable is. For the reference variable name, the variable just holds the address of where the actual data is.

OperatorsIn Java, there are different types of operators. There are arithmetic operators, relational operators, logical operators and conditional operators. These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first in case multiple operators are used in one statement.

Arithmetic operatorsHere are the basic arithmetic operators that can be used in creating your Java programs,

Increment and Decrement operatorsAside from the basic arithmetic operators, Java also includes a unary increment operator (++) and unary decrement operator (--). Increment and decrement operators increase and decrease a value stored in a number variable by 1.

For example, the expression,

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 27: CBLM LO1 LO2.docx

count = count + 1; //increment the value of count by 1is equivalent to,

count++;

Relational operatorsRelational operators compare two values and determines the relationship between those values. The output of evaluation are the boolean values true or false.

Logical operatorsLogical operators have one or two boolean operands that yield a boolean result. There are six logical operators: && (logical AND), & (boolean logical AND), || (logical OR), | (boolean logical inclusive OR), ^ (boolean logical exclusive OR), and ! (logical NOT).The basic expression for a logical operation is,

x1 op x2where x1, x2 can be boolean expressions, variables or constants, and op is either &&, &, ||, | or ^ operator. The truth tables that will be shown next, summarize the result of each operation for all possible combinations of x1 and x2.

Truth TablesX Y X &Y X | Y !XFALSE FALSE FALSE FALSE TRUEFALSE TRUE FALSE TRUE TRUETRUE FALSE FALSE TRUE FALSETRUE TRUE TRUE TRUE FALSE

Conditional Operator (?:)

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 28: CBLM LO1 LO2.docx

The conditional operator ?: is a ternary operator. This means that it takes in three arguments that together form a conditional expression. The structure of an expression using a conditional operator is,

exp1?exp2:exp3wherein exp1 is a boolean expression whose result must either be true or false.If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.For example, given the code,

public class ConditionalOperator{public static void main( String[] args ){String status = "";int grade = 80;//get status of the studentstatus = (grade >= 60)?"Passed":"Fail";//print statusSystem.out.println( status );}}

The output of this program will be,Passed

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 29: CBLM LO1 LO2.docx

SELF – CHECK 4.1-2

Direction: Answer the following questions to the best of your knowledge.

Question Answer

1. What is the importance of data type?

2. Why do we have to use a variable in storing data?

3. Enumerate the different operators used in Java.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 30: CBLM LO1 LO2.docx

SELF – CHECK 4.1-2 Answer Key

Question Answer

1. What is the importance of a data type?

It is used specify the amount of memory allocated for every stored data. This will maximize the use of memory space.

2. Why do we have to use a variable in storing data?

Variables hold the value stored in the memory that can be used some time in other parts of the program.

3. Enumerate the different operators used in Java.

ArithmeticLogicalRelationalIncrement/DecrementConditional

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 31: CBLM LO1 LO2.docx

OPERATION SHEET 4.1-2

OPERATION TITLE

Elements of Programming

PERFORMANCE OBJECTIVE

Develop a simple valid Java program using the concepts of primitive data types, variable types, identifiers and operators

SUPPLIES Reference Manual

EQUIPMENT : 1 complete computer set installed with Java SDK or Netbeans

ProcedureGiven the table below, declare the following variables with the corresponding data types and initialization values. Output to the screen the variable names together with the values.

The following should be the expected screen output,Number = 10letter = aresult = truestr = hello

PRECAUTIONS : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and variable names are however accepted.

ASSESSMENT METHOD

Performance Check

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 32: CBLM LO1 LO2.docx

PROCEDURAL CHECKLIST 4.1-2

4.1-3 Name:

Date

CRITERIASatisfactory Response

YES NO

Variables are named according to the given format and case

The program displayed the values that are stored in the variables

Declaration of variables are correct.

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 33: CBLM LO1 LO2.docx

Information Sheet 4.2-3

Topic: Program Control Structure

Objectives

At the end of the lesson, the student should be able to:

Use decision control structures (if, else, switch) which allows selection of specific sections of code to be executed

Use repetition control structures (while, do-while, for) which allow executing specific sections of code a number of times

Lesson Proper:

Decision Control StructuresDecision control structures are Java statements that allows us to select and execute specific blocks of code while skipping other sections.

if statementThe if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true.The if-statement has the form,

if( boolean_expression )statement;orif( boolean_expression ){statement1;statement2;. . .}

where, boolean_expression is either a boolean expression or boolean variable.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 34: CBLM LO1 LO2.docx

if-else statementThe if-else statement is used when we want to execute a certain statement if a conditionis true, and a different statement if the condition is false.The if-else statement has the form,

if( boolean_expression )statement;elsestatement;

or can also be written as,if( boolean_expression ){statement1;statement2;. . .}else{statement1;statement2;. . .}

For example, given the code snippet,int grade = 68;if( grade > 60 ) System.out.println("Congratulations!");else System.out.println("Sorry you failed");orint grade = 68;if( grade > 60 ){System.out.println("Congratulations!");System.out.println("You passed!");}else{System.out.println("Sorry you failed");}

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 35: CBLM LO1 LO2.docx

if-else-if statementThe statement in the else-clause of an if-else block can be another if-else structures. This cascading of structures allows us to make more complex selections. The if-else if statement has the form,

if( boolean_expression1 )statement1;else if( boolean_expression2 )statement2;elsestatement3;

Take note that you can have many else-if blocks after an if-statement. The else-block is optional and can be omitted. In the example shown above, if boolean_expression1 is true, then the program executes statement1 and skips the other statements. If boolean_expression2 is true, then the program executes statement 2 and skips to the statements following statement3.

switch statementAnother way to indicate a branch is through the switch keyword. The switch construct allows branching on multiple outcomes. The switch statement has the form,

switch( switch_expression ){case case_selector1:statement1; //statement2; //block 1. . . //break;case case_selector2:statement1; //statement2; //block 2

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 36: CBLM LO1 LO2.docx

. . . //break;. . .default:statement1; //statement2; //block n. . . //break;}

where, switch_expression is an integer or character expression and, case_selector1, case_selector2 and so on, are unique integer or character constants.

When a switch is encountered, Java first evaluates the switch_expression, and jumps to the case whose selector matches the value of the expression. The program executes the statements in order from that point on until a break statement is encountered, skipping then to the first statement after the end of the switch structure.

If none of the cases are satisfied, the default block is executed. Take note however, that the default part is optional. A switch statement can have no default block.

NOTES: Unlike with the if statement, the multiple statements are executed

in the switch statement without needing the curly braces. When a case in a switch statement has been matched, all the

statements associated with that case are executed. Not only that, the statements associated with the succeeding cases are also executed.

To prevent the program from executing statements in the subsequent cases, we use a break statement as our last statement.

Repetition Control StructuresRepetition control structures are Java statements that allows us to execute specific blocks of code a number of times. There are three types of repetition control structures, the while, do-while and for loops.

while loopThe while loop is a statement or block of statements that is repeated as long as some condition is satisfied. The while statement has the form,

while( boolean_expression ){statement1;

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 37: CBLM LO1 LO2.docx

statement2;. . .}

The statements inside the while loop are executed as long as the boolean_expression evaluates to true. For example, given the code snippet,

int i = 4;while ( i > 0 ){System.out.print(i);i--;}

The sample code shown will print 4321 on the screen. Take note that if the line containing the statement i--; is removed, this will result to an infinite loop, or a loop that does not terminate. Therefore, when using while loops or any kind of repetition control structures, make sure that you add some statements that will allow your loop to terminate at some point.

The following are other examples of while loops,Example 1:

int x = 0;while (x<10){System.out.println(x);x++;}

Example 2://infinite loopwhile(true)System.out.println(“hello”);

Example 3://no loops// statement is not even executedwhile (false)System.out.println(“hello”);

do-while loopThe do-while loop is similar to the while-loop. The statements inside a do-while loop are executed several times as long as the condition is satisfied. The main difference between a while and do-while loop is that, the statements inside a do-while loop are executed at least once. The do-while statement has the form,

do{SICAT

QASYSTEM

COMPETENCY BASED LEARNING

MATERIAL IN PROGRAMMING

NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 38: CBLM LO1 LO2.docx

statement1;statement2;. . .}while( boolean_expression );

The statements inside the do-while loop are first executed, and then the condition in the boolean_expression part is evaluated. If this evaluates to true, the statements inside the do-while loop are executed again. Here are a few examples that uses the do-while loop:Example 1:

int x = 0;do{System.out.println(x);x++;}while (x<10);This example will output 0123456789 on the screen.

Example 2://infinite loopdo{System.out.println(“hello”);} while (true);This example will result to an infinite loop, that prints hello on screen.

Example 3://one loop// statement is executed oncedoSystem.out.println(“hello”);while (false);This example will output hello on the screen.

for loopThe for loop, like the previous loops, allows execution of the same code a number of times. The for loop has the form,

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 39: CBLM LO1 LO2.docx

for (InitializationExpression; LoopCondition; StepExpression){statement1;statement2;. . .}

where,InitializationExpression -initializes the loop variable.LoopCondition - compares the loop variable to some limit value.StepExpression - updates the loop variable.

A simple example of the for loop is,int i;for( i = 0; i < 10; i++ ){System.out.print(i);}

In this example, the statement i=0, first initializes our variable. After that, the condition expression i<10 is evaluated. If this evaluates to true, then the statement inside the for loop is executed. Next, the expression i++ is executed, and then the condition expression is again evaluated. This goes on and on, until the condition expression evaluates to false. This example, is equivalent to the while loop shown below,

int i = 0;while( i < 10 ){System.out.print(i);i++;}

Branching StatementsBranching statements allows us to redirect the flow of program execution. Java offersthree branching statements: break, continue and return.

break statementThe break statement has two forms: unlabeled (we saw its unlabeled form in the switchstatement) and labeled.

Unlabeled break statementThe unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. You can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop. For example,

String names[] = {"Beah", "Bianca", "Lance", "Belle",SICAT

QASYSTEM

COMPETENCY BASED LEARNING

MATERIAL IN PROGRAMMING

NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 40: CBLM LO1 LO2.docx

"Nico", "Yza", "Gem", "Ethan"};String searchName = "Yza";boolean foundName = false;for( int i=0; i< names.length; i++ ){if( names[i].equals( searchName )){foundName = true;break;}}if( foundName ){System.out.println( searchName + " found!" );}else{System.out.println( searchName + " not found." );}

In this example, if the search string "Yza" is found, the for loop will stop and flow of control transfers to the statement following the for loop.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 41: CBLM LO1 LO2.docx

SELF – CHECK 4.1-3

Direction: Answer the following questions to the best of your knowledge.

Program Problem Output1. Write the following program

then draw the output on the Output column:

public class Grade{public static void main( String[] args ){double grade = 92.0;if( grade >= 90 ){System.out.println( "Excellent!" );}else if( (grade < 90) && (grade >= 80)){System.out.println("Good job!" );}else if( (grade < 80) && (grade >= 60)){System.out.println("Study harder!" );}else{System.out.println("Sorry, you failed.");}}}

2. Edit the Grade program then rewrite the if-then-else statement into switch statement.

3. When do we use conditional statements?

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 42: CBLM LO1 LO2.docx

4. When do we use repetition statements?

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 43: CBLM LO1 LO2.docx

SELF – CHECK 4.1-3 Answer Key

Question Answer1. Write the following program

then draw the output on the Output column:

public class Grade{public static void main( String[] args ){double grade = 92.0;if( grade >= 90 ){System.out.println( "Excellent!" );}else if( (grade < 90) && (grade >= 80)){System.out.println("Good job!" );}else if( (grade < 80) && (grade >= 60)){System.out.println("Study harder!" );}else{System.out.println("Sorry, you failed.");}}}

Excellent!

2. Edit the Grade program then rewrite the if-then-else statement into switch statement.

public class Grade{public static void main( String[] args ){int grade = 92;switch(grade){case 100:System.out.println( "Excellent!" );break;case 90:System.out.println("Good job!" );break;case 80:System.out.println("Study harder!" );break;default:System.out.println("Sorry, you failed.");}}}

3. When do you use conditional statements?

Conditional statements are used when the program has to choose between two or more possible results based on the given condition.

4. When do you use repetition statements?

Repetition statements are used when 2 or more statements are performed repeatedly to minimize time in writing the codes.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 44: CBLM LO1 LO2.docx

OPERATION SHEET 4.1-3

OPERATION TITLE

Program Control Structure

PERFORMANCE OBJECTIVE

Use decision control structures (if, else, switch) which allows selection of specific sections of code to be executed

Use repetition control structures (while, do-while, for) which allow executing specific sections of code a number of times

SUPPLIES Reference Manual

EQUIPMENT : 1 complete computer set installed with Java SDK or Netbeans

PROCEDURE

Program 1Step 1. Open your text editorStep 2. Evaluate the given problem.Step 3. Write the appropriate codes applying your knowledge in

using conditional statements.Get three exam grades from the user and compute the average of the grades. Output the average of the three exams. Together with the average, also include a smiley face in the output if the average is greater than or equal to 60, otherwise output :-(.

Step 4. Check your codes.Step 5. Run the program

Program 2Step 1. Open your text editorStep 2. Evaluate the given program.Step 3. Write the appropriate codes applying your knowledge in

using repetition statements.Create a program that prints your name a hundred times. Do three versions of this program using a while loop, a do-while loop and a for-loop.

Step 4. Check your codes.Step 5. Run the program

PRECAUTIONS : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 45: CBLM LO1 LO2.docx

variable names are however accepted.

ASSESSMENT METHOD

Performance Check

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 46: CBLM LO1 LO2.docx

PROCEDURAL CHECKLIST 4.1-3

4.1-3 Name:

Date

CRITERIASatisfactory Response

YES NO

The programs named variables according to its use

Variables are classified using correct data types

Conditional statements were declared appropriately

Repetition structure is used correctly

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 47: CBLM LO1 LO2.docx

JOB SHEET 4.1-3

Title Program Control Structure

Performance Objective

Use decision control structures (if, else, switch) which allows selection of specific sections of code to be executed

Use repetition control structures (while, do-while, for) which allow executing specific sections of code a number of times

Supplies Reference Materials/Modules

Equipment Computer sets with installed Java compiler or Netbeans

Steps/ Procedure:

Write a java program that will computer for the distance traveled and the fare of a passenger.

1. Take note of the following:a. Minimum fare for the first 3 kilometers is P8.00.b. 50 cents per kilometer is added beyond 3 kilometers traveled.c. Use integer value to identify location. The program will display

the location once the numeric representation of location and distance is entered.

d. Compute first the distance from location to destination. Each destination will be considered 1 kilometer away from each other.

e. Compute the fare based on the distance and from the given rules.

f. The program must be able to detect errors such as an input that is beyond 20.

g. Important variables to be declared are: location, destination, distance, fare.

Numeric representation of destination are as follows.

1. Sinsayon2. Dubinan West3. Dubinan East4. Victory Norte5. Centro East6. Malvar

11. Ramos East12. Quezon13. Ipil14. Maligaya15. Soyung16. Cabugao

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 48: CBLM LO1 LO2.docx

7. Villasis8. Mabini9. Batal10. Divisoria

17. San Fabian18. Castillo19. Victoria20. Apanay

2. Reading of an integer input must follow this format beyond the BufferedReader declaration of dataIn variable

<variable name> = <Datatype>.parse<shortened Datatype>(<BuffferedReader variable name>.readLine);

location = Integer.parseInt(dataIn.readLine);

3. Verify that the result is as following

Location: 4

Destination: 10

Location: Victory Norte

Destination: Divisoria

Distance: 6

Fare: Php 9.50

Location: 10

Destination: 4

Location: Divisoria

Destination: Victory Norte

Distance: 6

Fare: Php 9.50

Location: 1

Destination: 2

Location: Sinsayon

Destination: Apanay

Distance: 19

Fare: Php 16.00

Assessment Method:

Demonstration with questioning , Performance Criteria checklist

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 49: CBLM LO1 LO2.docx

PERFORMANCE CRITERIA CHECKLIST

JOB SHEET 4.1-3

4.1-3 Name:

Date

CRITERIA

Did you…

Response

YES NO

declare a minimum fare of P8.00 for the first 3 kilometers?

use integer value to identify location and destination?

write the program in such a way that the program can detect errors such as an input that is beyond 20?

declare the variables according to its use?

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 50: CBLM LO1 LO2.docx

WRITTEN TEST 4.1-3

Trainee’s Name:

Date:

QUESTION ANSWER

MULTIPLE CHOICE: Choose the letter of the correct answer then write your answer on the column for answers.

Java statements that check an expression then may or may not execute a statement or group of statements.

a. Conditional Statementb. Iterative Statementc. Begin Statementd. End Statement

This control statement executes the block of code if the comparison test is true.

a. if statementb. if-else statementc. if-else-if statementd. switch-case statement

This control statement executes either true or false statement depending on the result of the comparison test.

a. if statementb. if-else statementc. if-else-if statementd. switch-case statement

This control statement can compare at least two conditions and executes only one statement.

a. if statementb. if-else statementc. if-else-if statementd. switch-case statement

This control statement allows the program to choose among a series of actions based on the value of an expression.

a. if statementb. if-else statementc. if-else-if statementd. switch-case statement

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 51: CBLM LO1 LO2.docx

QUESTION ANSWER

TRUE OR FALSE: Examine the following statements. Write TRUE if the statement is true or write FALSE if the statement is wrong. Write your answer on the column for answers.

Programming constructs are different in every programming language

System requirements are different in every programming langauge

An if statement display a false statement.

Switch-case is a multiple-branch decision statement.

Nested if is sometimes referred to as “an if within an if”

QUESTION ANSWER

ESSAY: Answer the following questions to the best of your knowledge. Write your answer on the column for answers.

Define structured programming language.

Why do you think modular programming is called that way?

What is the systems and programming requirements and standards that you know?

Can you apply the Systems Analysis and Design steps as basis for systems and programming requirements?

What stage of Systems Analysis do you conduct requirements definition?

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 52: CBLM LO1 LO2.docx

Write an example of iterative statement syntax?

Write the syntax for a switch-case statement/expression used in sequence selection.

The trainee’s total score was:

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 53: CBLM LO1 LO2.docx

WRITTEN TEST 4.1-3 ANSWER KEY

QUESTION ANSWER

MULTIPLE CHOICE: Choose the letter of the correct answer then write your answer on the column for answers.

Java statements that check an expression then may or may not execute a statement or group of statements.

e. Conditional Statementf. Iterative Statementg. Begin Statementh. End Statement

a

This control statement executes the block of code if the comparison test is true.

e. if statementf. if-else statementg. if-else-if statementh. switch-case statement

a

This control statement executes either true or false statement depending on the result of the comparison test.

e. if statementf. if-else statementg. if-else-if statementh. switch-case statement

b

This control statement can compare at least two conditions and executes only one statement.

e. if statementf. if-else statementg. if-else-if statementh. switch-case statement

c

This control statement allows the program to choose among a series of actions based on the value of an expression.

e. if statementf. if-else statementg. if-else-if statementh. switch-case statement

d

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 54: CBLM LO1 LO2.docx

QUESTION ANSWER

TRUE OR FALSE: Examine the following statements. Write TRUE if the statement is true or write FALSE if the statement is wrong. Write your answer on the column for answers.

Programming constructs are different in every programming language

True

System requirements are different in every programming langauge False

True/False: Switch-case is a multiple-branch decision statement.

True

True/False: An if statement display a false statement. False

True/False: Nested if is sometimes referred to as “an if within an if” True

QUESTION ANSWER

ESSAY: Answer the following questions to the best of your knowledge. Write your answer on the column for answers.

Define structured programming language.

Structured programming is a programming style where parts

of a big program are divided into modules.

Why do you think modular programming is called that way?

Because programs are divided into different modules however

all connected into only one main function

What is the systems and programming requirements and standards that you know?

It follows the Systems Analysis and Design Stages

Can you apply the Systems Analysis and Design steps as basis for systems and programming requirements?

Yes

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 55: CBLM LO1 LO2.docx

What stage of Systems Analysis do you conduct requirements definition?

Analysis

Write the syntax for a switch-case statement/expression used in sequence selection.

initialization;

switch (condition)

{

case expression: statement;

case expression: statement;

default statement;

}

Write an example of iterative statement syntax?

for (initialization; condition; increment/decrement)

{

}

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 56: CBLM LO1 LO2.docx

Information Sheet 4.2-1

Topic: Algorithm

Objectives

At the end of the lesson, the student should be able to:

Use basic programming constructs algorithms based on the standard of Java Programming Language

Use flowchart

Lesson Proper:

The Program Development Life CycleProgrammers do not sit down and start writing code right away when trying to make a computer program. Instead, they follow an organized plan or methodology, that breaks the process into a series of tasks.

Here are the basic steps in trying to solve a problem on the computer:1. Problem Definition2. Problem Analysis3. Algorithm design and representation (Pseudocode or flowchart)4. Coding and debugging

In order to understand the basic steps in solving a problem on a computer, let us define a single problem that we will solve step-by-step as we discuss the problem solving methodologies in detail. The problem we will solve will be defined in the next section.

Problem DefinitionA programmer is usually given a task in the form of a problem. Before a program can be designed to solve a particular problem, the problem must be well and clearly defined first in terms of its input and output requirements.

A clearly defined problem is already half the solution. Computer programming requires us to define the problem first before we even try to create a solution.

Let us now define our example problem:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 57: CBLM LO1 LO2.docx

“Create a program that will determine the number of times a name occurs in a list.”

Problem AnalysisAfter the problem has been adequately defined, the simplest and yet the most efficient and effective approach to solve the problem must be formulated. Usually, this step involves breaking up the problem into smaller and simpler subproblems.

Example Problem:Determine the number of times a name occurs in a list

Input to the program:list of names, name to look for

Output of the program:the number of times the name occurs in a list

Algorithm design and representationOnce our problem is clearly defined, we can now set to finding a solution. In computer programming, it is normally required to express our solution in a step-by-step manner.

An Algorithm is a clear and unambiguous specification of the steps needed to solve a problem. It may be expressed in either Human language (English, Tagalog), through a graphical representation like a flowchart or through a pseudocode, which is a cross between human language and a programming language.

Now given the problem defined in the previous sections, how do we express our general solution in such a way that it is simple yet understandable?

Expressing our solution through Human language:1. Get the list of names2. Get the name to look for, let's call this the keyname3. Compare the keyname to each of the names in the list4. If the keyname is the same with a name in the list, add 1 to the count5. If all the names have been compared, output the result

Expressing our solution through a flowchart:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 58: CBLM LO1 LO2.docx

Flowcharting Symbols and their meaningsA flowchart is a design tool used to graphically represent the logic in a solution. Flowcharts typically do not display programming language commands. Rather, they state the concept in English or mathematical notation.

Here are some guidelines for commonly used symbols in creating flowcharts. You can use any symbols in creating your flowcharts, as long as you are consistent in using them.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 59: CBLM LO1 LO2.docx

Coding and DebuggingAfter constructing the algorithm, it is now possible to create the source code. Using the algorithm as basis, the source code can now be written using the chosen programming language.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 60: CBLM LO1 LO2.docx

Most of the time, after the programmer has written the program, the program isn't 100% working right away. The programmer has to add some fixes to the program in case of errors (also called bugs) that occurs in the program. This process of is called debugging.

There are two types of errors that a programmer will encounter along the way. The first one is compile-time error, and the other is runtime error.

Compile-Time Errors occur if there is a syntax error in the code. The compiler will detect the error and the program won't even compile. At this point, the programmer is unable to form an executable that a user can run until the error is fixed.

Forgetting a semi-colon at the end of a statement or misspelling a certain command, for example, is a compile-time error. It's something the compiler can detect as an error. Compilers aren't perfect and so can't catch all errors at compile time. This is especially true for logic errors such as infinite loops. This type of error is called runtime error.

For example, the actual syntax of the code looks okay. But when you follow the code's logic, the same piece of code keeps executing over and over again infinitely so that it loops. In such a case, compilers aren't really smart enough to catch all of these types of errors at compile-time, and therefore, the program compiles fine into an executable file.

However, and unfortunately, when the end-user runs the program, the program (or even their whole computer) freezes up due to an infinite loop. Other types of run-time errors are when an incorrect value is computed, the wrong thing happens, etc.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 61: CBLM LO1 LO2.docx

SELF – CHECK 4.2-1

Direction: Answer the following questions to the best of your knowledge.

Question Answer

Given the following set of tasks, create an algorithm (a flowchart) to accomplish the following tasks.

1. Baking Bread

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 62: CBLM LO1 LO2.docx

SELF – CHECK 4.2-1 Answer Key

Direction: Answer the following questions to the best of your knowledge.

Question Answer

Given the following set of tasks, create an algorithm (a flowchart) to accomplish the following tasks.

1. Baking Bread

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 63: CBLM LO1 LO2.docx

OPERATION SHEET 4.1-1

OPERATION TITLE

: Use basic programming constructs algorithms

PERFORMANCE OBJECTIVE

At the end of the lesson, the student should be able to:

Use basic programming constructs algorithms based on the standard of Java Programming Language

Use flowchart

SUPPLIES Reference Manual

EQUIPMENT : 1 complete computer set installed with Java SDK or Netbeans

PROCEDURE

Given the following set of tasks, create an algorithm (a flowchart) to accomplish the following tasks.

1. Get the average of three numbers

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 64: CBLM LO1 LO2.docx

PROCEDURAL CHECKLIST 4.2-1

Trainee’s Name:

Date

CRITERIASatisfactory Response

YES NO

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 65: CBLM LO1 LO2.docx

INFORMATION SHEET 4.2-2

Topic: Pseudo code

Objectives

At the end of the lesson, the student should be able to:

Use basic programming constructs algorithms based on the standard of Java Programming Language

Use pseudo code

Lesson Proper:

An Algorithm is a clear and unambiguous specification of the steps needed to solve a problem. It may be expressed in either Human language (English, Tagalog), through a graphical representation like a flowchart or through a pseudocode, which is a cross between human language and a programming language.

Now given the problem defined in the previous sections, how do we express our general solution in such a way that it is simple yet understandable?

Expressing our solution through Human language:1. Get the list of names2. Get the name to look for, let's call this the keyname3. Compare the keyname to each of the names in the list4. If the keyname is the same with a name in the list, add 1 to the count5. If all the names have been compared, output the result

This example shows how pseudocode is written as comments in the source file. Note that the double slashes are indented.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 66: CBLM LO1 LO2.docx

public boolean moveRobot (Robot aRobot) {     //IF robot has no obstacle in front THEN         // Call Move robot         // Add the move command to the command history         // RETURN true     //ELSE         // RETURN false without moving the robot     //END IF }

Example Java Implementation

source code statements are interleaved with pseudocode. comments that correspond exactly to source code are removed during coding.

public boolean moveRobot (Robot aRobot) {     //IF robot has no obstacle in front THEN     if (aRobot.isFrontClear())     {         // Call Move robot         aRobot.move();         // Add the move command to the command history         cmdHistory.add(RobotAction.MOVE);         return true;     }     else // don't move the robot     {         return false;     }//END IF }

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 67: CBLM LO1 LO2.docx

SELF – CHECK 4.2-2

Direction: Answer the following questions to the best of your knowledge.

Question Answer

Given the following set of tasks, create an algorithm (a pseudo code) to accomplish the following tasks.1. Baking Bread

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 68: CBLM LO1 LO2.docx

SELF – CHECK 4.2-2 Answer Key

Question Answer

Given the following set of tasks, create an algorithm (a pseudo code) to accomplish the following tasks.

1. Baking Bread

Pseudocode:prepare all ingredientspour all ingredients in mixing bowlwhile batter not smooth yetmix ingredientspour into bread panplace inside ovenwhile bread not yet donewaitremove from oven

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 69: CBLM LO1 LO2.docx

OPERATION SHEET 4.2-2

OPERATION TITLE

Pseudo Code

PERFORMANCE OBJECTIVE

Use basic programming constructs algorithms based on the standard of Java Programming Language

Use pseudo code

SUPPLIES Reference Manual

EQUIPMENT : 1 complete computer set installed with Java SDK or Netbeans

PROCEDUREGiven the following set of tasks, create an algorithm (a flowchart) to accomplish the following tasks.1. Get the average of three numbersPRECAUTIONS : Take note that Compilers are case sensitive. Do

not capitalize any command. String I/O and variable names are however accepted.

ASSESSMENT METHOD

Performance Check

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 70: CBLM LO1 LO2.docx

PROCEDURAL CHECKLIST 4.2-2

Trainee’s Name:

Date

CRITERIASatisfactory Response

YES NO

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 71: CBLM LO1 LO2.docx

INFORMATION SHEET 4.2-3

Topic: Arrays

Objectives

At the end of the lesson, the student should be able to:

• Declare and create arrays• Access array elements• Determine the number of elements in an array• Declare and create multidimensional arrays

Lesson Proper:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 72: CBLM LO1 LO2.docx

SELF – CHECK 4.2-3

Direction: Answer the following questions to the best of your knowledge.

Question Answer

4.

5.

6.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 73: CBLM LO1 LO2.docx

SELF – CHECK 4.2-1 Answer Key

Question Answer

4.

5.

6.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 74: CBLM LO1 LO2.docx

OPERATION SHEET 4.2-3

OPERATION TITLE

PERFORMANCE OBJECTIVE

SUPPLIES Reference Manual

EQUIPMENT : 1 complete computer set installed with Java SDK or Netbeans

PRECAUTIONS : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and variable names are however accepted.

ASSESSMENT METHOD

Performance Check

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 75: CBLM LO1 LO2.docx

PROCEDURAL CHECKLIST 4.2-3

Trainee’s Name:

Date

CRITERIASatisfactory Response

YES NO

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 76: CBLM LO1 LO2.docx

INFORMATION SHEET 4.2-4

Topic: Binary Files

Objectives

At the end of the lesson, the student should be able to:

Code and use standard sequential access algorithms for text and binary files

Lesson Proper:

Numerical data transfers faster and more compactly in a raw binary format than as text characters. Here we look at examples of writing numerical data to a binary file and reading numerical data from a binary file.

Data transfers faster and more compactly in binary than as text characters. Here we look at examples of writing numerical data to a binary file and reading numerical data from a file.

Writing to a Binary File

In the example program below called BinOutputFileApp, we first create some data arrays with some arbitrary values. We then open a stream to a file with the binary FileOutputStream class. We wrap this stream object with an instance of the DataOutputStream class, which contains many useful methods for writing primitive types of the writeX() form, where X indicates a primitive type.

We use the writeInt (int i) and the writeDouble (double d) methods, to write the data to the file as pairs of int/double type values. In the next subsection below, we will show next how to read the binary data from this file.

BinOutputFileApp.java Resources: numerical.dat

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 77: CBLM LO1 LO2.docx

import java.io.*;import java.util.*;

/**  Write a primitive type data array to a binary file.**/public class BinOutputFileApp{  public static void main (String arg[]) {    Random ran = new Random ();

    // Create an integer array and a double array.    int    [] i_data = new int[15];    double [] d_data = new double[15];    // and fill them    for  (int i=0; i < i_data.length; i++) {      i_data[i] = i;      d_data[i] = ran.nextDouble () * 10.0;    }

    File file = null;    // Get the output file name from the argument line.    if (arg.length > 0) file = new File (arg[0]);    // or use a default file name    if (file == null) {        System.out.println ("Default: numerical.dat");        file = new File ("numerical.dat");    }

    // Now write the data array to the file.    try {      // Create an output stream to the file.      FileOutputStream file_output = new FileOutputStream (file);      // Wrap the FileOutputStream with a DataOutputStream      DataOutputStream data_out = new DataOutputStream (file_output);

      // Write the data to the file in an integer/double pair      for (int i=0; i < i_data.length; i++) {          data_out.writeInt (i_data[i]);          data_out.writeDouble (d_data[i]);      }      // Close file when finished with it..      file_output.close ();    }    catch (IOException e) {       System.out.println ("IO exception = " + e );    }  } // main

} // class BinOutputFileApp

 

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 78: CBLM LO1 LO2.docx

Reading from a Binary File

In the example program BinInputFileApp, we read a binary file created by BinOutputFileApp discussed above. We begin by first opening a stream to the file with a FileInputStream object. Then we wrap this with a DataInputStream class to obtain the many readX() methods, where X represents the name of a primitive data type as in readInt() and readDouble(). The BinInputFileApp program reads pairs of integer and double values.

Rather than test for the return of a -1 value as we did in the text input streams, we simply continue to loop until the read method throws the EOFException. In the catch statement for this exception you can carry out the final housekeeping chores before closing the file stream.

BinInputFileApp.java

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 79: CBLM LO1 LO2.docx

import java.io.*;import java.util.*;

/**  Demonstrate reading primitive type values from a binary file. **/public class BinInputFileApp{  public static void main (String arg[]) {    File file = null;    int    i_data = 0;    double d_data = 0.0;

    // Get the file from the argument line.    if (arg.length > 0) file = new File (arg[0]);    if (file == null) {      System.out.println ("Default: numerical.dat");      file = new File ("numerical.dat");    }

    try {      // Wrap the FileInputStream with a DataInputStream      FileInputStream file_input = new FileInputStream (file);      DataInputStream data_in    = new DataInputStream (file_input );

      while (true) {        try {          i_data = data_in.readInt ();          d_data = data_in.readDouble ();        }        catch (EOFException eof) {          System.out.println ("End of File");          break;        }        // Print out the integer, double data pairs.        System.out.printf ("%3d. Data = %8.3e %n", i_data, d_data );      }      data_in.close ();    } catch  (IOException e) {       System.out.println ( "IO Exception =: " + e );    }  } // main} // class BinInputApp

We illustrate the output and input of binary data by first running BinOutputFileApp to produce the data file numerical.dat. We then run BinInputFileApp, which reads the file numerical.dat and produces the following output on the console.

Your output will vary since BinOutputFileApp uses the Random class to generate random values.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 80: CBLM LO1 LO2.docx

Example

Default: numerical.dat  0. Data = 2.633e+00  1. Data = 7.455e+00  2. Data = 2.447e+00  3. Data = 7.046e+00  4. Data = 2.652e+00  5. Data = 5.120e+00  6. Data = 1.754e+00  7. Data = 7.489e+00  8. Data = 7.386e-01  9. Data = 6.036e+00 10. Data = 7.002e-01 11. Data = 9.625e+00 12. Data = 5.966e+00 13. Data = 8.535e+00 14. Data = 2.744e+00End of File

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 81: CBLM LO1 LO2.docx

SELF – CHECK 4.2-4

Direction: Answer the following questions to the best of your knowledge.

Question Answer

7.

8.

9.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 82: CBLM LO1 LO2.docx

SELF – CHECK 4.2-4 Answer Key

Question Answer

7.

8.

9.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 83: CBLM LO1 LO2.docx

OPERATION SHEET 4.2-4

OPERATION TITLE

PERFORMANCE OBJECTIVE

SUPPLIES Reference Manual

EQUIPMENT : 1 complete computer set installed with Java SDK or Netbeans

PRECAUTIONS : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and variable names are however accepted.

ASSESSMENT METHOD

Performance Check

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 84: CBLM LO1 LO2.docx

PROCEDURAL CHECKLIST 4.2-4

Trainee’s Name:

Date

CRITERIASatisfactory Response

YES NO

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 85: CBLM LO1 LO2.docx

INFORMATION SHEET 4.2-5

Topic: Text File

Objectives

At the end of the lesson, the student should be able to:

Use of language facilities to access databases based on the standard of Java programming language

Lesson Proper:

A text file is a computer file that stores a typed document as a series of alphanumeric characters, usually without visual formatting information. The content may be a personal note or list, a journal or newspaper article, a book, or any other text that can be rendered accurately in typewritten form. Text files are similar to word processing files in that the content of both is primarily textual; they differ in that text files usually do not record information such as character style and size, pagination, or other details that would specify the appearance of a finished document. Some computer operating systems make a basic distinction between a text file, which is intended to be translated directly into human-readable text, and a binary file, which is interpreted directly by the computer.

In most of the schemes used for encoding text, each character is assigned a numeric value, with the text then written as a string of binary numbers. One family of encoding schemes, called the American Standard Code for Information Interchange (ASCII), became a widely-used standard early in the history of computing, despite its poor support for languages other than English. The ISO 8859 family of codes has provided much better support for languages based on the Latin alphabet and similar alphabets, but has been unable to encode the characters from East Asian languages like Japanese, leading to a proliferation of incompatible standards.

More recently, the Unicode® Consortium has been developing an encoding system called Unicode® that has the goal of assigning a unique number to every character used in every language on earth. This will allow a single code to be used for every language, and allow texts from multiple languages to appear in a single file. The first portion of Unicode is based on ISO 8859, which is itself based on ASCII. Using Unicode® can have advantages even in English-speaking countries, as text encoded using older schemes may display minor inconsistencies when moved from system to system.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 86: CBLM LO1 LO2.docx

Advantages of text files include small size and versatility. Kilobytes or megabytes smaller than the same data stored in other formats, they can be rapidly and massively exchanged via email or disk. Most can be opened on computers running diverse operating systems, using very basic software. The primary disadvantage is the lack of formatting. A text file may be a poor choice for representing a document that contains images or that relies on design elements to communicate its meaning — a file containing tabular data, mathematical formulas, or concrete poetry, for instance.

Text files are generally intended to be read and edited by humans, but not all of them contain content that is primarily for human consumption. Most programming code is stored in a text file prior to being compiled — that is, translated into a machine-readable binary file. Files may also contain machine-readable textual tags that give formatting information in addition to plain text. For instance, a Hypertext Markup Language (HTML) file can be opened as a plain text file in a text editor, or display as a formatted web page after being interpreted by a web browser. Similar schemes include LaTeX, used for laying out scientific papers, and Extensible Markup Language (XML), used for structuring data.

Following are sample programs that demonstrates the use of Text Files

Read the contents of a file and place them in a string object.

/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License.     */import java.io.File;import java.io.FileReader;

/**

 * *  @author <a href="mailto:[email protected]">Jason van Zyl</a> *  @author <a href="mailto:[email protected]">Daniel Rall</a>

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 87: CBLM LO1 LO2.docx

 *  @version $Id: StringUtils.java 685685 2008-08-13 21:43:27Z nbubna $ */public class Main {

  /**   * Read the contents of a file and place them in   * a string object.   *   * @param file path to file.   * @return String contents of the file.   */  public static String fileContentsToString(String file)  {      String contents = "";

      File f = null;      try      {          f = new File(file);

          if (f.exists())          {              FileReader fr = null;              try              {                  fr = new FileReader(f);                  char[] template = new char[(int) f.length()];                  fr.read(template);                  contents = new String(template);              }              catch (Exception e)              {                  e.printStackTrace();              }              finally              {                  if (fr != null)                  {                      fr.close();                  }              }          }      }      catch (Exception e)      {          e.printStackTrace();      }      return contents;  }}

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 88: CBLM LO1 LO2.docx

Dump a String to a text file with encoding.

/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at *  *      http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import java.io.File;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;

public class Main {

  /**   * Dump a <code>String</code> to a text file.   *   * @param file The output file   * @param string The string to be dumped   * @param encoding The encoding for the output file or null for default platform encoding   * @exception IOException IO Error

   */  public static void serializeString(File file, String string, String encoding)  throws IOException {      final Writer fw =              (encoding == null)?              new FileWriter(file):              new OutputStreamWriter(new FileOutputStream(file), encoding);      try {          fw.write(string);          fw.flush();      } finally {          fw.close();

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 89: CBLM LO1 LO2.docx

      }  }}

Load a text file contents as a String.

/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at *  *      http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import java.io.File;import java.io.FileReader;import java.io.IOException;

public class Main {

  /**   * Load a text file contents as a <code>String<code>.   * This method does not perform enconding conversions   *   * @param file The input file   * @return The file contents as a <code>String</code>   * @exception IOException IO Error   */  public static String deserializeString(File file)  throws IOException {      int len;      char[] chr = new char[4096];      final StringBuffer buffer = new StringBuffer();      final FileReader reader = new FileReader(file);      try {          while ((len = reader.read(chr)) > 0) {              buffer.append(chr, 0, len);          }

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 90: CBLM LO1 LO2.docx

      } finally {          reader.close();      }      return buffer.toString();  }

}

This short piece of code demonstrates how to write a text file in Java. The PrinterWriter class contains a number of methods for outputting text to a file. The FileWriter class is a convenience class for writing to a text file. It uses the default code page for the operating environment your virtual machine is running in. If you need to specify a specific code page, then you must use the OutputStreamWriter class instead.

1:/** Simple Program to write a text file 2:*/ 3: 4:import java.io.*; 5: 6:public class WriteText{ 7: public static void main(String[] args){ 8: try { 9: FileWriter outFile = new FileWriter(args[0]); 10: PrintWriter out = new PrintWriter(outFile); 11: 12: // Also could be written as follows on one line 13: // Printwriter out = new PrintWriter(new FileWriter(args[0])); 14: 15: // Write text to file 16: out.println("This is line 1"); 17: out.println("This is line 2"); 18: out.print("This is line3 part 1, "); 19: out.println("this is line 3 part 2"); 20: out.close(); 21: } catch (IOException e){ 22: e.printStackTrace(); 23: } 24: } 25:}

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 91: CBLM LO1 LO2.docx

SELF – CHECK 4.2-5

Direction: Answer the following questions to the best of your knowledge.

Question Answer

10.

11.

12.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 92: CBLM LO1 LO2.docx

SELF – CHECK 4.2-5 Answer Key

Question Answer

10.

11.

12.

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 93: CBLM LO1 LO2.docx

OPERATION SHEET 4.2-5

OPERATION TITLE

PERFORMANCE OBJECTIVE

SUPPLIES Reference Manual

EQUIPMENT : 1 complete computer set installed with Java SDK or Netbeans

PRECAUTIONS : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and variable names are however accepted.

ASSESSMENT METHOD

Performance Check

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 94: CBLM LO1 LO2.docx

PROCEDURAL CHECKLIST 4.2-5

Trainee’s Name:

Date

CRITERIASatisfactory Response

YES NO

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 95: CBLM LO1 LO2.docx

JOB SHEET 4.2-5

Title

Performance Objective

Supplies

Equipment

Steps/ Procedure:

Procedure in Bed Make Up

Assessment Method:

Demonstration with questioning , Performance Criteria checklist

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00

Page 96: CBLM LO1 LO2.docx

PERFORMANCE CRITERIA CHECKLIST

JOB SHEET 4.2-5

Name:

Date

CRITERIA

Did you…

Response

YES NO

The candidate’s underpinning knowledge was:

Satisfactory

Not Satisfactory

Trainer’s Signature: Date:

SICATQA

SYSTEMCOMPETENCY

BASED LEARNING MATERIAL IN

PROGRAMMING NCIV

Date Developed:

JUNE 4, 2011

Document No.

Issued by: Page

Developed by: Revision #

00