AP Computer Science AÜnite 1 · Using Objects and Methods
Primitive Types, Variables, and Expressions
Declare variables of primitive types, evaluate arithmetic expressions with integer division and modulus, cast between types, and use compound assignment.
Primitive types on the AP exam
| Type | Stores | Example |
|---|---|---|
| int | whole numbers | int count = 7; |
| double | decimal numbers | double price = 4.99; |
| boolean | true or false | boolean done = false; |
A variable must be declared with a type before it is used. A final variable cannot be changed after it is assigned.
Arithmetic
Operators: + - / %, with the usual precedence ( / % before + -).
- Integer division truncates:
7 / 2is3, not 3.5. - If either operand is a double, the result is a double:
7 / 2.0is3.5. - Modulus gives the remainder:
17 % 5is2.n % 2 == 0tests for even numbers.
Casting
(int) 3.9is3(truncation, not rounding).(double) 7 / 2is3.5(the cast applies to 7 first).- Rounding a positive double:
(int) (x + 0.5).
Compound assignment
x += 3; means x = x + 3;. Also -=, *=, /=, %=, and x++, x--.
Integer overflow
An int holds values from Integer.MIN_VALUE to Integer.MAX_VALUE. Going past the limit wraps around.
Tracing example
int a = 10;
int b = 4;
double c = a / b;
a %= 3;
b += a;
a / b is integer division, 2, so c is 2.0. Then a is 1 and b is 5.
Quick summary
- int division truncates; use a double operand or a cast for decimals.
%gives the remainder.(int)truncates toward zero.
Konu quizi
5 soru. Geçmek için en az %80 doğru gerekiyor; geçince sonraki konu açılır.
Quizi çözüp ilerlemeni kaydetmek için giriş yap. Hesap açmak ücretsiz.
Giriş yap ve quizi çöz