0% found this document useful (0 votes)
20 views66 pages

OOP1 UNIT2 PrimitiveStringsAndIO

This document discusses Unit 2 which covers primitive types, strings, and console I/O in Java. It will explain enough about the Java language to allow writing simple programs. It will focus on building familiarity with Java syntax while providing basic building blocks used throughout the course. The document includes a pre-test to assess existing knowledge of programming concepts before starting the lesson on primitive types and expressions. This lesson will differentiate Java's primitive and class data types, identify the characteristics of the main primitive types, and how to create programs using type conversions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views66 pages

OOP1 UNIT2 PrimitiveStringsAndIO

This document discusses Unit 2 which covers primitive types, strings, and console I/O in Java. It will explain enough about the Java language to allow writing simple programs. It will focus on building familiarity with Java syntax while providing basic building blocks used throughout the course. The document includes a pre-test to assess existing knowledge of programming concepts before starting the lesson on primitive types and expressions. This lesson will differentiate Java's primitive and class data types, identify the characteristics of the main primitive types, and how to create programs using type conversions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

UNIT 2: Primitive Types, Strings, and Console I/O

6
1
9

UNIT

2 PRIMITIVE TYPES,
STRINGS, AND
CONSOLE I/O

Wow! You’re one step ahead to become a


Programmer you are now in the second chapter
of the module.
In this chapter, we will explain enough about the
Java language that will allow you to write a simple
Java programs.
Since you have already passed the Programming
1 and 2 which is the C++ Programming language
and you are already awesome with that; it would
be much easier for you to understand this chapter
because most of the topics here are already
familiar to you.
Also, in the last chapter you have familiarized the
notions of class, objects, methods, and basics of
the Java Programming.
However, even if you are already well-equipped
with the concepts, you should learn the Java way
of expressing them.
We'll focus on building your comfort and familiarity
with the syntax of the language while giving you
the building blocks that you will use throughout
the rest of the course.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 55


UNIT 2: Primitive Types, Strings, and Console I/O

PRE-TEST FOR UNIT 2

WHAT DO YOU ALREADY KNOW?

Name: __________________________________ Date: ____________________


Course & Section: ________________________ Result: __________________
Can you recall the basics of programming concepts by answering this self-test
questions? Circle the letter of the BEST option that corresponds to your answer.

1. Which of the following may be used as variable names in Java? Choose all that
applies
a. rate1
b. 1stPlayer
c. myprogram.java
d. long
e. TimeLimit
f. numberOfWindows
2. Can a Java have two different variables with the terms aVariable and avariable?
a. aVariable only
b. Only avariable
c. Both avariable and aVariable
d. None of them
3. Choose the correct declaration for a variable called the count of type int. The
variable must be initialized to zero in the statement.
a. Int count = ‘0’;
b. Int count = 0;
c. int count = 0;
d. int count = ‘0’;
4. Which of the declaration for two variables of type double is correct? The variables are
to be termed rate and work. Both variables must be initialized to zero.
a. double rate = ‘0’; double work =0;
b. double rate = 0.0, work = ‘0.0’;
c. double rate = 0.0; double work =’0.0’;
d. double rate = 0.0, work = 0.0;

IT 203 OBJECT-ORIENTED PROGRAMMING 1 56


UNIT 2: Primitive Types, Strings, and Console I/O

5. Choose the correct assignment statement that will set the value of the variable
interest to the value of the variable balance multiplied by 0.05. Choose all that
is legal.
a. int interest = balance * 0.05;
b. double interest = balance * 0.05;
c. int interest = 0.05 * balance;
d. double interest = 0.05 * balance;
6. Which of the following assignment statement that will increase the value of the
variable count by 3 is correct? The variable is an int type.
a. int count = count * 3;
b. int count = +3;
c. int count +=3;
d. int count = count + 3;
7. What is the output produced by the following line of program code?
char a, b;
a = ‘b’;
b = ‘c’;
a = b;
System.out.println(a);
System.out.println(b);
System.out.println(a);
a. a
b
a
b. aba
c. b
c
b
d. bcb
e. c
c
c
f. ccc

IT 203 OBJECT-ORIENTED PROGRAMMING 1 57


UNIT 2: Primitive Types, Strings, and Console I/O

8. What is the output produced by the following codes?


int result = 10;
result *=3;
System.out.println(“result is “+ result);
a. 13 is 13
b. result is 13
c. 30 is 30
d. result is 30
9. What is the output produced by the following lines of the program code?
int div, mod;
div = 7/3;
mod = 7%3;
System.out.print(div);
System.out.print(mod);
a. 2.33
2
b. 2.332
c. 2
1
d. 21
10. What is the output produced by the following lines of the program code?
double result;
result = 1/2 * 2;
System.out.prinln(“1/2 * 2 equals ”+ result);
a. 0.25 equals 0.25
b. 1/2 * 2 equals 0.25
c. 1/2 * 2 equals 1
d. 1 equals 1
11. What is the output produced by the following lines of the program code?
int n = 2;
n++;
System.out.prinln(n);
n--;
System.out.prinln(n);
a. 3

IT 203 OBJECT-ORIENTED PROGRAMMING 1 58


UNIT 2: Primitive Types, Strings, and Console I/O

1
b. 3 1
c. 3
2
d. 3 2
12. Which of the following elements considered NOT required in a variable
declaration?
a. A type
b. An identifier
c. An assigned value
d. A semicolon
13. What is the size of the given String x = “new”;?
a. 0
b. 2
c. 1
d. 3
14. What is the result of 3 * 2.0?
a. 6
b. 6.0
c. 1
d. Error
15. An escape sequence always begins’ with a(n) __________.
a. ‘e’
b. Forward slash
c. Backslash
d. Equal sign

IT 203 OBJECT-ORIENTED PROGRAMMING 1 59


UNIT 2: Primitive Types, Strings, and Console I/O

LESSON 1:
PRIMITIVE TYPES AND EXPRESSIONS

OBJECTIVES:
At the end of this lesson, students will be able to:

▪ Differentiate and familiarize with the Java Primitive data types


versus Class type.

▪ Identify the characteristics and functions of different data types


available in Java language.

▪ Recall the rules in naming identifiers, the use of variable


declarations, escape sequence, and constants.

▪ Create simple programs implementing numeric type conversion


using type-casting.

Time Duration: 2.5 hours

IT 203 OBJECT-ORIENTED PROGRAMMING 1 60


UNIT 2: Primitive Types, Strings, and Console I/O

LET’S CONTINUE THE CODING JOURNEY

Simple Java Program Photo lifted from


https://wallpapersafari.com/w/3aVfim

So far, the only data that the program has used are Strings of characters
contained within double quotes, like “Hello, world!”. Computers process many different
types of data: numbers, pictures, sound, etc. Java is very strict about defining what
kind of data it is using at all times.

Java defines a few straightforward and efficient primitive data types. There
are eight of primitive types in total, but we’re going to focus on some of them.

Data Types in Java

• Class Type/Non-Primitive Type - a type for objects with both data and
methods. It begins with an uppercase letter.
Example: String
String class handles String, which is a sequence of zero or more
characters enclosed in double quotation marks. This class also contains various
operations that could be used to manipulate strings.
• Primitive type – its values are simple, indecomposable values, such as a single
letter or an available number. They are always passed by value when they are
parameters in Java and copied during assignment statements. It begins with a
lowercase letter. These data types also serve as the building blocks for more
complex data types, called reference types (Farrell J. , 1999).
Example: int, double, char, float

Primitive Types
They are predefined by the language and are named by reserved keywords.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 61


UNIT 2: Primitive Types, Strings, and Console I/O

Table 2.1 Java Primitive Data Types


Bytes
Data type Values Examples Size Range (Min to Max)
Used
1. boolean true or false 1 bit true, false not applicable
2. char single character 2 'A', '1', 'z', '%' all Unicode characters
such as letters,
symbols, and
spaces
3. byte integer 1 80, 127 -128 to 127
4. short integer 2 17, 3276 -32,768 to 32,767
5. int integer/whole 4 422, -13, 0 -2,147,483,648 to 2,147,483,647
numbers that
are not
fractions nor
have decimals
6. long integer 8 100000L, -9,223,372,036,854,775,808 to
-200000L 9,223,372,036,854,775,807
7. float floating-point 4 1.2f, 1.23e2f ± 3.40282347 x 10+38 to
number ± 1.40239846 x 10-45
8. double floating-point, 8 -23.1, 14.56, ± 1.76769313486231570 x 10+308
the number can 9.4e3 to
also write in the ± 4.94065645841246544 x 10-324
form of
scientific
notation.

Identifiers
Identifiers are the technical terms for a name in a programming language. It
includes the name of a variable, name of a class, a method, or an object.

Rules for naming Java Identifiers:


1. Identifiers may contain letters, digits, underscore (_), or a dollar sign ($).
2. Identifiers may not begin with a digit.
3. Identifiers cannot contain punctuation marks, math symbols, or other special
symbols.
4. The length of the name has no limit.
5. Words with predefined meanings cannot be used as identifiers.
6. Java is case-sensitive. Therefore, uppercase and lowercase letters are
considered to be different characters.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 62


UNIT 2: Primitive Types, Strings, and Console I/O

Table 2.2 Sample of Valid and Invalid Identifiers in Java

Valid Identifiers Invalid Identifiers


SampleClass String
sampleVariable 1stVariable
student_grades firstProgram!
SalaryIn$ My Java_Class
_grandTotal ?unknown_number

The common practice in naming classes is to start it with an uppercase letter, while
variables, objects, and methods usually begin with a lowercase. These names
generally spelled using only letters and digits.

Keywords
These words have a special predefined meaning (reserved keywords) and
cannot use as the names of classes or objects or anything else. Example: public, class,
static, void, String, int, and others exclusively Java language used for unique
purposes.

Variables
They are used to store data such as numbers and letters. They can be thought
of as data containers. The numbers, letters, or other data items in a variable is called
its value. This value is volatile, and it can be changed. You can think of a variable as
a named box (or cell) in memory that holds a value that the program can use or change
and refer to by name.

Variable Declaration
It consists of a data type name, followed by a list of variable names separated
by commas, an optional assigned value if the variable needs to contain an initial value.
The declaration usually terminates with a semicolon.

Syntax:
type variable1, variable2, . . ..;

IT 203 OBJECT-ORIENTED PROGRAMMING 1 63


UNIT 2: Primitive Types, Strings, and Console I/O

Examples:
int num1, num2;
char gender;
double grossIncome, netIncome;
String studentName, instructorName;

Assignment Statements
Use to give a value for the variable name or to change its value. The equal sign
(=) use as the assignment operator for assigning a value. From the right of the equals
sign sets the value for variable on the left of the equal sign (Farrell, 2012). Again, the
expression must be terminated with a semicolon.
Syntax:
variable = expression;
Examples:
num1 = 143; num2 = 341;
gender = ‘M’;
grossIncome = basicpay + overtime;
netIncome = grossIncome - deductions;
instructorName = “Ivy”
studentName = “Digna”;
status = true;

Declaring the variable generates the space in memory for value; to store a
variable in that space, you use an “assignment statement” associated with the given
value to the named variable.

Figure 2.1 Sample Java Program using Assignment Operator.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 64


UNIT 2: Primitive Types, Strings, and Console I/O

You can only declare a variable once. If you try to use it a second time, Java
will report it as an error. It also means you can only use the name of a variable once
within a single scope.

Scope
Any variable you declare between the curly braces of a method is called a local
variable because you can only use it locally inside the method. If you try to use it
outside the method, Java will report an error, “cannot find a symbol.” In over-all, we
say that a variable’s scope is the places in your code where it is “visible,” the lines of
code where it can be used.

You can, however, declare two different variables that use the same name in
two different methods! Consider this code:

public class Song {


public static void main (String[] args) {
String line = "This is the chorus";
System.out.println(line);
verse();
System.out.println(line);
}

public static void verse() {


String line = "This is my verse";
System.out.println(line);
}
}

This program has two variables named “line,” but one is local to the verse method and
can only be used there, and the other is local to the main method, and can only be
used there. So, the program prints:
This is the chorus
This is my verse
This is the chorus

IT 203 OBJECT-ORIENTED PROGRAMMING 1 65


UNIT 2: Primitive Types, Strings, and Console I/O

Sample Program:
The code below prints all the primitive types and shows how to name variables
and use assignment operators.

Figure 2. 2 The Primitive Data Types in Java.

Take note of the declarations of double data types used with and without the
suffix “F” and analyze the difference in their outputs. Various char declarations within
the program are also worth emphasizing. Take note on the first declaration (charOne)
is used to equate the ASCII equivalent of character 65 (not enclosed in a single quote)
which equivalent to capital letter ‘A.’ Whereas, the second declaration perhaps the
most familiar to you, equate a single character (‘a’) to the variable charTwo. Finally,
the third declaration (charUni) is used to correlate the Unicode character expressed
in hexadecimal form. (The ASCII code is the first 128 characters of the Unicode
Character Set.)

Figure 2. 3 Sample Output using Primitive Data Types in


Java.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 66


UNIT 2: Primitive Types, Strings, and Console I/O

Escapse Sequences
What if you want to create a String that contains a double quote character?
Tricky! If you wrote”” “, Java would be confused. The computer can’t tell if” ““ is an
empty String followed by a double quote, or a String consisting of a double quote
character. Java includes a way for you to clarify this ambiguity with what is called an
“escape sequence.” When Java sees a backslash in a String, this tells Java to
“escape” or skip the next character’s function and simply add it to the String. Here are
the escape sequences we’ll use:

Table 2.3 Java Escape Characters.

Escape
Description Example String as printed
Character
\n New line "\nline 1\nline 2"
line 1
line 2
\r Carriage return "Ryan\rRagos" Ragos
\b Backspace "Ryan\bRagos" RyaRagos
\t Tab "Ryan\tRagos" Ryan Ragos
\\ Displays a backslash "Use \\, not /" Use \, not /
\’ Displays a single quote “\'Ryan Ragos\’ “ ‘Ryan Ragos’
\” Displays a double quote “John \” JJ\” Doe” John “JJ” Doe

Constant
Data is constant when it cannot be changed after a program is compiled.
These are also used to store data like variables, but their values do not change.

Examples:
System.out.println(459);
‘B’ ‘S’ ‘ru’
12 56 12.28
“cat” “dog” “parrot”
true false

IT 203 OBJECT-ORIENTED PROGRAMMING 1 67


UNIT 2: Primitive Types, Strings, and Console I/O

Type Casting
In Java, a type-cast involves changing the data type of a value from its original
data type to some other data type. For example, changing the data type of 2.0 from
double to int because you cannot assign a variable with a broader range to a variable
with the least size unless you convert the variable with a broader scope to least range
as shown below in the examples.
Least range Widest range

byte int float

Examples.
1. You cannot put an int value like 42 in a variable of type char.
char digit;
int number;
number = 42;
digit = number;

Figure 2.4 Sample Error of Swapping Values from int to char Data Type.

2. You cannot put a double value like 3.5 in a variable of type int.
int whole;
double fraction;
fraction = 3.5;
whole = fraction;

Figure 2.5 Sample Error of Swapping Values from int to double Data Type.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 68


UNIT 2: Primitive Types, Strings, and Console I/O

3. You cannot even put the double value 3.0 in a variable of type int.
int whole;
double fraction;
fraction = 3.0;
whole = fraction;

Figure 2.6 Another Sample Error of Swapping Values from int to


double Data Type.

Java lets you explicitly change data from type to another or “cast” the data to a
different data type. You do this by expressly calling out what you want your data type
to be after evaluation:
(resulting data type) expression;
The most common use is to cast a double into an integer for rounding the result
of an integer by integer division instead of truncating it:

Table 2.4 Sample Type Casting.

Expression Value Comment


10/4 2 a more accurate arithmetic result is 2.5, but as both
numbers are integers the outcome is an int, and the
decimal is truncated
10/4.0 2.5 the result is a double, so decimal is included
(int)(10/4.0) 2 takes a double result of 2.5 and turns it into an int by
dropping the decimal
(int)10/4.0 2.5 Without the parenthesis, the number 10 is cast to an int,
even though it already is. The result is the int 10 / 4.0 who
results is 2.5

As the last expression shows, casting has higher precedence than any other
operator (except parentheses, of course), and only cast the value immediately to its
right.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 69


UNIT 2: Primitive Types, Strings, and Console I/O

You can also cast a data type int to a double, or accomplish the same thing by
combining the types:

Table 2.5 Sample Type Casting Using double Data Type.

Expression Value Comment


(double)10 10.0 cast int to double

10*1.0 10.0 combine int with double

The code below declares two variables named guess and answer of type
double and int respectively and assigns a value of 123.456 to the variable guess. By
using type-casting, the value of the variable guess is stored in the variable answer.

Figure 2.7 Sample Program Using Type Casting.

Figure 2.8 Sample Output using Type Cast.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 70


UNIT 2: Primitive Types, Strings, and Console I/O

You can also cast a char to int or get the numeric value of a char, for example:
int intChar = 'a';
System.out.println(intChar);
The output would be the ASCII value of character a which is 97.
char c='1';
int a=Character.getNumericValue(c);
System.out.println(a);
To Convert the data type char to int using character.getNumericValue(char)
method will return the integer value of a character; the output will be 1.

To convert the boolean to an integer value, let us now first declare a boolean value.
boolean value = true;
Now, to convert it to an integer, let us now take an integer variable and return a
value “1” for “true” and “0” for “false.”
int intBool = (bool) ? 1 : 0;
If the value of the boolean expression is true, it will return “1”, otherwise “0” for false.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 71


UNIT 2: Primitive Types, Strings, and Console I/O

APPLICATION ACTIVITY FOR LESSON 1

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?

Name: __________________________________ Date: ___________________


Course & Section: ________________________ Result: __________________

Try this Activity! I know you can do IT.


1. Write a program that determines the change to be dispensed from a vending
machine. An item in the machine can cost between 1 peso to 100-peso bill, and
assume that the machine accepts only a single bill worth 100 peso to pay for
the item. For example, see Figure below and name it VendingMachine.java.
This activity will be graded based on the rubric given.

Sample Output for Vending Machine Activity.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 72


UNIT 2: Primitive Types, Strings, and Console I/O

APPLICATION ACTIVITY FOR LESSON 1

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

Try this Activity! I know you can do IT.

2. Write a program that contains variables that holds the hourly rate and number
of hours worked for an employee who has the weekly salary for 250 an hour,
works 40 regular hours, and earns time and one-half (wage * 1.5) for overtime
hours worked. Display the gross pay, withholding tax, which is 15 percent of the
gross pay, and the net pay (gross pay – withholding). Save the program as
Payroll.java. For example, see the Figure below and it will be graded based on
the rubric given.

Sample Output for Payroll Activity.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 73


UNIT 2: Primitive Types, Strings, and Console I/O

HOW DO YOU EXTEND YOUR


LEARNING?
ASSIGNMENT #1

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Learning Never Stop, Let's Quiz IT!


❖ Simulate and trace the given program below.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = "Ryan M. Ragos", course="BSIT",
yearlevel="Second Year";
char a,b;
a='b';
b='c';
System.out.println("The following will be the output of
the code:");
a=b;
System.out.println("The character of variable a is: "+a);
System.out.println("\nEnter your name: "+name);
System.out.println("Enter you course: "+course);
System.out.println("Enter your yr level: "+yearlevel);
System.out.println("\nData Gathered!");
System.out.println("You are\t\'"+name+"\',,\b\nCurrently
\r"+yearlevel+" level taking \""+course+"\".");
}

Write Your Answer Here:

IT 203 OBJECT-ORIENTED PROGRAMMING 1 74


UNIT 2: Primitive Types, Strings, and Console I/O

LESSON 2:
OPERATORS

OBJECTIVES:
At the end of this lesson, students will be able to:

▪ Categorize the different operators commonly used in developing


Java applications.

▪ Learn and recall the order of precedence rules in evaluating


program statements and expressions.

▪ Write and solve problems involving arithmetic/mathematical,


relational, and logical operators.

Time Duration: 2.5 hours


IT 203 OBJECT-ORIENTED PROGRAMMING 1 75
UNIT 2: Primitive Types, Strings, and Console I/O

Operators
One of the best features of a computer is its ability to perform calculations, and
in order to execute calculations or manipulations in integral and floating-point data,
operators, i.e., arithmetic operators are used. The operator causes the compiler to
perform specific mathematical or logical manipulations or operations on one, two, or
three operands, and then return a result. All operators except for the assignment
operators are evaluated from left to right; assignment operators are evaluated right to
the left.

Unary Operator

It is an operator that has only one argument (one thing that it applies to), like
the negative operator ( - ) in the assignment statement:

bankBalance = -cost;

Binary Operator

It is an operator that has two arguments, like the + and * in the following
example:
total = cost + ( tax * discount );

Types of Operators
✓ Assignment - you can combine the simple assignment operator (=) with an
arithmetic operator such as + to produce a kind of specialized assignment
operator or special-purpose assignment operator.

Table 2.6 Assignment Operators and their use.


Operator Type Example Result
x = 5;
+= Addition 10
x += 5;
x = 5;
-= Subtraction 0
x -= 5;
x = 5;
*= Multiplication 25
x *= 5;
x = 5;
/= Division 1
x /= 5;
x = 5;
%= Modulus 0
x %= 5;

IT 203 OBJECT-ORIENTED PROGRAMMING 1 76


UNIT 2: Primitive Types, Strings, and Console I/O

Assignment Compatibilities
As mentioned in the previous lesson, trying to put a value of one type into a
variable of another kind of data type is like trying to put a square peg in a round table.
You cannot place an int value like 17 in a variable of type char. You cannot even put
the double 4.0 in a variable of type int. You cannot store a value of a single data type
in a variable of a different type unless the value is somehow converted to match the
data type of the variable. However, when dealing with numbers, this conversion will
sometimes (but not always) be performed automatically for you.

The conversion will always be done when you assign the value of an integer data type
to a variable of floating-point types, such as:

double doubleNum = 7;

or

int intNum = 7;

double doubleNum;

doubleNum = intNum;

Again, if you want to assign a value type double to a variable type int or vice versa,
you must change the type of the value using type-cast, as we explain in the previous
lesson.

• Arithmetic - in Java, you can perform arithmetic expressions involving addition


(+), subtraction (-), multiplication (*), and division (/) is the same way that you
would from them in ordinary arithmetic or algebra. You can combine variables
or numbers by using arithmetic operators.

Table 2.7 Arithmetic Operators and It’s Use.

Operator Description Example Result

x = 2;
+ Addition 4
Result = x + 2
x = 16
- Subtraction 10
Result = x - 6
x=4
* Multiplication 12
Result = x * 3
x = 25;
/ Division 5
Result = x / 5;
x = 10;
% Modulus 0
Result = x % 2;
x = 6;
x++ Post increment 7
Result = x++;
x = 12;
x-- Post decrement 11
Result = x--;

IT 203 OBJECT-ORIENTED PROGRAMMING 1 77


UNIT 2: Primitive Types, Strings, and Console I/O

x=1
++x Pre-increment 2
Result = ++x;
x=1
--x Pre-decrement 0
Result = --x;

Note: We can’t divide any whole numbers to zero (0), and when you divide floating-
point numbers to zero, it will just display an Infinity. Also, this division operator (/)
deserves special attention because the type of result can affect the value produced
dramatically.

For example,

System.out.println(9.0/2);

It has one operand type of double and integer. Hence, the result is always the type
(double) number 4.5; it doesn’t matter which comes first. However, when both
operands are of an integer type, the result is (always integer) 4, not 4.5. The fraction
after the decimal point is simply lost. Be sure to notice that when you divide two
integers, the result is not rounded; the section after the decimal point is discarded
or truncated, no matter how large it is.

If you put this into a variable for example:

double division = 9.0/2;

System.out.println(division);

The result is 4.5 because we divide first the 9.0/2 before we assigned the value to the
division variable, but if the data type is an integer:

int division = 9.0/2;

System.out.println(division);

The result is an error: incompatible types: possible lossy conversion from double to int
because when you divide the 9.0/2, the answer is in a double type were in, you cannot
be assigned it to an integer type unless you performed the type-cast, but again if you
use an operator with one int and one double, the result is always a double, and it
doesn’t matter which comes first.

Boolean Expressions
• Relational - sometimes called a comparison operator, it merely compares
two items; an expression containing a comparison operator has a Boolean
value either true or false.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 78


UNIT 2: Primitive Types, Strings, and Console I/O

Table 2.8 Relational Operators and It’s Use.

Operator Description Example Result

== is equal to 5 == 7 false
!= is not equal to 1! = 10 true
< is less than 5<12 true
> is greater than 5<12 false
<= is less than equal to 12<=12 true
>= is greater than equal to 12>=15 false

NOTE: When you use any of the operators that have two symbols (==,<=,>=, or !=),
you cannot place any whitespace between the two characters.

• Logical - is a boolean expression that is simply an expression that is either true


or false.

Table 2.9 Logical Operators and It’s Use.

Operator Description Example Result

x=4;
! Not true
! (x>=10)
x = 16; y=10
&& And false
(x<12 && y>7)
x = 4; y=18;
|| Or true
(x<=12 || y>12)

Using !, &&, and || you can form a more extensive boolean expression out of two
smaller boolean terms.

• The symbol ! means “not.” Use the NOT operator to negate the result of any
boolean expressions. Any expression that evaluates true becomes false when
preceded by the NOT operator.

• The symbol && means “and.” You can use the AND operator within a boolean
expression to determine whether two expressions are both true.

• The symbol || means “or.” Use the OR operator when you need some action
to occur, even if only one of the two conditions is true.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 79


UNIT 2: Primitive Types, Strings, and Console I/O

Evaluating Expressions
The table below shows the precedence rules for arithmetic, specialized,
relational, and logical operators when all the operators are given in different
expressions.

Table 2.10 Precedence Rule.

Highest Precedence
+, -, ++, -- Unary +, Unary -, Increment, Decrement
*, /, % Multiplication, Division, Modulus
+, - Binary Addition, Subtraction
<, >, <=, >= Binary Relational Operators
==, != Binary Equality Operators
! Logical NOT
&& Logical AND
|| Logical OR
=, *=, /=, %=, +=, -= Assignment Operators
Lowest Precedence

Examples:
x=-3; y=1; z=8; a=8; b=4; c=-2; d=-3; e=12

1. (x + 2) != 1 && y >= -2
(-3 + 2) != 1 && 1 >= -2
-1 != 1 && 1 >= -2
true && true
true

2. (y – 2) == 2 || 8 == x && (y + 2) == 1
(1 – 2) == 2 || 8 == -3 && (1 + 2) == 1
-1 == 2 || 8 == -3 && 3 == 1
false || false && false
false || false
false

3. ! (x >= 10) && y + 2/2 < 15 || x <= 0


! (-3 >= 10) && 1 + 2/2 < 15 || -3 <= 0
! (-3 >= 10) && 1 + 1 < 15 || -3 <= 0
! (-3 >= 10) && 2 < 15 || -3 <= 0
! true && true || true
false && true || true
false || true
true

IT 203 OBJECT-ORIENTED PROGRAMMING 1 80


UNIT 2: Primitive Types, Strings, and Console I/O

4. (a + b) * d/2 + 6 * c
(8 + 4) * -3/2 + 6 * -2
(12) * -3/2 + (-12)
-36/2 -12
-18 -12
-30

5. 6 + c * a/b – e (a + 2)
6 + (-2) * 8/4 – 12 (8 + 2)
6 – 16/4 – 12 (10)
6 – 4 – 120
2 – 120
-118

6. -8 * b%2 + 4 – (b + c)
-8 * 4%2 + 4 – (4 + (-2))
-32%2 + 4 – 2
0 + 4 – 2
4 – 2
2

Sample Program 2.1:

Figure 2.9 The Use of Different Operators in Java.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 81


UNIT 2: Primitive Types, Strings, and Console I/O

Figure 2.10 Sample Output using Different Operators in Java.

Program Explanation:

Line 7: Prints the original value of variable e -> e = 1.

Line 8: Prints the incremented value of e, since the operator is post-increment (e++),
the value would only change on the next evaluation or operation. Thus, on this line, e
is still equal to 1.

Line 9: Prints the new value of e after post increment operation. -> e = 2.

Line 10: Prints the incremented value of e, since the operator is pre-increment (++e),
the value would already be changed before the next evaluation. Thus, on this line, e
is already equal to 3.

Line 11: Prints the new value of e after pre-increment operation. -> e = 3. A new
line escape sequence (\n) is also printed on this line.

Line 14: This operation is also the same as y = y + x; thus, line 15 would print 12
as the value of y.

Line 16: Following the precedence rule, this line would first evaluate y * 5/2 % 3
from left to right which is equal to 0; thus, the simplified equation is now --x + 0 –
1, giving us the final value of z as 0.0 since the data type of variable z is double.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 82


UNIT 2: Primitive Types, Strings, and Console I/O

APPLICATION ACTIVITY FOR LESSON 2

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Try this Activity! I know you can do IT.

1. Write a program that swap the 2 inputted values of a variable int without using
a third variable. Name the activity as SwappingValues.java as shown in the
Figure below, it will be graded based on the rubric given.

Sample Output for Swapping Values Activity.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 83


UNIT 2: Primitive Types, Strings, and Console I/O

APPLICATION ACTIVITY FOR LESSON 2

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

Try this Activity! I know you can do IT.


2. Create a program that will accept four inputted numbers then
a. Compute and display the sum of 1st and 2nd, difference of 2nd and 3rd,
remainder of sum and difference, product of 3rd and 4th, and quotient of 4th
and 1st inputted numbers.

and display true or false if the following conditions satisfied:


b. If the product is less than and not equal to the quotient.
c. If the difference is equals to or not greater than the product.
d. If the sum is greater than or not equal to the difference.
e. If the quotient is not equal to and not less than the remainder.
f. If the remainder is not less than to the sum.
g. If the 3rd number is not greater than to the 4th number.
h. If the 2nd number is less than equal to the 3rd number.
i. If the 1st number is greater than equal to 2nd number.
Take note: Do not use any conditional statements like if. Name your project
Operators.java, see the Figure below as a sample. The grade of this activity will be
based on the rubric given.

Sample Output for Operators Activity.


IT 203 OBJECT-ORIENTED PROGRAMMING 1 84
UNIT 2: Primitive Types, Strings, and Console I/O

HOW DO YOU EXTEND YOUR


LEARNING?
ASSIGNMENT #2

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Learning Never Stop, Let's TAKE IT!


✓ What does the output base on the following line of codes?
public static void main(String[] args) {
int a=4, b=1, c=7, e=9;
System.out.println( ((a-- - 2)==1 && b-- >=2) == (a--
>= 10) );
System.out.println(!((b-=2)+2*2>15) || a++ >=0);
System.out.println(6+(c--)*(a++)+(b+=1)-(e*=2*(a++ -
2)));
}

Write the Output Here:

Write your Solution Here:

IT 203 OBJECT-ORIENTED PROGRAMMING 1 85


UNIT 2: Primitive Types, Strings, and Console I/O

LESSON 3:
THE MATH CLASS

OBJECTIVES:
At the end of this lesson, students will be able to:

▪ Create Java programs using appropriate methods from Math


Class.

▪ Develop applications implementing methods from


DecimalFormat class under Java.text package.

▪ Design a Java application that implements the advanced


mathematical calculations of Math Class combine with Random
and DecimalFormat Class.

▪ Assess the difference and analyze the use of random() method


in Math Class and Random Class.

Time Duration: 2.5 hours


IT 203 OBJECT-ORIENTED PROGRAMMING 1 86
UNIT 2: Primitive Types, Strings, and Console I/O

The Math Class


The Math class is a set of integrated mathematical operators in Java
that contains methods on performing necessary numeric procedures such as the
elementary exponential, logarithm, square root, and trigonometric functions.

Table 2.11 Math Class Fields.


Field Description
E the base of the natural logarithms
Pi the ratio of the circumference of a circle to its diameter

Table 2.12 Math Class Methods.

Math Class Methods Return Value


1. abs(num) It returns the absolute value of a numerical value.

Returns the arc cosine of value; the returned


2. acos(double angle)
angle is in the range 0.0 through pi.

Returns the arc sine value; the returned angle is


3. asin(double angle)
in the range -pi/2 through pi/2.

Returns the arc tangent value; the returned angle


4. atan(double angle)
is in the range -pi/2 through pi/2.

It returns the cube root value to a double data


5. cbrt(double num)
type.

Returns the smallest (closest to negative infinity)


double value that is greater than or equal to the
6. ceil(double num)
argument and is equivalent to a mathematical
integer.

7. cos(double angle) It returns the trigonometric cosine of an angle.

It returns the double value of the hyperbolic


8. cosh(double num)
cosine.

Returns Euler’s number e raised to the power of a


9. exp(double num)
double value.

Returns the largest (closest to positive infinity)


double value that is less than or equal to the
10. floor(double num)
argument and is equivalent to a mathematical
integer.

It returns sqrt(a2 +b2) without intermediate


11. hypot(double a, double b)
overflow or underflow.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 87


UNIT 2: Primitive Types, Strings, and Console I/O

Computes the remainder operation on two


12. IEEEremainder(double f1,
arguments as prescribed by the IEEE 754
double f2)
standard.

Returns the natural logarithm (base e) of a double


13. log(double num)
value.

It returns the base 10, logarithms of a double


14. log10(double num)
value.

Returns the natural logarithm of the sum of the


15. log1p(double num)
argument num and 1.

16. max(num1, num2) It returns the greater of two numerical values.

17. min(num1, num2) It returns the smaller of two numerical values.

18. pow(double base, It returns the value of the first argument raised to
double exponent) the power of the second argument.

It returns a double value with a positive sign,


19. random()
greater than or equal to 0.0 and less than 1.0.

20. round(double num) It returns the closest long to the argument.

21. round(float num) Returns the closest int to the argument.

Returns the signum function of the argument;


22. signum(double num) zero if the argument is zero, 1.0 if the argument is
23. signum(float num) greater than zero, -1.0 if the argument is less than
zero.

24. sin(double angle) It returns the trigonometric sine of an angle.

25. sinh(double num) It returns the hyperbolic sine of a double value.

It returns the correctly rounded positive square


26. sqrt(double num)
root of a double value.

27. tan(double a) It returns the trigonometric tangent of an angle.

It returns the hyperbolic tangent of a double


28. tanh(double x)
value.

It converts an angle measured in radians to an


29. toDegrees(double angrad) approximately equivalent angle measured in
degrees.

It converts an angle measured in degrees to an


30. toRadians(double angdeg) approximately equivalent angle measured in
radians.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 88


UNIT 2: Primitive Types, Strings, and Console I/O

The program below shows the use and functions of most commonly used Math
methods from java.lang package.

Figure 2.11 Sample Program using some Math Class Methods.

Figure 2.12 Sample Output using some Math Class Methods.

Program Explanation:

Line 2: This line shows an import statement for the class Scanner that would be
used to get console inputs from the users.
Line 3: Show the import statement necessary for decimal formatting.
Line 7: Create an object of type Scanner (instantiate) so that the program could
invoke its methods.” in” is a user-defined identifier, then the rest are Java keywords.
Line 8: Create an object of type DecimalFormat (instantiate) so that the program
could invoke its methods.”twodDcPt” is a user-defined identifier, then the rests
are Java keywords.
Line 12 & 14: Invoke the method “nextInt” from the Scanner class and save the
user’s input into variables “n1” and “n2”.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 89


UNIT 2: Primitive Types, Strings, and Console I/O

Line 16 to 19: Invoke various methods from the Math class. (Take note that Math
class requires no import statements since this class is from the default java.lang
package)
Line 20 & 23: Printing of values returned by the methods invoked from the previous
lines.
Line 24 & 27: These lines show that you can also have calculations or method
invocations (and other operations) as direct arguments inside the print statements.

Sample Program 2.1:

The program would generate a number greater than or equal to zero but less
than or equal to 100. Then, prompt the user to input the guess number. If the player
assumes the number correctly, output an appropriate message. If the inputted
guessed number is smaller than the random number, output the phrase, “Your guess
is lower than the number. Guess again!”; otherwise, output the message, “Your guess
is greater than the number. Guess again!”. Then prompt the player to try another
number. The player is encouraged to guess the random number until the player enters
the correct number.

Code 2.1:

1. import java.io.*;
2. import java.text.DecimalFormat;
3. public class NumberGuessingGame {
4. public static void main(String[] args) throws IOException
5. {
6. InputStreamReader reader = newInputStreamReader(System.in);
7. BufferedReader input = new BufferedReader(reader);
8. int number, guess;
9. System.out.println("\tNUMBER GUESSING GAME");
10. number = (int)(100 * Math.random());
11. do
12. {
13. System.out.println("Guess the number: ");
14. guess = Integer.parseInt(input.readLine());
15. if (number == guess)
16. {
17. System.out.println(“You have guessed the
correct number!!!”);
18. }
19. else if (number < guess)
20. {
21. System.out.println(“Your guess is greater than the
number. Guess again!”);
22. }
23. else if (number > guess)
24. {
25. System.out.println(“Your guess is lower than the
number. Guess again!”);
26. }
27. }
28. while (number != guess);

IT 203 OBJECT-ORIENTED PROGRAMMING 1 90


UNIT 2: Primitive Types, Strings, and Console I/O

29. }
30. }

Figure 2.13 Sample Output of Number Guessing Game Program.

Random Class
The instance of this class is used to generate a stream of pseudo-random
numbers (Knuth, 1997), an algorithm that produces an order of numbers that meet
specific statistical requirements for randomness.

The syntax to declare a Random class is:

Random variable_name = new Random();

Make sure you import the Java.util packager for you to be able to use the Random
class.

Example:

Random rand = new Random();

int num = rand.nextInt()

num variable will store the randomized integer number using the Random Class.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 91


UNIT 2: Primitive Types, Strings, and Console I/O

Decimal Format Class


An object of the class DecimalFormat has several different methods that can
be used to produce numerical strings in various formats (Savitch W. , 2004). We
describe and use some of the uses of these methods.

The syntax to declare a DecimalFormat:

DecimalFormat variable_name = new DecimalFormat(Pattern);

Example:

DecimalFormat format = new DecimalFormat(“00.00”);

The pattern “00.00” means there will be two digits before the decimal points
and two digits after the decimal point. Note that the result will is rounded when the
number of digits is less than the number of digits available. If the pattern of decimal
format is not consistent with the value of the number, such as a form that asks for two
digits before the decimal point like a number 4.17, it will add 0 at the beginning of
number 4 like 04.17. If the number is 417.95, then the format will be violated so that
no digits are lost (Savitch W. , 2004). Examples of some Math Class methods, Random
Class and DecimalFormat, are shown in the Figure below.

Figure 2.14 Sample Program for Math, Random and DecimalFormat Class.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 92


UNIT 2: Primitive Types, Strings, and Console I/O

Program Explanation:

Line 8: DecimalFormat declaration:

Line 9: DecimalFormat declaration with Percent Notation.

Line 10: Random Class declaration.

Line 11: Sample output for Randomly generated integer number can be a positive or
negative value.

Line 12: Random numbers with a count of 10 digits starting at 0. The range will be 0
to 9 only.

Line 13: Random numbers with a count of 5 digits starting at 1. The range will be 1 to
5 only.

Line 14: Random numbers with count depending on the starting and ending value or
maximum and minimum digit starting at 10. The range will be five, only beginning at
10 to 15. The possible output will be 10 – 14 only.

Line 15: The character “%” on the pattern at line 9 that placed at the end. It indicates
that the number is to be express as a percentage. The “%” causes the random number
to be multiplied by 100 and has a percent sign (%) appended to it.

Line 16: Declaration of Math class random() method.

Line 17: Sample Random number using Math.random().

Line 18: Random numbers converted to an integer using type-casting.

Line 19: Generated numbers that will be rounded off using the Math.round() method.

Line 20: Randomly created numbers with a count of 10 digits starting at 0 and will be
converted to an integer by type-casting. The range will be 0 to 9 only.

Line 21: Randomly generated numbers with a count of 100 digits starting at 0. The
range will be 0 to 99 only; since the pattern was violated, there will be no digit lost or
add.

Line 22: Random numbers with a count of 5 digits starting at 1. The range will be 1 to
5 only.

Line 23: Random numbers with count depending on the starting and ending value or
maximum and minimum digit starting at 10. The range will be 5, only starting at 10 to 15. The
possible output will be 10 – 14 only.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 93


UNIT 2: Primitive Types, Strings, and Console I/O

APPLICATION ACTIVITY FOR LESSON 3

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

Try this Activity! I know you can do IT.

1. Create a Program that will determine which among the three generated
numbers are the highest, second highest and the lowest number and display
the average of the three generated numbers, format it with percentage using
decimal format. Do not use any conditional statement to test the problem. Name
the activity as MathClass.java, For sample output, see Figure below, it will be
graded based on the rubric given.

Sample Output for Math Class Activity.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 94


UNIT 2: Primitive Types, Strings, and Console I/O

APPLICATION ACTIVITY FOR LESSON 3

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Try this Activity! I know you can do IT.


2. Create a Program that will process the BINGO Game:
a. Create your BINGO card by inputting your chosen number between 5
values only to make the generated number quicker, for example, B=1-5,
I=16-20, N=31-35, G=46-50, and O=61-65.
b. If all numbers match, including FREE (if you set your numbers on the
middle row of the card) on the straight format, then you won the BINGO
Game by displaying true otherwise false.
c. Do not use any conditional statement to test the problem. Name the
activity as Bingo.java, For sample output, see Figure below, the activity
grade will be based on the rubric given.

Sample Output:

IT 203 OBJECT-ORIENTED PROGRAMMING 1 95


UNIT 2: Primitive Types, Strings, and Console I/O

HOW DO YOU EXTEND YOUR


LEARNING?
ASSIGNMENT #3

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Learning Never Stop, Let's Quiz IT!


❖ Simulate and trace the given program below.
public static void main(String[] args) {
DecimalFormat dcf = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Random rand = new Random();
int number1, num2, sum;
number1 = rand.nextInt(1)+10;
num2 = (int)(Math.random()*1)+2; sum = number1 + num2;
System.out.println("The sum of "+ number1 +" and "+num2+"
is: "+sum);
System.out.println("The absolute value of number1 is:
"+Math.abs(number1));
System.out.println("Using Math.PI and decimalformat:
"+dcf.format(Math.PI));
System.out.println("number1: "+ number1 +" raise to
"+num2+" is: "+Math.round(Math.pow(number1, num2)));
System.out.println("The sqrt of number1 is:
"+dcf.format(Math.sqrt(number1)));
System.out.println("The cbrt of num2 is:
"+dcf.format(Math.cbrt(num2)));
System.out.println("Using math.round:
"+Math.round(Math.cbrt(num2)));
}

Write Your Answer Here:

IT 203 OBJECT-ORIENTED PROGRAMMING 1 96


UNIT 2: Primitive Types, Strings, and Console I/O

LESSON 4:
THE STRING CLASS

OBJECTIVES:
At the end of this lesson, students will be able to:

▪ Explain the characteristics of String variables as a Class type.

▪ Create Java programs using appropriate methods from String


Class.

▪ Declare a String object, compare the String values, and


implements the use of other String methods.

Time Duration: 2.5 hours


IT 203 OBJECT-ORIENTED PROGRAMMING 1 97
UNIT 2: Primitive Types, Strings, and Console I/O

The String Class


The String of characters, such as “Welcome to the world of Programming!”, “Do
you want to learn JAVA?” and the simple “Hi!” are treated slightly differently from the
values of the primitive types. Java has no primitive type for strings. Though, there is a
class called String that can be used to store and process lines of characters.

String Variables

A sequence of characters is a value of type String – letters, digits, spaces,


punctuation, and other “special characters” treated as a single item. A variable of type
String can name one of these string values.

Examples:

String name;

name = “Dariene Ruth”;

String department = “CICT”;

String message = “Hello Everyone!!!”;

String text = “143”;

Concatenation of Strings
You can connect two strings using the + operator. Combining two strings to
obtain a larger string is called concatenation. So, when it is used with strings, the +
symbol is sometimes called the concatenation operator.

Examples:

String fName = "Dariene Ruth";


String lName = “Evale”;
String fullName = fName + “ “ + lName;
String address = “City of Malolos”;
String statement;
Statement = fullName + " lives in " + address + ".";

It will set the variable statement to “Dariene Ruth Evale” “inCity of Malolos.” and
will write the following on the screen:

Dariene Ruth Evale lives in City of Malolos.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 98


UNIT 2: Primitive Types, Strings, and Console I/O

String Methods
The String variable is not just a simple variable as a variable of type int is. A
String variable is a class type variable that can name an object, and an object has
methods as well as a value. These String methods can be used to manage string
values. Ant method you call (or invoke) a String method by writing a dot and the name
of the method after the object name. objectName.method();

1. length() – returns the size of the String object.

Figure 2.15 Sample Program using length() method.

2. equals(Other_String) – returns true if the calling object String and the


Other_String are equal. Otherwise, it returns false.
callingString.equals(Other_String);

Figure 2.16 Sample Program using equals() method.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 99


UNIT 2: Primitive Types, Strings, and Console I/O

Note: Line 5 and 6 are for capturing the user’s input. It can be written too as:
BufferedReader input = new BufferedReader (new InputStreamReader(System.in));
Both BufferedReader and InputStreamReader Classes are imported from the java.io
package.

Figure 2.17 Sample Output that met the if Condition.

Figure 2.18 Another Output but did not met the Condition.

3. equalsIgnoreCase(Other_String) – returns true if the calling String object and


the Other_String are the same, considering uppercase and lowercase
versions of a letter to be the same. Otherwise, it returns false.

Figure 2.19 Java Program using equalsIgnoreCase() method.

Figure 2.20 equalsIgnoreCase() method Sample Output.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 100


UNIT 2: Primitive Types, Strings, and Console I/O

4. toLowerCase() – returns a string with the same characters as the calling object
String, but with all characters converted to lowercase.

5. toUpperCase() – returns a string with the same characters as the calling object
String, but with all characters converted to uppercase.

Figure 2.21 Sample Program using toLowerCase() and


toUpperCase() method.

6. trim() – returns a string with the same characters as the calling object String,
but with leading and trailing white space removed.

7. charAt(Position) – returns the character in the calling object string at the


position. Positions are counted 0, 1, 2, etc.

Figure 2.22 Sample charAt() program.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 101


UNIT 2: Primitive Types, Strings, and Console I/O

Figure 2.23 Sample Output for charAt() method.

Figure 2.24 Invalid index position for charAt() method.

As shown in Figure 2.33, the length or size of the word xenophobia is 10, while the
index position looking for a character is 25, which is more than or greater than the
actual length of the series of characters in that way it returns an error message.

8. substring(Start) – returns the substring of the calling object String from


Position Start through to the end of the calling object. Positions are counted 0,
1, 2, etc.

Figure 2.25 Sample subString(start) method.

Note: StringIndexOutOfBoundsException error would be generated if you try to use


an invalid index position.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 102


UNIT 2: Primitive Types, Strings, and Console I/O

9. subString(Start, End) – returns the substring of the calling object String


beginning Position Start through, but not including the End position of the calling
object. Positions are counted 0, 1, 2, … etc.

Figure 2.26 Sample subString(start, end) method.

10. indexOf (A_String) – returns the position of the first occurrence of the String
A_String in the calling object String. Places are counted 0, 1, 2, ... etc. Else,
returns -1 if A_String is not found.

Figure 2.27 Sample Program of indefOf() method.

11. indexOf (A_String, Start) – returns the position of the first occurrence of the
String A_String in the calling object that appears at or after position Start.
Positions are counted 0, 1, 2,.. etc. Otherwise, returns -1 if A_String is not
found.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 103


UNIT 2: Primitive Types, Strings, and Console I/O

Figure 2.28 Sample Code using indexOf(String, start)


method.

12. lastIndexOf (A_String) – returns the position of the last occurrence of the
String A_String in the calling object String. Places are counted 0, 1, 2, ... etc.
Otherwise, returns -1 if A_String is not found.

Figure 2.29 lastIndexOf() Sample Program.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 104


UNIT 2: Primitive Types, Strings, and Console I/O

13. compareTo(A_String) – compares the calling object String with A_String to


see which comes first in lexicographic ordering. Lexicographic ordering is
similar to alphabetical order when both strings are either all uppercase or
lowercase. If the calling String comes first, compareTo argument string
(A_string), it returns a negative value; otherwise, it produces a positive number.
If both Strings are the same, it returns 0.

Figure 2.30 Sample Program using compareTo() method.

Figure 2.31 Different Outputs using compareTo() method.

The comparison proceeds as follows:


• The “a” in apple and the “a” in avocado are compared and found to be equal.
• The “p” in apple and the “v” in avocado are compared - they are different.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 105


UNIT 2: Primitive Types, Strings, and Console I/O

• The numeric value of p (16) minus the numeric value of v (22) is -6 (because
p is 6, letters before v in the alphabet), so to compareTo(), the method returns
the value 5.

14. replace(oldChar, newChar) – Returns a new string resulting from changing all
existences of oldChar in this String with newChar.

Figure 2.32 Different Sample using replace() method.

If the oldChar character does not occur in the sequence represented by


this String object, then the same reference to this String object is returned. Otherwise,
a new String object is formed that means a character sequence equal to the line of
character represented by this String object, except that an occurrence of newChar
replaces every existence of oldChar.

15. startsWith(String prefix) – Returns true if the String starts with the string
prefix. Otherwise, it returns false.

callingString.startsWith(String_prefix);

Figure 2.33 Sample Program of startWith() method.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 106


UNIT 2: Primitive Types, Strings, and Console I/O

16. startsWith(String Prefix, int StartingPoint) – Returns true if the String starts
with the string prefix that begins at the starting point. You can define the starting
point, 0 as the first index position.

callingString.startsWith(String_prefix, Starting_point);

Figure 2.34 startWith() method Program with starting point.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 107


UNIT 2: Primitive Types, Strings, and Console I/O

APPLICATION ACTIVITY FOR LESSON 4

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Try this Activity! I know you can do IT.


1. Write a program that will print out statistics for eight-coin tosses. The user will
input either an ‘h’ for heads or a ‘t’ for tails for the eight tosses. The program
will then print out the total number and percentages of heads and tails. Use
decimal format to display the percentage and DO NOT USE conditional
statements like if statement. For sample output, see Figure below, name the
activity as TossCoin.java, it will be graded based on the rubric given.

Sample Output:

IT 203 OBJECT-ORIENTED PROGRAMMING 1 108


UNIT 2: Primitive Types, Strings, and Console I/O

APPLICATION ACTIVITY FOR LESSON 4

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Try this Activity! I know you can do IT.


2. Create a program that will process the Game Jack ‘n Poy. The user will input
either a/an ‘r’, “paper”, ‘S’ or “RoCK”, PAPER for rock, paper, scissor choices.
The program will then print out the player choice and computer choice.
Determine who is the winner: player 1, computer or if it’s a draw game. For
sample output, see Figure 2.45, name the activity as JackNPoy.java, it will be
graded based on the rubric given.

Sample Output:

IT 203 OBJECT-ORIENTED PROGRAMMING 1 109


UNIT 2: Primitive Types, Strings, and Console I/O

GRADING RUBRIC

HOW WELL DID YOU PERFORM?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Rubric for Java Program Activity


Program Poor Fair Good Excellent
Rating
Specification (2) (5) (8) (10)
Following Did not follow 50% followed 80% followed 100%
Instructions the given the given the given followed the
instructions instructions instructions given
instructions
Program The program The program The program The program
execution does not executes with a runs but with executes
execute minor (easily logical Error correctly with
find the Error) no syntax or
run-time
errors
Correct Output is The Program With result but The program
output incorrect displays but has has minor displays the
multiple errors errors correct output
with no errors
Design of Poorly work The program Program Program
output designed. does not display display more
display the minimally than expected
required output expected output
Design of Program is The program The program The design
logic incorrect has significant has slight logic program is
logic errors errors that do logically well.
not significantly
affect the
results
Standards The program Several Few The design of
was written inappropriate inappropriate the program is
poorly in the design choices design choices stylistically
standard. (i.e., poor (i.e., poor well.
variable names, variable names,
improper improper
indention) indention)
Readability The The code is The code is The
organization readable only reasonably organization
of the code is by someone easy to read of the code is
poorly and who knows exceptional
very difficult to what it is and very easy
read supposed to be to follow
doing
IT 203 OBJECT-ORIENTED PROGRAMMING 1 110
UNIT 2: Primitive Types, Strings, and Console I/O

HOW DO YOU EXTEND YOUR


LEARNING?
ASSIGNMENT #4

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Learning Never Stop, Let's Quiz IT!


❖ Simulate and trace the given program below.
public static void main(String[] args) {
String text =” Object Oriented Programming.”;
int index1 = text.indexOf("o",7);
int index2 = text.lastIndexOf("o");
int index3 = text.indexOf(",");
int index4 = index1-index2-index3;
System.out.println(index1);
System.out.println(index2);
System.out.println(index3);
System.out.println(index4);
System.out.println(text.replace(text.charAt(index2),
text.charAt(index3+1)) +"\n"
+text.substring(index3+1,3)+text.toUpperCase().charAt(
18+1));
}

Write the Output Here:

IT 203 OBJECT-ORIENTED PROGRAMMING 1 111


UNIT 2: Primitive Types, Strings, and Console I/O

POST-TEST FOR UNIT 2

HOW MUCH HAVE YOU LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________
INSTRUCTION: Encircle the letter of the BEST option that corresponds to your
answer.

1. Programmer – named computer memory locations are called ____________.


a. Compilers
b. Variables
c. Addresses
d. Appellations
2. Which of the following is the possible return value of the statement res=" A"
.compareTo("a");
a. -32
b. -1
c. true
d. false
3. When data cannot be changed after a program is compiled, the data is _____.
a. Constant
b. Volatile
c. Mutable
d. Variable
4. Which of the following is considered NOT a primitive data type in the Java
programming language?
a. boolean
b. byte
c. String
d. Int
5. Nonexecuting program statements that provide documentation are called ____.
a. Classes
b. Comments

IT 203 OBJECT-ORIENTED PROGRAMMING 1 112


UNIT 2: Primitive Types, Strings, and Console I/O

c. Computations
d. Commands
6. An escape sequence always begins with a(n) ____________________.
a. Letter
b. Forward slash
c. equal sign
d. backslash
7. Which of the following declaration uses primitive data types? Choose all that
applies.
a. char c;
b. string s;
c. int y;
d. Double a;
8. Which of the following declaration uses class data types? Choose all that
applies.
a. Character c;
b. String s;
c. double D;
d. Float f;
9. Which of the following is considered as valid variable declarations? Choose all
that applies.
a. String s= ‘x’;
b. string name=”ruth”;
c. int $peso=5;
d. String publicclass = “class”;
10. The Java programming language supports three types of comments:
__________, __________, and Javadoc.
a. Line, block
b. String, literal
c. single, multiple
d. constant, variable
11. The assignment operator in the Java programming language is
_____________.
a. =
b. ==
c. ::
d. :=

IT 203 OBJECT-ORIENTED PROGRAMMING 1 113


UNIT 2: Primitive Types, Strings, and Console I/O

12. Which of the following is the correct way of concatenating elements in the print
method? Assume that var is a valid variable. Choose all that applies.
a. System.out.println(var + “hope”);
b. System.out.println(“var” + hope);
c. System.out.println(“hope” +var);
d. System.out.println(hope + “var”);
13. Which of these data type can store a value in the least amount of memory?
a. short
b. int
c. byte
d. long
14. The modulus operator _____________________.
a. is represented by a forward slash
b. provides the remainder of integer division
c. provides the remainder of floating – point division
d. two of the preceding answers are correct.
15. Which of the following is correct? Choose all that applies
a. && stops if the first operand is false while & always evaluate both
operands
b. & stops if the first operand is false while && always evaluate both
operands
c. | breaks if the first operand is true while || always evaluate both operands
d. || breaks if the first operand is true while | always evaluate both operands
16. What do you call a name used to identify a class variable, function, or any
other user-defined item?
a. Variables
b. Data Types
c. Identifiers
d. Constant

For number 17 - 23. Assuming that int num1=2, num2=4, num3=6, num4=8;

17. Using the given values, what do you think is the evaluated result of the
expression (num1-- - 2) ==1 && num2-- >=2)?
a. true
b. false
c. 1

IT 203 OBJECT-ORIENTED PROGRAMMING 1 114


UNIT 2: Primitive Types, Strings, and Console I/O

d. 0
18. Using the given values, what do you think is the evaluated result of

!((num2 -= 2)+2*2>15)

a. true
b. false
c. 6
d. -1
19. Using the given values, what do you think is the evaluated result of

(num1-- >= 10) || (num1++ >=0)

a. true
b. false
c. 1
d. -1
20. Using the given values, what do you think is the evaluated result of the
condition below?

num2 % 2 * 4 - (num2 * num3)

a. true
b. false
c. -24
d. 21
21. Using the given values, what do you think is the evaluated result of

6+(num3++) - (num1--) * (num2+=1)

a. true
b. false
c. 2
d. 50
22. Using the given values, what do you think is the evaluated result of

(num4 -= 2 / ((num1+2) - 2))== 8

a. true
b. false
c. 8

IT 203 OBJECT-ORIENTED PROGRAMMING 1 115


UNIT 2: Primitive Types, Strings, and Console I/O

d. -6
23. Using the given values, what do you think is the evaluated result of
(num3%num4*num2 <= num2+num3%num2)
a. true
b. false
c. -18
d. 21
24. String val = “Java is fun!”; What is the return value of
val.substring(8, 11)?
a. fun!
b. fun
c. fun
d. Error
25. What is the output of the following code?
String pass1 = "abc123", pass2 = "abc132";
System.out.println(pass1.equals(pass2));
a. 1
b. -1
c. true
d. false
26. If String movie = new String(“West Side Story”); then the value
of movie.indexOf(“s”) is.__________.
a. -1
b. 2
c. False
d. 3
27. String text = “Object Oriented Programming.”; What would be
the output of text if?
System.out.println(text.replace(text.substring(0,1),
text.substring(2,3)));
a. jbject jriented Programming.
b. jbject jriented Prjgramming.
c. Object jriented Prjgramming.
d. StringIndexOutofBound Exception: -1

IT 203 OBJECT-ORIENTED PROGRAMMING 1 116


UNIT 2: Primitive Types, Strings, and Console I/O

For number 28 -30:


char letter;
if (letter == ‘y’)
System.out.println(“Nice weather we are having!”);
System.out.println("Good bye!");
System.out.println("Press Enter key to end program.");

28. – 29. From the given code above, what would be the output if the value of the
letter is: char letter = “y”;
a. Nice weather we are having!
b. Nice weather we are having!
Good bye!
Press Enter key to end program.

c. Good bye!
Press Enter key to end program.

d. Error

30. From the given code above, what would be the output if the value of the
letter is: char letter = ‘n’;

a. Nice weather we are having!


b. Nice weather we are having!
Good bye!
Press Enter key to end program.

c. Good bye!
Press Enter key to end program.

d. Error

IT 203 OBJECT-ORIENTED PROGRAMMING 1 117


UNIT 2: Primitive Types, Strings, and Console I/O

UNIT 2 FINAL REQUIREMENTS.

Before you end this module:


✓ Compile in one program all the Hands-On activities we did
on this chapter and save it as
Chapter2FinalRequirements.java, When running the
program make a Main Menu to choose on which activity
the user wants to display for example 1. Vending
Machine, 2. Payroll, etc. See Figure below for example.

✓ Share your significant learnings and insights related to


your experience and apply it to you as a student and as a
future professional. Write the journey and treasures you
have obtained, see the example below, use Microsoft
Word or any word processor to accomplish this module.

✓ Send the softcopy using the zip file format your Java
Project as well as the documentation of your journey to
your professor.
Congratulations! 😊

My journey to this lesson enabled me:


______________________________

It made me realized that:


______________________________

I, therefore commit to:


______________________________

IT 203 OBJECT-ORIENTED PROGRAMMING 1 118


UNIT 2: Primitive Types, Strings, and Console I/O

GLOSSARY
Arithmetic - in Java, you can perform arithmetic expressions involving +, -, *, and /.

Assignment Statements - It is used to give a value for the variable name or to change
its value.
Binary Operator - An operator that has two arguments, like the + and *.

Class Type – is a type of object with both data and methods. It begins with an
uppercase letter.
Decimal Format Class - has several different methods that can be used to produce
numerical strings in various formats.
Escape Sequence - includes a way for you to clarify this ambiguity.

Identifiers - Identifiers are the technical terms for a name in a programming language.

Keywords - these words have a special predefined meaning and cannot be used as
the names of classes or objects or anything else.

Logical - is a boolean expression that is simply an expression that is either true or


false.
Math Class - is a set of integrated mathematical operators
Operator – it causes the compiler to perform specific mathematical or logical
manipulations.
Primitive type – its values are simple, indecomposable values, such as a single letter
or a number.
Random Class - an instance of this class is used to generate a stream of pseudo-
random numbers.
Relational - sometimes called a comparison operator it only compares two items

String Class - that can be used to store and process strings of characters.

Type Casting - a type-cast involves changing the data type of a value from its original.

Unary Operator – is an operator that has one argument like the negative operator (-
).

Variables - They are used to store data such as numbers and letters.

IT 203 OBJECT-ORIENTED PROGRAMMING 1 119


UNIT 2: Primitive Types, Strings, and Console I/O

REFERENCES
Books
Cadenhead, R. &. (2004). SAMS TEACH YOURSELF JAVA 2 IN 21 DAYS (4th ed.).
ED. Sams Publishing.
Farrel, J. (1999). JAVA PROGRAMMING COMPREHENSIVE. Course Technology.
Farrell, J. (2012). Java Programming (Sixth ed.). Boston, MA: Course Technology
Cengage Learning. Retrieved 2020, from
https://books.google.com.ph/books?id=pnwTLvCJKh0C&printsec=frontcover&
dq=java+programming+by+joyce+farrell+2012&hl=en&sa=X&ved=2ahUKEwj
Dh7DyhJrrAhUowosBHWE-
ApEQ6AEwA3oECAEQAg#v=onepage&q=java%20programming%20by%20j
oyce%20farrell%202012&f=false
Knuth, D. E. (1997). The Art of Computer Programming (3rd ed., Vol. 2). Grove
Press, Inc. Retrieved 2020, from
https://doc.lagout.org/science/0_Computer%20Science/2_Algorithms/The%20
Art%20of%20Computer%20Programming%20%28vol.%202_%20Seminumeri
cal%20Algorithms%29%20%283rd%20ed.%29%20%5BKnuth%201997-11-
14%5D.pdf
Malik, D. (2008). JAVA PROGRAMMING FROM PROBLEM ANALYSIS TO
PROBLEM DESIGN. Cengage Learning Asia Pte Ltd: Philippines.
Savitch, W. (2004). Java: An Introduction to Computer Science & Programming (3rd
ed.). New Jersey: Pearson Education, Inc.
Savitch, W. (2006). JAVA: AN INTRODUCTION TO COMPUTER SCIENCE AND
PROGRAMMING. San Diego, California: Prentice Hall.
Online References
Kjell, B. (2019, July). Introduction to Computer Science using Java. Central
Connecticut State University. Retrieved August 29, 2020, from
http://programmedlessons.org/Java9/index.html
https://docs.oracle.com/javase/tutorial/java/
https://java.sun.com/docs/books/tutorial/
https://java.sun.com/developer/onlineTraining/
https://www.freewarejava.com/tutorials/index.shtml
http://www.functionx.com/java/

IT 203 OBJECT-ORIENTED PROGRAMMING 1 120

You might also like