OOP1 UNIT2 PrimitiveStringsAndIO
OOP1 UNIT2 PrimitiveStringsAndIO
6
1
9
UNIT
2 PRIMITIVE TYPES,
STRINGS, AND
CONSOLE I/O
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;
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
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
LESSON 1:
PRIMITIVE TYPES AND EXPRESSIONS
OBJECTIVES:
At the end of this lesson, students will be able to:
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.
• 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.
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.
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, . . ..;
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.
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:
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
Sample Program:
The code below prints all the primitive types and shows how to name variables
and use assignment operators.
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.)
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:
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
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
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.
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;
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:
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.
You can also cast a data type int to a double, or accomplish the same thing by
combining the types:
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.
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.
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.
LESSON 2:
OPERATORS
OBJECTIVES:
At the end of this lesson, students will be able to:
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.
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.
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--;
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.
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:
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.
== 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.
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.
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.
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
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
Program Explanation:
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.
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.
LESSON 3:
THE MATH CLASS
OBJECTIVES:
At the end of this lesson, students will be able to:
18. pow(double base, It returns the value of the first argument raised to
double exponent) the power of the second argument.
The program below shows the use and functions of most commonly used Math
methods from java.lang package.
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”.
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.
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);
29. }
30. }
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.
Make sure you import the Java.util packager for you to be able to use the Random
class.
Example:
num variable will store the randomized integer number using the Random Class.
Example:
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.
Program Explanation:
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 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.
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:
LESSON 4:
THE STRING CLASS
OBJECTIVES:
At the end of this lesson, students will be able to:
String Variables
Examples:
String name;
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:
It will set the variable statement to “Dariene Ruth Evale” “inCity of Malolos.” and
will write the following on the screen:
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();
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.18 Another Output but did not met the Condition.
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.
6. trim() – returns a string with the same characters as the calling object String,
but with leading and trailing white space removed.
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.
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.
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.
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.
• 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.
15. startsWith(String prefix) – Returns true if the String starts with the string
prefix. Otherwise, it returns false.
callingString.startsWith(String_prefix);
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);
Sample Output:
Sample Output:
GRADING RUBRIC
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. :=
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
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
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?
a. true
b. false
c. -24
d. 21
21. Using the given values, what do you think is the evaluated result of
a. true
b. false
c. 2
d. 50
22. Using the given values, what do you think is the evaluated result of
a. true
b. false
c. 8
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
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’;
c. Good bye!
Press Enter key to end program.
d. Error
✓ Send the softcopy using the zip file format your Java
Project as well as the documentation of your journey to
your professor.
Congratulations! 😊
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.
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.
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/