Lecture 3
Lecture 3
Fall 2020/21
Object-Oriented Programming
CS-201
Lec. (3)
Chapter 3
Numerical Data
Abstract
Abstraction is a way of describing complex problems
in simple terms, by ignoring some details.
Eliminating the nitty-gritty details let us focus on the bigger picture.
We can dig deeper once we have a broader understanding.
Encapsulation
The next fundamental idea to keep in mind when dealing with object-oriented
programming and classes is called "encapsulation".
We encapsulate something to protect it and keep its parts together.
Think of how medicine is enclosed in a shell called capsule.
In object-orientation,
this translates to packing together our properties and methods in a class.
Encapsulation also means hiding the gears and the levers.
What is Inheritance?
Generalization vs. Specialization
10-70
Overriding
By overriding a method of the superclass, we basically tell that we want a
different behavior in our subclass than the one we inherited.
Method overriding is straightforward:
we re-implement the method with the same name and parameters as the one
defined in the parent class and provide our own behavior.
Objectives
After you have read and studied this chapter, you should
be able to
• Select proper types for numerical data.
• Write arithmetic expressions in Java.
• Evaluate arithmetic expressions using the precedence rules.
• Describe how the memory allocation works for objects and primitive
data values.
• Write mathematical expressions, using methods in the Math class.
• Use the GregorianCalendar class in manipulating date information
such as year, month, and day.
• Use the DecimalFormat class to format numerical data
• Convert input string values to numerical data
• Perform input and output by using System.in and System.out
Data Type Precisions
The six data types differ in the precision of values they can store in
memory.
Arithmetic Operators
• The following table summarizes the arithmetic operators available in
Java.
firstNumber 234
A
int firstNumber, secondNumber;
secondNumber 87
firstNumber = 234;
secondNumber = 87; B
int number;
number = 237;
number = 35; number 35
237
A. The variable
is allocated in
int number; A memory.
number = 237; B B. The value 237
number = 35; C is assigned to
number.
C. The value 35
overwrites the
previous value 237.
Customer Customer
A
B A. The variable is
Customer customer;
allocated in memory.
customer = new Customer( );
B. The reference to the
customer = new Customer( ); new object is assigned
to customer.
C C. The reference to
another object overwrites
the reference in customer.
A Customer
C C. The reference in
clemens is assigned to
customer.
int age;
age = JOptionPane.showInputDialog(
null, “Enter your age”);
• No.
String value cannot be assigned directly to an
int variable.
Type Conversion
• Wrapper classes are used to perform necessary type
conversions, such as converting a String object to a
numerical value.
int age;
String inputStr;
inputStr = JOptionPane.showInputDialog(
null, “Enter your age”);
age = Integer.parseInt(inputStr);
Other Conversion Methods
Common Scanner Methods:
Method Example
System.out.print(num); 123.45789345
System.out.print(df.format(num));
123.458
The Math class
• The Math class in the java.lang package contains class
methods for commonly used mathematical functions.
double num, x, y;
x = …;
y = …;
alphaRad = Math.toRadians(alpha);
betaRad = Math.toRadians(beta);
Passing Side 1
class LibraryCard { 2
private Student owner;
public void setOwner(Student st) {
owner = st; 2 : LibraryCard : Student
}
}
owner name
Receiving Side “Jon Java”
borrowCnt email
1 Argument is passed 0 “[email protected]”
Client Service
Data Members Should Be private
• Data members are the implementation details of the
class, so they should be invisible to the clients. Declare
them private .
• Exception: Constants can (should) be declared public if
they are meant to be used directly by the outside
methods.
Access Modifiers
▪ There are 4 types of java access specifiers:
✔ default
✔ private
✔ protected
✔ public
Modifier Access Level
return result;
}
Local, Parameter & Data Member
Selection Statements
Objectives
After you have read and studied this chapter, you should be able to
else
This statement is
JOptionPane.showMessageDialog(null, executed if the testScore
"You did pass" ); is 70 or higher.
Syntax for the ifif (Statement
<boolean expression> )
<then block>
else
if ( testScore < 70 )
else
JOptionPane. JOptionPane.
showMessageDialog showMessageDialog
(null, "You did pass"); (null, "You did not pass");
Relational Operators
< //less than
<= //less than or equal to
== //equal to
!= //not equal to
> //greater than
>= //greater than or equal to
testScore < 80
testScore * 2 >= 350
30 < w / (h * h)
x + y != 2 * (a + b)
2 * Math.PI * radius <= 359.99
Compound Statements
• Use braces if the <then> or <else> block has multiple statements.
if ( <boolean expression> )
{
…
} Style 2
else
{
…
}
The if-then Statement
if ( <boolean expression> )
<then block>
Boolean Expression
if ( testScore >= 95 )
JOptionPane.
showMessageDialog (null,
false "You are an honor student");
The Nested-if Statement
• The then and else block of an if statement can contain
any valid statements, including other if statements. An if
statement containing another if statement is called a
nested-if statement.
messageBox.show
messageBox.show
("You did a great
("You did pass");
job");
Writing a Proper if Control
if (num1 < 0) negativeCount = 0;
if (num2 < 0)
if (num3 < 0)
negativeCount = 3; if (num1 < 0)
else negativeCount++;
negativeCount = 2;
if (num2 < 0)
else
if (num3 < 0)
negativeCount++;
negativeCount = 2; if (num3 < 0)
else negativeCount++;
negativeCount = 1;
else
if (num2 < 0)
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 1; The statement
else
if (num3 < 0) negativeCount++;
negativeCount = 1;
else increments the variable by one
negativeCount = 0;
if – else if Control
if (score >= 90)
System.out.print("Your grade is A");
P Q P && Q P || Q !P
false false false false true
false true false true true
true false false true false
true true true true false
Boolean Variables
• The result of a boolean expression is either true or
false. These are the two values of data type
boolean.
• We can declare a variable of data type boolean
and assign a boolean value to it.
boolean pass, done;
pass = 70 < x;
done = true;
if (pass) {
…
} else {
…
}
Boolean Methods
• A method that returns a boolean value, such as
private boolean isValid(int value) {
if (value < MAX_ALLOWED)
return true;
} else {
return false;
}
}
if (isValid(30)) {
…
Can be used as } else {
…
}
Comparing Objects
• With primitive data types, we have only one way to compare them,
but with objects (reference data type), we have two ways to
compare them.
1. We can test whether two variables point to the same object (use ==), or
2. We can test whether two distinct objects have the same contents.
Using == With Objects (Sample 1)
String str1 = new String("Java");
String str2 = new String("Java");
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
if (str1.equals(str2)) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
Repetition Statements
Objectives
After you have read and studied this chapter, you should be able to
• Implement repetition control in a program using while statements.
• Implement repetition control in a program using do-while statements.
• Implement a generic loop-and-a-half repetition control statement
• Implement repetition control in a program using for statements.
• Nest a loop repetition statement inside another repetition statement.
• Choose the appropriate repetition control statement for a given task
• Prompt the user for a yes-no reply using the showConfirmDialog method of
JOptionPane.
• (Optional) Write simple recursive methods
Definition
• Repetition statements control a block of code to
be executed for a fixed number of times or until
a certain condition is met.
• Count-controlled repetitions terminate the
execution of the block after it is executed for a
fixed number of times.
• Sentinel-controlled repetitions terminate the
execution of the block after one of the
designated values called a sentinel is
encountered.
• Repetition statements are called loop statements
also.
The while Statement
int sum = 0, number = 1;
}
Syntax for the while Statement
while ( <boolean expression> )
<statement>
Boolean Expression
true
number <=
100 ?
false
sum = sum + number;
number = number + 1;
More Examples
1 int sum = 0, number = 1; Keeps adding the
numbers 1, 2, 3, … until
while ( sum <= 1000000 ) { the sum becomes larger
than 1,000,000.
sum = sum + number;
number = number + 1;
}
2
int product = 1, number = 1,
count = 20, lastNumber; Computes the product of
the first 20 odd integers.
lastNumber = 2 * count - 1;
inputStr = JOptionPane.showInputDialog(null,
"Your Age (between 0 and 130):");
age = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog(null,
"Your Age (between 0 and 130):");
age = Integer.parseInt(inputStr);
}
Useful Shorthand Operators
sum = sum + number; is equivalent to sum += number;
Infinite Loops
Both loops will not
terminate because the
boolean expressions will
2 int count = 1; never become false.
while ( count != 10 ) {
count = count + 2;
}
Overflow
Avoid using real numbers for counter variables as much as possible. If you use
them, then be aware of the pitfall and ensure that the loop terminates.
Loop Pitfall – 2a
1 int result = 0; double cnt = 1.0;
while (cnt <= 10.0){
cnt += 1.0;
result++;
}
System.out.println(result);
10 Using Real Numbers
Loop 1 prints out 10, as
expected, but Loop 2 prints
out 11. The value 0.1 cannot
be stored precisely in
2 int result = 0; double cnt = 0.0; computer memory.
while (cnt <= 1.0){
cnt += 0.1;
result++;
}
System.out.println(result);
11
Avoid using real numbers for counter variables as much as possible. If you use
them, then be aware of the pitfall and ensure that the loop terminates.
Loop Pitfall - 3
• Goal: Execute the loop body 10 times.
1 count = 1; 2 count = 1;
while ( count < 10 ){ while ( count <= 10 ){
. . . . . .
count++; count++;
} }
3 count = 0; 4 count = 0;
while ( count <= 10 ){ while ( count < 10 ){
. . . . . .
count++; count++;
} }
do {
do {
Boolean Expression
Control Flow of do-while
int sum = 0, number = 1
sum += number;
number++;
true
sum <=
1000000 ?
false
Loop-and-a-Half Repetition Control
String name;
while (true){
• Multiple exit points. It is possible, although complex, to write a correct control loop with
multiple exit points (breaks). It is good practice to enforce the one-entry one-exit control
flow.
Confirmation Dialog
• A confirmation dialog can be used to prompt the user to
determine whether to continue a repetition or not.
JOptionPane.showConfirmDialog(null,
/*prompt*/ "Play Another Game?",
/*dialog title*/ "Confirmation",
/*button options*/ JOptionPane.YES_NO_OPTION);
Example: Confirmation Dialog
boolean keepPlaying = true;
int selection;
while (keepPlaying){
selection = JOptionPane.showConfirmDialog(null,
"Play Another Game?",
"Confirmation",
JOptionPane.YES_NO_OPTION);
number = scanner.nextInt( );
sum += number;
}
These statements are
executed for 20 times
( i = 0, 1, 2, … , 19).
Syntax for the for Statement
for ( <initialization>; <boolean expression>; <increment> )
<statement>
Boolean
Initialization Increment
Expression
i = 0;
i < 20 ?
false
true
number = . . . ;
sum += number;
i ++;
More for Loop Examples
1 for (int i = 0; i < 100; i += 5)
i = 0, 5, 10, … , 95
j = 2, 4, 8, 16, 32
long elapsedTimeInMilliSec =
endTime.getTime() – startTime.getTime();
What will be the output of the program?
Answer: 15 15
What will be the output of the program?
Answer: sst s st
With x = 0, which of the following are legal lines of Java code for changing the
value of x to 1?
1. x++;
2. x = x + 1;
3. x += 1;
4. x =+ 1;
Answer: 1, 2, 3, & 4
What will be the output of the program?
Answer: 1.5 1
What will be the output of the program?
Answer:
Enter your marks
85
You pass the exam
What will be the output of the program?
Answer: t
What will be the output of the program?
Answer: 48
What will be the output of the program?
Answer: FALSE
What will be the output of the program?
Answer: FALSE
What will be the output of the program?
Answer: 12
What will be the output of the program?
Answer: 27 9
What will be the output of the program?
Answer: 40
What will be the output of the program?
Answer: iiiii
What will be the output of the program?
Answer: 15
What will be the output of the program?
Answer: 2
What will be the output of the program?
Answer: 6
What will be the output of the program?
Answer: i = 5 and j = 6