Week 3 - Numerical - DataAndExpression-part1
Week 3 - Numerical - DataAndExpression-part1
COMPUTATION
&
EXPRESSION
(part 1)
NUMERICAL COMPUTATION &
EXPRESSION (part 1)
• This topic focuses on:
• the declaration and use of variables
• primitive data types
• character strings
• expressions and order of precedence
Outline
Identifiers, Variables, Constants
Primitive Data Types and Assignment
Character Strings
Expressions
Identifiers
• Identifier: name of a class, variable, constant and method
• Rules for identifiers in Java:
– Can be made up of letters, digits, and the underscore (_) character
– Cannot start with a digit
– Cannot use other symbols such as ? or %
– Spaces are not permitted inside identifiers
– You cannot use reserved words
– They are case sensitive
Legal and illegal variable names
Java Language Reserve words
abstract default if private throw
boolean do implements protected
throws
break double import public transient
byte else instanceof return
try
case extends int short void
catch final interface static volatile
char finally long super while
class float native switch
const for new synchronized
continue goto package this
Identifiers
• By convention, variable names start with a lowercase letter
• By convention, class names start with an uppercase letter
• By convention, constant names are in uppercase letters
Variables
• A variable is a name for a location in memory that holds a
value
• A variable declaration specifies the variable's name and the
type of information that it will hold
int total;
int count, temp, result;
int luckyNumber;
System.out.println(luckyNumber);
// ERROR - uninitialized variable
Examples:
int count = 0;
char grade = 'A';
Initializing Variables
Syntax
type variable_1 = expression_1,
variable_2 = expression_2, …;
Constants
• A constant is an identifier that is similar to a variable except
that it holds the same value during its entire existence
• As the name implies, it is constant, not 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
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
System.out.println ();
continue
continue
X: 25
Y: 65
Z: 30050
The println Method
• In the previous examples, we invoked the println
method to print a character string
• The System.out object represents a destination (the
monitor screen) to which we can send output
object method
information provided to the method
name
(parameters)
Simple Screen Output
System.out.println("The count is " + count);
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
Copyright © 2012 Pearson Education, Inc.
Formating Exercises:
1. What is the output from each of the following print statements?
System.out.printf("%3d", 5);
System.out.printf("%3d", 12345);
System.out.printf("%5.2f", 7.24);
System.out.printf("%5.2f", 7.277);
System.out.printf("%5.2f", 123.456);
System.out.printf("%5.2f", 123.4);
System.out.printf("%-5.2f", 7.277);
System.out.printf("%-5.2f", 123.456);
\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.
//********************************************************************
+ (addition)
5 common arithmetic operators
- (subtraction or negation)
* (multiplication)
/ (division)
% (modulus, a.k.a. remainder)
59
Evaluating expressions When your Java program executes and encounters a line with an
expression, the expression is evaluated (its value is computed).
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)
60
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
62
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
63
Applications of % operator
What expression obtains the last digit (units place) of a number?
Example: From 230857, obtain the 7.
64
Operator precedence
How does Java evaluate 1 + 3 * 4? Is it (1 + 3) * 4, or is it
1 + (3 * 4)?
65
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
\___/
|
69
-3
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))
70
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
71
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
• \____________/
|
72
9.3
Real number precision
Consider the following statement:
System.out.println((35.0 + 22.4 + 11.9) / 3.0);
73
Mixing integers and reals
• When a Java operator is used on an integer and
a real number, the result is a real number.
74
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
75
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.).