Sie sind auf Seite 1von 11

Lesson 3 - Basic Java Elements

- Expressions

Lecture B Slide 1 of 69.


Assignment Statements

• An assignment statement takes the following form


variable-name = expression;
• The expression is first evaluated
• Then, the result is stored in the variable, overwriting the
value currently stored in the variable

Lecture
CECSD B Slide 2 of 69.
Arithmetic Operators

• An operator is a mapping that maps one or more values


to a single value:
• Binary Operators:
a + b adds a and b
a - b subtracts b from a
a * b multiplies a and b
a / b divides a by b
a % b the reminder of divining a by b
• Unary Operator:
-a The negation of a

Lecture
CECSD B Slide 3 of 69.
Pounds to Kg conversion

public class PoundsToKg


{
public static void main(String[] args)
{
double weightInPounds = 200.0;
final double KILOS_IN_POUND = 0.455;
double weightInKg;

weightInKg = weightInPounds * KILOS_IN_POUND ;


System.out.println(weightInKg);
}
}

Lecture
CECSD B Slide 4 of 69.
Pounds to Kg conversion 2

public class PoundsToKg2


{
public static void main(String[] args)
{
final double KILOS_IN_POUND = 0.455;
System.out.println(200.0 * KILOS_IN_POUND);
}
}

Lecture
CECSD B Slide 5 of 69.
Integer Division
• When division is performed on integers (byte, short,
int, long), the result is truncated to an integer.

int j = 5;
double x = 5.0, y;
System.out.println(j / 2); // 2
System.out.println(x / 2.0); // 2.5
System.out.println(5 / 2); // 2
y = j / 2 ; // 2

Lecture
CECSD B Slide 6 of 69.
Complex Expressions

• Expressions can combine many operators and operands


• Examples:
x
-34
weight * 2.73
2 * PI * r
a - (7 – b)
1 + 2 + 3 + 4
(x + y) * (2 - z + (5 - q)) * -(1-x)

Lecture
CECSD B Slide 7 of 69.
Operator Precedence

• Multiplication, division, and remainder (%) have a higher


precedence than addition and subtraction.
• Operators with same precedence evaluate from left to
right.
• Parenthesis can be used to force order of evaluation.

Lecture
CECSD B Slide 8 of 69.
Operator Precedence Examples

Expression Result
10 - 7 - 1 2

10 - (7 - 1) 4

1 + 2 * 3 7

(1 + 2) * 3 9

1 - 2 * 3 + 4 * 5 15

Lecture
CECSD B Slide 9 of 69.
Conversions

• Data types can be mixed in an expression


• When the expression is evaluated one type is converted
to another
• Data is converted to a wider type in three cases
 assignment conversion
 arithmetic promotion
 casting
• Can be converted to a narrower type only by casting
• List of types from narrowest to widest:
Narrow … Wide
byte short int long float double

Lecture
CECSD B Slide 10 of 69.
Conversion Examples

double f, x;
int j;
f = 5;
f = 5.0 / 2;
f = x * j;
f = 5 / 2;
f = (float) j / 5;
j = (int) f;
j = (int) 5.0 / 2.0;

Lecture
CECSD B Slide 11 of 69.

Das könnte Ihnen auch gefallen