SDF III Chapter2
SDF III Chapter2
radius = 1.0;
area = radius * radius * 3.14159
System.out.println("The area is “ + area +
" for radius "+radius);
Declare x to be an
int x;
integer variable;
Declare radius to be a
double radius; double variable;
Declare a to be a
char a; character variable;
Assignment Statements
x = 1; Assign 1 to x
a = ‘A’; Assign A to a
1= x; Wrong
Computing the Area of a Circle
Method Description
nextByte() reads an integer of the byte type
9 }
10 }
Named Constants
Named Constants
1 import java.util.Scanner;
2 public class ComputeAreaWithConstant {
3 public static void main(String[] args) {
Declare a
4 final double PI = 3.14159;
constant
5 Scanner input = new Scanner(System.in);
+ Addition 34 + 1 35
% Remainder 20 % 3 2
Augmented Assignment Operators
Example
Operator Name Description
(Assume i=1)
Increment var by 1, and use
int j = ++i;
++var preincrement the new var value in the
// j is 2, i is 2
statement
Increment var by 1, but use the int j = i++;
var++ postincrement
original var value in the statement // j is 1, i is 2
Decrement var by 1, and use
int j = --i;
--var predecrement the new var value in the
// j is 0, i is 0
statement
postdecremen Decrement var by 1, and use the int j = i--;
var--
t original var value in the statement // j is 1, i is 0
Integer Division
+, -, *, /, and %
5/2 2
5.0/2 2.5
5%2 1
Type Casting
Implicit casting
Explicit casting
• int i = (int)3.0; (type
narrowing)
• int i = (int)3.9; (Fraction
part is truncated)
Undeclared/Uninitialized Variables and Unused Variables
Integer Overflow
Round-off Errors
• System.out.println(1.0 -
0.1 - 0.1 - 0.1 - 0.1 - 0.1);
• System.out.println(1.0 -
0.9);
Unintended Integer Division
1 int number1 = 1;
2 int number2 = 2;
3 double average = (number1 + number2) / 2;
4 System.out.println(average);
(a)
1 int number1 = 1;
2 int number2 = 2;
3 double average = (number1 + number2) / 2.0;
4 System.out.println(average);
(b)
Redundant Input Objects
1 import java.util.Scanner;