Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.
lab document created by Marty Stepp, Stuart Reges and Whitaker Brand
Goals for today:
for
loops for repeating
lines of code
Java has operators for the standard mathematical
operations. Note that +
works a little differently
depending on the type of the operands.
Operator | Description |
---|---|
+ |
Addition for int s and double s, concatenation for String s
|
- |
Subtraction for int s and double s, doesn't compile for String s
|
* |
Multiplication for int s and double s, doesn't compile for String s
|
/ |
Division for Note that |
% |
Modulus for |
Generally speaking, Java tries to evaluate your expression from left to right. However, some operations happen before others. Java follows a set of rules of precedence that should be familiar from Algebra class, abbreviated PEMDAS.
Java doesn't have an exponent operator, but it does have the modulus (%) operator, so the mnemonic becomes:
Recall that Java has expressions to represent math and other computations. Expressions may use operators, which are evaluated according to rules of precedence. Every expression produces a value of a given type.
Type | Description | Expression Example | Result |
---|---|---|---|
int |
integers (up to 231 - 1) | 3 + 4 * 5 |
23 |
double |
real numbers (up to 10308) | 3.0 / 2.0 + 4.1 |
5.6 |
String |
text characters | "hi" + (1 + 1) + "u" |
"hi2u" |
Write the results of each of the following expressions. If you're stuck, ask a TA or neighbor.
12 / 5
|
2 |
|
12.0 / 5
|
2.4 |
|
12 / 5 + 8 / 4
|
4 |
|
3 * 4 + 15 / 2
|
19 |
|
42 % 5 + 3 % 16***
|
5 |
The +
operator does addition on numbers, but on
Strings
, it instead appends the two String
s
together.
System.out.println("Hello, World!"); // prints: Hello, World!
System.out.println("Hello, " + "World!"); // prints: Hello, World!
System.out.println("You " + "can" + " add" +
"many" + " Strings together"); // prints: You can addmany Strings together
System.out.println("Numbers " + 2 + "!"); // prints: Numbers 2!
Note that only the whitespace inside the quotation marks is preserved.
Using quotation marks tells Java to keep track of every character from the opening " to the closing ", including the whitespaces like spaces, tabs, and newlines.
Outside the quotes, we're back in the Java program itself, where Java doesn't notice or care about the newline we've used to format the long line of source code.
We do String
concatenation instead of addition if either of the operands are String
s.
We only add the numbers together if both of them are numbers (not String
s). Java keeps track of the type of pieces of data in your program. It treats "4"
(a String
) differently than it treats 4
(a numerical value).
Having the distinction is crucial for some tasks: if the computer always treated numerical String
s as numbers, then we wouldn't have a way to prepend an area code to the beginning of a phone number.
// All are using the + on a String -- all perform concatenation.
System.out.println("1" + "2"); // prints 12
System.out.println("1" + 2); // same, prints 12
System.out.println(1 + "2"); // same, prints 12
// Since both operators here are numbers, we do addition:
System.out.println(1 + 2); // does addition before printing -- prints 3
Note: Even though the +
operator works differently on
String
s, it still follows the same precedence rules.
Write the results of each of the following expressions.
Some of these expressions include String
concatenation. When the
result of the expression evaluates to a String
, put "quotation marks"
around the result:
"x" + 2
|
"x2" |
// Add the other quote to get the correct answer
|
|
2 + 6 + "cse 142"
|
"8cse 142" |
||
"cse 142" + 2 + 6
|
"cse 14226" |
||
1 + 9 / 2 * 2.0
|
9.0 |
||
46 / 3 / 2.0 / 3 * 4/5
|
2.0 |
continued on the next slide...
In this exercise, you'll use the Interactions Pane to quickly discover the result of some expressions that would be difficult to evaluate by hand. Copy/paste each expression below into the Interactions Pane to evaluate it, then input the answer into this slide.
123 * 456 - 789
|
55299 |
|
3.14 + 1.59 * 2.65
|
7.3535 |
|
2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2
|
1024 |
|
2 + 2 + "xyz" + 3 + 3
|
"4xyz33" |
(For the last expression, the Interactions Pane doesn't put ""
quotes around Strings when displaying results, so you must add those yourself if needed. For example, if the Interactions Pane gives you a result of abc123
, it should be written here as "abc123"
.)
Recall that you can use a variable to store the results of an expression in memory and use them later in the program.
type name; // declare name = value or expression; // assign a value ... type name = value or expression; // declare-and-initialize together
Examples:
double iPhonePrice; iPhonePrice = 299.95; int siblings = 3; System.out.println("I have " + siblings + " brothers/sisters.");
Which of the following choices is the correct syntax for declaring a real
number variable named grade
and initializing its value
to 4.0
?
Suppose you have a variable named grade
, set
to 1.6
:
double grade = 1.6; // uh-oh
Suppose later in the program's code, we want to change the value
of grade
to 4.0
. Which is the correct syntax to
do this?
Assume that we have executed the following line of code:
int x = 5;
How could we add 6 to the value currently stored in x
? A naive approach might be to try this line of code:
x + 6;
However, this line of code is an expression that results in a value: we have not altered the value of x
.
// Remember, x is a variable that is holding the value 5 x + 6; // evaluates to: 5 + 6; // and then to: 11; // But 11; isn't a statement that Java understands, // so the compiler throws an error when it sees: x + 6;
To increase the value of x
by 6, we need to actually reassign the value of x
to be the result of x + 6
:
x = x + 6; // evaluates to: x = 5 + 6; // and then to: x = 11;
Here, we've used the value of x
to calculate and store a new value into the variable x
; in this case, 11.
Suppose you have a variable named balance
, set
to 463.23
:
double balance = 463.23
Suppose later in the program's code, we want to add 5 to the account balance. Which is a correct statement to do this?
a
,
b
, and c
What are the values of a
, b
, and c
after the following statements? Write your answers in the boxes on the
right.
int a = 5; int b = 10; int c = b; a = a + 1; // a? 6 b = b - 1; // b? 9 c = c + a; // c? 16
print
vs println
There is a method called System.out.print
that is similar to
System.out.println
.
They are different in that print
doesn't add a "new line" (line break, '\n
')
character to the end of your output.
System.out.print("hello,");
System.out.print("helloooo");
// prints: hello,helloooo
System.out.println("hello,");
System.out.println("helloooo");
// prints:
// hello,
// helloooo
Every time you call System.out.println()
Java will add a "new line" character to your output.
for
loops
A for
loop repeats a group of statements a given number of times.
for (initialization; test; update) { statement(s) to repeat; }
Example:
for (int i = 1; i <= 3; i++) { System.out.println("We're number one!"); } System.out.println("/cheering");Output:
We're number one! We're number one! We're number one! /cheering
for
loops
for (initialization; test; update) { statement(s) to repeat; } |
for (int i = 1; i <= 3; i++) { System.out.println("We're number one!"); } System.out.println("/cheering"); |
The for
loop keeps executing the println
as long as the test condition is met:
int i = 1;
:: start a counter at 1i <= 3;
:: continue as long as the counter i
is less than 3{ System.out.println("We're number one!"); }
i++
:: add 1 to the counteri
is 1 bigger than it was last time through the loop
Once the test isn't true anymore, Java exits the for loop :: System.out.println("/cheering");
for
loop repeating
for(int i = 1; i <= 3; i++) { System.out.print("*"); } |
output: *** |
for(int i = 1; i <= 4; i++) { System.out.print("!-!"); } |
output: !-!!-!!-!!-! |
// Note the number/String concatenation here in the print().
// i is an int variable that holds onto a numerical value.
//
// For which numerical values does i hold as the for loop executes?
for(int i = 1; i <= 5; i++) {
System.out.print(i + "~");
}
|
output: 1~2~3~4~5~ |
for
loop!
Write a Java class called Stars
that, using a for
loop, produces the following output:
Then modify your program to instead produce the following output:
Stars
Solution
One possible solution for the first part of Stars
:
Stars
:
print
, println
, and for
loops
Write a Java class called PrintLoops
that produces the following output:
>>>> CSE142<<<<
To accomplish this:
for
loop that prints out 4 ">
" characters
System.out.println()
after the for
loop
System.out.print
to print "CSE142"for
loop to print out 4 "<
" charactersPrintLoops
SolutionOne possible solution:
public class PrintLoops { public static void main(String[] args) { // Step 1 -- print the > characters for (int i = 1; i <= 4; i++) { System.out.print(">"); } // Step 2 -- print the blank line System.out.println(); // Step 3 -- careful to use print here, not println System.out.print("CSE142"); // Step 4 -- print the < characters: for (int i = 1; i <= 4; i++) { System.out.print("<"); } } }
Nice job making it this far--labs are tough! Feel free to work with the person next to you for the remaining slides. Labs are a unique opportunity (unlike homework) to collaborate directly on ideas, and practice peer programming.
These next problems get a little more challenging as we explore earlier concepts further.
We put a lot of problems in here so that you have plenty to refer back to later when working on homework. Don't feel bad if you don't finish all of them--Brett can't finish them all in a 50 minute lab, either! :)
Forest the cat says good job!
for
loop
public class Count2 { public static void main(String[] args) { for ( fill me in! ) { System.out.println( fill me in! ); } } }
2 times 1 = 2 2 times 2 = 4 2 times 3 = 6 2 times 4 = 8
Our Practice-It! system lets you solve Java problems online.
What output is produced by the following Java program? Write the output in the box on the right side.
public class OddStuff { public static void main(String[] args) { int number = 32; for (int count = 1; count <= number; count++) { System.out.println(number); number = number / 2; } } } |
Output: 32 16 8 4 |
Write a for
loop that produces the following output:
for
loop
Write a Java program called StarSquared
that uses nested for loops (one inner, one outer) to produce the following output:
StarSquared
Part 1 Solution
One possible solution for the first problem:
StarSquared
Part 2 Solution
One possible solution for the second problem:
for
loop
practicepublic class Triangle { public static void main(String[] args) { for (int line = 1; line <= 4; line++) { for (int stars = 1; stars <= expression ; stars++) { System.out.print("*"); } System.out.println(); } } }
continued on the next slide...
We want to produce the following output:
******* ***** *** *
Fill in the table below indicating how many stars appear on each line of output.
Line | Stars |
---|---|
1
|
7 |
2
|
5 |
3
|
3 |
4
|
1 |
We need an expression for the number of stars on each line of this form:
multiplier * line + constant
for (int stars = 1; stars <= expression ; stars++) {Your program should now produce the correct output. You can verify with the Output Comparison Tool.
for
loops to produce the
following output:
000111222333444555666777888999 000111222333444555666777888999 000111222333444555666777888999
99999888887777766666555554444433333222221111100000 99999888887777766666555554444433333222221111100000 99999888887777766666555554444433333222221111100000 99999888887777766666555554444433333222221111100000 99999888887777766666555554444433333222221111100000
Write a Java program in a class named SlashFigure
to produce the following output with nested for
loops. Use a loop table if necessary to figure out the expressions.
!!!!!!!!!!!!!!!!!!!!!! \\!!!!!!!!!!!!!!!!!!// \\\\!!!!!!!!!!!!!!//// \\\\\\!!!!!!!!!!////// \\\\\\\\!!!!!!//////// \\\\\\\\\\!!////////// |
|
Test your code in Practice-It! or the Output Comparison Tool.
Class constants are variables that are assigned and unchangeable throughout a program. They make it simpler to improve the flexibility of code.
Example:
Make a table of "\", "!", and "/" counts in the size 4 figure. Then, write a for loop to produce the size 4 figure. Finally, compare the loop tests for the size 4 and 7 figures, and write a for loop with a class constant that will produce a figure of any SIZE.
size 4 | size 7 |
---|---|
!!!!!!!!!!!!!! \\!!!!!!!!!!// \\\\!!!!!!//// \\\\\\!!////// |
!!!!!!!!!!!!!!!!!!!!!!!!!! \\!!!!!!!!!!!!!!!!!!!!!!// \\\\!!!!!!!!!!!!!!!!!!//// \\\\\\!!!!!!!!!!!!!!////// \\\\\\\\!!!!!!!!!!//////// \\\\\\\\\\!!!!!!////////// \\\\\\\\\\\\!!//////////// |
Test your code in the Output Comparison Tool or in PracticeIt!
If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.
You can view an exercise, type a solution, and submit it to see if you have solved it correctly.
Choose some problems from the book and try to solve them!