程序代写 COMP2021: Object-Oriented Programming – cscodehelp代写

COMP2021: Object-Oriented Programming
Java Basics

Learning Objectives
❖ After the lecture, students should be able to
➢ understand the need for names and data types in
programming languages;
➢ understand how values of different basic types are stored in Java programs;
➢ convert between decimal and binary numbers;
➢ master the operations on data of basic data types;
➢ understand how control structures influence the execution of programs; and
➢ use control structures to construct programs.

Identifiers, Names, and Basic Data Types

Variable Declaration
❖ Identifier
➢ A sequence of characters that consist of letters, digits,
underscores (_), and dollar signs ($)
▪ Start with a letter, an underscore (_), or a dollar sign ($) ▪ Cannot be a reserved word
▪ Can be of any length
➢ Variables and method names: camelCase
➢ Class names: capitalized camelCase
➢ Constants: all in upper case and connected using underscores final double MINIMUM_HEALTH = 0;
double sideLength = 10;
class BoardGame {…}

float: 3.73062899E15
double: 2.0721738140865223E122
short: 22868
int: 1498681292
long: 6436787136929482322

Java Primitive Data Types
true or false
Unicode character (Unsigned integer)
u0000 to uFFFF
Signed integer
-128 to 127
Signed integer
-32768 to 32767
Signed integer
-2147483648 to 2147483647
Signed integer
-9223372036854775808 to 9223372036854775807
floating point
±1.4E-45 to ±3.4028235E+38
floating point
±4.9E-324 to ±1.7976931348623157E+308
Integer values Real values

Number Systems

Integer Types
❖ Integer types
➢ byte/char/short/int/long ➢ signed/unsigned
➢ Unsigned: only positive values ▪ All bits expressing the magnitude
➢ Signed: positive or negative values
▪ Signed Magnitude: Left bit (Most-Significant Bit, MSB) as the sign
bit, the rest bits to express the magnitude
▪ Two’s complement: 2n – N for negative values, where n is the number of bits and N is the magnitude

Integer Values
Signed magnitude
Two’s Complement
Signed magnitude
Two’s Complement
❖ Benefits of Two’s complement ➢ One representation of zero ➢ Subtraction by Addition
= x – y + 2n (n bit encoding) = x + (2n – y)
= x + (-y)

Conversion between Integer Types
❖ Between signed and unsigned
➢ Preserve the bit pattern, use different interpretations
❖ Widening
➢ Sign-extend
❖ Narrowing
➢ Discard the high order bits
First make the size (i.e., the number of bits) match through widening or narrowing.
0110signed = 610 <=> 0110unsigned = 610 1010signed = -610 <=> 1010unsigned = 1010
0110signed = 610 => 00000110signed = 610 1010signed = -610 => 11111010signed = -610
00001010signed = 1010 => 1010signed = -610 11110010signed = -1410 => 0010signed = 210
Then change the interpretation when necessary.

Floating-Point Types
❖ Floating-point types ➢ float and double
❖ Scientific notation
Magnitude = 2Exponent * 1.Mantissa
Sign Exponent Implicit bit
+1010001.1101 <-6 -111.000011 <-2 +0.00000111001 6-> -0.001110011 3->
+2 -2 +2 -2
1. 1. 1. 1.
01000111001 11000011 11001 110011
❖ IEEE standards for floating-point representation float
Sign Exponent Excess 127
Sign Exponent Excess 1023

Range vs. Precision
➢ Integer:
▪ Two’s complement
➢ Floating point
▪ Sign: 1 bit; Exponent: 6 bits (excess 25-1); Mantissa: 1 bit
Integer to floating point: Nearest value Floating point to integer: Round towards zero
(-1.2: -1; 1.2: 1)
10000000 … 11111111 00000000 00000001 … 01111111
-27 … -1 0 1 … 27-1
000000 … 011111 … 111111
-31 ~ 32 -1.5*232 ~ +1.5*232
Range -128 ~ 127
Integer Values
… -2, -1, 0, 1, 2, …
…, -1, 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, …

Reading from the Keyboard
❖ In coursework
nextByte()
nextShort()
nextLong()
nextFloat()
Scanner input = new Scanner(System.in); int value = input.nextInt();
23 // 23 will be read into value
nextDouble()
Description
Reads an integer of the byte type
Reads an integer of the short type
Reads an integer of the int type
Reads an integer of the long type
Reads a number of the float type
Reads a number of the double type
❖ In practice
➢ Do not use Scanner together with System.in;
➢ Always first read the input as a string, then parse the string.
String str = input.nextLine();

Numeric Operators
Side-effect
Subtraction
Multiplication
4.25 % 2.0
(int)(x / y) * y + (x % y) == x for any two values x and y (y != 0)
-7.0 % 2 =
-7.0 / 2 =

Which Day Is It?
❖ We know that the first day of 2019, i.e., Jan. 1st, 2019, is a Tuesday. Given an integer x (1 <= x <= 365), what day is the x- th day of 2019? (1 for Monday, 2 for Tuesday, ..., and 0 for Sunday) ➢ Example: ▪ Input: 1; ▪ Input: 2; ▪ Input: 3; ▪ Input: 4; ▪ Input: 8; Output: 2 Output: 3 Output: 4 Output: 5 Side-effect: modifications to the state (i.e., the memory) of the program. More Operators ❖ Assuming i has value 1 var op= expr;var = var op (expr); Side-effect Addition assignment Subtraction assignment Multiplication assignment Division assignment Remainder assignment Preincrement Postincrement Predecrement Postdecrement int i = 3, j = 3; // what are i and j’s values afterwards ? i = ++j; i = j++; i = (j += 2); i += j + 1; Assignment Expressions and Assignment Statements ❖ Prior to Java 2, all the expressions can be used as statements. ❖ Since Java 2, only the following types of expressions can be statements: variable = expression; variable op= expression; ++variable; variable++; --variable; variable--; Numeric Type Conversion ❖ Consider the following statements: byte i = 100; long k = i * 3 + 4; // 3.1 is of type double. To double d = i * 3.1 + k / 2; // get a float, use 3.1f. ❖ When performing a binary operation involving two operands of different types, convert the operands: ➢ If one of the operands is double, the other is converted into double. ➢ Otherwise, if one of the operands is float, the other is converted into float. ➢ Otherwise, if one of the operands is long, the other is converted into long. ➢ Otherwise, both operands are converted into int. Numeric Type Conversion (Cont’d) byte, short, int, long, float, double ❖ Implicit double d = 3; ❖ Explicit (casting) ❖ Attention ➢ Precision vs. Range range larger // type widening int i = (int)3.5; // type narrowing int i = 5 / 2.0; // error! ➢ Augmented assignment int x = 1234567890; float y = x; int z = (int) y; // z is 1234567936 short x = 2; x = x + 1.1; // x = (short)(x + 1.1) // error! // OK! Common Errors ❖ Integer Overflow int value = 2147483647 + 1; // value will be -2147483648 long longValue = 2147483649L; // Error: 2147483649 ❖ Round-off Errors float f = 0.1f; System.out.println(1.0 - f); // will print 0.8999999985098839 ❖ Unintended Integer Division int x = 1, y = 2; double z = (x + y) / 2; System.out.println(z); // will print 1.0 The boolean Type and Operators ❖ Use a boolean value to denote true or false boolean b = (1 > 2);
❖ Suppose we have
Less than or equal to
Greater than
Greater than or equal to
Not equal to
int radius = 1;
radius < 0 radius <= 0 radius > 0
radius >= 0
radius == 0
radius != 0
Side-effect

Logical Operators
Side-effect
true && true
true && false
false && true
false && false
true || true
true || false
false || true
false || false
Exclusive or
true ^ true
true ^ false
false ^ true
false ^ false

Short Circuit Logical Operators
❖ Short circuit evaluation
➢ If the value of the left operand is enough to decide the result of the logical operator, the right operand will not be evaluated
int x = 1, y = 2;
boolean b = x < 0 && y++ > 2; System.out.println(x + “,” + y);

Bitwise and Bit Shift Operators
❖ Perform bitwise and bit shift operations on integral types
byte b1 = (byte)0B10100001, b2 = (byte)0B00100000; System.out.println(Integer.toBinaryString((byte)~b1));
Side-effect
bitwise complement
0B01011110
Bitwise AND
(byte)(b1 & b2)
0B00100000
Bitwise OR
(byte)(b1 | b2)
0B10100001
Signed right shift
(byte)(b1 >> 2)
0B11101000
Signed left shift
(byte)(b1 << 2) 0B10000100 Unsigned right shift (byte)(b1 >>> 2)
0B00101000
What if “(byte)” is removed from the output statement?

Eager Logical Operators
❖ Eager evaluation
➢ Both operands are always evaluated first, then the result of
the operator is computed ➢ &, |
int x = 1, y = 2;
boolean b = x < 0 & y++ > 2; System.out.println(x + “,” + y);

Conditional Expressions
boolean-expression ? exp1 : exp2
❖ If boolean-expression evaluates to true, then the value of the whole expression is that of exp1; otherwise, that of exp2.
if (num % 2 == 0)
System.out.println(num + “is even”);
// is equivalent to the following
System.out.println(
(num % 2 == 0)? num + “is even” : num + “is odd”);
System.out.println(num + “is odd”);

Java Operator Precedence Table
Description
Associativity
[] . () ++ —
access array element access object member invoke a method post-increment post-decrement
left to right
++ — + – ! ~
pre-increment pre-decrement unary plus unary minus logical NOT bitwise NOT
right to left
cast object creation
right to left
multiplicative
left to right

Java Operator Precedence Table (Cont’d)
Description
Associativity
additive string concatenation
left to right
left to right
instanceof
relational type comparison
left to right
left to right
bitwise AND
left to right
bitwise XOR
left to right
bitwise OR
left to right
conditional AND
left to right
conditional OR
left to right
conditional
right to left
= += -= *= /= %=
&= ^= |= <<= >>=
assignment
right to left

Evaluation Order
❖ Precedence
➢ When two different operators are adjacent, the operator with
the higher precedence gets evaluated first. ❖ Associativity (left to right, right to left)
➢ When two operators with the same precedence are adjacent, the operators are evaluated according to their associativity.
❖ Operands are evaluated from left to right
1 * 2 + 3 is treated as (1 * 2) + 3
1 + 2 * 3 is treated as 1 + (2 * 3)
x = y = z = 7 is treated as x = (y = (z = 7))
x + y + z + 7 is treated as ((x + y) + z) + 7
int i = 1;
y = (i += 3) / (i == 1 ? 4 : 2);

How Are They Evaluated?
int a = 1, b = 2, c = 3;
what are the values of a, b, and c after executing the following statement?
a = b += c = a + 5;
❖ When in doubt, use parentheses!

Control Structures

Control Structures
❖ Selection ➢if
❖ Loop ➢ for
➢ while and do-while ❖ break and continue

if Statements
if(boolean-expression) statement1;
statement2;
if(boolean-expression) statement;
boolean-expression true false
statement1
statement2
false true
boolean-expression
Unlike in C, if conditions in Java must be of type boolean. Otherwise, you will get a compilation error.

What Does It Print?
int i = 1, j = 2, k = 3;
if(i > j) if(i > k)
System.out.println(“A”); else
System.out.println(“B”);
if(i > j); if(i > k)
System.out.println(“A”); else
System.out.println(“B”);

if(condition1) statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
statement4;
if(condition1) statement1;
else if(condition2) statement2;
else if(condition3) statement3;
statement4;
is equivalent to
if(number % 2 == 0) isEven = true;
isEven = false;
is equivalent to
is equivalent to
boolean isEven
= number % 2 == 0;
if(even == true){ statement(s);
if(even){ statement(s);

switch Statements
expr == const1 expr == const2 expr == const3 default
statements1
statements2
statements3
statements4
switch(expr){
case const1: statements1;
break; case const1: statements2;
break; case const1: statements3;
break; default: statements4;
o expr type must be char, byte, short, int, boolean, String, or enum; • Not long, float, double;
o Constants must be of the same type as expr (and use no variable); o default is optional;
• Does nothing if expr cannot match any constant and there is no default; o breaks are optional;
• Without a break, execution falls through;

break Statement and Falling Through
❖ A break statement causes control to transfer to the end of the
➢ If not present, the flow of control will continue into the next case (fall through)
n == 4 n == 3 n == 2 n == 1
switch(n){ case 1:
System.out.println(“1”); case 2:
System.out.println(“2”);
break; case 3:
System.out.println(“3”);

while Statements
false true
loop-condition
while(loop-condition) // loop body
statement;
loop-condition
statement; while(loop-condition)
// loop body

for Statements
initial-action
loop-continuation-condition false true
action-after-each-iteration
for(initial-action; loop-continuation-condition; action-after-each-iteration)
// loop body
statement;
o Both initial-action and action- after-each-iteration can be empty o loop-continuation-condition must
be of type boolean
o If loop-continuation-condition is
missing, true is used by default
// enhanced for loop
for(element-type var: element-collection) // loop body
statement;
int[] numbers = …; for(int n: numbers){
System.out.println(n); }

Which Loop to Use?
❖ while and for statements have equal expressive power ➢ You can write a loop in any of the two forms
➢ Examples
for(initial-action; loop-continuation-condition; action-after-each-iteration){
// loop body
statements; }
while(loop-condition){ // loop body
statements;
for(; loop-condition; ){ // loop body
statements; }
initial-action; while(loop-continuation-condition){
// loop body
statements;
action-after-each-iteration;

break and continue
❖ A break statement causes control to transfer to the end of the
enclosing switch/for/while/do-while structure
❖ A continue statement causes control to transfer to the end of
the body of the enclosing for/while/do-while structure
for(int i = 0; i < 6; i++){ if(i == 3){ System.out.println(i); for(int i = 0; i < 6; i++){ if(i == 3){ continue; } System.out.println(i); ❖ Identifiers, names, and basic data types ➢ Type conversion and casting (range and precision) ➢ Short circuit and eager logical operators ➢ Evaluation order ❖ Control structures ➢ Condition expressions must be of type boolean ➢ break and continue

Leave a Reply

Your email address will not be published. Required fields are marked *