AP COMPUTER
SCIENCE
CHAPTER 2
STATEMENTS VS. EXPRESSIONS
⦿ A statement is a complete snippet of code that can be executed
◼ Statements are terminated by semi-colons
◼ A statement typically does not represent a value
⦿ An expression is something that has a value, including:
◼ Literals
◼ Variables
◼ Results of operators
TYPES
⦿
Every expression and value in Java has a
type.
⦿
Types differentiate how data is interpreted.
◼ Why is this necessary?
⦿
Types also dictate what operations can be
performed.
ARITHMETIC
⦿
Integers are represented in Java by the
int
type
⦿
int
is one of several primitive types in Java
◼ Primitive types are built into Java
◼ Primitives cannot have messages passed to them!
ARITHMETIC
⦿
All four basic arithmetic operations exist in
Java as operators:
◼ Addition: +
◼ Subtraction:
-◼ Multiplication: *
◼ Division: /
⦿
There is also the modulo (remainder)
operator:
ARITHMETIC
⦿
Addition, subtraction, and multiplication
work just like normal arithmetic:
System.out.println(4 + 7); // ???
System.out.println(12 – 9); // ???
System.out.println(5 * 3); // ???
⦿
These operations can be strung together:
ARITHMETIC
⦿ Division with integers gives the quotient only: System.out.println(4 / 2); // ???
System.out.println(10 / 3); // ???
System.out.println(1 / 2); // ???
⦿ The modulo operators gives the remainder: System.out.println(4 % 2); // ???
System.out.println(10 % 3); // ???
ARITHMETIC
⦿
The normal arithmetic order of operations is
followed (including parentheses):
◼ Modulo with multiplication/division
System.out.println(3 + 4 * 5); // ???
System.out.println((5 – 1) / 2); // ???
NON-INTEGERS
⦿
Real numbers are represented in Java using
the
double
type
⦿
Arithmetic on
double
s
is the same as on
int
s, with two exceptions:
◼ Division is real number division
ARITHMETIC
⦿ Exercise 1: Write a program to convert a temperature from Fahrenheit to Celsius.
⦿ Exercise 2: Write a program to print out the digits of a five digit integer, one per line.
⦿ Exercise 3: Write a program to reverse the digits of a three digit integer
◼ e.g. 123 -> 321
VARIABLES
⦿ To store data for later use, we use variables:
String myString;
myString = “Hello, world!”; System.out.println(myString);
⦿ Before using a variable, we must declare it using the following syntax:
<type> <name>;
e.g. String word;
ASSIGNMENT
⦿ Once a variable has been declared, we must assign it a value
String myString; Declaration
myString = “Hello, world!”; Assignment
⦿ Until a variable has been assigned a value, it is useless
⦿ You can combine a declaration and an assignment into one statement, called an initialization
ASSIGNMENT
⦿
Variables and assignments are independent:
String str1 = “Hello”; String str2 = str1;
str1 = “Goodbye”;
System.out.println(str2); // ???
⦿
Literals are not variables
String str;
ASSIGNMENT
⦿
Variables only hold one value at a time:
String str1 = “Hello”; String str2 = “Goodbye”; str1 = str2;
str2 = str1;
System.out.println(str1); // ???
VARIABLES
⦿ Exercise 1: Write a program to convert a temperature from Fahrenheit to Celsius.
⦿ Exercise 2: Write a program to print out the digits of a five digit integer, one per line.
⦿ Exercise 3: Write a program to reverse the digits of a three digit integer
◼ e.g. 123 -> 321
CONSOLE INPUT
⦿
Input, despite being necessary for most
useful programs, is pretty complicated
⦿
Java has numerous methods for getting
input from a bunch of different sources
◼ keyboard, local files, web pages, network resources, etc.
⦿
For now, we will focus on one simple
CONSOLE INPUT
⦿ The simplest way to read input from the keyboard is to use a Scanner and the predefined stream System.in
Scanner keyboard = new Scanner(System.in);
⦿ Once you’ve done this, you can read a line of input using the nextLine method and store the result in a String
String input = keyboard.nextLine();
⦿ To read an int, use nextInt:
int x = keyboard.nextInt();
CONSOLE INPUT
⦿ Exercise 1: Write a program to ask the user their name and then greet them by name.
Hello, what’s your name? > Brett
Nice to meet you, Brett!
⦿ Exercise 2: Write a program to ask the user for two integers and then print out their product.
Enter first number > 5
Enter second number > 7
MINI-PROJECT
MORE ON PRIMITIVES
⦿
So far, we have seen two primitive types
(
int
and
double
)
MORE ON PRIMITIVES
Type Description Range of values
byte 8-bit signed integer -128 to 127
short 16-bit signed integer -32,768 to 32,767
int 32-bit signed integer -2, 147, 483, 648 to 2, 147, 483, 647
long 64-bit signed integer -9E18 to 9E18 (approx.)
float 32-bit floating point (real number)
double 64-bit floating point (real number)
char 16-bit Unicode character (unsigned)
MORE ON PRIMITIVES
⦿
int
,
short
, and
byte
values are all simple
integers:
◼ int i = 40000;
◼ short s = 1000;
◼ byte b = 100;
⦿
long
values require an ‘
L
’ to be appended:
MORE ON PRIMITIVES
⦿
float
s require appending an ‘
f
’:
◼ float f = 3.1415927f;
⦿
double
s have an optional appended ‘
d
’:
◼ double d1 = 2.718281828d;
MORE ON PRIMITIVES
⦿ chars are enclosed in single quotes:
◼ char c1 = ‘a’; ◼ char c2 = ‘5’;
Note that this is very
different from int i = 5;
◼ char c3 = ‘ ’;
⦿ Certain special chars require an escape
sequence (just like in
strings):
MORE ON PRIMITIVES
⦿ true and false are the only boolean values, and are reserved words:
◼ boolean b1 = true; ◼ boolean b2 = false;
⦿ The result of a Boolean expression is also a
boolean value:
◼ boolean b3 = x < 5;
TYPE CONVERSION
⦿ Some primitive types can be implicitly converted to one another:
int i = 10; long l = i;
⦿ Others require a explicit conversion, called a
cast:
double d = 5.0; int i2 = (int)d;
TYPE CONVERSION
⦿
Exercise: Try out the following expressions,
and see if you can determine any rules about
mixing types:
2.0 + 3 "1" + "2" 'a' + 1
3 / 2 + 1.0 "abc" + 1 + 2'A' + 1 1.0 + 3 / 2 1 + 2 + "abc"'e' – 'a'
TYPE CONVERSION
⦿ Exercise 2: Write a Java program to print the
“alpha-index” of the first five letters of a string (A=0, B=1, … , Z = 25)
⦿ Exercise 3: Write a Java program to perform a “Caesar shift” on a five-character string.
◼ In a Caesar shift, each character is shifted forward three (A -> D, B -> E, C ->F, etc.)
COMPOUND ASSIGNMENT
⦿ Frequently in programming, we want to do something like this:
price = price * 1.09; // apply tax price = price + 2.95; // add shipping price = price – 5.00; // apply coupon
⦿ Because this is so common, Java gives us a shortcut for this kind of operation:
COMPOUND ASSIGNMENT
⦿ These operators are called compound assignment operators
⦿ There is a compound assignment operator corresponding to each arithmetic operator:
+ += - -= * *= / /= % %=
⦿ Since these are assignments, only variables can be on the left-hand side
◼ Any expression of the correct type can go on the right-hand
INCREMENT/DECREMENT
⦿ Even more common are these operations:
x = x + 1; x = x – 1;
⦿ How could we rewrite these using compound assignment?
x += 1; x -= 1;
⦿ Java lets us shortcut these operations even further with the increment and decrement operators:
INCREMENT/DECREMENT
⦿ These are called postfix operators, because the operator comes after the operand
◼ There are also prefix versions of these (++x, --x)
◼ For now, assume the prefix and postfix versions are the same, and prefer the postfix version
⦿ As with compound assignment, only variables can be the operand
COMPOUND ASSIGNMENT
⦿ Exercise 1: Write a program to calculate and print the average of three integers. Use as few variables as possible and use compound
assignment.
MINI-PROJECT
⦿ Write a Java program to track an employee’s pay at their job. Your program should ask for the number of hours the employee worked each day Monday through Friday. You should then calculate and output the following information:
◼ The total number of hours worked for the week
◼ The employee’s gross pay (at a wage of $12.50 per hour)
FOR
LOOPS
⦿ Loops are a control flow structure that allows us
to repeat code
◼ Why might this be useful?
⦿ The simplest type of loop is the for loop
for (<initialization>; <condition>; <update>) {
<statement>; <statement>;
…
<statement>;
FOR
LOOPS
⦿
The initialization is usually just that (but
doesn’t have to be).
⦿
The update is usually an assignment, and
often a compound assignment.
⦿
Most common form: counting loop:
for (int i = 0; i < n; i++) { <some operation>
FOR
LOOPS
⦿
Order of execution:
1. Execute initialization
2. Test condition
3. If condition is false, skip to step 7
4. Execute the body of the loop
5. Execute the update
6. Return to step 2 (iterate)
7. Continue with the statement after the body
FOR
LOOPS
CONDITIONS
⦿ We have the following relational operators for comparing
values:
⦿ Note that "equal to" is a double equals!!
◼ What is single equals?
⦿ Avoid using == and != with double
== Equal to
!= Not equal to
> Greater than
< Less than
FOR
LOOPS
⦿ Exercise 1: Write a Java program to read in a String and an integer from the user, then print out the String the given number of times.
⦿ Exercise 2: Write a Java program to print out the factorial of an integer input by the user.
◼ Recall that n! = n * (n-1) * (n-2) * … * 2 * 1
⦿ Exercise 3: Write a Java program to ask the user for a
NESTED
FOR
LOOPS
⦿
When we place a loop in the body of another
loop, it is called a nested loop
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 10; j++) { System.out.print("*"); }
NESTED
FOR
LOOPS
⦿
In the previous example, the outer loops runs 5
times
⦿
The inner loop runs 10 times
for each time the
outer loop runs
for (int i = 0; i < 5; i++) {
for (int j = 0; i < 10; j++) { System.out.print("*"); }
System.out.println(); }
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 10; i++) { System.out.print("*"); }
System.out.println(); }
NESTED LOOPS
⦿ Exercise 1: Write a program to produce the following using nested loops:
11111 22222 33333 44444 55555
⦿ Exercise 2: Write a program to produce the following using nested loops:
1 22 333 4444 55555