You are on page 1of 96

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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, dont 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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

LIST OF COMPETENCIES
NO 1 2 3 4 UNIT OF COMPETENCIES Design Program Logic Apply Program Development Approach Apply Object-Oriented Program Language Skills Apply Programming Skills in a Second Langauge MODULE TITLE Designing Program Logic Applying Program Development Approach Applying Object-Oriented Program Language Skills Applying Programming Skills in a Second Language CODE ICT313328 ICT313329 ICT313330 ICT313331

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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. LO2. LO3. LO4. LO5. Apply basic language syntax and layout Code using standard algorithms Debug code Document activities Test code

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

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)

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

LEARNING EXPERIENCES
Learning Outcome 1 Apply basic language syntax rules and layout Learning Activities Special Instructions 1. Read information sheet If you have some problem on the content 4.1-1 Semantics and of the information sheet dont hesitate to Syntax 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 selfcheck again. 3. Perform operation sheet Evaluate your work if is performed 4.1-1 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 Evaluate your work it is done correctly checklist 4.1-1 using procedural criteria checklist. If it is done properly, can move to the new information sheet. 5. Read information sheet If you have some problem on the content 4.1-2 Elements of of the information sheet dont hesitate to programming. 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 Evaluate your work if you it performs properly. If it is made appropriately you 4.1-2 can move to the next procedural sheet. If
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

8. Perform procedural checklist 4.1-2 9. Read information sheet 4.1-3 Program control structure

10. Answer self-check 4.1-3

not go over the operation sheet again. Evaluate your work it is done correctly using procedural criteria checklist. If it is made properly, can move to the new information sheet. If you have some problems on the content of the information sheet dont 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. 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. 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. 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.

11. Perform operation sheet 4.1-3 12. Perform the Written test 4.1-3

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 program We 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 screen System.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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 { or public 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.
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Issued by: Revision #


00

Page

Developed by:

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 Comments Comments 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, Cstyle multiline comments and special javadoc comments. C++-Style Comments C++ 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 Comments C-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 a C style or multiline comments */ Special Javadoc Comments Special 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 \n generating an html documentation. It uses tags like: @author Florence Balagtas @version 1.2
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

*/ Java Statements and blocks A 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 Identifiers Identifiers 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. Coding Guidelines:
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

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: ThisIsAnExampleOfClassName thisIsAnExampleOfMethodName 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 Keywords Keywords 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 Literals Literals 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 Literals Integer 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.
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

Floating-Point Literals Floating 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 Literals Boolean literals have only two values, true or false. Character Literals Character 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 Literals String literals represent multiple characters and are enclosed by double quotes. An example of a string literal is, Hello World.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.1-1


Direction: Answer the following questions to the best of your knowledge. Question Answer 1. 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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.1-1 Answer Key


Question 1. 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? Answer public class hello C++ Style uses // as one line comment C Style uses /** */ as a multi-line comment

Keywords are predefined identifiers reserved by Java for a specific 3. Differentiate keyword from literal. purpose. Literals are tokens that do not change or are constant.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

OPERATION SHEET 4.1-1


OPERATION TITLE PERFORMANCE OBJECTIVE : Apply basic language syntax and layout
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 EQUIPMENT PROCEDURE

Reference Manual : 1 complete computer set installed with Java SDK or Netbeans

My First Java Program public class Hello { /** * My first Java program */ public static void main( String[] args ){ //prints the string Hello world on screen System.out.println(Hello world); } } Using Text Editor and Console NOTE: This will be demonstrated by the teacher Environment used: Ubuntu Dapper For Windows Environment: Refer to Appendix B in your student Manual Step 1: Start the Text Editor To start the Text Editor in Linux, click on Menu-> Accessories-> Text Editor Step 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
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

Step 4: Save your Java Program Filename: Hello.java Folder name: MYJAVAPROGRAMS To 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 folder Step 5: Compiling your program Go to the Terminal window Go to the folder MYJAVAPROGRAMS where you saved the program To 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 Program To run your Java program, type in the command: java [filename without the extension] so in the case of our example, type in: java Hello You can see on the screen after running the program: "Hello world!" Syntax Errors Syntax errors are usually typing errors Common Syntax Errors: misspelled a command in Java forgot to write a semi-colon at the end of a statement Run-time Errors errors that will not display until you run or execute your program Even 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
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Issued by: Revision #


00

Page

Developed by:

Using NetBeans NOTE: This will be demonstrated by the teacher Environment used: Ubuntu Dapper For Windows Environment: Refer to Appendix B in your student Manual Step 1: Run NetBeans Two ways to run NetBeans: Through command-line using terminal By just clicking on the shortcut button found on the menu To 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 NetBeans Click on shortcut on the desktop Step 2: Make a project To make a project, click on File-> New Project After doing this, a New Project dialog will appear On the right pane of the project dialog, click on Java Application and click on the NEXT button A 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 doubleclick 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
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

Project If there are no errors in your program, you will see a build successful message on the output window Step 5: Run your program To run your program, click on Run-> Run Main Project The 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. Performance Check

ASSESSMENT METHOD

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PROCEDURAL CHECKLIST 4.1-1


4.1-3 Name: Date CRITERIA 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. Satisfactory Not Satisfactory Trainers Signature: Date: Satisfactory Response YES NO

The candidates underpinning knowledge was:

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 types The 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 - boolean A 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 char A character data type (char), represents a single Unicode character. It must have its literal 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 escape character \. 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 its literal enclosed in double quotes(). For example,
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

String message=Hello world! Integral byte, short, int & long Integral data types in Java uses three forms decimal, octal or hexadecimal. Examples are, 2 //The decimal value 2 077 //The leading 0 indicates an octal value 0xBACC //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 double Floating 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 value 2.718F //A simple float size value 123.4E+306D //A large double value with redundant D 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:
SICAT QA SYSTEM COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

Issued by: Revision #


00

Page

Developed by:

Variables A 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 Variables To 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 Data In 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; System.out.println( value ); System.out.println( The value of x= + x ); }
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

} The program will output the following text on screen, 10 The value of x=A System.out.println() vs. System.out.print() What is the difference between the commands System.out.println() and System.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, Hello world! 4.9.4 Reference Variables vs. Primitive Variables We 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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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. Operators In 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 operators Here are the basic arithmetic operators that can be used in creating your Java programs,

Increment and Decrement operators Aside 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,
SICAT QA SYSTEM COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

Issued by: Revision #


00

Page

Developed by:

count = count + 1; //increment the value of count by 1 is equivalent to, count++; Relational operators Relational operators compare two values and determines the relationship between those values. The output of evaluation are the boolean values true or false.

Logical operators Logical 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 x2 where 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 Tables X FALSE FALSE TRUE TRUE Y FALSE TRUE FALSE TRUE X &Y FALSE FALSE FALSE TRUE X|Y FALSE TRUE TRUE TRUE !X TRUE TRUE FALSE FALSE

Conditional Operator (?:)

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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:exp3 wherein 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 student status = (grade >= 60)?"Passed":"Fail"; //print status System.out.println( status ); } } The output of this program will be, Passed

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.1-2 Answer Key

Question 1. What is the importance of a data type? 2. Why do we have to use a variable in storing data? 3. Enumerate the different operators used in Java.

Answer It is used specify the amount of memory allocated for every stored data. This will maximize the use of memory space. Variables hold the value stored in the memory that can be used some time in other parts of the program. Arithmetic Logical Relational Increment/Decrement Conditional

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

OPERATION SHEET 4.1-2


OPERATION TITLE PERFORMANCE OBJECTIVE SUPPLIES EQUIPMENT Elements of Programming Develop a simple valid Java program using the concepts of primitive data types, variable types, identifiers and operators

Reference Manual : 1 complete computer set installed with Java SDK or Netbeans

Procedure Given 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 = 10 letter = a result = true str = 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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PROCEDURAL CHECKLIST 4.1-2

4.1-3 Name: Date CRITERIA 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. Satisfactory Not Satisfactory Trainers Signature: Date: Satisfactory Response YES NO

The candidates underpinning knowledge was:

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 Structures Decision control structures are Java statements that allows us to select and execute specific blocks of code while skipping other sections. if statement The 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; or if( boolean_expression ){ statement1; statement2; ... } where, boolean_expression is either a boolean expression or boolean variable.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

if-else statement The if-else statement is used when we want to execute a certain statement if a condition is true, and a different statement if the condition is false. The if-else statement has the form, if( boolean_expression ) statement; else statement; 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"); or int grade = 68; if( grade > 60 ){ System.out.println("Congratulations!"); System.out.println("You passed!"); } else{ System.out.println("Sorry you failed"); }

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

if-else-if statement The 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; else statement3; 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 statement Another 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 . . . //
SICAT QA SYSTEM COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

Issued by: Revision #


00

Page

Developed by:

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 Structures Repetition 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 loop The 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; statement2;
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

... } 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 loop while(true) System.out.println(hello); Example 3: //no loops // statement is not even executed while (false) System.out.println(hello); do-while loop The do-while loop is similar to the while-loop. The statements inside a dowhile 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{ statement1; statement2;
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

... }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 loop do{ 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 once do System.out.println(hello); while (false); This example will output hello on the screen.

for loop The for loop, like the previous loops, allows execution of the same code a number of times. The for loop has the form, for (InitializationExpression; LoopCondition; StepExpression){ statement1;
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

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 Statements Branching statements allows us to redirect the flow of program execution. Java offers three branching statements: break, continue and return. break statement The break statement has two forms: unlabeled (we saw its unlabeled form in the switch statement) and labeled. Unlabeled break statement The 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", "Nico", "Yza", "Gem", "Ethan"};
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.1-3


Direction: Answer the following questions to the best of your knowledge. Program Problem 1. 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.");}}}

Output

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

3. When do we use conditional statements?

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

4. When do we use repetition statements?

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.1-3 Answer Key


Question 1. 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.");}}}

Answer

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?

4. When do you use repetition statements?

Conditional statements are used when the program has to choose between two or more possible results based on the given condition. Repetition statements are used when 2 or more statements are performed repeatedly to minimize time in writing the codes.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

OPERATION SHEET 4.1-3


OPERATION TITLE PERFORMANCE OBJECTIVE Program Control Structure 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 Reference Manual

SUPPLIES EQUIPMENT PROCEDURE

: 1 complete computer set installed with Java SDK or Netbeans

Program 1 Step 1. Open your text editor Step 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 2 Step 1. Open your text editor Step 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
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Issued by: Revision #


00

Page

Developed by:

capitalize any command. String I/O and variable names are however accepted. ASSESSMENT METHOD Performance Check

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PROCEDURAL CHECKLIST 4.1-3


4.1-3 Name: Date CRITERIA 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 Satisfactory Not Satisfactory Trainers Signature: Date: Satisfactory Response YES NO

The candidates underpinning knowledge was:

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

JOB SHEET 4.1-3


Title Performance Objective Program Control Structure Use decision control structures (if, else, switch) which allows selection of specific sections of code to be executed Use repetition control structures (while, dowhile, for) which allow executing specific sections of code a number of times Reference Materials/Modules

Supplies Equipment Steps/ Procedure:

Computer sets with installed Java compiler or Netbeans

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. 2. 3. 4. 5. 6. 7. Sinsayon Dubinan West Dubinan East Victory Norte Centro East Malvar Villasis 11. 12. 13. 14. 15. 16. 17. Ramos East Quezon Ipil Maligaya Soyung Cabugao San Fabian
Document No.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Issued by: Revision #


00

Page

Developed by:

8. Mabini 9. Batal 10. Divisoria

18. 19. 20.

Castillo Victoria 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: Norte Destination: Divisoria Distance: 6 Fare: Php 9.50 Assessment Method: Demonstration with questioning , Performance Criteria checklist Location: 10 Destination: 4 Victory Location: Divisoria Location: 1 Destination: 2 Location: Sinsayon

Destination: Victory Destination: Apanay Norte Distance: 19 Distance: 6 Fare: Php 16.00 Fare: Php 9.50

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PERFORMANCE CRITERIA CHECKLIST JOB SHEET 4.1-3


4.1-3 Name: Date CRITERIA Did you 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? Satisfactory Not Satisfactory Trainers Signature: Date: Response YES NO

The candidates underpinning knowledge was:

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

WRITTEN TEST 4.1-3


Trainees 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 Statement b. Iterative Statement c. Begin Statement d. End Statement This control statement executes the block of code if the comparison test is true. a. if statement b. if-else statement c. if-else-if statement d. switch-case statement This control statement executes either true or false statement depending on the result of the comparison test. a. if statement b. if-else statement c. if-else-if statement d. switch-case statement This control statement can compare at least two conditions and executes only one statement. a. if statement b. if-else statement c. if-else-if statement d. 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 statement b. if-else statement c. if-else-if statement d. switch-case statement

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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?

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

Write an example of iterative statement syntax?

Write the syntax for a switchcase statement/expression used in sequence selection.

The trainees total score was: Trainers Signature: Date:

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 Statement f. Iterative Statement g. Begin Statement h. End Statement This control statement executes the block of code if the comparison test is true. e. if statement f. if-else statement g. if-else-if statement h. switch-case statement This control statement executes either true or false statement depending on the result of the comparison test. e. if statement f. if-else statement g. if-else-if statement h. switch-case statement This control statement can compare at least two conditions and executes only one statement. e. if statement f. if-else statement g. if-else-if statement h. switch-case statement This control statement allows the program to choose among a series of actions based on the value of an expression. e. if statement f. if-else statement g. if-else-if statement h. switch-case statement

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 True/False: Switch-case is a multiple-branch decision statement. True/False: An if statement display a false statement. True/False: Nested if is sometimes referred to as an if within an if QUESTION True False True False True 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. Because programs are divided into different modules however all connected into only one main function It follows the Systems Analysis and Design Stages Yes

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?
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

SICAT QA SYSTEM

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

What stage of Systems Analysis do you conduct requirements definition?

Analysis initialization; switch (condition) { case expression: statement; case expression: statement; default statement; } for (initialization; condition; increment/decrement) { }

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

Write an example of iterative statement syntax?

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 Cycle Programmers 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 Definition 2. Problem Analysis 3. 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 Definition A 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:
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Issued by: Revision #


00

Page

Developed by:

Create a program that will determine the number of times a name occurs in a list. Problem Analysis After 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 representation Once 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 names 2. Get the name to look for, let's call this the keyname 3. Compare the keyname to each of the names in the list 4. If the keyname is the same with a name in the list, add 1 to the count 5. If all the names have been compared, output the result Expressing our solution through a flowchart:
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Issued by: Revision #


00

Page

Developed by:

Flowcharting Symbols and their meanings A 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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

Coding and Debugging After 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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

OPERATION SHEET 4.1-1


OPERATION TITLE PERFORMANCE OBJECTIVE : Use basic programming constructs algorithms
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 EQUIPMENT PROCEDURE

Reference Manual : 1 complete computer set installed with Java SDK or Netbeans

Given the following set of tasks, create an algorithm (a flowchart) to accomplish the following tasks. 1. Get the average of three numbers

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PROCEDURAL CHECKLIST 4.2-1


Trainees Name: Date CRITERIA Satisfactory Response YES The candidates underpinning knowledge was: Satisfactory Not Satisfactory Trainers Signature: Date: NO

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 names 2. Get the name to look for, let's call this the keyname 3. Compare the keyname to each of the names in the list 4. If the keyname is the same with a name in the list, add 1 to the count 5. 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.
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

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 }

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.2-2 Answer Key


Question Answer
Pseudocode: prepare all ingredients pour all ingredients in mixing bowl while batter not smooth yet mix ingredients pour into bread pan place inside oven while bread not yet done wait remove from oven

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

OPERATION SHEET 4.2-2


OPERATION TITLE PERFORMANCE OBJECTIVE Pseudo Code Use basic programming constructs algorithms based on the standard of Java Programming Language Use pseudo code

SUPPLIES EQUIPMENT PROCEDURE

Reference Manual : 1 complete computer set installed with Java SDK or Netbeans

Given the following set of tasks, create an algorithm (a flowchart) to accomplish the following tasks. 1. Get the average of three numbers

PRECAUTIONS

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

ASSESSMENT METHOD

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PROCEDURAL CHECKLIST 4.2-2


Trainees Name: Date CRITERIA Satisfactory Response YES The candidates underpinning knowledge was: Satisfactory Not Satisfactory Trainers Signature: Date: NO

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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:

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.2-3


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

4.

5.

6.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.2-1 Answer Key


Question 4. 5. 6. Answer

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

OPERATION SHEET 4.2-3


OPERATION TITLE PERFORMANCE OBJECTIVE SUPPLIES EQUIPMENT

Reference Manual : 1 complete computer set installed with Java SDK or Netbeans : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and variable names are however accepted. Performance Check

PRECAUTIONS

ASSESSMENT METHOD

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PROCEDURAL CHECKLIST 4.2-3


Trainees Name: Date CRITERIA Satisfactory Response YES The candidates underpinning knowledge was: Satisfactory Not Satisfactory Trainers Signature: Date: NO

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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.
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Issued by: Revision #


00

Page

Developed by:

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK

4.2-4

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

7.

8.

9.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK
Question 7. 8. 9.

4.2-4 Answer Key


Answer

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

OPERATION SHEET 4.2-4 OPERATION TITLE PERFORMANCE OBJECTIVE SUPPLIES EQUIPMENT

Reference Manual : 1 complete computer set installed with Java SDK or Netbeans : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and variable names are however accepted. Performance Check

PRECAUTIONS

ASSESSMENT METHOD

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PROCEDURAL CHECKLIST 4.2-4


Trainees Name: Date CRITERIA Satisfactory Response YES The candidates underpinning knowledge was: Satisfactory Not Satisfactory Trainers Signature: Date: NO

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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 widelyused 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.
COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV
Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

Issued by: Revision #


00

Page

Developed by:

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:jvanzyl@apache.org">Jason van Zyl</a>

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

* @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @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; } } Date Developed: JUNE 4, 2011 Document No.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Issued by: Revision #


00

Page

Developed by:

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 p latform encoding * @exception IOException IO Error */ public static void serializeString(File file, String string, String encod ing) throws IOException { final Writer fw = (encoding == null)? new FileWriter(file): new OutputStreamWriter(new FileOutputStream(file), encoding); try { fw.write(string);

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

fw.flush(); } finally { fw.close(); } } }

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 {

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

while ((len = reader.read(chr)) > 0) { buffer.append(chr, 0, len); } } 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:}

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.2-5


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

10.

11.

12.

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

SELF CHECK 4.2-5 Answer Key


Question 10. 11. 12. Answer

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

OPERATION SHEET 4.2-5


OPERATION TITLE PERFORMANCE OBJECTIVE SUPPLIES EQUIPMENT

Reference Manual : 1 complete computer set installed with Java SDK or Netbeans : Take note that Compilers are case sensitive. Do not capitalize any command. String I/O and variable names are however accepted. Performance Check

PRECAUTIONS

ASSESSMENT METHOD

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PROCEDURAL CHECKLIST 4.2-5


Trainees Name: Date CRITERIA Satisfactory Response YES The candidates underpinning knowledge was: Satisfactory Not Satisfactory Trainers Signature: Date: NO

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

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

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

PERFORMANCE CRITERIA CHECKLIST JOB SHEET 4.2-5


Name: Date CRITERIA Did you The candidates underpinning knowledge was: Satisfactory Not Satisfactory Trainers Signature: Date: Response YES NO

SICAT QA SYSTEM

COMPETENCY BASED LEARNING MATERIAL IN PROGRAMMING NCIV

Date Developed: JUNE 4, 2011

Document No.

Issued by: Revision #


00

Page

Developed by:

You might also like