Professional Documents
Culture Documents
Sector :
INFORMATION AND COMMUNICATIONS TECHNOLOGY
Qualification :
Programming NC IV
LEARNING OUTCOMES: NC IV
LO1
LO2
3. Coded and used standard sequential access algorithms for text and
binary files
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
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)
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:
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.
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.
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.
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 */
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:
Date Document No.
COMPETENCY Developed:
BASED JUNE 4, 2011
SICAT
LEARNING Issued by: Page
QA
MATERIAL IN Developed by:
SYSTEM
PROGRAMMING
NCIV Revision #
00
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 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.
Date Document No.
COMPETENCY Developed:
BASED JUNE 4, 2011
SICAT
LEARNING Issued by: Page
QA
MATERIAL IN Developed by:
SYSTEM
PROGRAMMING
NCIV Revision #
00
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.
String Literals
String literals represent multiple characters and are enclosed by double
quotes. An example of a string literal is, Hello World.
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.
Question Answer
1. What is the first line of code in a
public class hello
simple Java program?
C++ Style uses // as one line
comment
2. What is the difference between
the C++ and the C Style
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.
PROCEDURE
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);
}
}
4.1-3 Name:
Date
Satisfactory
CRITERIA Response
YES NO
Did the student follow the proper indention and
coding spacing?
Hello World appeared on the screen observing
case format (Capital H and W).
No syntax error during runtime was observed.
The candidates underpinning knowledge was:
Satisfactory
Not Satisfactory
Trainers Signature: Date:
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,
Date Document No.
COMPETENCY Developed:
BASED JUNE 4, 2011
SICAT
LEARNING Issued by: Page
QA
MATERIAL IN Developed by:
SYSTEM
PROGRAMMING
NCIV Revision #
00
String message=Hello world!
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.
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,
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 Y X &Y X|Y !X
FALSE FALSE FALSE FALSE TRUE
FALSE TRUE FALSE TRUE TRUE
TRUE FALSE FALSE TRUE FALSE
TRUE TRUE TRUE TRUE FALSE
Question Answer
Question Answer
It is used specify the amount of
1. What is the importance of a data memory allocated for every stored
type? data. This will maximize the use of
memory space.
Variables hold the value stored in
2. Why do we have to use a variable
the memory that can be used some
in storing data?
time in other parts of the program.
Arithmetic
Logical
3. Enumerate the different
Relational
operators used in Java.
Increment/Decrement
Conditional
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.
ASSESSMENT
METHOD
Performance Check
4.1-3 Name:
Date
Satisfactory
CRITERIA Response
YES NO
Variables are named according to the given
format and case
The program displayed the values that are stored
in the variables
Declaration of variables are correct.
The candidates underpinning knowledge was:
Satisfactory
Not Satisfactory
Trainers Signature: Date:
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.
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
. . . //
Date Document No.
COMPETENCY Developed:
BASED JUNE 4, 2011
SICAT
LEARNING Issued by: Page
QA
MATERIAL IN Developed by:
SYSTEM
PROGRAMMING
NCIV Revision #
00
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.
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.
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;
Date Document No.
COMPETENCY Developed:
BASED JUNE 4, 2011
SICAT
LEARNING Issued by: Page
QA
MATERIAL IN Developed by:
SYSTEM
PROGRAMMING
NCIV Revision #
00
...
}
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.
do-while loop
The do-while loop is similar to the while-loop. The statements inside a do-
while loop are executed several times as long as the condition is satisfied.
The main difference between a while and do-while loop is that, the
statements inside a do-while loop are executed at least once. The do-while
statement has the form,
do{
statement1;
statement2;
Date Document No.
COMPETENCY Developed:
BASED JUNE 4, 2011
SICAT
LEARNING Issued by: Page
QA
MATERIAL IN Developed by:
SYSTEM
PROGRAMMING
NCIV Revision #
00
...
}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;
Date Document No.
COMPETENCY Developed:
BASED JUNE 4, 2011
SICAT
LEARNING Issued by: Page
QA
MATERIAL IN Developed by:
SYSTEM
PROGRAMMING
NCIV Revision #
00
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.
Question Answer
1. Write the following program then
draw the output on the Output
column:
PROCEDURE
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
4.1-3 Name:
Date
Satisfactory
CRITERIA Response
YES NO
The programs named variables according to its
use
Variables are classified using correct data types
Conditional statements were declared
appropriately
Repetition structure is used correctly
The candidates underpinning knowledge was:
Satisfactory
Not Satisfactory
Trainers Signature: Date:
Assessment Method:
Demonstration with questioning , Performance Criteria checklist
4.1-3 Name:
Date
CRITERIA Response
Did you
YES NO
declare a minimum fare of P8.00 for the first 3
kilometers?
use integer value to identify location and
destination?
write the program in such a way that the
program can detect errors such as an input that
is beyond 20?
declare the variables according to its use?
The candidates underpinning knowledge was:
Satisfactory
Not Satisfactory
Trainers Signature: 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
QUESTION ANSWER
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
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 a
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. b
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 c
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. d
e. if statement
f. if-else statement
g. if-else-if statement
h. switch-case statement
QUESTION ANSWER
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
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.
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
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?
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.
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.
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.
PROCEDURE
Trainees Name:
Date
Satisfactory
CRITERIA Response
YES NO
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?
This example shows how pseudocode is written as comments in the source file. Note that the
double slashes are indented.
Question Answer
Question Answer
Pseudocode:
prepare all ingredients
pour all ingredients in mixing bowl
Given the following set of tasks, create an while batter not smooth yet
algorithm (a pseudo code) to accomplish mix ingredients
the following tasks. pour into bread pan
1. Baking Bread place inside oven
while bread not yet done
wait
remove from oven
PROCEDURE
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.
Trainees Name:
Date
Satisfactory
CRITERIA Response
YES NO
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:
Question Answer
4.
5.
6.
Question Answer
4.
5.
6.
Trainees Name:
Date
Satisfactory
CRITERIA Response
YES NO
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.
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
} // class BinOutputFileApp
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
/** 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;
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.
Question Answer
7.
8.
9.
Question Answer
7.
8.
9.
Trainees Name:
Date
Satisfactory
CRITERIA Response
YES NO
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:
In most of the schemes used for encoding text, each character is assigned a numeric value,
with the text then written as a string of binary numbers. One family of encoding schemes,
called the American Standard Code for Information Interchange (ASCII), became a widely-
used standard early in the history of computing, despite its poor support for languages other
than English. The ISO 8859 family of codes has provided much better support for languages
based on the Latin alphabet and similar alphabets, but has been unable to encode the
characters from East Asian languages like Japanese, leading to a proliferation of incompatible
standards.
More recently, the Unicode Consortium has been developing an encoding system called
Unicode that has the goal of assigning a unique number to every character used in every
language on earth. This will allow a single code to be used for every language, and allow
texts from multiple languages to appear in a single file. The first portion of Unicode is based
on ISO 8859, which is itself based on ASCII. Using Unicode can have advantages even in
English-speaking countries, as text encoded using older schemes may display minor
inconsistencies when moved from system to system.
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
/*
* 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>
/**
* 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;
}
}
/*
* 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;
/**
* 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);
/*
* 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;
/**
* 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 {
Date Document No.
COMPETENCY Developed:
BASED JUNE 4, 2011
SICAT
LEARNING Issued by: Page
QA
MATERIAL IN Developed by:
SYSTEM
PROGRAMMING
NCIV Revision #
00
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:}
Question Answer
10.
11.
12.
Question Answer
10.
11.
12.
Trainees Name:
Date
Satisfactory
CRITERIA Response
YES NO
Title
Performance Objective
Supplies
Equipment
Steps/ Procedure:
Procedure in Bed Make Up
Assessment Method:
Demonstration with questioning , Performance Criteria checklist
Name:
Date
CRITERIA Response
Did you
YES NO