0% found this document useful (0 votes)
2 views175 pages

MA104 JavaLab Presentation

The document provides an overview of basic Java programming concepts, including syntax, data types, methods, and control flow. It compares Java with C++, highlighting Java's platform independence and object-oriented nature. Additionally, it covers practical aspects such as compiling and running Java programs, using println statements, and the importance of comments in code.

Uploaded by

avinmendi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views175 pages

MA104 JavaLab Presentation

The document provides an overview of basic Java programming concepts, including syntax, data types, methods, and control flow. It compares Java with C++, highlighting Java's platform independence and object-oriented nature. Additionally, it covers practical aspects such as compiling and running Java programs, using println statements, and the importance of comments in code.

Uploaded by

avinmendi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Building Java Programs

MA 104: ITC Workshop

Copyright 2009 by Pearson Education


Outline
 Basic Java programs
 Output with println statements
 Syntax and errors
 String literals and escape sequences
 Methods
 Data and expressions
 Loops
 Variables
 Conditional

Copyright 2009 by Pearson Education 2


Introduction

Copyright 2009 by Pearson Education


Why Java?
 When Sun Microsystems released Java in 1995, they
published a document called a “white paper” describing
their new programming language. Perhaps the key
sentence from that paper is the following:

Java: A simple, object-oriented, network-savvy,


interpreted, robust, secure, architecture neutral,
portable, high-performance, multithreaded, dynamic
language

This sentence covers many of the reasons why Java is a


good programming language

Copyright 2009 by Pearson Education 4


C++ vs Java
Comparison C++ Java
Index

Platform- platform-dependent platform-independent


independent
Mainly used for mainly used for system mainly used for
programming application programming
Object oriented both procedure and Object oriented.
object oriented Everything is an object in
Java
Multiple supports multiple Doesn’t support multiple
inheritance inheritance inheritance
Operator supports operator doesn't support operator
Overloading overloading overloading
Structure and supports structures and doesn't support structures
union unions and unions
Goto Supports the goto doesn’t support the goto
statement statement
Copyright 2009 by Pearson Education 5
Compariso
n Index
C++
C++ vs Java cont... Java

Pointers supports pointers. You supports pointer internally.


can write pointer However, you can't write the
program in C++ pointer program in java
Compiler C++ uses compiler only. Java uses compiler and
and C++ is compiled and run interpreter both. Java source
Interpreter using the compiler which code is converted into bytecode
converts source code at compilation time. The
into machine code so, interpreter executes this
C++ is platform bytecode at runtime and
dependent produces output. Java is
interpreted that is why it is
platform independent
Hardware C++ is nearer to Java is not so interactive with
hardware hardware
Call by C++ supports both call Java supports call by value only.
Value and by value and call by There is no call by reference in
Call by reference java
reference

Copyright 2009 by Pearson Education 6


Basic Java programs with
println statements

Copyright 2009 by Pearson Education


Compiling/running a program
1. Write it.
 code or source code: The set of instructions in a program.

2. Compile it.
• compile: Translate a program from one language to another.
 byte code: The Java compiler converts your code into a format
named byte code that runs on many computer types.
3. Run (execute) it.
 output: The messages printed to the user by a program.

source code byte code output


compile run

Copyright 2009 by Pearson Education 8


A Java Program
public class Hello {
public static void main(String[] args) {
[Link]("Hello, world!");
[Link]();
[Link]("This program produces");
[Link]("four lines of output");
}
}

 Its output:
Hello, world!
This program produces
four lines of output

Copyright 2009 by Pearson Education 9


Structure of a Java program
class: a program
public class name {
public static void main(String[] args) {
statement;
statement; method: a named group
... of statements
statement;
}
} statement: a command to be executed

 Every executable Java program consists of a class,


 that contains a method named main,
 that contains the statements (commands) to be executed.

Copyright 2009 by Pearson Education 10


[Link]
 A statement that prints a line of output on the console.
 pronounced "print-linn"
 sometimes called a "println statement" for short

 Two ways to use [Link] :


• [Link]("text");
Prints the given message as output.

• [Link]();
Prints a blank line of output.

Copyright 2009 by Pearson Education 11


Names and identifiers
 You must give your program a name.
public class CakeRecipe {
 Naming convention: capitalize each word (e.g. MyClassName)
 Your program's file must match exactly ([Link])
 includes capitalization (Java is "case-sensitive")

 identifier: A name given to an item in your program.


 must start with a letter or _ or $
 subsequent characters can be any of those or a number
 legal: _myName GuyBrush ANSWER_IS_42 $bling$
 illegal: me+u 49ers side-swipe Ph.D's

Copyright 2009 by Pearson Education 12


Keywords
 keyword: An identifier that you cannot use because it
already has a reserved meaning in Java.

 i.e., You may not use char or while for the name of a class.
 57 in total; 55 are in use and 2 are not in use.
Copyright 2009 by Pearson Education 13
Syntax
 syntax: The set of legal structures and commands that can
be used in a particular language.
 Every basic Java statement ends with a semicolon ;
 The contents of a class or method occur between { and }

 syntax error (compiler error): A problem in the structure


of a program that causes the compiler to fail.
Examples:
 Missing semicolon
 Too many or too few { } braces
 Illegal identifier for class name
 Class and file names do not match
 ...
Copyright 2009 by Pearson Education 14
Syntax error example
1 public class Hello {
2 pooblic static void main(String[] args) {
3 [Link]("Hello, world!")_
4 }
5 }

 Compiler output:
[Link]: <identifier> expected
pooblic static void main(String[] args) {
^
[Link]: ';' expected
}
^
2 errors

 The compiler shows the line number where it found the error.
 The error messages can be tough to understand!

Copyright 2009 by Pearson Education 15


Strings
 string: A sequence of characters to be printed.
 Starts and ends with a " quote " character.
 The quotes do not appear in the output.
 Examples:
"hello"
"This is a string. It's very long!"

 Restrictions:
 May not span multiple lines.
"This is not
a legal String."

 May not contain a " character.


"This is not a "legal" String either."

Copyright 2009 by Pearson Education 16


Escape sequences
 escape sequence: A special sequence of characters used
to represent certain special characters in a string.

\t tab character
\n new line character
\" quotation mark character
\\ backslash character

 Example:
[Link]("\\hello\nhow\tare \"you\"?\\\\");

 Output:
\hello
how are "you"?\\

Copyright 2009 by Pearson Education 17


Questions
 What is the output of the following println
statements?
[Link]("\ta\tb\tc");
[Link]("\\\\");
[Link]("'");
[Link]("\"\"\"");
[Link]("C:\the beatles\norwegian
wood.mp3");

 Write a println statement to produce this output:


/ \ // \\ /// \\\

Copyright 2009 by Pearson Education 18


Answers
 Output of each println statement:
a b c
\\
'
"""
C: he beatles
orwegian wood.mp3

 println statement to produce the line of output:


[Link]("/ \\ // \\\\ ///
\\\\\\");

Copyright 2009 by Pearson Education 19


Questions
 What println statements will generate this output?
This program prints a
quote from the Gettysburg Address.

"Four score and seven years ago,


our 'fore fathers' brought forth on
this continent a new nation."

 What println statements will generate this output?


A "quoted" String is
'much' better if you learn
the rules of "escape sequences."

Also, "" represents an empty String.


Don't forget: use \" instead of " !
'' is not the same as "

Copyright 2009 by Pearson Education 20


Answers
 println statements to generate the output:
[Link]("This program prints a");
[Link]("quote from the Gettysburg Address.");
[Link]();
[Link]("\"Four score and seven years ago,");
[Link]("our 'fore fathers' brought forth on");
[Link]("this continent a new nation.\"");

 println statements to generate the output:


[Link]("A \"quoted\" String is");
[Link]("'much' better if you learn");
[Link]("the rules of \"escape sequences.\"");
[Link]();
[Link]("Also, \"\" represents an empty String.");
[Link]("Don't forget: use \\\" instead of \" !");
[Link]("'' is not the same as \"");

Copyright 2009 by Pearson Education 21


Comments
 comment: A note written in the source code by the
programmer to make the code easier to understand.
 Comments are not executed when your program runs.
 Comment, general syntax:
// <comment text, on one line>
or,
/* <comment text; may span multiple lines> */

 Examples:
/* A comment goes here. */
/* It can even span
multiple lines. */
// This is a one-line comment.

Copyright 2009 by Pearson Education 22


Using comments
 Where to place comments:
 at the top of each file (a "comment header")
 at the start of every method (seen later)
 to explain complex pieces of code

 Comments are useful for:


 Understanding larger, more complex programs.
 Multiple programmers working together, who must understand
each other's code.

Copyright 2009 by Pearson Education 23


Comments example
/* Patty Println, CS 101, Fall 2019
This program prints lyrics from my favorite song! */
public class Washington {
// The code to print the song on the console.
public static void main(String[] args) {
// first verse
[Link](“Washington, Washington");
[Link](“6 foot 8");
[Link](“Weighs a friendly ton");

// separate the lyrics with a blank line


[Link]();

// second verse
[Link](“Opponents beware");
[Link](“Opponents beware");
}
}

Copyright 2009 by Pearson Education 24


Static methods

Copyright 2009 by Pearson Education


Static methods
 static method: A named group of statements.
 denotes the structure of a program
 eliminates redundancy by code reuse class
method A
statement
 procedural decomposition:
statement
dividing a problem into methods statement
method B
statement
 Writing a static method is like statement
adding a new command to Java. method C
statement
statement
statement
Copyright 2009 by Pearson Education 26
Using static methods
1. Design the algorithm.
 Look at the structure, and which commands are repeated.
 Decide what are the important overall tasks.

2. Declare (write down) the methods.


 Arrange statements into groups and give each group a name.

3. Call (run) the methods.


 The program's main method executes the other methods to
perform the overall task.

Copyright 2009 by Pearson Education 27


Declaring a method
Gives your method a name so it can be executed
 Syntax:
public static void name() {
statement;
statement;
...
statement;
}

 Example:
public static void printWarning() {
[Link]("This product causes cancer");
[Link]("in lab rats and humans.");
}
Copyright 2009 by Pearson Education 28
Calling a method
Executes the method's code
 Syntax:
name();

 You can call the same method many times if you like.

 Example:
printWarning();

 Output:

This product causes cancer


in lab rats and humans.
Copyright 2009 by Pearson Education 29
Program with static method
public class FreshPrince {
public static void main(String[] args) {
rap(); // Calling (running) the rap method
[Link]();
rap(); // Calling the rap method again
}

// This method prints the lyrics to my favorite song.


public static void rap() {
[Link]("Now this is the story all about how");
[Link]("My life got flipped turned upside-down");
}
}

Output:
Now this is the story all about how
My life got flipped turned upside-down

Now this is the story all about how


My life got flipped turned upside-down

Copyright 2009 by Pearson Education 30


Methods calling methods
public class MethodsExample {
public static void main(String[] args) {
message1();
message2();
[Link]("Done with main.");
}
public static void message1() {
[Link]("This is message1.");
}
public static void message2() {
[Link]("This is message2.");
message1();
[Link]("Done with message2.");
}
}
 Output:
This is message1.
This is message2.
This is message1.
Done with message2.
Done with main.

Copyright 2009 by Pearson Education 31


Control flow
 When a method is called, the program's execution...
 "jumps" into that method, executing its statements, then
 "jumps" back to the point where the method was called.

public class MethodsExample {


public static void main(String[] args) {
public static void message1() {
message1(); [Link]("This is message1.");
}

public static void message2() {


message2(); [Link]("This is message2.");
message1();

[Link]("Done with message2.");


}
[Link]("Done with main.");
public static void message1() {
} [Link]("This is message1.");
}

...
Copyright 2009 by Pearson Education 32
When to use methods
 Place statements into a static method if:
 The statements are related structurally, and/or
 The statements are repeated.

 You should not create static methods for:


 An individual println statement.
 Only blank lines. (Put blank printlns in main.)
 Unrelated or weakly related statements.
(Consider splitting them into two smaller methods.)

Copyright 2009 by Pearson Education 33


Drawing complex figures with
static methods

Copyright 2009 by Pearson Education


Static methods question
 Write a program to print these figures using methods.
______
/ \
/ \
\ /
\______/
\ /
\______/
+--------+
______
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+

Copyright 2009 by Pearson Education 35


Development strategy
______
/ \
/ \
\
\______/
/ First version (unstructured):

\ /
Create an empty program and main method.
\______/
+--------+ Copy the expected output into it, surrounding
each line with [Link] syntax.
______
/ \ Run it to verify the output.
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+

Copyright 2009 by Pearson Education 36


Development strategy 2
______
/ \
/ \
\
\______/
/ Second version (structured, with redundancy):

\ / Identify the structure of the output.


\______/
+--------+
Divide the main method into static methods
______ based on this structure.
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+

Copyright 2009 by Pearson Education 37


Output structure
______
/ \ The structure of the output:
/ \
\ / initial "egg" figure
\______/ second "teacup" figure
\ / third "stop sign" figure
\______/
+--------+
fourth "hat" figure

______ This structure can be represented by methods:


/ \
/ \ egg
| STOP | teaCup
\ /
\______/ stopSign
______ hat
/ \
/ \
+--------+

Copyright 2009 by Pearson Education 38


Program version 2
public class Figures2 {
public static void main(String[] args) {
egg();
teaCup();
stopSign();
hat();
}
public static void egg() {
[Link](" ______");
[Link](" / \\");
[Link]("/ \\");
[Link]("\\ /");
[Link](" \\______/");
[Link]();
}
public static void teaCup() {
[Link]("\\ /");
[Link](" \\______/");
[Link]("+--------+");
[Link]();
}
...

Copyright 2009 by Pearson Education 39


Development strategy 2
______
/ \
/ \
\
\______/
/ Second version (structured, with redundancy):

\ / Identify the structure of the output.


\______/
+--------+
Divide the main method into static methods
______ based on this structure.
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+

Copyright 2009 by Pearson Education 40


Output structure
______
/ \ The structure of the output:
/ \
\ / initial "egg" figure
\______/ second "teacup" figure
\ / third "stop sign" figure
\______/
+--------+
fourth "hat" figure

______ This structure can be represented by methods:


/ \
/ \ egg
| STOP | teaCup
\ /
\______/ stopSign
______ hat
/ \
/ \
+--------+

Copyright 2009 by Pearson Education 41


Program version 2
public class Figures2 {
public static void main(String[] args) {
egg();
teaCup();
stopSign();
hat();
}
public static void egg() {
[Link](" ______");
[Link](" / \\");
[Link]("/ \\");
[Link]("\\ /");
[Link](" \\______/");
[Link]();
}
public static void teaCup() {
[Link]("\\ /");
[Link](" \\______/");
[Link]("+--------+");
[Link]();
}
...

Copyright 2009 by Pearson Education 42


Program version 2, cont'd.
...
public static void stopSign() {
[Link](" ______");
[Link](" / \\");
[Link]("/ \\");
[Link]("| STOP |");
[Link]("\\ /");
[Link](" \\______/");
[Link]();
}
public static void hat() {
[Link](" ______");
[Link](" / \\");
[Link]("/ \\");
[Link]("+--------+");
}
}

Copyright 2009 by Pearson Education 43


Development strategy 3
______
/ \
/ \
\
\______/
/ Third version (structured, without redundancy):

\ / Identify redundancy in the output, and create


\______/ methods to eliminate as much as possible.
+--------+
______ Add comments to the program.
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+

Copyright 2009 by Pearson Education 44


Output redundancy
______
/
/ \
\
The redundancy in the output:
\ /
\______/ egg top: reused on stop sign, hat
egg bottom: reused on teacup, stop sign
\ /
\______/ divider line: used on teacup, hat
+--------+
______ This redundancy can be fixed by methods:
/ \ eggTop
/ \
| STOP | eggBottom
\ / line
\______/
______
/ \
/ \
+--------+

Copyright 2009 by Pearson Education 45


Program version 3
// Suzy Student, CSE 138, Spring 2094
// Prints several figures, with methods for structure and redundancy.
public class Figures3 {
public static void main(String[] args) {
egg();
teaCup();
stopSign();
hat();
}
// Draws the top half of an an egg figure.
public static void eggTop() {
[Link](" ______");
[Link](" / \\");
[Link]("/ \\");
}
// Draws the bottom half of an egg figure.
public static void eggBottom() {
[Link]("\\ /");
[Link](" \\______/");
}
// Draws a complete egg figure.
public static void egg() {
eggTop();
eggBottom();
[Link]();
}
...

Copyright 2009 by Pearson Education 46


Program version 3, cont'd.
...
// Draws a teacup figure.
public static void teaCup() {
eggBottom();
line();
[Link]();
}
// Draws a stop sign figure.
public static void stopSign() {
eggTop();
[Link]("| STOP |");
eggBottom();
[Link]();
}
// Draws a figure that looks sort of like a hat.
public static void hat() {
eggTop();
line();
}
// Draws a line of dashes.
public static void line() {
[Link]("+--------+");
}
}

Copyright 2009 by Pearson Education 47


Data and expressions

Copyright 2009 by Pearson Education


Data types
 type: A category or set of data values.
 Constrains the operations that can be performed on data
 Many languages ask the programmer to specify types

 Examples: integer, real number, string

 Internally, computers store everything as 1s and 0s


104  01101000
"hi"  01101000110101

Copyright 2009 by Pearson Education 49


Java's primitive types
 primitive types: 8 simple types for numbers, text, etc.
 Java also has object types, which we'll talk about later

Copyright 2009 by Pearson Education 50


Arithmetic operators
 operator: Combines multiple values or expressions.
 + addition
 - subtraction (or negation)
 * multiplication
 / division
 % modulus (a.k.a. remainder)

 As a program runs, its expressions are evaluated.


 1 + 1 evaluates to 2
 [Link](3 * 4); prints 12
 How would we print the text 3 * 4 ?

Copyright 2009 by Pearson Education 51


Integer division with /
 When we divide integers, the quotient is also an integer.
 14 / 4 is 3, not 3.5

3 4 52
4 ) 14 10 ) 45 27 ) 1425
12 40 135
2 5 75
54
21
 More examples:
 32 / 5 is 6
 84 / 10 is 8
 156 / 100is 1

 Dividing by 0 causes an error when your program runs.

Copyright 2009 by Pearson Education 52


Integer remainder with %
 The % operator computes the remainder from integer division.
 14 % 4 is 2
 218 % 5 is 3
What is the result?
3 43 45 % 6
4 ) 14 5 ) 218
12 20 2 % 2
2 18 8 % 20
15 11 % 0
3

 Applications of % operator:
 Obtain last digit of a number: 230857 % 10 is 7
 Obtain last 4 digits: 658236489 % 10000 is
6489
 See whether a number is odd: 7 % 2 is 1, 42 % 2 is 0

Copyright 2009 by Pearson Education 53


Precedence
 precedence: Order in which operators are evaluated.
 Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4
 But */% have a higher level of precedence than +-
1 + 3 * 4 is 13
6 + 8 / 2 * 3
6 + 4 * 3
6 + 12 is 18
 Parentheses can force a certain order of evaluation:
(1 + 3) * 4 is 16
 Spacing does not affect order of evaluation
1+3 * 4-2 is 11

Copyright 2009 by Pearson Education 54


Real numbers (type double)
 Examples: 6.022 , -42.0 , 2.143e17
 Placing .0 or . after an integer makes it a double.

 The operators +-*/%() all still work with double.


 / produces an exact answer: 15.0 / 2.0 is 7.5
 Precedence is the same: () before */% before +-

Copyright 2009 by Pearson Education 55


Mixing types
 When int and double are mixed, the result is a double.
 4.2 * 3 is 12.6
 The conversion is per-operator, affecting only its operands.
 7 / 3 * 1.2 + 3 / 2
 \_/
 2.0 + 10 / 3 * 2.5 - 6 / 4
|
2 * 1.2 + 3 / 2  \___/
 \___/ |
| 2.0 + 3 * 2.5 - 6 / 4
2.4 + 3 / 2  \_____/
 \_/ |
| 2.0 + 7.5 - 6 / 4
2.4 + 1  \_/
 \________/ |
| 2.0 + 7.5 - 1
3.4  \_________/
 3 / 2 is 1 above, not 1.5. |
9.5 - 1
 \______________/
|
8.5
Copyright 2009 by Pearson Education 56
String concatenation
 string concatenation: Using + between a string and
another value to make a longer string.
"hello" + 42 is "hello42"
1 + "abc" + 2 is "1abc2"
"abc" + 1 + 2 is "abc12"
1 + 2 + "abc" is "3abc"
"abc" + 9 * 3 is "abc27"
"1" + 1 is "11"
4 - 1 + "abc" is "3abc"

 Use + to print a string and an expression's value together.


 [Link]("Grade: " + (95.1 + 71.9) / 2);

• Output: Grade: 83.5

Copyright 2009 by Pearson Education 57


Variables

Copyright 2009 by Pearson Education


Receipt example
What's bad about the following code?
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
[Link]("Subtotal:");
[Link](38 + 40 + 30);
[Link]("Tax:");
[Link]((38 + 40 + 30) * .08);
[Link]("Tip:");
[Link]((38 + 40 + 30) * .15);
[Link]("Total:");
[Link](38 + 40 + 30 +
(38 + 40 + 30) * .08 +
(38 + 40 + 30) * .15);
}
}

 The subtotal expression (38 + 40 + 30) is repeated


 So many println statements

Copyright 2009 by Pearson Education 59


Variables
 variable: A piece of the computer's memory that is given a
name and type, and can store a value.
 Like preset stations on a car stereo, or cell phone speed dial:

 Steps for using a variable:


 Declare it - state its name and type
 Initialize it - store a value into it
 Use it - print it or use it as part of an expression

Copyright 2009 by Pearson Education 60


Declaration
 variable declaration: Sets aside memory for storing a value.
 Variables must be declared before they can be used.

 Syntax:

type name;
 The name is an identifier.

 int x; x

 double myGPA;
myGPA

Copyright 2009 by Pearson Education 61


Assignment
 assignment: Stores a value into a variable.
 The value can be an expression; the variable stores its result.

 Syntax:
name = expression;

 int x;
x = 3; x 3

 double myGPA;
myGPA = 1.0 + 2.25; myGPA 3.25

Copyright 2009 by Pearson Education 62


Using variables
 Once given a value, a variable can be used in expressions:
int x;
x = 3;
[Link]("x is " + x); // x is 3
[Link](5 * x - 1); // 5 * 3 - 1

 You can assign a value more than once:


int x; x 11
3
x = 3;
[Link](x + " here"); // 3 here

x = 4 + 7;
[Link]("now x is " + x); // now x is 11

Copyright 2009 by Pearson Education 63


Declaration/initialization
 A variable can be declared/initialized in one statement.

 Syntax:
type name = value;

 double myGPA = 3.95;


x 14

 int x = (11 % 3) + 12;


myGPA 3.95

Copyright 2009 by Pearson Education 64


Assignment and algebra
 Assignment uses = , but it is not an algebraic equation.
= means, "store the value at right in variable at left"
 x = 3; means "x becomes 3" or "x should now store 3"

 What happens here?


int x = 3;
x = x + 2; // ???
x 3
5

Copyright 2009 by Pearson Education 65


Assignment and types
 A variable can only store a value of its own type.
 int x = 2.5; // ERROR: incompatible types

 An int value can be stored in a double variable.


 The value is converted into the equivalent real number.

 double myGPA = 4;

myGPA 4.0
 double avg = 11 / 2;

 Why does avg store 5.0


and not 5.5 ? avg 5.0

Copyright 2009 by Pearson Education 66


Compiler errors
 A variable can't be used until it is assigned a value.
 int x;
[Link](x); // ERROR: x has no value

 You may not declare the same variable twice.


 int x;
int x; // ERROR: x already exists

 int x = 3;
int x = 5; // ERROR: x already exists
 How can this code be fixed?

Copyright 2009 by Pearson Education 67


Printing a variable's value
 Use + to print a string and a variable's value on one line.
 double grade = (95.1 + 71.9 + 82.6) / 3.0;
[Link]("Your grade was " + grade);

int students = 11 + 17 + 4 + 19 + 14;


[Link]("There are " + students +
" students in the course.");

• Output:
Your grade was 83.2
There are 65 students in the course.

Copyright 2009 by Pearson Education 68


Receipt question
Improve the receipt program using variables.
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
[Link]("Subtotal:");
[Link](38 + 40 + 30);
[Link]("Tax:");
[Link]((38 + 40 + 30) * .08);
[Link]("Tip:");
[Link]((38 + 40 + 30) * .15);
[Link]("Total:");
[Link](38 + 40 + 30 +
(38 + 40 + 30) * .15 +
(38 + 40 + 30) * .08);
}
}

Copyright 2009 by Pearson Education 69


Receipt answer
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
int subtotal = 38 + 40 + 30;
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;

[Link]("Subtotal: " + subtotal);


[Link]("Tax: " + tax);
[Link]("Tip: " + tip);
[Link]("Total: " + total);
}
}

Copyright 2009 by Pearson Education 70


Increment and decrement
shortcuts to increase or decrease a variable's value by 1

Shorthand Equivalent longer version


variable++; variable = variable + 1;
variable--; variable = variable - 1;

int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5

Copyright 2009 by Pearson Education 71


Modify-and-assign operators
shortcuts to modify a variable's value
Shorthand Equivalent longer version
variable += value; variable = variable + value;
variable -= value; variable = variable - value;
variable *= value; variable = variable * value;
variable /= value; variable = variable / value;
variable %= value; variable = variable % value;

x += 3; // x = x + 3;
gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;

Copyright 2009 by Pearson Education 72


Loops

Copyright 2009 by Pearson Education


Redundant repetition
 Repeating the same task multiple times can result in
redundant code:
[Link](“Nananana, Hey Jude");
[Link](“Nananana, Hey Jude");
[Link](“Nananana, Hey Jude");
[Link](“Nananana, Hey Jude");
[Link](“Nananana, Hey Jude");

 Intuition: “I want to print this line 5 times”

 for loop: control structure that instructs the computer to


execute a group of instructions repeatedly:
for (int i = 1; i <= 5; i++) { // repeat 5 times
[Link](“Nananana, Hey Jude");
}

Copyright 2009 by Pearson Education 74


Repetition over a range
 Similarly redundant task:
[Link]("1 squared = " + 1 * 1);
[Link]("2 squared = " + 2 * 2);
[Link]("3 squared = " + 3 * 3);
[Link]("4 squared = " + 4 * 4);
[Link]("5 squared = " + 5 * 5);
[Link]("6 squared = " + 6 * 6);

 Intuition: "I want to print a line for each number from 1 to 6"

 Can use for-loop with loop variable (i) in the body:


for (int i = 1; i <= 6; i++) {
[Link](i + " squared = " + (i * i));
}

 "For each integer i from 1 through 6, print ..."

Copyright 2009 by Pearson Education 75


for loop syntax
for (initialization; test; update) { header
statement;
statement;
... body
statement;
}

 Perform initialization once.


 Repeat the following:
 Check if the test is true. If not, stop.
 Execute the statements.
 Perform the update.

Copyright 2009 by Pearson Education 76


Initialization
for (int i = 1; i <= 6; i++) {
[Link](i + " squared = " + (i * i));
}

 Tells Java what variable to use in the loop


 Called a loop counter
 Can use any variable name, not just i
 Can start at any value, not just 1

Copyright 2009 by Pearson Education 77


Test
for (int i = 1; i <= 6; i++) {
[Link](i + " squared = " + (i * i));
}

 Tests the loop counter variable against a bound


 Uses comparison operators:
< less than
<= less than or equal to
> greater than
>= greater than or equal to

Copyright 2009 by Pearson Education 78


Update
for (int i = 1; i <= 6; i++) {
[Link](i + " squared = " + (i * i));
}

 Changes loop counter's value after each repetition


 Without an update, you would have an infinite loop

 Can be any expression:


for (int i = 1; i <= 9; i += 2) {
[Link](i);
}

Copyright 2009 by Pearson Education 79


Loop walkthrough
1 2 3
for (int i = 1; i <= 4; i++) {
4 [Link](i + " squared = " + (i * i));
}
[Link]("Hooray!");
5

Output:
1
1 squared = 1
2 squared = 4
3 squared = 9 2
4 squared = 16
Hooray!
4

Copyright 2009 by Pearson Education 80


Multi-line loop body
[Link]("+----+");
for (int i = 1; i <= 3; i++) {
[Link]("\\ /");
[Link]("/ \\");
}
[Link]("+----+");

 Output:
+----+
\ /
/ \
\ /
/ \
\ /
/ \
+----+

Copyright 2009 by Pearson Education 81


[Link]
 Prints without moving to a new line
 allows you to print partial messages on the same line

int highestTemp = 5;
for (int i = -3; i <= highestTemp / 2; i++) {
[Link]((i * 1.8 + 32) + " ");
}

• Output:
26.6 28.4 30.2 32.0 33.8 35.6

Copyright 2009 by Pearson Education 82


Counting down
 The update can use -- to make the loop count down.
 The test must say > instead of <

[Link]("T-minus ");
for (int i = 10; i >= 1; i--) {
[Link](i + ", ");
}
[Link]("blastoff!");

 Output:
T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff!

Copyright 2009 by Pearson Education 83


Mapping loops to numbers
for (int count = 1; count <= 5; count++) {
[Link](count + " ");
}

 Output:
1 2 3 4 5

 How could we modify the body of the loop to print:


3 6 9 12 15

for (int count = 1; count <= 5; count++) {


[Link](3 * count + " ");
}

Copyright 2009 by Pearson Education 84


Nested loops

Copyright 2009 by Pearson Education


Redundancy between loops
for (int j = 1; j <= 10; j++) {
[Link]("*");
} Output:
[Link](); **********
**********
for (int j = 1; j <= 10; j++) { **********
[Link]("*"); **********
}
[Link]();
for (int j = 1; j <= 10; j++) {
[Link]("*");
}
[Link]();
for (int j = 1; j <= 10; j++) {
[Link]("*");
}
[Link]();

Copyright 2009 by Pearson Education 86


Nested loops
 nested loop: A loop placed inside another loop.
 The inner loop's counter variable must have a different name.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 10; j++) {
[Link]("*");
}
[Link](); // to end the line
}
 Output:
**********
**********
**********
**********

 Statements in the outer loop's body are executed 4 times.


 The inner loop prints 10 stars each time it is run.

Copyright 2009 by Pearson Education 87


Nested for loop exercise
 What is the output of the following nested for loops?
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
[Link]("*");
}
[Link]();
}

 Output:
*
**
***
****

Copyright 2009 by Pearson Education 88


Nested for loop exercise
 What is the output of the following nested for loops?
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
[Link](i);
}
[Link]();
}

 Output:
1
22
333
4444

Copyright 2009 by Pearson Education 89


Complex lines
 What nested for loops produce the following output?

inner loop (repeated characters on each line)

....1
...2
..3 outer loop (loops 5 times because there are 5 lines)
.4
5

 We must build multiple complex lines of output using:


 an outer "vertical" loop for each of the lines
 inner "horizontal" loop(s) for the patterns within each line

Copyright 2009 by Pearson Education 90


Outer and inner loop
 First write the outer loop, from 1 to the number of lines.
for (int line = 1; line <= 5; line++) {
...
}

 Now look at the line contents. Each line has a pattern:


 some dots (0 dots on the last line)
 a number
....1
...2
..3
.4
5

Copyright 2009 by Pearson Education 91


Nested for loop exercise
 Make a table to represent any patterns on each line.
....1
...2 line # of dots -1 * line -1 * line + 5
..3 1 4 -1 4
.4 2 3 -2 3
5 3 2 -3 2
4 1 -4 1
5 0 -5 0

 To print a character multiple times, use a for loop.


for (int j = 1; j <= 4; j++) {
[Link]("."); // 4 dots
}

Copyright 2009 by Pearson Education 92


Nested for loop solution
 Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
[Link](".");
}
[Link](line);
}

 Output:
....1
...2
..3
.4
5

Copyright 2009 by Pearson Education 93


Nested for loop exercise
 What is the output of the following nested for loops?
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
[Link](".");
}
for (int k = 1; k <= line; k++) {
[Link](line);
}
[Link]();
}

 Answer:
....1
...22
..333
.4444
55555

Copyright 2009 by Pearson Education 94


Nested for loop exercise
 Modify the previous code to produce this output:
....1
...2.
..3..
.4...
5....

 Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
[Link](".");
}
[Link](line);
for (int j = 1; j <= (line - 1); j++) {
[Link](".");
}
[Link]();
}

Copyright 2009 by Pearson Education 95


Nested for loop exercise
 Rewrite this code to reduce redundancy

for (int i = 1; i <= 5; i++) {


[Link](i + "\t");
} Output:
[Link](); 1 2 3 4 5
for (int i = 1; i <= 5; i++) { 2 4 6 8 10
[Link](i * 2 + "\t"); 3 6 9 12 15
} 4 8 12 16 20
[Link]();
for (int i = 1; i <= 5; i++) {
[Link](i * 3 + "\t");
}
[Link]();
for (int i = 1; i <= 5; i++) {
[Link](i * 4 + "\t"){
}
[Link]();

Copyright 2009 by Pearson Education 96


Nested for loop exercise
 Answer:
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 5; j++) {
[Link]((i * j) + "\t");
}
[Link](); // to end the line
}

 Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20

Copyright 2009 by Pearson Education 97


Common errors
 Both of the following sets of code produce infinite loops:
for (int i = 1; i <= 10; i++) {
for (int j = 1; i <= 5; j++) {
[Link](j);
}
[Link]();
}

for (int i = 1; i <= 10; i++) {


for (int j = 1; j <= 5; i++) {
[Link](j);
}
[Link]();
}

Copyright 2009 by Pearson Education 98


Variable scope
 scope: The part of a program where a variable exists.
 From its declaration to the end of the { } braces
 A variable declared in a for loop exists only in that loop.
 A variable declared in a method exists only in that method.

public static void example() {


i's scope

int x = 3;
for (int i = 1; i <= 10; i++) {
[Link](x);
} x's scope
// i no longer exists here
} // x ceases to exist here

Copyright 2009 by Pearson Education 99


Scope implications
 Variables without overlapping scope can have same name.
for (int i = 1; i <= 100; i++) {
[Link]("/");
}
for (int i = 1; i <= 100; i++) { // OK
[Link]("\\");
}
int i = 5; // OK: outside of loop's scope

 A variable can't be declared twice or used out of its scope.


for (int i = 1; i <= 100 * line; i++) {
int i = 2; // ERROR: overlapping scope
[Link]("/");
}
i = 4; // ERROR: outside scope

Copyright 2009 by Pearson Education 100


Class constants
 class constant: A value visible to the whole program.
 value can only be set at declaration
 value can't be changed while the program is running

 Syntax:
public static final type name = value;
 name is usually in ALL_UPPER_CASE

 Examples:
public static final int DAYS_IN_WEEK = 7;
public static final double INTEREST_RATE = 3.5;
public static final int SSN = 658234569;

Copyright 2009 by Pearson Education 101


Parameters

Copyright 2009 by Pearson Education


Parameterization and Declaration
 parameter: A value passed to a method by its caller.
 Declaration: Stating that a method requires a parameter
in order to run
public static void name ( type name ) {
statement(s);
}

 Example:
public static void sayPassword(int code) {
[Link]("The password is: " + code);
}
 When sayPassword is called, the caller must specify
the integer code to print.
Copyright 2009 by Pearson Education 103
Passing parameters
Calling a method and specifying values for its parameters
name (expression);

 Example:
public static void main(String[] args) {
sayPassword(42);
sayPassword(12345);
}
Output:
The password is 42
The password is 12345

Copyright 2009 by Pearson Education 104


Multiple parameters
 A method can accept multiple parameters. (separate by ,
)
 When calling it, you must pass values for each parameter.
 Parameter values are distinguished by the order
 The first value written in the call corresponds to the first parameter,
etc.

 Declaration:
public static void name (type name, ..., type name) {
statement(s);
}

 Call:
methodName (value, value, ..., value);

Copyright 2009 by Pearson Education 105


Multiple parameters example
public static void main(String[] args) {
printNumber(4, 9);
printNumber(17, 6);
printNumber(8, 0);
printNumber(0, 8);
}
public static void printNumber(int number, int count) {
for (int i = 1; i <= count; i++) {
[Link](number);
}
[Link]();
}

Output:
444444444
171717171717
00000000

Copyright 2009 by Pearson Education 106


Value semantics
 value semantics: When primitive variables (int, double)
are passed as parameters, their values are copied.
 Modifying the parameter will not affect the variable passed in.

public static void strange(int x) {


x = x + 1;
[Link]("1. x = " + x);
}

public static void main(String[] args) {


int x = 23;
strange(x);
[Link]("2. x = " + x);
...
}
Output:
1. x = 24
2. x = 23

Copyright 2009 by Pearson Education 107


Return Values

Copyright 2009 by Pearson Education


Returning a value
return: To send out a value as the result of a method.
 The opposite of a parameter:
Parameters send information in from the caller to the method.

 Return values send information out from a method to its caller.
public static type name(parameters) {
statements;
...
return expression;
}
 Example:
// Returns the slope of the line between the given points.
public static double slope(int x1, int y1, int x2, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
return dy / dx;
}
Copyright 2009 by Pearson Education 109
Return examples
// Converts Fahrenheit to Celsius.
public static double fToC(double degreesF) {
double degreesC = 5.0 / 9.0 * (degreesF - 32);
return degreesC;
}

// Computes triangle hypotenuse length given its side lengths.


public static double hypotenuse(int a, int b) {
double c = [Link](a * a + b * b);
return c;
}

 You can shorten the examples by returning an expression:


public static double fToC(double degreesF) {
return 5.0 / 9.0 * (degreesF - 32);
}

Copyright 2009 by Pearson Education 110


Common error: Not storing
 It is incorrect to think that a return statement sends a
variable's name back to the calling method.
public static void main(String[] args) {
slope(0, 0, 6, 3);
[Link]("The slope is " + result); // ERROR:
} // result not defined

public static double slope(int x1, int x2, int y1, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
double result = dy / dx;
return result;
}

Copyright 2009 by Pearson Education 111


Fixing the common error
 Instead, returning sends the variable's value back.
 The returned value must be stored into a variable or used in an
expression to be useful to the caller.
public static void main(String[] args) {
double ourSlope = slope(0, 0, 6, 3);
[Link]("The slope is " + ourSlope);
}

public static double slope(int x1, int x2, int y1, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
double result = dy / dx;
return result;
}

Copyright 2009 by Pearson Education 112


Java's Math class
Method name Description
[Link](value) absolute value
[Link](value) nearest whole number
[Link](value) rounds up
[Link](value) rounds down
Math.log10(value) logarithm, base 10
[Link](value1, value2) larger of two values
[Link](value1, value2) smaller of two values
[Link](base, exp) base to the exp power
[Link](value) square root
[Link](value) sine/cosine/tangent of
[Link](value) an angle in radians Constant Description
[Link](value) E 2.7182818...
[Link](value) convert degrees to PI 3.1415926...
[Link](value) radians and back
[Link]() random double between 0 and 1

Copyright 2009 by Pearson Education 113


Calling Math methods
First write import [Link].*;
[Link](parameters)

 Examples:
double squareRoot = [Link](121.0);
[Link](squareRoot); // 11.0
int absoluteValue = [Link](-50);
[Link](absoluteValue); // 50
[Link]([Link](3, 7) + 2); // 5

 The Math methods do not print to the console.


 Each method produces ("returns") a numeric result.
 The results are used as expressions (printed, stored, etc.).

Copyright 2009 by Pearson Education 114


Quirks of real numbers
 Some Math methods return double or other non-int
types.
int x = [Link](10, 3); // ERROR: incompat. types

 Some double values print poorly (too many digits).


double result = 1.0 / 3.0;
[Link](result); // 0.3333333333333

 The computer represents doubles in an imprecise way.


[Link](0.1 + 0.2);
 Instead of 0.3, the output is 0.30000000000000004

Copyright 2009 by Pearson Education 115


Type casting
 type cast: A conversion from one type to another.
 To promote an int into a double to get exact division from /
 To truncate a double from a real number to an integer

 Syntax:
(type) expression

Examples:
double result = (double) 19 / 5; // 3.8
int result2 = (int) result; // 3
int x = (int) [Link](10, 3); // 1000

Copyright 2009 by Pearson Education 116


More about type casting
 Type casting has high precedence and only casts the item
immediately next to it.
 double x = (double) 1 + 1 / 2; // 1
 double y = 1 + (double) 1 / 2; // 1.5

 You can use parentheses to force evaluation order.


 double average = (double) (a + b + c) / 3;

 A conversion to double can be achieved in other ways.


 double average = 1.0 * (a + b + c) / 3;

Copyright 2009 by Pearson Education 117


Interactive Programs w/ Scanner

Copyright 2009 by Pearson Education


Interactive programs
 We have written programs that print console output, but
it is also possible to read input from the console.
 The user types input into the console. We capture the input and
use it in our program.
 Such a program is called an interactive program.

 Interactive programs can be challenging.


 Computers and users think in very different ways.
 Users misbehave.

Copyright 2009 by Pearson Education 119


Input and [Link]
 [Link]
 An object with methods named println and print
 [Link]
 not intended to be used directly
 We use a second object, from a class Scanner, to help us.

 Constructing a Scanner object to read console input:


Scanner name = new Scanner([Link]);
 Example:
Scanner console = new Scanner([Link]);

Copyright 2009 by Pearson Education 120


Java class libraries, import
 Java class libraries: Classes included with Java's JDK.
 organized into groups named packages
 To use a package, put an import declaration in your program.

 Syntax:
// put this at the very top of your program
import packageName.*;

 Scanner is in a package named [Link]


import [Link].*;

 To use Scanner, you must place the above line at the top of
your program (before the public class header).

Copyright 2009 by Pearson Education 121


Scanner methods
Method Description
nextInt() reads a token of user input as an int
nextDouble() reads a token of user input as a double
next() reads a token of user input as a String
nextLine() reads a line of user input as a String

 Each method waits until the user presses Enter.


 The value typed is returned.
[Link]("How old are you? "); // prompt
int age = [Link]();
[Link]("You'll be 40 in " +
(40 - age) + " years.");

 prompt: A message telling the user what input to type.

Copyright 2009 by Pearson Education 122


Example Scanner usage
import [Link].*; // so that I can use Scanner
public class ReadSomeInput {
public static void main(String[] args) {
Scanner console = new Scanner([Link]);
[Link]("How old are you? ");
int age = [Link]();
[Link](age + "... That's quite old!");
}
}

 Output (user input underlined):


How old are you? 14
14... That's quite old!

Copyright 2009 by Pearson Education 123


Input tokens
 token: A unit of user input, as read by the Scanner.
 Tokens are separated by whitespace (spaces, tabs, newlines).
 How many tokens appear on the following line of input?
23 John Smith 42.0 "Hello world" $2.50 " 19"

 When a token is not the type you ask for, it crashes.


[Link]("What is your age? ");
int age = [Link]();
Output:
What is your age? Timmy
[Link]
at [Link](Unknown Source)
at [Link](Unknown Source)
...

Copyright 2009 by Pearson Education 124


Another Scanner example
import [Link].*; // so that I can use Scanner
public class ScannerSum {
public static void main(String[] args) {
Scanner console = new Scanner([Link]);
[Link]("Please type three numbers: ");
int num1 = [Link]();
int num2 = [Link]();
int num3 = [Link]();
int sum = num1 + num2 + num3;
[Link]("The sum is " + sum);
}
}

 Output (user input underlined):


Please type three numbers: 8 6 13
The sum is 27

 The Scanner can read multiple values from one line.

Copyright 2009 by Pearson Education 125


Scanners as parameters
 If many methods read input, declare a Scanner in main
and pass it to the others as a parameter.
public static void main(String[] args) {
Scanner console = new Scanner([Link]);
int sum = readSum3(console);
[Link]("The sum is " + sum);
}
// Prompts for 3 numbers and returns their sum.
public static int readSum3(Scanner console) {
[Link]("Type 3 numbers: ");
int num1 = [Link]();
int num2 = [Link]();
int num3 = [Link]();
return num1 + num2 + num3;
}

Copyright 2009 by Pearson Education 126


Scanner BMI question
A person's body mass index (BMI) is defined to be:
weight
BMI  2
 703
height

 Write a program that produces the following output:


This program reads in data for two people
and computes their body mass index (BMI)
and weight status.
Enter next person's information:
height (in inches)? 62.5
weight (in pounds)? 130.5
Enter next person's information:
height (in inches)? 58.5
weight (in pounds)? 90
Person #1 body mass index = 23.485824
Person #2 body mass index = 18.487836949375414
Difference = 4.997987050624587

Copyright 2009 by Pearson Education 127


Scanner BMI solution
// This program computes two people's body mass index (BMI)
// and compares them. The code uses parameters and returns.
import [Link].*; // so that I can use Scanner
public class BMI {
public static void main(String[] args) {
introduction();
Scanner console = new Scanner([Link]);
double bmi1 = processPerson(console);
double bmi2 = processPerson(console);
// report overall results
[Link]("Person #1 body mass index = " + bmi1);
[Link]("Person #2 body mass index = " + bmi2);
double difference = [Link](bmi1 - bmi2);
[Link]("Difference = " + difference);
}
// prints a welcome message explaining the program
public static void introduction() {
[Link]("This program reads in data for two people");
[Link]("and computes their body mass index (BMI)");
[Link]("and weight status.");
[Link]();
}
...

Copyright 2009 by Pearson Education 128


Scanner BMI solution, cont.
...
// reads information for one person, computes their BMI, and returns it
public static double processPerson(Scanner console) {
[Link]("Enter next person's information:");
[Link]("height (in inches)? ");
double height = [Link]();
[Link]("weight (in pounds)? ");
double weight = [Link]();
[Link]();
double bmi = getBMI(height, weight);
return bmi;
}
// Computes a person's body mass index based on their height and weight
// and returns the BMI as its result.
public static double getBMI(double height, double weight) {
double bmi = weight / (height * height) * 703;
return bmi;
}
}

Copyright 2009 by Pearson Education 129


Scanner and cumulative sum
 We can do a cumulative sum of user input:
Scanner console = new Scanner([Link]);
int sum = 0;
for (int i = 1; i <= 100; i++) {
[Link]("Type a number: ");
sum = sum + [Link]();
}
[Link]("The sum is " + sum);

Copyright 2009 by Pearson Education 130


User-guided cumulative sum
Scanner console = new Scanner([Link]);
[Link]("How many numbers to add? ");
int count = [Link]();
int sum = 0;
for (int i = 1; i <= count; i++) {
[Link]("Type a number: ");
sum = sum + [Link]();
}
[Link]("The sum is " + sum);

 Output:
How many numbers to add? 3
Type a number: 2
Type a number: 6
Type a number: 3
The sum is 11

Copyright 2009 by Pearson Education 131


Cumulative sum question
 Write a program that reads two employees' hours and
displays each employee's total and the overall total hours.
 The company doesn't pay overtime; cap each day at 8 hours.
 Example log of execution:
Employee 1: How many days? 3
Hours? 6
Hours? 12
Hours? 5
Employee 1's total hours = 19 (6.3 / day)

Employee 2: How many days? 2


Hours? 11
Hours? 6
Employee 2's total hours = 14 (7.0 / day)

Total hours for both = 33

Copyright 2009 by Pearson Education 132


Cumulative sum answer
// Computes the total paid hours worked by two employees.
// The company does not pay for more than 8 hours per day.
// Uses a "cumulative sum" loop to compute the total hours.

import [Link].*;

public class Hours {


public static void main(String[] args) {
Scanner console = new Scanner([Link]);

int hours1 = processEmployee(console, 1);


int hours2 = processEmployee(console, 2);

int total = hours1 + hours2;


[Link]("Total hours for both = " + total);
}

...

Copyright 2009 by Pearson Education 133


Cumulative sum answer 2
...

// Reads hours information about an employee with the given number.


// Returns total hours worked by the employee.
public static int processEmployee(Scanner console, int number) {
[Link]("Employee " + number + ": How many days? ");
int days = [Link]();

// totalHours is a cumulative sum of all days' hours worked.


int totalHours = 0;
for (int i = 1; i <= days; i++) {
[Link]("Hours? ");
int hours = [Link]();
totalHours = totalHours + [Link](hours, 8);
}

double hoursPerDay = (double) totalHours / days;


[Link]("Employee %d's total hours = %d (%.1f / day)\n",
number, totalHours, hoursPerDay);
[Link]();
return totalHours;
}
}

Copyright 2009 by Pearson Education 134


if and if/else Statements

Copyright 2009 by Pearson Education


The if statement
Executes a block of statements only if a test is true
if (test) {
statement;
...
statement;
}

 Example:
double gpa = [Link]();
if (gpa >= 2.0) {
[Link]("Application accepted.");
}

Copyright 2009 by Pearson Education 136


The if/else statement
Executes one block if a test is true, another if false
if (test) {
statement(s);
} else {
statement(s);
}

 Example:
double gpa = [Link]();
if (gpa >= 2.0) {
[Link]("Welcome to Mars University!");
} else {
[Link]("Application denied.");
}

Copyright 2009 by Pearson Education 137


Relational expressions
 A test in an if is the same as in a for loop.
for (int i = 1; i <= 10; i++) { ...
if (i <= 10) { ...
 These are boolean expressions, seen in Ch. 5.

 Tests use relational operators:


Operator Meaning Example Value
== equals 1 + 1 == 2 true
!= does not equal 3.2 != 2.5 true
< less than 10 < 5 false
> greater than 10 > 5 true
<= less than or equal to 126 <= 100 false
>= greater than or equal to 5.0 >= 5.0 true

Copyright 2009 by Pearson Education 138


Logical operators: &&, ||, !
 Conditions can be combined using logical operators:
Operator Description Example Result

&& and (2 == 3) && (-1 < 5) false


|| or (2 == 3) || (-1 < 5) true
! not !(2 == 3) true

 Relational operators cannot be "chained" as in algebra.


2 <= x <= 10 (assume that x is 15)
true <= 10
error!
 Instead, combine multiple tests with && or ||
2 <= x && x <= 10 (assume that x is 15)
true && false
false
Copyright 2009 by Pearson Education 139
Nested if/else
Chooses between outcomes using many tests
if (test) {
statement(s);
} else if (test) {
statement(s);
} else {
statement(s);
}

 Example:
if (number > 0) {
[Link]("Positive");
} else if (number < 0) {
[Link]("Negative");
} else {
[Link]("Zero");
}

Copyright 2009 by Pearson Education 140


Nested if/else/if
 If it ends with else, one code path must be taken.
 If it ends with else if, the program might not execute any path.
if (test) {
statement(s);
} else if (test) {
statement(s);
} else if (test) {
statement(s);
}

 Example:
if (place == 1) {
[Link]("You win the gold medal!");
} else if (place == 2) {
[Link]("You win a silver medal!");
} else if (place == 3) {
[Link]("You earned a bronze medal.");
}

Copyright 2009 by Pearson Education 141


Strings

Copyright 2009 by Pearson Education


Strings
 string: An object storing a sequence of text characters.
 Unlike most other objects, a String is not created with new.
String name = "text";
String name = expression;

 Examples:
String name = "Toucan Sam";
int x = 3;
int y = 5;
String point = "(" + x + ", " + y + ")";

Copyright 2009 by Pearson Education 143


Indexes
 Characters of a string are numbered with 0-based indexes:
String name = "J. Crew";

index 0 1 2 3 4 5 6
char J . C r e w

 The first character's index is always 0


 The last character's index is 1 less than the string's length

 The individual characters are values of type char (seen later)

Copyright 2009 by Pearson Education 144


String methods
Method name Description
trim() removes the leading and trailing spaces

length() number of characters in this string


substring(index1, index2) the characters in this string from index1
or (inclusive) to index2 (exclusive);
substring(index1) if index2 omitted, grabs till end of string
toLowerCase() a new string with all lowercase letters
toUpperCase() a new string with all uppercase letters

 These methods are called using the dot notation:


String course = "CSE 142";
[Link]([Link]()); // 7

Copyright 2009 by Pearson Education 145


String method examples
// index 012345678901
String s1 = "Stuart Reges";
String s2 = "Marty Stepp";
[Link]([Link]()); // 12
[Link]([Link]("e")); // 8
[Link]([Link](7, 10)) // "Reg"
String s3 = [Link](2, 8);
[Link]([Link]()); // "rty st"

 Given the following string:


// index 0123456789012345678901
String book = "Building Java Programs";
 How would you extract the word "Java" ?
 How would you extract the first word from any string?

Copyright 2009 by Pearson Education 146


Modifying strings
 Methods like substring, toLowerCase, etc.
create/return a new string, rather than modifying the
current string.
String s = "judy garland";
[Link]();
[Link](s); // judy garland

 To modify a variable, you must reassign it:


String s = "judy garland";
s = [Link]();
[Link](s); // JUDY GARLAND

Copyright 2009 by Pearson Education 147


Strings as parameters
public class StringParameters {
public static void main(String[] args) {
sayHello("Alice");
String friend = "Bob";
sayHello(friend);
}
public static void sayHello(String name) {
[Link]("Welcome, " + name);
}
}
Output:
Welcome, Alice
Welcome, Bob

Copyright 2009 by Pearson Education 148


Strings as user input
 Scanner's next method reads a word of input as a String.
Scanner console = new Scanner([Link]);
[Link]("What is your name? ");
String name = [Link]();
name = [Link]();
[Link](name + " has " + [Link]() +
" letters and starts with " + [Link](0, 1));

Output:
What is your name? Madonna
MADONNA has 7 letters and starts with M

 The nextLine method reads a line of input as a String.


[Link]("What is your address? ");
String address = [Link]();

Copyright 2009 by Pearson Education 149


Comparing strings
 Relational operators such as < and == fail on objects.
Scanner console = new Scanner([Link]);
[Link]("What is your name? ");
String name = [Link]();
if (name == "Tigger") {
[Link]("The wonderful thing about tiggers");
[Link]("is tiggers are wonderful things!");
}

 This code will compile, but it will not print the song.

 == compares objects by references (seen later), so it often gives


false even when two Strings have the same letters.

Copyright 2009 by Pearson Education 150


The equals method
 Objects are compared using a method named equals.
Scanner console = new Scanner([Link]);
[Link]("What is your name? ");
String name = [Link]();
if ([Link]("Tigger")) {
[Link]("The wonderful thing about tiggers");
[Link]("is tiggers are wonderful things!");
}

 Technically this is a method that returns a value of type


boolean, the type used in logical tests.

Copyright 2009 by Pearson Education 151


String test methods
Method Description
equals(str) whether two strings contain the same characters
equalsIgnoreCase(str) whether two strings contain the same characters,
ignoring upper vs. lower case
startsWith(str) whether one contains other's characters at start
endsWith(str) whether one contains other's characters at end
contains(str) whether the given string is found within this one
String name = [Link]();
if ([Link]("Dr.")) {
[Link]("What's up, doc?");
} else if ([Link]("LUMBERG")) {
[Link]("I need your TPS reports.");
}

Copyright 2009 by Pearson Education 152


Type char
 char : A primitive type representing single characters.
 Each character inside a String is stored as a char value.
 Literal char values are surrounded with apostrophe
(single-quote) marks, such as 'a' or '4' or '\n' or '\''

 It is legal to have variables, parameters, returns of type char


char letter = 'S';
[Link](letter); // S

 char values can be concatenated with strings.


char initial = 'J';
[Link](initial + " Lennon"); // J Lennon

Copyright 2009 by Pearson Education 153


The charAt method
 The chars in a String can be accessed using the charAt
method.
String food = "cookie";
char firstLetter = [Link](0); // 'c'
[Link](firstLetter + " is for " + food);
[Link]("That's good enough for me!");

 You can use a for loop to print or examine each character.


String major = "CSE";
for (int i = 0; i < [Link](); i++) {
char c = [Link](i);
[Link](c);
}
Output:
C
S
E

Copyright 2009 by Pearson Education 154


char vs. String
 "h" is a String
'h' is a char (the two behave differently)

 String is an object; it contains methods


String s = "h";
s = [Link](); // 'H'
int len = [Link](); // 1
char first = [Link](0); // 'H'

 char is primitive; you can't call methods on it


char c = 'h';
c = [Link](); // ERROR: "cannot be dereferenced“

Copyright 2009 by Pearson Education 155


char vs. int
 All char values are assigned numbers internally by the
computer, called ASCII values.

 Examples:
'A' is 65, 'B' is 66, ' ' is 32
'a' is 97, 'b' is 98, '*' is 42

 Mixing char and int causes automatic conversion to int.


'a' + 10 is 107, 'A' + 'A' is 130

 To convert an int into the equivalent char, type-cast it.


(char) ('a' + 2) is 'c'

Copyright 2009 by Pearson Education 156


Comparing char values
 You can compare char values with relational operators:
'a' < 'b' and 'X' == 'X' and 'Q' != 'q'

 An example that prints the alphabet:


for (char c = 'a'; c <= 'z'; c++) {
[Link](c);
}

 You can test the value of a string's character:


String word = [Link]();
if ([Link]([Link]() - 1) == 's') {
[Link](word + " is plural.");
}

Copyright 2009 by Pearson Education 157


While Loop

Copyright 2009 by Pearson Education


Categories of loops
 definite loop: Executes a known number of times.
 The for loops we have seen are definite loops.
 Examples:
 Print "hello" 10 times.
 Find all the prime numbers up to an integer n.
 Print each odd number between 5 and 127.

 indefinite loop: One where the number of times its body


repeats is not known in advance.
 Examples:
 Prompt the user until they type a non-negative number.
 Print random numbers until a prime number is printed.
 Repeat until the user has types "q" to quit.

Copyright 2009 by Pearson Education 159


The while loop
 while loop: Repeatedly executes its
body as long as a logical test is true.
while (test) {
statement(s);
}

 Example:
int num = 1; // initialization
while (num <= 200) { // test
[Link](num + " ");
num = num * 2; // update
}
 OUTPUT:
1 2 4 8 16 32 64 128

Copyright 2009 by Pearson Education 160


Example while loop
// finds a number's first factor other than 1
Scanner console = new Scanner([Link]);
[Link]("Type a number: ");
int number = [Link]();
int factor = 2;
while (number % factor != 0) {
factor++;
}
[Link]("First factor: " + factor);

 Example log of execution:


Type a number: 91
First factor: 7

 while is better than for here because we don't know


how many times we will need to increment to find the
factor.
Copyright 2009 by Pearson Education 161
for vs. while loops
 The for loop is just a specialized form of the while
loop.

 The following loops are equivalent:


for (int num = 1; num <= 200; num = num * 2) {
[Link](num + " ");
}

// actually, not a very compelling use of a while loop


// (a for loop is better because the # of reps is definite)
int num = 1;
while (num <= 200) {
[Link](num + " ");
num = num * 2;
}

Copyright 2009 by Pearson Education 162


while and Scanner
 while loops are often used with Scanner input.
 You don't know many times you'll need to re-prompt the user if
they type bad data. (an indefinite loop!)

 Write code that repeatedly prompts until the user types a


non-negative number, then computes its square root.
 Example log of execution:
Type a non-negative integer: -5
Invalid number, try again: -1
Invalid number, try again: -235
Invalid number, try again: -87
Invalid number, try again: 121
The square root of 121 is 11.0

Copyright 2009 by Pearson Education 163


while loop answer
[Link]("Type a non-negative integer: ");
int number = [Link]();
while (number < 0) {
[Link]("Invalid number, try again: ");
number = [Link]();
}
[Link]("The square root of " + number +
" is " + [Link](number));

 Notice that number has to be declared outside the loop.

Copyright 2009 by Pearson Education 164


do/while loop

Copyright 2009 by Pearson Education


The do/while loop
 do/while loop: Executes statements repeatedly while a
condition is true, testing it at the end of each repetition.
do {
statement(s);
} while (test);

 Example:
// prompt until the user gets the right password
String phrase;
do {
[Link]("Password: ");
phrase = [Link]();
} while (![Link]("abracadabra"));

Copyright 2009 by Pearson Education 166


do/while flow chart
 How does this differ from the while loop?
 The controlled statement(s) will always execute the first time,
regardless of whether the test is true or false.

Copyright 2009 by Pearson Education 167


Random Numbers

Copyright 2009 by Pearson Education


The Random class
 Random objects generate pseudo-random numbers.
 Class Random is found in the [Link] package.
import [Link].*;
Method name Description
nextInt() returns a random integer
nextInt(max) returns a random integer in the range [0, max)
in other words, 0 to max-1 inclusive
nextDouble() returns a random real number in the range [0.0, 1.0)

 Example:
Random rand = new Random();
int randomNumber = [Link](10);
// randomNumber has a random value between 0 and 9

Copyright 2009 by Pearson Education 169


Generating random numbers
 Common usage: to get a random number from 1 to N
int n = [Link](20) + 1; // 1-20 inclusive

 To get a number in arbitrary range [min, max]:


nextInt(<size of range>) + <min>
where <size of range> is <max> - <min> + 1

 Example: A random integer between 5 and 10 inclusive:


int n = [Link](6) + 5;

Copyright 2009 by Pearson Education 170


Random questions
 Given the following declaration, how would you get:
Random rand = new Random();

 A random number between 1 and 100 inclusive?


int random1 = [Link](100) + 1;

 A random number between 50 and 100 inclusive?


int random2 = [Link](51) + 50;

 A random number between 4 and 17 inclusive?


int random3 = [Link](14) + 4;

Copyright 2009 by Pearson Education 171


Random: not only for ints
 Often, the values that need to be generated aren't
numeric
 5 cards to deal out for poker
 a series of coin tosses
 a day of the week to assign a chore

 The possible values can be mapped to integers


 code to randomly play Rock-Paper-Scissors:
int r = [Link](3);
if (r == 0) {
[Link]("Rock");
} else if (r == 1) {
[Link]("Paper");
} else {
[Link]("Scissors");
}

Copyright 2009 by Pearson Education 172


Random question
 Write a program that simulates rolling of two 6-sided dice
until their combined result comes up as 7.
2 + 4 = 6
3 + 5 = 8
5 + 6 = 11
1 + 1 = 2
4 + 3 = 7
You won after 5 tries!

Copyright 2009 by Pearson Education 173


answer using while
// Rolls two dice until a sum of 7 is reached.
import [Link].*;

public class Roll {


public static void main(String[] args) {
Random rand = new Random();
int sum = 0;
int tries = 0;
while (sum != 7) {
int roll1 = [Link](6) + 1;
int roll2 = [Link](6) + 1;
sum = roll1 + roll2;
[Link](roll1 + " + " + roll2 + " = " + sum);
tries++;
}

[Link]("You won after " + tries + " tries!");


}
}

Copyright 2009 by Pearson Education 174


Answer using do/while
// Rolls two dice until a sum of 7 is reached.
import [Link].*;

public class Dice {


public static void main(String[] args) {
Random rand = new Random();
int tries = 0;
int sum;
do {
int roll1 = [Link](6) + 1;
int roll2 = [Link](6) + 1;
sum = roll1 + roll2;
[Link](roll1 + " + " + roll2 + " = " + sum);
tries++;
} while (sum != 7);

[Link]("You won after " + tries + " tries!");


}
}

Copyright 2009 by Pearson Education 175

You might also like