Numerical Data in Java: From Wu Chapter 3
Numerical Data in Java: From Wu Chapter 3
CSE 213
From Wu Chapter 3
Manipulating Numbers
In Java, to add two numbers x and y, we write
x + y
or
int x;
int y;
From Wu Chapter 3
Variables
When the declaration is made, memory space is
allocated to store the values of x and y.
x and y are called variables. A variable has three
properties:
A memory location to store the value,
The type of data stored in the memory location, and
The name used to refer to the memory location.
From Wu Chapter 3
i, j, k;
float
numberOne, numberTwo;
long
bigInteger;
double
bigNumber;
From Wu Chapter 3
Assignment Statements
We assign a value to a variable using an
assignment statements.
The syntax is
<variable> = <expression> ;
Examples:
sum = firstNumber + secondNumber;
avg = (one + two + three) / 3.0;
From Wu Chapter 3
firstNumber
A
int firstNumber, secondNumber;
firstNumber = 234;
B
secondNumber = 87;
Code
From Wu Chapter 3
secondNumber
234
87
State of Memory
number
35
237
A
B
C
Code
From Wu Chapter 3
State of Memory
Assigning Objects
customer
Customer
Customer
A
B
C
Code
From Wu Chapter 3
State of Memory
clemens
twain
A
Customer
C
Code
From Wu Chapter 3
State of Memory
From Wu Chapter 3
Arithmetic Operators
The following table summarizes the arithmetic
operators available in Java.
Arithmetic Expression
How does the expression
x + 3 * y
From Wu Chapter 3
Type Casting
If x is a float and y is an int, what will be the data type of
the following expression?
x * y
From Wu Chapter 3
Example
(float) x / 3;
(int) (x / y * 3.0);
From Wu Chapter 3
Constants
We can change the value of a variable. If we
want the value to remain the same, we use a
constant.
final double PI
= 3.14159;
final int
MONTH_IN_YEAR
= 12;
final short FARADAY_CONSTANT = 23060;
From Wu Chapter 3
From Wu Chapter 3
Overloaded Operator +
The plus operator + can mean two different operations,
depending on the context.
<val1> + <val2> is an addition if both are numbers. If either
one of them is a String, the it is a concatenation.
Evaluation goes from left to right.
output = test + 1 + 2;
From Wu Chapter 3
output = 1 + 2 + test;
From Wu Chapter 3
System.out.print(num);
123.45789345
System.out.print(df.format(num));
123.458
From Wu Chapter 3
From Wu Chapter 3
Scanner Methods
Method
Example
nextByte( )
nextDouble( )
nextFloat( )
nextInt( )
nextLong( )
nextShort( )
next()
byte b = scanner.nextByte( );
double d = scanner.nextDouble( );
float f = scanner.nextFloat( );
int i = scanner.nextInt( );
long l = scanner.nextLong( );
short s = scanner.nextShort( );
String str = scanner.next();
From Wu Chapter 3
num, x, y;
x = ;
y = ;
num = Math.sqrt(Math.max(x, y) + 12.4);
From Wu Chapter 3
Description
exp(a)
log(a)
floor(a)
max(a,b)
pow(a,b)
sqrt(a)
sin(a)
From Wu Chapter 3
From Wu Chapter 3
From Wu Chapter 3
From Wu Chapter 3
From Wu Chapter 3
Output
From Wu Chapter 3
Today is 9/9/2011