Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 79

NUMERICAL

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:

"This is a string literal."


"123 Main Street"
"X"

• Every character string is an object in Java, defined by the


String class
• Every string literal represents a String object
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

System.out.println ("Whatever you are, be a good one.");

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

– The %10.2f is called a format specifier


Formating Output
-Format specifier specifies how item should be displayed
-Frequently used format type specifiers
specifier output example
%d decimal integer 200
%f a float number 35.3404
%s a string “Java”
%c a character ‘T’
%b a boolean value true
%n line separator
%e exponential 1.23e+1
Formating Output

Usage of format specifier:

%[flag][width][.precision]format type

%wd – output integer with width of w (eg. %5d)


%w.pf – output double value with width of w including decimal point
and p digits after the decimal point (eg. %10.2f)

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.
//********************************************************************

public class Facts


{
//-----------------------------------------------------------------
// Prints various facts.
//-----------------------------------------------------------------
public static void main (String[] args)
{
// Strings can be concatenated into one long string
System.out.println ("We present the following facts for your "
+ "extracurricular edification:");

System.out.println ();

// A string can contain numeric digits


System.out.println ("Letters in the Hawaiian alphabet: 12");

continue
continue

// A numeric value can be concatenated to a string


System.out.println ("Dialing code for Antarctica: " + 672);

System.out.println ("Year in which Leonardo da Vinci invented "


+ "the parachute: " + 1515);

System.out.println ("Speed of ketchup: " + 40 + " km per year");


}
}
Output
continue
We present the following facts for your extracurricular edification:
// A numeric value can be concatenated to a string
Letters in the Hawaiian ("Dialing
System.out.println alphabet: code
12 for Antarctica: " + 672);
Dialing code for Antarctica: 672
Year System.out.println
in which Leonardo da Vinciininvented
("Year the parachute:
which Leonardo da Vinci1515
invented "
Speed of ketchup: 40 km per year
+ "the parachute: " + 1515);

System.out.println ("Speed of ketchup: " + 40 + " km per year");


}
}
String Concatenation
• The + operator is also used for arithmetic addition

• The function that it performs depends on the type of the


information on which it operates
• If both operands are strings, or if one is a string and one is
a number, it performs string concatenation
• If both operands are numeric, it adds them

• The + operator is evaluated left to right, but parentheses


can be used to force the order
• See Addition.java
//********************************************************************
// Addition.java Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************

public class Addition


{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);

System.out.println ("24 and 45 added: " + (24 + 45));


}
}
Output
//********************************************************************
// Addition.java Author: Lewis/Loftus
// 24 and 45 concatenated: 2445
24the
// Demonstrates and 45 added:
difference between69
the addition and string
// concatenation operators.
//********************************************************************

public class Addition


{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);

System.out.println ("24 and 45 added: " + (24 + 45));


}
}
Quick Check
What output is produced by the following?

System.out.println ("X: " + 25);


System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);
Quick Check
What output is produced by the following?

System.out.println ("X: " + 25);


System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);

X: 25
Y: 65
Z: 30050
Escape Sequences
• What if we wanted to print the quote character?

• The following line would confuse the compiler because it


would interpret the second quote as the end of the string
System.out.println ("I said "Hello" to you.");

• An escape sequence is a series of characters that


represents a special character
• An escape sequence begins with a backslash character (\)

System.out.println ("I said \"Hello\" to you.");


Escape Sequences
• Some Java escape sequences:

Escape Sequence Meaning

\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.
//********************************************************************

public class Roses


{
//-----------------------------------------------------------------
// Prints a poem (of sorts) on multiple lines.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Roses are red,\n\tViolets are blue,\n" +
"Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" +
"So I'd rather just be friends\n\tAt this point in our " +
"relationship.");
}
}
Output
//********************************************************************
Roses areAuthor:
// Roses.java red, Lewis/Loftus
//
Violets are blue,
// Demonstrates the use of escape sequences.
Sugar is sweet,
//********************************************************************
But I have "commitment issues",
public class Roses
{ So I'd rather just be friends
At this point in our relationship.
//-----------------------------------------------------------------
// Prints a poem (of sorts) on multiple lines.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Roses are red,\n\tViolets are blue,\n" +
"Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" +
"So I'd rather just be friends\n\tAt this point in our " +
"relationship.");
}
}
Quick Check
Write a single println statement that produces the
following output:
"Thank you all for coming to my home
tonight," he said mysteriously.
Quick Check
Write a single println statement that produces the
following output:
"Thank you all for coming to my home
tonight," he said mysteriously.

System.out.println ("\"Thank you all for " +


"coming to my home\ntonight,\" he said " +
"mysteriously.");
Outline
Character Strings
Variables
Primitive Data Types and Assignment
Expressions
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

data type variable name

int total;
int count, temp, result;

Multiple variables can be created in one declaration


It is an error to store a value whose type does not match the
type of the variable:
String greeting = 20; // ERROR: Types don’t match
Uninitialized Variables
• Error:

int luckyNumber;
System.out.println(luckyNumber);
   // ERROR - uninitialized variable

An Uninitialized Object Variable


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
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

final int MIN_HEIGHT = 69;


Constants
• Constants are useful for three important reasons

• First, they give meaning to otherwise unclear literal values


– Example: MAX_LOAD means more than the literal 250

• Second, they facilitate program maintenance


– If a constant is used in multiple places, its value need only be set in
one place

• Third, they formally establish that a value should not change,


avoiding inadvertent errors by other programmers
Outline
Character Strings
Variables
Primitive Data Types and Assignment
Expressions
Primitive Data
• There are eight primitive data types in Java

• Four of them represent integers:


– byte, short, int, long

• Two of them represent floating point numbers:


– float, double

• One of them represents characters:


– char

• And one of them represents boolean values:


– boolean
Primitive Data
Storage per Type (in bytes)
Numeric Primitive Data
• The difference between the numeric primitive types is their
size and the values they can store:

Type Storage Min Value Max Value

byte 8 bits -128 127


short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018

float 32 bits +/- 3.4 x 1038 with 7 significant digits


double 64 bits +/- 1.7 x 10308 with 15 significant digits
Overflo
wstorage for a variable cannot hold the result.
Example:
int oneThousand = 1000; // no problem
int oneMillion = 1000 * oneThousand; // OK
int oneBillion = 1000 * oneMillion; // OK
int threeBillion = 3 * oneBillion;
System.out.println(threeBillion); // ??

Will print out -1294976296 Why?

The result (3 billion) overflowed int capacity


Maximum value for an int is +2,147,483,647
Use a long instead of an int (or a double)
Assignment Statements
An assignment statement is used to assign a value
to a variable.
We say, "The variable
answer = 42;
named answer is
assigned a value of
42," or more simply,
"equal sign" (=) "answer is assigned
assignment operator. 42."
Assignment Statements
Syntax
variable = expression

where expression can be another variable, a


literal or constant (such as a number), or
something more complicated which combines
variables and literals using operators (such as +
and -)
Examples
amount = 3.99;
firstInitial = 'W';
score = numberOfCards + handicap;
eggsPerBasket = eggsPerBasket - 2;
Assignment Compatibilities
A value of one type can be assigned to a variable of any type further to the right
If at least one of the operands is a floating-point type and the rest are integers, the result will be a
floating point type.
The result is the rightmost type from the following list that occurs in the expression.

byte-->short -->int-->long-->float-->double

• But not to a variable of any type further to the left.

You can assign a value of type char to a variable of type int.


Assignment
Compatibilities
Java is said to be strongly typed.
You can't, for example, assign a floating point value to a
variable declared to store an integer.

Sometimes conversions between numbers are


possible.

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.

The result is used to set the value of the variable on


the left-hand side of the assignment operator.
score = numberOfCards + handicap;
eggsPerBasket = eggsPerBasket - 2;
Initializing Variables
A variable that has been declared, but no yet given
a value is said to be uninitialized.

Uninitialized class variables have the value null.

Uninitialized primitive variables may have a default


value.

It's good practice not to rely on a default value.


Initializing Variables
To protect against an uninitialized variable (and to
keep the compiler happy), assign a value at the
time the variable is declared.

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);

Outputs the sting literal “The count is "

Followed by the current value of the variable count.


e Notation
e notation is also called scientific notation or
floating-point notation.

Examples
865000000.0 can be written as 8.65e8
0.000483 can be written as 4.83e-4

The number in front of the e does not need to


contain a decimal point.
Imprecision in Floating-Point
Numbers
Floating-point numbers often are only approximations
since they are stored with a finite number of bits.

Hence 1.0/3.0 is slightly less than 1/3.

1.0/3.0 + 1.0/3.0 + 1.0/3.0 is less than 1.


Characters
• A char variable stores a single character

• Character literals are delimited by single quotes:

'a' 'X' '7' '$' ',' '\n'


• Example declarations:

char topGrade = 'A';


char terminator = ';', separator = ' ';

• Note the difference between a primitive character variable,


which holds only one character, and a String object, which
can hold multiple characters
Character Sets
• A character set is an ordered list of characters, with each
character corresponding to a unique number
• A char variable in Java can store any character from the
Unicode character set
• The Unicode character set uses sixteen bits per character,
allowing for 65,536 unique characters
• It is an international character set, containing symbols and
characters from many world languages
Characters
• The ASCII character set is older and smaller than Unicode,
but is still quite popular
• The ASCII characters are a subset of the Unicode character
set, including:

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

boolean done = false;

• A boolean variable can also be used to represent any two


states, such as a light bulb being on or off
Outline
Character Strings
Variables
Primitive Data Types and Assignment
Expressions
Expressions
expression: A data value, or a set of operations that
compute a data value.
Example: 1 + 4 * 3
• The simplest expression is a literal value.
• A more complex expression can have operators
and/or parentheses.

The values that an operator applies to are called operands.

+ (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).

The expression 3 * 4 is evaluated to obtain 12.


System.out.println(3 * 4) prints 12, not 3 * 4.
(How could we print the text 3 * 4 on the screen?)

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

• Examples: 35 / 5 is 7, 84 / 10 is 8, 156 / 100 is 1


• Dividing by 0 causes a runtime error in your program.

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.

How could we obtain the last 4 digits of a Social Security Number?


Example: From 658236489, obtain 6489.

What expression obtains the second-to-last digit (tens place) of a


number?
Example: From 7342, obtain the 4.

Can the % operator help us determine whether a number is odd?


Can it help us determine whether a number is divisible by, say, 27?

63
Operator precedence
How does Java evaluate 1 + 3 * 4? Is it (1 + 3) * 4, or is it 1
+ (3 * 4)?

precedence: Order in which operations are computed in an


expression. Multiplicative operators have a higher level of
precedence than additive operators.
* / % are evaluated before + -
In our example, * has higher precedence than +, just like on a scientific calculator,
so 1 + 3 * 4 is 13.

Parentheses can be used to force a certain order of


evaluation.
(1 + 3) * 4 is 16.
Spacing does not affect order of evaluation.
1+3 * 4-2 is 11.

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 operators we saw, + - * / % ( ) , all work for real numbers as


well.
The / produces an exact answer when used on real numbers.
• Example: 15.0 / 2.0 is 7.5

• 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);

• The mathematically correct answer should be 23.1


• Instead, the output is 23.099999999999998

The computer internally represents real numbers in an


imprecise way, so some calculations with them are slightly
incorrect.
• Later we will learn some ways to produce a better output
for examples like above.

72
Mixing integers and reals
• When a Java operator is used on an integer and
a real number, the result is a real number.

• Example: 3 * 4.2 is 12.6


• Example: 1 + 1.0 is 2.0

• The kind of number that results from a given


operator depends only on its operands, not any
other operands.

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.).

 You have learned about assignment


statements and expressions.

 You have learned about assigning a value


to variable.

You might also like