Objectives
- Use primitive types
- Use expressions
- Use variables and assignment statements
- Use Scanner for keyboard input
- Use for loops
- Introduce pseudocode
Assignments
- Read Chapter 2 and pp. 162-165
(subsection on Interactive Programs and Scanner Objects)
- Lab 1 Due beginning of Week 3
- Quiz 2 Available end of Week 3
- Lab 2 Due beginning of Week 4
- Quiz 3 Available end of Week 4
- Finish Project 1 (Due beginning of Week 5)
Outline
Data Types
Variables
For Loops
Managing Complexity
Data types
A
data type is a category or set of values that are
related. A data type indicates what operations can be performed
on the values. For example, numbers have different operations
from strings. Java is a strongly typed language, meaning that
the compiler requires a data type to be specified for every value.
In Java, a data type is either a
primitive type or
a
class. Classes will be discussed later.
Java has eight primitive types. We will focus on four
of them.
Primitive Type |
What It Represents |
Example Values |
int |
integers |
3, -44, 0 |
double |
real numbers |
3.14, -0.5, 25.4 |
char |
characters |
'a', '#', 'X' |
boolean |
logic |
true, false |
How does Java distinguish between an
int and
a
double? A
double has a decimal point,
while an
int does not, so
3.0 and
3
belong to different data types.
Expressions
An
expression is a value or combination of operations that
computes a value. The simplest expression is a single value,
which is also called a
literal. A complex expression can
use operators and parentheses. For example,
42 is a
literal, and
1 + 4 * 5
and
(7 + 2) * 6 / 3 are complex
expressions.
An
operator combines multiple values or expressions.
There are five arithmetic operators for combining two
ints or two
doubles.
Arithmetic Operator |
What It Does |
Examples |
|
+ |
addition |
23 + 10 is 33, |
2.3 + 1.0 is 3.3 |
- |
subtraction |
23 - 10 is 13, |
2.3 - 1.0 is 1.3 |
* |
multiplication |
23 * 10 is 230, |
2.3 * 1.0 is 2.3 |
/ |
division |
23 / 10 is 2, |
23.0 / 10.0 is 2.3 |
% |
remainder (or mod) |
23 % 10 is 3, |
23.0 % 10.0 is 3.0 |
As a program runs, its expressions are
evaluated.
We can use
System.out.println to see the result.
public class ExpressionExample {
public static void main(String[] args) {
System.out.println(23 + 10);
}
}
Activity: Print Expressions
Print out other expressions using all the
arithmetic operators with ints and
doubles.
Integer Division and Remainder
When we divide
ints, the result
is also an
int.
For example,
32 / 5 is
6,
-84 / 10 is
-8, and
156 / 100 is
1.
Dividing by
0 causes an error when your program runs.
The
% operator computes the remainder from integer
division.
For example,
32 % 5 is
2,
-84 % 10 is
-4, and
156 % 100 is
56.
At first, integer division and remainder may seem odd to you,
but they have many applications.
-
Obtain the last digit of a number: 1234 % 10
is 4.
-
Obtain the last 2 digits of a number: 1234 % 100
is 34.
-
Obtain the number without the last 2 digits: 1234 / 100
is 12.
-
See whether a number is odd: 6 % 2
is 0, 7 % 2
is 1.
Activity: Convert Minutes
Determine the expressions to convert 1000 minutes
into number of hours and the number of minutes leftover.
Precedence
Precedence is the order in which operators are evaluated.
Generally operators in an expression are evaluated from left to
right.
1 - 2 - 3 is (1 - 2) - 3 which
is -4.
8 / 4 / 2 is (8 / 4) / 2 which is 1.
However, the "multiplicative" operators
*,
/, and
%
have a higher level of precedence than the "additive" operators
+ and
-.
1 + 2 * 3 is 1 + (2 * 3) which is 7.
6 + 8 / 2 * 3 is 6 + 4 * 3 which is 6 + 12.
Also, it is possible to use
+ and
- as
"unary" operators, for example,
-3 and
+2.
Unary operators have a higher level of precedence than the
multiplicative and additive operators.
2 * - 3 is 2 * (- 3) which is -6.
- 2 * 2 + 2 is (- 2) * 2 + 2 which
is ((- 2) * 2) + 2 which
is -2.
Parentheses can force a certain order of evaluation, but
spacing has no effect.
(1 + 2) * 3 is 3 * 3 which is 9.
1+3 * 4-2 is 1 + 12 - 2 which is 11.
Activity: Precedence Examples
What values result from the following expressions?
9 / 5
695 % 20
7 + 6 * 5
7 * 6 + 5
248 % 100 / 5
6 * 3 - 9 / 4
(5 - 7) * 4
6 + (18 % (17 - 12))
Precedence Activity
Today's News: January 26
The
main lab
is open for expanded tutoring hours.
Lab 1 must be turned in Tuesday at 11:50 pm.
Mixing types
When
ints and
doubles are mixed, the result is a
double. For
example,
4.2 * 3
is
12.6. However, the conversion is per-operator,
so strange things can happen if integer division is involved.
For
example,
7 / 3 * 1.2 + 3 / 2
is
3.4, not
4.3.
Sometimes, we want to convert between
ints
and
doubles. Maybe we want to avoid integer division,
or maybe we want to obtain the integer part of a
double
(called
truncation). A
cast can be used to force a
conversion. For example,
(int) 7.7
is
7, and
(double) 7
is
7.0.
String Concatenation
String concatenation is combining two or
more strings into a longer string. The
+ operator
is used for concatenation. If a string is concatenated
with another type of value, the value is first converted to a
string. For example:
"Hello" + "World" is "HelloWorld"
"hello" + 42 is "hello42"
Seemingly strange results can occur because of precedence. Java
will try to evaluate an expression with
+ and
- from
left to right, but
*,
/, and
%
still have a higher level of precedence.
"abc" + 9 * 3 is "abc27"
"abc" + 9 + 3 is "abc93"
"abc" + 9 - 3 results in a syntax error.
String concatenation can be used with
System.out.println to
print strings and arithmetic expressions together on one line.
Remember to add spaces as needed. For example:
System.out.println("The value of pi is about " + 3.14);
Activity: The World
Write a program to print out the circumference of the
world (about 40000 kilometers) and the diameter of the world (divide
40000 by pi).
Variables
A
variable is a location of the computer's memory that is given a
name and type, and can store a value.
To use a variable in Java, you must first
declare and
initialize the variable. Then, every statement afterwards
that is within the
scope of the variable can use the
value of the variable or store a different value in the variable.
Consider the following program for computing the body mass index.
public class BMI1 {
public static void main(String[] args) {
// declare variables
double height;
double weight;
double bmi;
// initialize variables
height = 70.0;
weight = 195.0;
bmi = weight / (height * height) * 703.0;
// use values of variables
System.out.println("Height is " + height);
System.out.println("Weight is " + weight);
System.out.println("Body mass index is " + bmi);
}
}
Declarations
The program declares three variables. Their names are
height,
weight, and
bmi. Their type
is
double, meaning that they can store
double
values. After they are declared, the computer gives each
variable a location, but they have no value.
In general, a variable
declaration allocates memory for a new
variable with a given name and type. A declaration can be made
with the syntax:
type name;
For example, here is how to declare the
names
lucy,
linus, and
snoopy as the
types
int,
char, and
boolean, respectively.
int lucy;
char linus;
boolean snoopy;
Book: Multiple Declarations
Find out how to declare the three double
variables of the BMI1 program in one statement.
Note: In this class we will not put more than one declaration on a line.
Assignments
The next three statements in the
BMI1 program are
assignment statements, which are used to store
values in the variables. First,
70.0 is stored in
height.
height |
70.0 |
|
weight |
? |
|
bmi |
? |
Next,
195.0 is stored in
weight.
height |
70.0 |
|
weight |
195.0 |
|
bmi |
? |
Finally,
weight / (height * height) * 703.0 is evaluated
using the current values of
weight and
height,
and that value is stored in
bmi (note that the value
for
bmi is not exact even though there are 17 digits; more
about this in later weeks).
height |
70.0 |
|
weight |
195.0 |
|
bmi |
27.976530612244897 |
In general, an
assignment first evaluates the expression to the
right of the
= sign and then stores the value into the
variable on the left. An assignment can be made with the syntax:
variable = expression;
Book: Declare and Initialize
Find out how to declare and initialize a
variable in a single statement.
Using Variables
We already used
height and
weight for
assigning a value to
bmi. The last three statements
of the
BMI1 program report the values of these variables and
produce the following output:
Height is 70.0
Weight is 195.0
Body mass index is 27.976530612244897
Activity: Add to BMI1
Add statements to the BMI1 program to
change the values of the variables and report the new values
of the variables.
Activity: Trace Product
Keep track of the values of the variables and determine the
output of the following program.
public class Product {
public static void main(String[] args) {
// declare variables
int x;
int y;
int product;
// some assignments
x = 2;
y = 10;
x = 3;
product = x * y;
y = 100;
// report values
System.out.println("x is " + x);
System.out.println("y is " + y);
System.out.println("product is " + product);
// another assignment
x = 4;
}
}
Using Variables Activity
Adjusting the Value of a Variable
Often, we want to modify the value of a variable by
incrementing (adding one to) or
decrementing
(subtracting one from) its value, or: add, subtract, multiply, or
divide a variable by a certain amount.
Activity: Assignment Statements
What is the effect of each assignment statement below?
x = x + 1;
a = a - 1;
y = y + 2;
b = b - 2;
z = z * 2;
c = c / 2;
Suppose the above assignment statements are in the middle of
a program that has no syntax errors.
What must be true about other parts of the program?
Java has shortcuts that are equivalent to the above statements.
Original Statement | Shortcut |
x = x + 1;
a = a - 1;
y = y + 2;
b = b - 2;
z = z * 2;
c = c / 2;
|
x++;
a--;
y += 2;
b -= 2;
z *= 2;
c /= 2;
|
Using Scanner to Input Values from the Keyboard
In the
BMI1 program, we need to modify the program to
to compute the body mass index for different heights and
weights.
A better solution is to allow the user to
input values.
The
BMI2 program shows how this can be done.
// We need a Java utility (the Scanner class) for keyboard input.
import java.util.*;
public class BMI2 {
// set up a class constant named CONSOLE to read from the keyboard
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
// declare variables
double height;
double weight;
double bmi;
// get values from keyboard, store them in variables
System.out.println("Enter height:");
height = CONSOLE.nextDouble();
System.out.println("Enter weight:");
weight = CONSOLE.nextDouble();
// compute BMI and store it in a variable
bmi = weight / (height * height) * 703;
// Print values and BMI
System.out.println("Height is " + height);
System.out.println("Weight is " + weight);
System.out.println("BMI is " + bmi);
}
}
The important new elements in this program are:
-
The import statement tells Java we want to use
its java.util package. The Scanner class
is part of this package.
-
The statement:
public static final Scanner CONSOLE = new Scanner(System.in);
declares a special kind of variable named CONSOLE of type
Scanner, creates a Scanner "object" for keyboard input, and
stores the object in the variable. This kind of variable is
called a class constant. It can be used anywhere in the
class, except that its value cannot be changed. The
name is all uppercase because that is the convention for
constants. Class constants are discussed in more detail later in
these notes.
-
The statement:
System.out.println("Enter height:");
prompts the user for information.
-
The statement:
height = CONSOLE.nextDouble();
inputs a number from the keyboard
and stores the number in the variable height.
The combination of a prompt before an input should be used whenever
you want the user to enter a value. If you want to read an
int instead of a
double, replace
CONSOLE.nextDouble() with
CONSOLE.nextInt().
Activity: Sphere
Write a program called Sphere that prints out the circumference
and diameter of a sphere as follows:
Prompt the user for the diameter of a sphere and store the value in a variable.
Choose an appropriate name for this variable.
Print out the diameter along with a descriptive message.
Then calculate the circumference of that sphere and store it in a variable.
Again, print out the calculated value with a descriptive message.
Use your program to find the circumference of a sphere from its diameter.
When you have this working, also calculate the volume of the sphere.
(You can use Google to find the formula.)
Use your program to find volume of a sphere of diameter 5.
Sphere Progress
For Loops
The following program prints the squares of the first six integers.
public class PrintSquares1 {
public static void main(String[] args) {
System.out.println(1 + " squared is " + (1 * 1));
System.out.println(2 + " squared is " + (2 * 2));
System.out.println(3 + " squared is " + (3 * 3));
System.out.println(4 + " squared is " + (4 * 4));
System.out.println(5 + " squared is " + (5 * 5));
System.out.println(6 + " squared is " + (6 * 6));
}
}
This is repetitious. We can make it so that all of the print statements are
identical by using a variable.
public class PrintSquares1a {
public static void main(String[] args) {
int count;
count = 1;
System.out.println(count + " squared is " + (count * count));
count++;
System.out.println(count + " squared is " + (count * count));
count++;
System.out.println(count + " squared is " + (count * count));
count++;
System.out.println(count + " squared is " + (count * count));
count++;
System.out.println(count + " squared is " + (count * count));
count++;
System.out.println(count + " squared is " + (count * count));
}
}
This is repetitious. What we would like is have some way of
writing the print statement once, and telling the computer not only to
repeat it six times, but also how to vary the value of the variable appropriately each
time. The for loop allows us to do this.
public class PrintSquares2 {
public static void main(String[] args) {
int count;
// count from 1 to 6
for (count = 1; count <= 6; count++) {
// print a line using the current value of count
System.out.println(count + " squared is " + (count * count));
}
}
}
This program declares a variable named
count with
type
int. The "for" line tells Java to initialize
count to 1, to keep repeating as long as
count is
less than or equal to 6, and to increment
count after each
iteration (a repetition of the loop). The
{ at
the end of the line and its corresponding
} three lines below
indicate what statements are in the
body of the loop, that is, what
statements are to be repeated. The print statement uses
the
count variable to vary what is printed out in an
appropriate way. For obvious reasons,
count is
the
control variable of the for loop.
In general, the syntax of the for loop is:
for (initialization; test; update) {
statement(s)
}
A for loop is executed in the following manner:
- Perform the initialization.
- If the test is false, go to step 6.
- Execute the body of the loop, that is, the statements inside
the curly braces.
- Perform the update.
- Go to step 2.
- Execute the statement(s) after the loop.
for loops 1
Activity: Revise PrintSquares2 1
Revise the PrintSquares2 program to print the
squares from -4 to 4.
Activity: Revise PrintSquares2 2
Revise the PrintSquares2 program to input two
ints from the keyboard, store the inputs into variables, and
then print the squares from the first input to the
second input.
System.out.print
Suppose we want to print the squares on one line as follows:
To do this, we need to print one number at a time without a
newline. This can be done using
System.out.print, for
example:
public class PrintSquares3 {
public static void main(String[] args) {
int count;
// count from 1 to 6
for (count = 1; count <= 6; count++) {
// print count squared
System.out.print(count * count);
}
// print a new line
System.out.println();
}
}
Unfortunately, the above program does not print spaces between the
numbers, but you should be able to fix this either by
another
System.out.print or by concatenation. Note that
if we want to just print a newline without any other characters, we
can use
System.out.println with nothing between the
parentheses.
PrintSquares3
for Loop Variations
For loops are usually used to count from one value to another
value, but there are many common variations.
-
Declare the control variable (i in this example) in the
initialization.
// prints 1 2 3 4 5 6
for (int i = 1; i <= 6; i++) {
System.out.print(i + " ");
}
System.out.println();
-
Another way to perform a certain number of iterations is to start
counting at 0 and then go up to but not including the number of
iterations.
// prints $$$$$$$$$$
for (int j = 0; j < 10; j++) {
System.out.print("$");
}
System.out.println();
-
To count down, decrement the control variable in the update, and use
> or >= in the test.
// prints 10 9 8 7 6 5 4 3 2 1 Lift off!
for (int k = 10; k > 0; k--) {
System.out.print(k + " ");
}
System.out.println("Lift off!");
Activity: Loop Update
The update can also be any statement that modifies
the control variable. Try i += 2, j += 2,
and k -= 2 in the above loops.
Nested Loops
Consider printing the following figure one star at a time:
*
**
***
****
*****
******
We could write six for loops with a newline after each loop.
That is, we might have the following plan.
- Perform a loop that prints one star.
- Print a newline.
- Perform a loop that prints two stars.
- Print a newline.
- Perform a loop that prints three stars.
- Print a newline.
- Perform a loop that prints four stars.
- Print a newline.
- Perform a loop that prints five stars.
- Print a newline.
- Perform a loop that prints six stars.
- Print a newline.
This could be coded in the following way.
public class PrintStars1 {
public static void main(String[] args) {
for (int column = 1; column <= 1; column++) {
System.out.print("*");
}
System.out.println();
for (int column = 1; column <= 2; column++) {
System.out.print("*");
}
System.out.println();
for (int column = 1; column <= 3; column++) {
System.out.print("*");
}
System.out.println();
for (int column = 1; column <= 4; column++) {
System.out.print("*");
}
System.out.println();
for (int column = 1; column <= 5; column++) {
System.out.print("*");
}
System.out.println();
for (int column = 1; column <= 6; column++) {
System.out.print("*");
}
System.out.println();
}
}
This is clearly repetitious. We should have a variable (let's name it
row) that starts at 1 and goes up to 6.
Here is another version which is similar, but shows the pattern more clearly.
The advantage of this code is that there are 4 lines that are exactly duplicated
for each line printed.
They only differ in the value of
row.
public class PrintStars1a {
public static void main(String[] args) {
int row = 1;
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
row++;
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
row++;
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
row++;
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
row++;
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
row++;
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
}
This corresponds to the following plan.
- Perform a loop so that row goes from 1 to 6,
- Perform a loop that prints ??? stars.
- Print a newline.
Note that we have a loop within a loop. We want to print a
certain number of rows. To print a row, we want to print a
certain number of stars followed by a newline. Note that the
value of
row is also the number of stars we want to
print. Our new program is:
public class PrintStars2 {
public static void main(String[] args) {
// print six rows
for (int row = 1; row <= 6; row++) {
// print row stars and a newline
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
}
}
Activity: Print Stars
Modify the program to print
******
*****
****
***
**
*
Print Stars Activity
Managing Complexity
Consider the task of producing the following output, a 12 by 7 box
using asterisks for the sides.
************
* *
* *
* *
* *
* *
************
Pseudocode
Pseudocode is an English description of an algorithm as a
sequence of steps.
- Print 12 asterisks.
- For 5 lines:
- Print an asterisk.
- Print 10 spaces.
- Print an asterisk.
- Print 12 asterisks.
Where should "Print a newline." appear in the pseudocode?
Procedural Decomposition
As you might recall,
procedural decomposition separates a task
into subtasks. We implement each subtask with a static method.
"Print 12 asterisks" can be coded as:
public static void printAsterisks( ) {
for (int i = 1; i <= 12; i++) {
System.out.print("*");
}
System.out.println( );
}
The steps within the pseudocode's loop can be coded as:
public static void printAsteriskSpacesAsterisk( ) {
System.out.print("*");
for (int i = 1; i <= 10; i++) {
System.out.print(" ");
}
System.out.print("*");
System.out.println( );
}
The main method calls these methods as specified by the pseudocode:
public static void main(String[] args) {
printAsterisks( );
for (int i = 1; i <= 5; i++) {
printAsteriskSpacesAsterisk( );
}
printAsterisks( );
}
Activity: PrintBox
Create a class named PrintBox to test and experiment with
the above methods.
Scope
The
scope of a variable is the part of a program where the
variable exists. A
local variable is a variable declared
inside a method, which means that variable is accessible only in that
method. In addition, a local variable declared in a for loop is
accessible only in that loop.
For example, each method in the above PrintBox program has a variable
named
i. Because these variables are local, they are
considered separate variables. Otherwise, the for loop in the
main method would only have one iteration
because
printAsteriskSpacesAsterisk would have
changed
i to 11. Scope prevents a method from
interfering with the local variables of other methods.
Blocks
A block is a collection of statements, usually starting with an open brace and ending with a closing brace.
For example the main program for printing a box:
1. public static void main(String[] args) {
2. printAsterisks( );
3. for (int i = 1; i <= 5; i++) {
4. printAsteriskSpacesAsterisk( );
5. }
6. printAsterisks( );
7. }
contains two blocks, one for the main program consisting of lines 1-7 and one the for loop in lines 3-5.
The scope of a variable declared inside a block, ends at the end of the block
A
for statement also starts a block, so the
i declared
in line 3 has scope consisting of lines 3-5. This variable cannot be accessed outside this block.
When the body of a
for contains only one statement, the braces are not needed, so the above main method
can also be witten as:
public static void main(String[] args) {
printAsterisks( );
for (int i = 1; i <= 5; i++)
printAsteriskSpacesAsterisk( );
printAsterisks( );
}
Class Constants
A
class constant is a variable accessible to the whole class,
whose value can only be set when it is declared, and whose value can't
be changed while the program is running.
Suppose we want to generalize the PrintBox program so that the
dimensions of the box can be easily changed. Only the main
method needs to know the height of the box, but both of the other
methods need to know the width of the box to print the right number of
asterisks or spaces. A class constant is declared within the
class, but outside of the methods. Note that the convention for
naming constants is all capitals with underscores between words:
public class PrintBox {
public static final int BOX_HEIGHT = 7;
public static final int BOX_WIDTH = 12;
// methods go here
}
To use the class constants inside the methods, the
magic
numbers (5, 12, and 10) need to be replaced with the constants or
with variables calculated from the constants. For example, a
statement like the following should appear in the main method:
int numberOfLinesWithSpaces = BOX_HEIGHT - 2;
where
numberOfLinesWithSpaces should replace
10 in
the for loop test. Likewise, a statement like the following should
appear in the
AsteriskSpacesAsterisk method:
int numberOfSpaces = BOX_WIDTH - 2;
where
numberOfSpaces should replace
5 in the for loop test.
Activity: Modify PrintBox
Modify your PrintBox program to include and
use the above constants. Experiment with different heights
and widths.
Activity: Wavy
Apply the above techniques to create a Wavy
program that can print a figure like the following:
////////
\\\\\\\\
////////
\\\\\\\\
////////
\\\\\\\\
Printbox and Wavy