Week 3 - Numerical Data and Expression Part 1
Week 3 - Numerical Data and Expression Part 1
COMPUTATION
&
EXPRESSION
(part 1)
NUMERICAL COMPUTATION &
EXPRESSION (part 1)
• This topic focuses on:
• character strings
• primitive data
• the declaration and use of variables
• expressions and order of precedence
Outline
Character Strings
Variables
Primitive Data Types and Assignment
Expressions
Character Strings
• A string literal is represented by putting double quotes around
the text
• Examples:
object method
information provided to the method
name
(parameters)
The printf Method
- To Format Output
Usage (Syntax):
System.out.printf(formatString , items);
where
-formatString: a string with format specifiers
- items: list of data/variables to be displayed
Use printf method in order to used the above format.
printf method only supported in JDK 5 and higher
version.
Formating Output
• Outputting floating point values can look strange:
Price per liter: 1.21997
• To control the output appearance of numeric variables, use
formatted output tools such as:
a) System.out.printf(“%.2f”, price);
Price per liter: 1.22
b) System.out.printf(“%10.2f”, price);
Price per liter: 1.22
%[flag][width][.precision]format type
e.g.
int x= 10; double y = 5.373123;
System.out.printf(“Value of x is %d and value of y is %6.2f
%n”, x , y);
Note:
items MUST match specifiers in order, in number and in exact type
Formating Output
- Flag
Flag Description
- Left justifies the converted value
, Include comma separator for >= 1000
value
( Enclose ( ) for negative value
Formating examples
String Concatenation
• The string concatenation operator (+) is used to append one
string to the end of another
"Peanut butter " + "and jelly"
• It can also be used to append a number to a string
• A string literal cannot be broken across two lines in a
program
• See Facts.java
//********************************************************************
// Facts.java Author: Lewis/Loftus
//
// Demonstrates the use of the string concatenation operator and the
// automatic conversion of an integer to a string.
//********************************************************************
System.out.println ();
continue
continue
X: 25
Y: 65
Z: 30050
Escape Sequences
• What if we wanted to print the quote character?
\b backspace
\t tab
\n newline
\r carriage return
\" double quote
\' single quote
\\ backslash
• See Roses.java
//********************************************************************
// Roses.java Author: Lewis/Loftus
//
// Demonstrates the use of escape sequences.
//********************************************************************
int total;
int count, temp, result;
int luckyNumber;
System.out.println(luckyNumber);
// ERROR - uninitialized variable
• The compiler will issue an error if you try to change the value
of a constant
• In Java, we use the final modifier to declare a constant
byte-->short -->int-->long-->float-->double
Example
double doubleVariable = 7;
is possible even if doubleVariable is of type
double.
Assignment Evaluation
The expression on the right-hand side of the
assignment operator (=) is evaluated first.
Examples:
int count = 0;
char grade = 'A';
Initializing Variables
Syntax
type variable_1 = expression_1,
variable_2 = expression_2, …;
Simple Screen Output
System.out.println("The count is " + count);
Examples
865000000.0 can be written as 8.65e8
0.000483 can be written as 4.83e-4
uppercase letters A, B, C, …
lowercase letters a, b, c, …
punctuation period, semi-colon, …
digits 0, 1, 2, …
special symbols &, |, \, …
control characters carriage return, tab, ...
Boolean
• A boolean value represents a true or false condition
• The reserved words true and false are the only valid
values for a boolean type
+ (addition)
5 common arithmetic operators
- (subtraction or negation)
* (multiplication)
/ (division)
% (modulus, a.k.a. remainder)
58
Evaluating expressions When your Java program executes and encounters a line with an
expression, the expression is evaluated (its value is computed).
When an expression contains more than one operator of the same kind,
it is evaluated left-to-right.
Example: 1 + 2 + 3 is (1 + 2) + 3 which is 6
Example: 1 - 2 - 3 is (1 - 2) - 3 which is -4
(not the same as 1 - (2 - 3) which is 2)
59
Sample Expressions
Some Arithmetic Expressions in Java
Integer division with /
Strangely, 14 / 4 evaluates to 3, not 3.5.
• In Java, when we divide integers, the result is also an integer: the integer
quotient.
• The integer quotient of dividing 14 by 4 is 3.
The integer remainder of dividing 14 by 4 is 2.
• Imagine that you were doing long division:
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
61
Integer remainder with %
The % operator computes the remainder from a division of integers.
• Example: 14 % 4 is 2
• Example: 218 % 5 is 3
3 43
4 ) 14 5 ) 218
12 20
2 18
15
3
What are the results of the following expressions?
• 45 % 6
• 2 % 2
• 8 % 20
• 11 % 0
62
Applications of % operator
What expression obtains the last digit (units place) of a number?
Example: From 230857, obtain the 7.
63
Operator precedence
How does Java evaluate 1 + 3 * 4? Is it (1 + 3) * 4, or is it 1
+ (3 * 4)?
64
Precedence Rules
• The binary arithmetic operators *, /, and %,
have lower precedence than the unary operators
+, -, ++, --, and !, but have higher
precedence than the binary arithmetic operators
+ and -.
• When binary operators have equal precedence,
the operator on the left acts before the
operator(s) on the right.
Precedence Rules
• When unary operators have equal precedence,
the operator on the right acts before the
operation(s) on the left.
• Even when parentheses are not needed, they can
be used to make the code clearer.
balance + (interestRate * balance)
• Spaces also make code clearer
balance + interestRate*balance
but spaces do not dictate precedence.
Precedence Rules
Precedence examples
•1 * 2 + 3 * 5 / 4 1 + 2 / 3 * 5 - 4
• \_/ \_/
| |
2 + 3 * 5 / 4
1 + 0 * 5 - 4
• \_/
|
\___/
2 + 15 / 4 |
• \___/ 1 + 0 - 4
| \______/
2 + 3 |
• \________/ 1 - 4
| \___/
5
|
-3
68
Precedence questions
What values result from the following expressions?
• 9 / 5
• 695 % 20
• 7 + 6 * 5
• 7 * 6 + 5
• 248 % 100 / 5
• 6 * 3 - 9 / 4
• (5 - 7) * 4
• 6 + (18 % (17 - 12))
69
Real numbers (double)
• The expressions we have seen so far used integers (type int), but
Java also can manipulate real numbers with a decimal point (type
double).
Examples: 6.022 -15.9997 42.0 2.143e17
• The same rules of precedence that apply to integers also apply to real
numbers.
( ) before * / % before + -
70
Real number example
• 2.0 * 2.4 + 2.25 * 4.0 / 2.0
• \___/
|
4.8 + 2.25 * 4.0 / 2.0
• \___/
|
4.8 + 9.0 / 2.0
• \_____/
|
4.8 + 4.5
• \____________/
|
71 9.3
Real number precision
Consider the following statement:
System.out.println((35.0 + 22.4 + 11.9) / 3.0);
72
Mixing integers and reals
• When a Java operator is used on an integer and
a real number, the result is a real number.
73
Mixed types example
• 2.0 + 10 / 3 * 2.5 - 6 / 4
• \___/
|
2.0 + 3 * 2.5 - 6 / 4
• \_____/
|
2.0 + 7.5 - 6 / 4
• \_/
|
2.0 + 7.5 - 1
• \_________/
|
9.5 - 1
• \______________/
|
8.5
74
Specialized Assignment
Operators
Assignment operators can be combined with
arithmetic operators (including -, *, /, and %,
discussed later).
amount = amount + 5;
can be written as
amount += 5;
yielding the same results.
Increment and Decrement
Operators
• Used to increase (or decrease) the value of a
variable by 1
• Easy to use, important to recognize
• The increment operator
count++ or ++count
• The decrement operator
count-- or --count
Increment and Decrement
Operators
• equivalent operations
count++;
++count;
count = count + 1;
count--;
--count;
count = count - 1;
Increment and Decrement
Operators in Expressions
• after executing
int m = 4;
int result = 3 * (++m)
result has a value of 15 and m has a value of 5
• after executing
int m = 4;
int result = 3 * (m++)
result has a value of 12 and m has a value of 5
Summary
You have become familiar with Java
primitive types (numbers, characters, etc.).