Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
630 views

Text Chapter 2 Basic Objects

1) Objects allow programmers to think at a higher level of abstraction by grouping related data and operations. An object represents a real-world item like an oven that can perform operations like set temperature. 2) A Java program uses objects by defining classes that specify the data and methods of an object. An object is an instance of a class that encapsulates data and allows calling methods on that data. 3) Variables are used in programs to store and manipulate data values. A variable is declared with a name and type, and is assigned values through assignments using the = operator. The variable on the left of = is assigned the value of the expression on the right.

Uploaded by

Levin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
630 views

Text Chapter 2 Basic Objects

1) Objects allow programmers to think at a higher level of abstraction by grouping related data and operations. An object represents a real-world item like an oven that can perform operations like set temperature. 2) A Java program uses objects by defining classes that specify the data and methods of an object. An object is an instance of a class that encapsulates data and allows calling methods on that data. 3) Variables are used in programs to store and manipulate data values. A variable is declared with a name and type, and is assigned values through assignments using the = operator. The variable on the left of = is assigned the value of the expression on the right.

Uploaded by

Levin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 126

Chapter - 2 JAVA:BASIC OBJECTS

2.1 Objects: An early introduction (EO)

In the physical world, we are surrounded by basic items made from


wood, metal, plastic, etc. But to keep the world understandable, we think
at a higher level, in terms of objects like an oven. The oven allows us to
perform a few specific operations, like set the temperature, open the
door, or start the exhaust fan.
Thinking in terms of objects can be powerful when designing programs.
Suppose a program should keep track of the number of people attending
an event, such as a concert. A programmer might use an "object" called
PeopleCounter. The PeopleCounter object supports operations like
increment count, get count, reset count, and print count.
In a program, an object consists of some internal data items plus
operations that can be performed on that data. An object's internal data
are called private fields, as the data is private to the object. The
operations that can be called on an object are called public methods, as
those operations can be called from outside the object.
A programmer only needs to understand the operations for that object;
detailed knowledge of how the object is implemented, such as the
internal data members, is not required.
PARTICIPATION ACTIVITY

2.1.2: Objects.

Some of the data and operations for a used-car inventory program are
grouped into an object named carOnLot. Select True if the operation should
be supported by the carOnLot object, and False otherwise.

1) incrementCarDaysOnLot()
True.This is an operation that would be applied to a car object.

2) decreaseStickerPrice()

True.This is an operation that would be applied to a car object.

3) determineTopSalesperson()

False.This operation might be applied on a salesperson object, but not on a car object.

A class defines a type that groups data and methods to form an object. A class'
public methods define the operations that can be performed on objects of that class
type. The class definition (discussed later) is like a blueprint explaining how to create
objects and an instruction manual explaining how to use an object.

The below code creates an object attendeeCounter using a class named


PeopleCounter, with relevant code highlighted below.

Figure 2.1.1: Using objects.

public class AttendanceExample {


public static void main(String[] args) {
PeopleCounter attendeeCounter = new PeopleCounter();

attendeeCounter.incrementCount();
attendeeCounter.incrementCount();
attendeeCounter.incrementCount();

System.out.print("Attendee count: ");


attendeeCounter.printCount();
}

Attendee count: 3
To use objects, the programmer declared and created a new object of type
PeopleCounter named attendeeCounter. The program then called operations on the
attendeeCounter object by invoking methods on the objects, such as

attendeeCounter.incrementCount() and attendeeCounter.printCount().


Previous programs used objects for printing output, as in the statement

.
System.out.print("Keep calm"); System.out is an object of type PrintStream
that is automatically created when a Java program starts. The print() method called
on this object allows a program to print various output, such as the string "Keep
calm".

PARTICIPATION ACTIVITY

2.1.3: Object creation and method calls.

Select the statement that correctly performs the requested task.

1) Declare and create a new object of type PeopleCounter named


passengerCounter.

PeopleCounter passengerCounter = new PeopleCounter();

The "PeopleCounter passengerCounter" part declares a variable passengerCounter for


a PeopleCounter object. The "= new PeopleCounter()" part creates a new object of type
PeopleCounter.

2) Declare and create two objects of type PeopleCounter named entranceCount


and exitCount.

PeopleCounter entranceCount = new PeopleCounter();

PeopleCounter exitCount = new PeopleCounter();


Declare and creates two objects of type PeopleCounter.

3) Call the printCount() method on a PeopleCounter object named


studentCounter.

studentCounter.printCount();

The object name comes before the period, and the method being called on that object
comes after the period.

zyDE 2.1.1: Creating and using objects: PeopleCounter.

Try to create and use PeopleCounter objects in the following program. Methods for
PeopleCounter include resetCount(), incrementCount(), printCount(), and getCount().

public class AttendanceExample {


public static void main(String[] args) {
PeopleCounter attendeeCounter = new PeopleCounter();

attendeeCounter.incrementCount();
attendeeCounter.incrementCount();
attendeeCounter.incrementCount();

System.out.print("Attendee count: ");


attendeeCounter.printCount();
}
}

OUTPUT:
Attendee count: 3

2.2 Variables and assignments (general)


Variables and assignments
In a program, a variable is a named item, such as x or numPeople, used to hold
a value.
An assignment assigns a variable with a value, such as x = 5. That assignment
means x is assigned with 5, and x keeps that value during subsequent
assignments, until x is assigned again.
An assignment's left side must be a variable. The right side can be an
expression, so an assignment may be x = 5, y = x, or z = x + 2. The 5, x, and x +
2 are each an expression that evaluates to a value.

1. In programming, a variable is a place to hold a value. Here, variables x, y, and z


are depicted graphically as boxes.
2. An assignment assigns the left-side variable with the right-side expression's
value. x = 5 assigns x with 5.
3. y = x assigns y with x's value, which presently is 5. z = x + 2 assigns z with x's
present value plus 2, so 5 + 2 or 7.
4. A subsequent x = 3 assigns x with 3. x's former value of 5 is overwritten and
thus lost. Note that the values held in y and z are unaffected, remaining as 5
and 7.
5. In algebra, an equation means "the item on the left always equals the item on
the right". So for x + y = 5 and x * y = 6, one can determine that x = 2 and y = 3
is a solution.
6. Assignments look similar but have VERY different meaning. The left side
MUST be one variable.
7. The = isn't "equals", but is an action that PUTS a value into the variable.
Assignments only make sense when executed in sequence.

PARTICIPATION ACTIVITY

2.2.3: Valid assignments.

Indicate which assignments are valid.

1) x = 1
Valid.x is assigned with 1.

2) x = y

Valid.x is assigned with y's current value. If y is 9, x is assigned with 9.

3) x = y + 2

Valid.x is assigned with y's current value plus 2. If y is 4, x is assigned with 4 + 2, or 6

4) x + 1 = 3

Invalid.The left side must be a variable, not an expression like x + 1. In programming,


= does not mean equal. = means assign the left-side variable with the right-side's
value. Thus, the left side MUST be a variable.

5) x + y = y + x

Invalid.In programming, the left side of = must be a variable, which will be assigned
with the right side's value. Thus, having x + y on the left side doesn't make sense.

PARTICIPATION ACTIVITY

2.2.4: Variables and assignments.

Given variables x, y, and z.

1) x = 9
y=x+1

What is y?

10.x is currently 9, so y is assigned with 9 + 1, or 10.

2) x = 9

y=x+1

What is x?

9.x was assigned with 9. Then, y was assigned with x + 1, so 9 + 1, or 10. That assignment to
y has no effect on x's value, so x remains 9. Note how different assignment is from algebraic
equations.

3) x = 9

y=x+1

x=5

What is y?

10.x was assigned with 9. Then y was assigned with 10. Then x was assigned with 5. That
assignment doesn't affect y, so y is still 10.
Assignments with variable on left and right
Because in programming = means assignment, a variable may appear on both the
left and right as in x = x + 1. If x was originally 6, x is assigned with 6 + 1, or 7. The
assignment overwrites the original 6 in x.

Increasing a variable's value by 1, as in x = x + 1, is common, and known as


incrementing the variable.

CAPTIONS

1. A variable may appear on both sides of an assignment. After x = 1, then x = x *


20 assigns x with 1 * 20 or 20, overwriting x's previous 1.
2. Another x = x * 20 assigns x with 20 * 20 or 400, which overwrites x's previous
20.
3. Only the latest value is held in x. The previous values are shown greyed out
above but in actuality are completely gone.

PARTICIPATION ACTIVITY

2.2.7: Variable on both sides.

Indicate the value of x after the assignments execute.

1) x = 5

x=x+7

12.x is first assigned with 5. Then x is assigned with x + 7, meaning 5 + 7, so


12. (The 12 overwrites x's previous 5). The assignment x = x + 7 confuses
some new programmers who are thinking of math: If x is 5, how can 5 = 5 + 7?
But = does NOT MEAN EQUAL in programming; = means ASSIGN the left-side
variable with the right-side value.

2) x = 2

y=3
x=x*y

x=x*y

18.x is first assigned with 2. Then x is assigned with 2 * 3, or 6. Finally, x is assigned with 6 *
3, or 18.

3) y = 30

x=y+2

x=x+1

33.x is first assigned with 30 + 2 or 32. Then x is assigned with 32 + 1 or 33.

4) Complete this assignment to increment y: y = _____

y+1.y's current value gets 1 added, and y is assigned with that new value. If y was 7,
then y is assigned with 7 + 1 or 8.

2.3 Variables (int)


Variable declarations
A variable declaration is a statement that declares a new variable, specifying the
variable's name and type. Ex: int userAge; declares a new variable named userAge
that can hold an integer value. The compiler allocates a memory location for
userAge capable of storing an integer. Ex: In the animation below, the compiler
allocated userAge to memory location 97, which is known as the variable's address.
The choice of 97 is arbitrary and irrelevant to the programmer, but the idea that a
variable corresponds to a memory location is important to understand.

When a statement that assigns a variable with a value executes, the processor writes
the value into the variable's memory location. Likewise, reading a variable's value
reads the value from the variable's memory location. The programmer must declare
a variable before any statement that assigns or reads the variable, so that the
variable's memory location is known.

PARTICIPATION ACTIVITY

2.3.1: A variable refers to a memory location.

import java.util.Scanner;

public class AgePrinter {

public static void main(String[] args) {

int userAge;

System.out.print("Enter your age: ");

Scanner scnr = new Scanner(System.in);

userAge = scnr.nextInt();

System.out.println(userAge + " is a great age.");

CAPTIONS

1. Compiler allocates a memory location for userAge, in this case location 97.
2. First print statement executes.
3. User types 23. Statement assigns userAge with 23.
4. Print statement prints userAge's value to screen.

PARTICIPATION ACTIVITY

2.3.2: Declaring integer variables.


Note: Capitalization matters, so MyNumber is not the same as myNumber.

1) Declare an integer variable named numPeople. (Do not initialize the variable.)

int numPeople;.The compiler will allocate a particular memory location for numPeople.

2) Using two statements on two separate lines, declare integer variables named newSales
and totalSales. (Do not initialize the variables.)

int newSales;

int totalSales;

Multiple variables can be declared in the same statement, as in: int newSales,
totalSales;, but this material usually avoids that style.

3) What memory location (address) will a compiler allocate for the variable declaration
below? If appropriate, type: Unknown

int numHouses = 99;

A programmer does not know the specific location, but understanding that a specific
location is allocated for a variable is important.

Assignment statements
An assignment statement assigns the variable on the left-side of the = with the current value of
the right-side expression. Ex: numApples = 8; assigns numApples with the value of the
right-side expression (in this case 8). assign

An expression may be a number like 80, a variable name like numApples, or a simple calculation
like numApples + 1. Simple calculations can involve standard math operators like +, -, and *, and
parentheses as in 2 * (numApples - 1). An integer like 80 appearing in an expression is known as
an integer literal.
In the code below, litterSize is assigned with 3, and yearlyLitters is assigned with 5. Later,
annualMice is assigned with the value of litterSize * yearlyLitters (3 * 5, or 15), which is then
printed. Next, litterSize is assigned with 14, yearlyLitters is assigned with 10, and annualMice is
assigned with their product (14 * 10, or 140), which is printed.

Figure 2.3.1: Assigning a variable.

public class Mice {


public static void main(String[] args) {
int litterSize;
int yearlyLitters;
int annualMice;
litterSize = 3; // Low end of litter size range
yearlyLitters = 5; // Low end of litters per year

System.out.print("One female mouse may give birth to ");


annualMice = litterSize * yearlyLitters;
System.out.println(annualMice + " mice,");

litterSize = 14; // High end


yearlyLitters = 10; // High end

System.out.print("and up to ");
annualMice = litterSize * yearlyLitters;
System.out.println(annualMice + " mice, in a year.");
}
}

OUTPUT

One female mouse may give birth to 15 mice,


and up to 140 mice, in a year.

PARTICIPATION ACTIVITY

2.3.3: Assignment statements.

Be sure to end assignment statements with a semicolon (;).

1)Write an assignment statement to assign numCars with 99.

numCars = 99;

The statement assigns the variable numCars with the value 99.

2) Assign houseSize with 2300.

houseSize = 2300;

The program assigns the variable houseSize with the value 2300.

3) Assign numFruit with the current value of numApples.

numFruit = numApples;
The program evaluates the value of numApples by reading the value held in numApples'
memory location, and then assigns numFruit with that value.

4) The current value in houseRats is 200. What is in houseRats after executing


the statement below? Valid answers: 0, 199, 200, or unknown.

numRodents = houseRats;

200.The statement evaluates the value of houseRats by


reading the value held in houseRats' memory location, and
stores a copy of that value into numRodents. houseRats
doesn't change.

5) Assign numItems with the result of ballCount - 3.

numItems = ballCount - 3;

The program reads the value of ballCount, subtract 3 from that value, and assigns numItems
with the result.

6) dogCount is 5. What is in animalsTotal after executing the


statement below?

animalsTotal = dogCount + 3;

The statement reads the value of dogCount (5), adds 3, and assigns animalsTotal with the
result of 8.

7) dogCount is 5. What is in dogCount after executing the


statement below?

animalsTotal = dogCount + 3;

5.The statement reads the value of dogCount, but does not change the value of
dogCount.
8)What is in numBooks after both statements execute?

numBooks = 5;
numBooks = 3;

3.The first statement assigns numBooks with 5. The second statement assigns numBooks
with 3, replacing the previously held value 5.

CHALLENGE ACTIVITY

2.3.2: Assigning a sum.

Write a statement that assigns numCoins with numNickels + numDimes. Ex:


5 nickels and 6 dimes results in 11 coins.

Note: These activities may test code with different test values. This activity
will perform two tests: the first with nickels = 5 and dimes = 6, the second
with nickels = 9 and dimes = 0.

import java.util.Scanner;

public class AssigningSum {


public static void main(String[] args) {
int numCoins;
int numNickels;
int numDimes;

numNickels = 5;
numDimes = 6;
numCoins=numNickels+ numDimes;
/* Your solution goes here */

System.out.print("There are ");


System.out.print(numCoins);
System.out.println(" coins");
}
}

Initializing variables
Although not required, an integer variable is often assigned an initial value when declared. Ex: int
maxScore = 100; declares an int variable named maxScore with an initial value of 100.

Figure 2.3.2: Variable initialization: Example program.


import java.util.Scanner;

public class AgePrinter {

public static void main(String[] args) {

int avgLifespan = 70;

int userAge;

System.out.print("Enter your age: ");

Scanner scnr = new Scanner(System.in);

userAge = scnr.nextInt();

System.out.println(userAge + " is a great age");

System.out.println("Average lifespan is " + avgLifespan);

}
OUTPUT
Enter your age: 24
24 is a great age
Average lifespan is 70

PARTICIPATION ACTIVITY
2.3.4: Declaring and initializing integer variables.

1) Declare an integer variable named numDogs, initializing the variable to 0 in


the declaration.

int numDogs = 0;

The compiler will allocate a particular memory location for numDogs, and initially
store 0 in that location.
2) Declare an integer variable named daysCount, initializing the variable to 365
in the declaration.

int daysCount = 365;.The compiler will allocate a particular memory location


for daysCount, and initially store 365 in that location.

CHALLENGE ACTIVITY

2.3.3: Declaring and initializing variables.

Write one statement that declares an integer variable numHouses initialized to 25.

import java.util.Scanner;

public class DeclaringVariables {

public static void main(String[] args) {

int numHouses=25;

System.out.println(numHouses);

Assignment statement with same variable on both sides

a variable appears on both the right and left side of the = operator. Ex: If numItems is 5, after
numItems = numItems + 1; executes, numItems will be 6.

PARTICIPATION ACTIVITY

2.3.5: Variable assignments overwrite a variable's previous values: People-known example.

import java.util.Scanner;
public class PeopleKnown {

public static void main(String[] args) {

int yourFriends;

int totalFriends;

System.out.print("Enter the number of people you know: ");

Scanner scnr = new Scanner(System.in);

yourFriends = scnr.nextInt();

totalFriends = yourFriends;

System.out.println(" You know " + totalFriends + " people.");

totalFriends = totalFriends * yourFriends;

System.out.println(" Those people know " + totalFriends + " people.");

totalFriends = totalFriends * yourFriends;

System.out.println(" And they know " + totalFriends + " people.");

OUTPUT

Enter the number of people you know:200

You know 200 people.

Those people know 40000 people.


And they know 8000000 people.

CAPTION

1. The compiler allocated memory for variables.


2. Prompt user with system.out.print.
3. The scnr statement assigns to yourFriends.
4. totalFriends is assigned with the value of yourFriends.
5. The println statement outputs totalFriends.
6. The assignment statement reads totalFriends (200) and yourFriends (200), multiplies those
values, and assigns totalFriends with the product of 40000.
7. The println statement outputs totalFriends.
8. Assignment reads totalFriends (now 40000) and yourFriends (200), multiplies those values,
and assigns totalFriends with the result of 8000000.

PARTICIPATION ACTIVITY

2.3.6: Assignment statements with same variable on both sides.

1.numApples is initially 5. What is numApples after:

numApples = numApples + 3;

8.The statement reads the current value of numApples (5), adds 3, and assign
numApples with the result of 8.

2. numApples is initially 5. What is numFruit after:

numFruit = numApples;

numFruit = numFruit + 1;

6.The first statement assigns numFruit with 5. The second statement reads
numFruit (5), adds 1, and assigns numFruit with the result of 6.

3.Write a statement ending with - 1 that decreases the value of variable


flyCount by 1.

flyCount = flyCount - 1;.The statement reads the value of flyCount, subtracts 1,


and assigns flyCount with the result (overwriting the previous value).

CHALLENGE ACTIVITY
2.3.4: Adding a number to a variable.

Write a statement that increases numPeople by 5. Ex: If numPeople is initially 10, the
output is: There are 15 people.

import java.util.Scanner;

public class AssigningNumberToVariable {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int numPeople;

numPeople = scnr.nextInt();

numPeople=numPeople+5;

/* Your solution goes here */

System.out.print("There are ");

System.out.print(numPeople);

System.out.println(" people.");

Common errors
A common error is to read a variable that has not yet been assigned a value. A programmer must
ensure that a program assigns a variable with a value before reading.

A common error by new programmers is to write an assignment statement in reverse. Ex:


numKids + numAdults = numPeople, or 9 = beansCount. Those statements won't
compile, but writing numCats = numDogs in reverse will compile, leading to a hard-to-find
bug.

PARTICIPATION ACTIVITY

2.3.7: Common errors. Which code segments have an error?

1) 21 = dogCount;

Error.The statement will not compile because the left side must be a variable. The
programmer likely meant to write dogCount = 21;

2) int amountOwed = -999;

No error.A variable can be initialized when declared, and an int variable can hold
negative values.

3) int numDays;

int numYears;

numDays = numYears * 365;

Error.numYears is used without having been assigned with a value, so the value of
numYears is unknown. Most modern compilers check if a variable is used before being
assigned with a value, reporting an error or warning.

2.4 Identifiers
Rules for identifiers
A name created by a programmer for an item like a variable or method is called an identifier. An
identifier must:

● be a sequence of letters (a-z, A-Z), underscore (_), dollar signs ($), and digits (0-9)
● start with a letter, underscore, or dollar sign

Note that "_", called an underscore, and "$", called a dollar sign or currency symbol, are
considered to be letters. A good practice followed by many Java programmers is to not use _ or $
in programmer-created identifiers.

Identifiers are case sensitive, meaning upper and lower case letters differ. So numCats and
NumCats are different.

A reserved word is a word that is part of the language, like int, short, or double. A reserved word
is also known as a keyword. A programmer cannot use a reserved word as an identifier. Many
language editors will automatically color a program's reserved words. A list of reserved words
appears at the end of this section.

A reserved word is a word that is part of the language, like int, short, or double. A reserved word
is also known as a keyword. A programmer cannot use a reserved word as an identifier.

PARTICIPATION ACTIVITY

2.4.2: Valid identifiers.

Which are valid identifiers?

1) numCars

Valid.Letters are always valid (upper or lower case).

2) num_Cars1

Valid.An underscore is treated as a letter.

3) _numCars

Valid.The underscore can be in the first position just like any other letter.

4) ___numCars

Valid.Two or more underscores may look strange, but the underscore is just like any
other letter and can be repeated. However, convention is to not use more than one
underscore.
5) 3rdPlace

Invalid.Identifiers must start with a letter.

6) thirdPlace_

Valid.Ending with an underscore is okay.

7) thirdPlace!

Invalid."!" is not allowed.

8) short

Invalid."short" is a language keyword so it can't be used as an identifier.

9) very tall

Invalid.Spaces are not allowed. Instead, an underscore can be used (very_tall) or the
words can be abutted (veryTall).

Style guidelines for identifiers


While various (crazy-looking) identifiers may be valid, programmers may follow
identifier naming conventions (style) defined by their company, team, teacher, etc.
Two common conventions for naming variables are:

● Camel case: Lower camel case abuts multiple words, capitalizing each
word except the first, as in numApples or peopleOnBus.
● Underscore separated: Words are lowercase and separated by an
underscore, as in num_apples or people_on_bus.

Neither convention is better. The key is to be consistent so code is easier to read


and maintain.

Good practice is to create meaningful identifier names that self-describe an


item's purpose. Good practice minimizes use of abbreviations in identifiers except
for well-known ones like num in numPassengers. Programmers must strive to
find a balance. Abbreviations make programs harder to read and can lead to
confusion. Long variable names, such as averageAgeOfUclaGraduateStudent
may be meaningful, but can make subsequent statements too long and thus hard
to read.

PARTICIPATION ACTIVITY

2.4.3: Meaningful identifiers.

Choose the "best" identifier for a variable with the stated purpose, given
the above discussion.

1) The number of students attending UCLA.

numStudentsUcla.Ucla is likely a well-known abbreviation, so shouldn't cause a


problem.

2) The size of an LCD monitor

sizeLcdMonitor.Lcd is abbreviated but may be OK.

3) The number of jelly beans in a jar.

jellyBeansInJar.Looks OK. Could start with num, but should be fine as is.

zyBook's naming conventions

Lower camel case is used for variable naming, which is a common Java naming
convention. This material strives to follow another good practice of using two or
more words per variable such as numStudents rather than just students, to provide
meaningfulness, to make variables more recognizable when variable names appear
in writing like in this text or in a comment, and to reduce conflicts with reserved
words or other already-defined identifiers.

Table 2.4.1: Java reserved words / keywords.

abstract final public

assert finally return

boolean float short

break for static

byte goto strictfp

case if super

catch implement switch


s
char synchronize
import d
class
instanceof this
const
int throw
continu
e interface throws

default long transient

do native try
double new void

else package volatile

enum private while

extends protected

The words "true", "false", and "null" are also reserved, and used for literals.

2.5 Arithmetic expressions (general)


Basics
An expression is any individual item or combination of items, like variables, literals, operators,
and parentheses, that evaluates to a value, like 2 * (x + 1). A common place where expressions
are used is on the right side of an assignment statement, as in y = 2 * (x + 1).

A literal is a specific value in code like 2. An operator is a symbol that performs a built-in
calculation, like +, which performs addition. Common programming operators are shown below.

Table 2.5.1: Arithmetic operators.

Arithmetic Description
operator

+ The addition operator is +, as in x + y.

- The subtraction operator is -, as in x - y. Also, the - operator is for negation, as


in -x + y, or x + -y.
* The multiplication operator is *, as in x * y.

/ The division operator is /, as in x / y.

PARTICIPATION ACTIVITY

2.5.1: Expressions.

Indicate which are valid expressions. x and y are variables, and are the
only available variables.

1) x + 1

Valid.The text consists of a variable (x), operator (+), and literal (1). If x is 5, the
expression evaluates to 5 + 1 or 6.

2) 2 * (x - y)

Valid.The text consists of a literal (2), two operators (*, -), and two variables (x, y),
properly combined with parentheses. If x is 7 and y is 3, the expression evaluates to 2 *
(7 - 3), or 2 * (4), so 8.

3) x

Valid.An expression can just be a variable.

4) 2
Valid.An expression can just be a literal.

5) 2x

Not valid.In programming, multiplication typically must be indicated explicitly using


the * operator. Abutment is allowed in math, but not usually in programming.

6) 2 + (xy)

Not valid.In programming, doing multiplication via abutment, as in xy, is not usually
allowed, because xy could be the name of another variable.

7) x - -2

Valid.The first - represents subtraction, while the second - represents negation. If x were
5, the expression would evaluate to 7.

PARTICIPATION ACTIVITY

2.5.2: Capturing behavior with an expression.

Does the expression correctly capture the intended behavior?

1) 6 plus numItems:

6 + numItems

Yes.Straightforward addition.
2) 6 times numItems:

6 x numItems

No.The multiplication operator is *, not x.

3) totDays divided by 12:

totDays / 12

Yes.Straightforward division.

4) 5 times i:

5i

No.Abutment not allowed. Requires 5 * i

5) The negative of userVal:

-userVal

Yes.- serves as subtraction, but also negation.

6) n factorial

n!
No.Most languages don't use the ! symbol for factorial.

Evaluation of expressions
An expression evaluates to a value, which replaces the expression. Ex: If x is 5,
then x + 1 evaluates to 6, and y = x + 1 assigns y with 6.

An expression is evaluated using the order of standard mathematics, such order


known in programming as precedence rules, listed below.

Table 2.5.2: Precedence rules for arithmetic operators.

Operator/C Description Explanation


onvention

() Items within parentheses are In 2 * (x + 1), the x + 1 is


evaluated first evaluated first, with the result
then multiplied by 2.

unary - - used for negation (unary In 2 * -x, the -x is computed


minus) is next first, with the result then
multiplied by 2.

*/% Next to be evaluated are *, /, (% is discussed elsewhere)


and %, having equal
precedence.

+- Finally come + and - with equal In y = 3 + 2 * x, the 2 * x is


precedence. evaluated first, with the result
then added to 3, because * has
higher precedence than +.
Spacing doesn't matter: y = 3+2
* x would still evaluate 2 * x
first.

left-to-righ If more than one operator of In y = x * 2 / 3, the x * 2 is first


t equal precedence could be evaluated, with the result then
evaluated, evaluation occurs divided by 3.
left to right.

Feedback?

PARTICIPATION ACTIVITY

2.5.3: Evaluating expressions.

1. An expression like 3 * (x + 10 / w) evaluates to a value, using precedence rules. Items


within parentheses come first, and / comes before +, yielding 3 * (x + 5).
2. Evaluation finishes inside the parentheses: 3 * (x + 5) becomes 3 * 9.
3. Thus, the original expression evaluates to 3 * 9 or 27. That value replaces the expression.
So y = 3 * (x + 10 / w) becomes y = 27, so y is assigned with 27.
4. Many programmers prefer to use parentheses to make order of evaluation more clear
when such order is not obvious.

PARTICIPATION ACTIVITY

2.5.4: Evaluating expressions and precedence rules.

Select the expression whose parentheses match the evaluation order of


the original expression.

1) y + 2 * z

y + (2 * z).* has precedence over +, so is evaluated first.


2) z / 2-x

(z / 2) - x./ has precedence over -.

3) x * y * z

(x * y) * z.The two operators have equal precedence, so evaluation occurs


left-to-right.

4) x + 1 * y/2

x + ((1 * y) / 2).* and / have precedence over + so will be evaluated first. * and / have
equal precedence so are evaluated left-to-right, despite what the original spacing
implied.

5) x / 2 + y / 2

(x / 2) + (y / 2)./ has precedence over +. The two / are evaluated left-to-right.

6) What is totCount after executing the following?

numItems = 5;

totCount = 1 + (2 * numItems) * 4;

41.After (2 * 5) is evaluated, * 4 is evaluated because * has precedence over +.

Using parentheses to make the order of evaluation explicit


A common error is to omit parentheses and assume a different order of evaluation
than actually occurs, leading to a bug. Ex: If x is 3, then 5 * x+1 might appear to
evaluate as 5 * (3+1) or 20, but actually evaluates as (5 * 3) + 1 or 16 (spacing
doesn't matter). Good practice is to use parentheses to make order of evaluation
explicit, rather than relying on precedence rules, as in: y = (m * x) + b, unless order
doesn't matter as in x + y + z.

Example: Calorie expenditure


A website lists the calories expended by men and women during exercise as
follows (source):

Men: Calories = [(Age × 0.2017) + (Weight × 0.09036) + (Heart Rate × 0.6309) —


55.0969] × Time / 4.184

Women: Calories = [(Age × 0.074) — (Weight × 0.05741) + (Heart Rate × 0.4472)


— 20.4022] × Time / 4.184

Below are those expressions written using programming notation:

caloriesMan = ( (ageYears * 0.2017) + (weightPounds * 0.09036) + (heartBPM *


0.6309) - 55.0969 ) * timeMinutes / 4.184

caloriesWoman = ( (ageYears * 0.074) - (weightPounds * 0.05741) + (heartBPM *


0.4472) - 20.4022 )* timeMinutes / 4.184

2.6 Arithmetic expressions (int)


Below is a simple program that includes an expression involving integers.

Figure 2.6.1: Expressions examples: Leasing cost.


import java.util.Scanner; Enter down payment:
500
/* Computes the total cost of leasing a car given the Enter monthly payment:
down payment, 300
monthly rate, and number of months Enter number of
*/ months: 60

public class CarLeaseCost { Total cost: 18500


public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int downPayment;
int paymentPerMonth;
int numMonths;
int totalCost; // Computed total cost to be output

System.out.print("Enter down payment: ");


downPayment = scnr.nextInt();

System.out.print("Enter monthly payment: ");


paymentPerMonth = scnr.nextInt();

System.out.print("Enter number of months: ");


numMonths = scnr.nextInt();

totalCost = downPayment + (paymentPerMonth *


numMonths);

System.out.println("Total cost: " + totalCost);


}

PARTICIPATION ACTIVITY

2.6.1: Simple program with an arithmetic expression.

Consider the example above.

1) Would removing the parentheses as below have yielded the same result?

downPayment + paymentPerMonth * numMonths;

Yes.The * would still be evaluated first, because * has higher precedence than +. But
using parentheses makes the programmer's intent more clear to people reading the
program.
2) Would using two assignment statements as below have yielded the same result? Assume
this declaration exists: int totalMonthly

totalMonthly = paymentPerMonth * numMonths;

totalCost = downPayment + totalMonthly;

Yes.The evaluation is ultimately the same, yielding the same result. Breaking larger
expressions into multiple assignments with smaller expressions can sometimes
improve code readability.

Style: Single space around operators


A good practice is to include a single space around operators for readability, as in numItems + 2,
rather than numItems+2. An exception is minus used as negative, as in: xCoord = -yCoord. Minus (-)
used as negative is known as unary minus.

PARTICIPATION ACTIVITY

2.6.2: Single space around operators.

Retype each statement to follow the good practice of a single space around operators.

1) housesCity = housesBlock *10;

housesCity = housesBlock * 10;

The spaces ensure the operator is clearly visible. Note that a semicolon (;) is not an
operator and should not be preceded by a space.

2) tot = num1+num2+2;

tot = num1 + num2 + 2;

The spaces reduce human reader confusion with num2 and 2.


3) numBalls=numBalls+1;

numBalls = numBalls + 1;

The spaces around the = ensure the assignment is clearly visible.

4) numEntries = (userVal+1)*2;

numEntries = (userVal + 1) * 2;

The spaces may lead to more readable expressions.

Compound operators
Special operators called compound operators provide a shorthand way to update a variable, such as
userAge += 1 being shorthand for userAge = userAge + 1. Other compound operators include -=, *=,
/=, and %=.

PARTICIPATION ACTIVITY

2.6.3: Compound operators.

1) numAtoms is initially 7. What is numAtoms after: numAtoms += 5?

12

Same as numAtoms = numAtoms + 5, so 7 + 5 is 12.

2) numAtoms is initially 7. What is numAtoms after: numAtoms *= 2?

14

Same as numAtoms = numAtoms * 2, so 7 * 2 is 14.


3) Rewrite the statement using a compound operator. If the statement can't be rewritten using
a compound operator, type: Not possible

carCount = carCount / 2;

carCount /= 2;

carCount /= 2 is same as carCount = carCount / 2.

4) Rewrite the statement using a compound operator. If the statement can't be rewritten using
a compound operator, type: Not possible

numItems = boxCount + 1;

Not possible.A compound operator is shorthand for when a variable is being updated, not
for a more general assignment. Both sides must thus have the same variable, but here the
variables are different (numItems and boxCount).

No commas allowed
Commas are not allowed in an integer literal. So 1,333,555 is written as 1333555.

PARTICIPATION ACTIVITY

2.6.4: Expression in statements.

1) Is the following an error? Suppose an int's maximum value is 2,147,483,647.

int numYears = 1,999,999,999;

Yes.Commas aren't allowed in an integer literal.

CHALLENGE ACTIVITY
2.6.2: Compute an expression.

Write a statement that assigns finalResult with the sum of num1 and num2, divided by 3.
Ex: If num1 is 4 and num2 is 5, finalResult is 3.

import java.util.Scanner;

public class ComputingFinalResult {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int num1;

int num2;

int finalResult;

num1 = scnr.nextInt();

num2 = scnr.nextInt();

/* Your solution goes here */

finalResult=(num1 +num2)/3;

System.out.print("Final result: ");

System.out.println(finalResult);

}
CHALLENGE ACTIVITY

2.6.3: Total cost.

A drink costs 2 dollars. A taco costs 3 dollars. Given the number of each, compute total
cost and assign totalCost with the result. Ex: 4 drinks and 6 tacos yields totalCost of 26.

import java.util.Scanner;

public class ComputingTotalCost {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int numDrinks;

int numTacos;

int totalCost;

numDrinks = scnr.nextInt();

numTacos = scnr.nextInt();

/* Your solution goes here */

totalCost= (numDrinks*2)+(numTacos*3);
System.out.print("Total cost: ");

System.out.println(totalCost);

2.7 Example: Health data


Calculating user's age in days
The section presents an example program that computes various health related data based on a
user's age using incremental development. Incremental development is the process of writing,
compiling, and testing a small amount of code, then writing, compiling, and testing a small amount
more (an incremental amount), and so on.

The initial program below calculates a user's age in days based on the user's age in years. The
assignment statement userAgeDays = userAgeYears * 365; assigns userAgeDays with
the product of the user's age and 365, which does not take into account leap years.

Figure 2.7.1: Calculating user health data.

import java.util.Scanner;

public class HealthData {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int userAgeYears;
int userAgeDays;

System.out.print("Enter your age in years: ");

userAgeYears = scnr.nextInt();

userAgeDays = userAgeYears * 365;

System.out.println("You are " + userAgeDays + " days old.");

OUTPUT

Enter your age in years: 19

You are 6935 days old.

PARTICIPATION ACTIVITY

2.7.1: Calculating user age in days.

1) Which variable is used for the user's age in years?

userAgeYears

The variable name userAgeYears clearly indicates the variable will hold the user's age
in years. Similarly, userAgeDays is for the user's age in days.

2) If the user enters 10, what will userAgeYears be assigned?


10

userAgeYears is assigned with the user-entered value, or 10.

3) If the user enters 10, what is userAgeDays assigned?

3650

userAgeDays is assigned with userAgeYears * 365, which is 10 * 365, or 3650.

Considering leap years and calculating age in minutes


The program below extends the previous program by accounting for leap years when calculating the
user's age in days. Since each leap year has one extra day, the statement userAgeDays =
userAgeDays + (userAgeYears / 4) adds the number of leap years to userAgeDays.
Note that the parentheses are not needed but are used to make the statement easier to read.

The program also computes and outputs the user's age in minutes.

Figure 2.7.2: Health data: Calculating user's age in days and


minutes.

import java.util.Scanner;

public class HealthData {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int userAgeYears;

int userAgeDays;
int userAgeMinutes;

System.out.print("Enter your age in years: ");

userAgeYears = scnr.nextInt();

userAgeDays = userAgeYears * 365; // Calculate days


without leap years

userAgeDays = userAgeDays + (userAgeYears / 4); // Add days for leap


years

System.out.println("You are " + userAgeDays + " days old.");

userAgeMinutes = userAgeDays * 24 * 60; // 24 hours/day, 60


minutes/hour

System.out.println("You are " + userAgeMinutes + " minutes old.");

OUTPUT

Enter your age in years: 19

You are 6939 days old.

You are 9992160 minutes old.


PARTICIPATION ACTIVITY

2.7.2: Calculating user age in days.

1) The expression (userAgeYears / 4) assumes a leap year occurs every four years?

True.Since the program does not ask what year the user was born, the calculation does
not account for the absence of leap years in some years that are multiples of 100.

2) The statement userAgeDays = userAgeDays + (userAgeYears / 4);


requires parentheses to evaluate correctly.

False.Parentheses are not required because / has higher precedence than +. But, the
parentheses make the order of evaluation explicit, which makes the programmer's
intention clear.

3) If the user enters 20, what is userAgeDays after the first assignment statement?

7300.The first assignment statement assigns userAgeDays with 20 * 365 or 7300.

4) If the user enters 20, what is userAgeDays after the second assignment statement?

7305.The second assignment statement assigns userAgeDays with 7300 + (20 / 4),
which is 7300 + 5 or 7305.

Estimating total heartbeats in user's lifetime


The program is incrementally extended again to calculate the approximate number of times the user's
heart has beat in his/her lifetime using an average heart rate of 72 beats per minutes.

Figure 2.7.3: Health data: Calculating total heartbeats lifetime.

import java.util.Scanner;
public class HealthData {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int userAgeYears;

int userAgeDays;

int userAgeMinutes;

int totalHeartbeats;

int avgBeatsPerMinute = 72;

System.out.print("Enter your age in years: ");

userAgeYears = scnr.nextInt();

userAgeDays = userAgeYears * 365; // Calculate days


without leap years

userAgeDays = userAgeDays + (userAgeYears / 4); // Add days for leap


years

System.out.println("You are " + userAgeDays + " days old.");

userAgeMinutes = userAgeDays * 24 * 60; // 24 hours/day, 60


minutes/hour
System.out.println("You are " + userAgeMinutes + " minutes old.");

totalHeartbeats = userAgeMinutes * avgBeatsPerMinute;

System.out.println("Your heart has beat " + totalHeartbeats + "


times.");

OUTPUT

Enter your age in years: 19

You are 6939 days old.

You are 9992160 minutes old.

Your heart has beat 719435520 times.

PARTICIPATION ACTIVITY

2.7.3: Calculating user's heartbeats.

1) Which variable is initialized when declared?

avgBeatsPerMinute-The variable declaration for avgBeatsPerMinute initializes the


variable with 72.

2) If the user enters 10, what value is held in totalHeartbeats after the statement
userAgeDays = userAgeYears * 365;
Unknown.totalHeartbeats has not yet been assigned, so the value held in the variable is
not known. The later statement totalHeartbeats = userAgeMinutes *
avgBeatsPerMinute; assigns totalHeartbeats with 378639360.

Limits on int values

In the above example, a userAge value of 57 or greater may yield an incorrect output for
totalHeartbeats. The reason is that an int variable can typically only hold values up to about 2 billion;
trying to store larger values results in "overflow". Other sections discuss overflow as well as other data
types that can hold larger values.

2.8 Floating-point numbers (double)


Floating-point (double) variables
A floating-point number is a real number containing a decimal point that can appear anywhere (or
"float") in the number. Ex: 98.6, 0.0001, or -55.667. A double variable stores a floating-point number.
Ex: double milesTravel; declares a double variable.

A floating-point literal is a number with a fractional part, even if the fraction is 0, as in 1.0, 0.0, or
99.573. Good practice is to always have a digit before the decimal point, as in 0.5, since .5 might
mistakenly be viewed as 5.

Scanner's nextDouble() method reads a floating-point value from input. Ex: currentTemp =
scnr.nextDouble(); reads a floating-point value from the input and assigns currentTemp with
that value.

Figure 2.8.1: Variables of type double: Travel time example.


import java.util.Scanner; 400.5 miles would
take:
public class TravelTime { 0.801 hours to
public static void main(String[] args) { fly,
Scanner scnr = new Scanner(System.in);
double milesTravel; // User input of miles to 6.675 hours
travel to drive.
double hoursFly; // Travel hours if flying those
miles
double hoursDrive; // Travel hours if driving
those miles

System.out.print("Enter distance in miles: ");


milesTravel = scnr.nextDouble();

hoursFly = milesTravel / 500.0;


hoursDrive = milesTravel / 60.0;

System.out.println(milesTravel + " miles would


take:");
System.out.println(" " + hoursFly + " hours to
fly,");
System.out.println(" " + hoursDrive + " hours to
drive.");
}
}

PARTICIPATION ACTIVITY

2.8.1: Declaring and assigning double variables.

All variables are of type double and already declared unless otherwise noted.

1) Declare a double variable named personHeight.

double personHeight;

The compiler will allocate a particular memory location for personHeight.

2) Declare a double variable named packageWeight and initialize the variable to 7.1.
double packageWeight = 7.1;

The compiler will allocate a particular memory location for packageWeight and store
7.1 in that memory location.

3) Assign ballRadius with ballHeight divided by 2.0. Do not use the fraction 1.0 / 2.0; instead,
divide ballHeight directly by 2.0.

ballRadius = ballHeight / 2.0;

Note that 2.0, not 2, should be used when dealing with floating-point numbers.

4) Assign ballRadius with ballHeight multiplied by one half, namely (1.0 / 2.0). Use the
parentheses around the fraction.

ballRadius = ballHeight * (1.0 / 2.0);orballRadius = (1.0 / 2.0) * ballHeight;

The statement first evaluates (1.0 / 2.0), which is 0.5, and then evaluates ballHeight *
0.5. Ex: If ballHeight is 12.0, the expression evaluates to 12.0 * (1.0 / 2.0), which is
12.0 * 0.5, or 6.0.

PARTICIPATION ACTIVITY

2.8.2: Floating-point literals.

1) Which statement best declares and initializes the double variable?

double currHumidity = 99.0;.A floating-point literal should have a fractional


part, even if 0.

2) Which statement best assigns the variable? Both variables are of type double.
cityRainfall = measuredRain - 5.0;.Best to use a floating-point literal like
5.0, rather than an integer literal like 5, when dealing with floating-point variables.

3) Which statement best assigns the variable? cityRainfall is of type double.

cityRainfall = 0.97;.Best to have the 0 before the decimal point so that the
decimal point isn't overlooked. Just .97 might be seen as 97 by a person reading the
code.

Scientific notation

Very large and very small floating-point values may be printed using scientific notation. Ex: If a
floating variable holds the value 299792458.0 (the speed of light in m/s), the value will be
printed as 2.99792458E8.

Choosing a variable type (double vs. int)


A programmer should choose a variable's type based on the type of value held.

● Integer variables are typically used for values that are counted, like 42 cars, 10 pizzas, or -95
days.
● Floating-point variables are typically used for measurements, like 98.6 degrees, 0.00001
meters, or -55.667 degrees.
● Floating-point variables are also used when dealing with fractions of countable items, such as
the average number of cars per household.

Floating-point for money

Some programmers warn against using floating-point for money, as in 14.53 representing 14
dollars and 53 cents, because money is a countable item (reasons are discussed further in
another section). int may be used to represent cents or to represent dollars when cents are not
included as for an annual salary, as in 40000 dollars, which are countable.

PARTICIPATION ACTIVITY

2.8.3: Floating-point versus integer.


Choose the best type for a variable to represent each item.

1) The number of cars in a parking lot.

int.Countable: 1 car, 2 cars, 3 cars, etc.

2) The current temperature in Celsius.

double.A measurement.

3) A person's height in centimeters.

double.A measurement.

4) The number of hairs on a person's head.

int.The number of hairs may be large, but is still countable: 1 hair, 2 hairs, etc.

5) The average number of kids per household.

double.Nobody has exactly 2.2 kids, but the average almost certainly should involve a
fraction.

Floating-point division by zero


Dividing a nonzero floating-point number by zero is undefined in regular arithmetic. Many
programming languages produce an error when performing floating-point division by 0, but Java does
not. Java handles this operation by producing infinity or -infinity, depending on the signs of the
operands. Printing a floating-point variable that holds infinity or -infinity outputs Infinity or
-Infinity.
If the dividend and divisor in floating-point division are both 0, the division results in a "not a number".
Not a number (NaN) indicates an unrepresentable or undefined value. Printing a floating-point variable
that is not a number outputs NaN.

Figure 2.8.2: Floating-point division by zero example.

import java.util.Scanner;

public class GasOilMixRatio {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

double gasVolume;

double oilVolume;

double mixRatio;

System.out.print("Enter gas volume: ");

gasVolume = scnr.nextDouble();

System.out.print("Enter oil volume: ");

oilVolume = scnr.nextDouble();
mixRatio = gasVolume / oilVolume;

System.out.print("Gas to oil mix ratio is " + mixRatio + ":1");

Enter gas volume: 10.5

Enter oil volume: 0.0

Gas to oil mix ratio is Infinity:1

Feedback?

PARTICIPATION ACTIVITY

2.8.4: Floating-point division.

Determine the result.

1) 13.0 / 3.0

4.333333 . Floating-point division retains the fractional value.

2) 0.0 / 5.0
0.0

3) 12.0 / 0.0

Positive infinity

4) 0.0 / 0.0

Not a number.Floating-point division of zero by zero is a special case that results in not a
number, or NaN.

Manipulating floating-point output


Some floating-point numbers have many digits after the decimal point. Ex: Irrational numbers (Ex:
3.14159265359...) and repeating decimals (Ex: 4.33333333...) have an infinite number of digits after
the decimal. By default, most programming languages output at least 5 digits after the decimal point.
But for many simple programs, this level of detail is not necessary. A common approach is to output
floating-point numbers with a specific number of digits after the decimal to reduce complexity or
produce a certain numerical type (Ex: Representing currency with two digits after the decimal). The
syntax for outputting the double myFloat with two digits after the decimal point is

System.out.printf("%.2f", myFloat);

When outputting a certain number of digits after the decimal using printf(), Java rounds the last
output digit, but the floating-point value remains the same. Manipulating how numbers are output is
discussed in detail elsewhere.

PARTICIPATION ACTIVITY

2.8.5: Reducing the output of pi.

1. The mathematical constant pi (π) is irrational, a floating-point number whose digits after the
decimal point are infinite and non-repeating. The value of pi is contained in the Java defined
constant Math.PI.
2. Though Java does not attempt to output the full value of pi, by default, 15 digits after the
decimal are output.
3. System.out.printf("%.4f", Math.PI) outputs pi to only four digits after the decimal. The last
digit is rounded up in the output, but the value of pi remains the same.
PARTICIPATION ACTIVITY

2.8.6: Reducing floating-point output.

1) Which of the following arguments completes printf() to output two digits after the decimal
point?

System.out.printf(_____, 7.0 / 3.0);

"%.2f". System.out.printf("%.2f", 7.0 / 3.0); outputs 2.33.

2) What is output by System.out.printf("%.1f", 0.125);?

0.1 System.out.printf("%.1f", 0.125); outputs the value with one digit after
the decimal point.

3) What is output by System.out.printf("%.3f", 9.1357);?

9.136.System.out.printf("%.3f", 9.1357); outputs 9.136 because the third


digit after the decimal point is rounded.

CHALLENGE ACTIVITY

2.8.1: Sphere volume.

Given sphereRadius, compute the volume of a sphere and assign sphereVolume with the
result. Use (4.0 / 3.0) to perform floating-point division, instead of (4 / 3) which performs
integer division.

Volume of sphere = (4.0 / 3.0) π r3 (Hint: r3 can be computed using *)


import java.util.Scanner;

public class SphereVolumeCalculator {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

double sphereVolume;

double sphereRadius;

sphereRadius = scnr.nextDouble();

/* Your solution goes here */

sphereVolume = (4.0 / 3.0) * Math.PI * (sphereRadius*sphereRadius*sphereRadius);

System.out.printf("%.2f\n", sphereVolume);

2.9 Scientific notation for floating-point


literals
Scientific notation is useful for representing floating-point numbers that are much greater than or
much less than 0, such as 6.02 x 1023. A floating-point literal using scientific notation is written using
an e preceding the power-of-10 exponent, as in 6.02e23 to represent 6.02 x 1023. The e stands for
exponent. Likewise, 0.001 is 1 x 10-3 and can be written as 1.0e-3. For a floating-point literal, good
practice is to make the leading digit non-zero.

Figure 2.9.1: Calculating atoms of gold.

import java.util.Scanner;

public class GoldAtoms {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

double avogadrosNumber = 6.02e23; // Approximation of atoms per mole

double gramsPerMoleGold = 196.9665;

double gramsGold;

double atomsGold;

System.out.print("Enter grams of gold: ");

gramsGold = scnr.nextDouble();

atomsGold = gramsGold / gramsPerMoleGold * avogadrosNumber;

System.out.print(gramsGold + " grams of gold contains ");


System.out.println(atomsGold + " atoms");

Enter grams of gold: 4.5

4.5 grams of gold contains 1.375360784701967E22 atoms

Feedback?

PARTICIPATION ACTIVITY

2.9.1: Scientific notation.

1) Type 1.0e-4 as a floating-point literal with a single digit before and four digits after the
decimal point. Note: Do not use scientific notation.

0.0001

The e-4 shifts the decimal point four places to the left.

2) Type 7.2e-4 as a floating-point literal with a single digit before and five digits after the
decimal point. Note: Do not use scientific notation.

0.00072

The e-4 shifts the decimal point four places to the left.
3) Type 540,000,000 as a floating-point literal using scientific notation with a single digit before
and after the decimal point.

5.4e8

Represents 5.4x108.

4) Type 0.000001 as a floating-point literal using scientific notation with a single digit before
and after the decimal point.

1.0e-6

Represents 1.0x10-6. Note: Although 0.1e-5 is also correct, good practice is to start with
a non-zero digit.

5) Type 623.596 as a floating-point literal using scientific notation with a single digit before and
five digits after the decimal point.

6.23596e2

The e2 shifts the decimal two places to the right, thus adjusting 6.23596 into the desired
623.596.

CHALLENGE ACTIVITY

2.9.1: Acceleration of gravity.

Compute the acceleration of gravity for a given distance from the earth's center, distCenter,
assigning the result to accelGravity. The expression for the acceleration of gravity is: (G *
M) / (d2), where G is the gravitational constant 6.673 x 10-11, M is the mass of the earth
5.98 x 1024 (in kg) and d is the distance in meters from the earth's center (stored in variable
distCenter). Note: Assume distance is at least the radius of the earth.
import java.util.Scanner;

public class GravityCalculation {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

double G = 6.673e-11;

double M = 5.98e24;

double accelGravity;

double distCenter;

distCenter = scnr.nextDouble();

/* Your solution goes here */

accelGravity=(G * M)/(distCenter * distCenter);


System.out.println(accelGravity);

2.10 Comments and whitespace


Comments
A comment is text a programmer adds to code, to be read by humans to better understand the code
but ignored by the compiler. Two common kinds of comments exist:

● A single-line comment starts with // and includes all the following text on that line. Single-line
comments commonly appear after a statement on the same line.
● A multi-line comment starts with /* and ends with */, where all text between /* and */ is part
of the comment. A multi-line comment is also known as a block comment.

Figure 2.10.1: Comments example.

import java.util.Scanner

/*

This program calculates the amount of pasta to cook, given the

number of people eating.


Author: Andrea Giada

Date: May 30, 2017

*/

public class PastaCalculator {

public static void main (String [] args) {

Scanner scnr = new Scanner(System.in);

int numPeople; // Number of people that will be eating

int totalOuncesPasta; // Total ounces of pasta to serve numPeople

// Get number of people

System.out.println("Enter number of people: ");

numPeople = scnr.nextInt();

// Calculate and print total ounces of pasta

totalOuncesPasta = numPeople * 3; // Typical ounces per person

System.out.println("Cook " + totalOuncesPasta + " ounces of


pasta.");

}
}

PARTICIPATION ACTIVITY

2.10.1: Comments.

Indicate which are valid comments.

1) // Get user input

Valid. standard single-line comment.

2) /* Get user input */

Valid.A multi-line comment is allowed on a single line, but good practice is to use // for
single-line comments, reserving /* */ for multi-line comments.

3) /* Determine width and height,

calculate volume,

and return volume squared.

*/

Valid.A typical multi-line comment.

4) // Print "Hello" to the screen //


Valid.The second // is ignored just like other text after the first //.

5) // Print "Hello"

Then print "Goodbye"

And finally return.

//

Valid.The first line's // only applies to the remainder of the line. The second and third
lines would yield compiler errors.

6)/*

* Author: Michelangelo

* Date: 2014

* Address: 111 Main St, Pacific Ocean

*/

Valid.Programmers commonly use single asterisks to make clear which lines are
contained in the comment. Those single asterisks have no special meaning; they are
just text within the /* ... */.

7) // numKids = 2; // Typical number


Valid.The entire line after the first // is ignored. The numKids = 2 statement won't
execute, but the code is valid. (Perhaps the programmer intentionally commented out
the code for the moment).

8)/*

numKids = 2; // Typical number

numCars = 5;

*/

Valid.The programmer has likely temporarily "commented out" those two statements.
The // within the /* .. */ will be ignored, like the other text.

9)/*

numKids = 2; /* Typical number */

numCars = 5;

*/

Not Valid.The first /* starts a multi-line comment. That comment ENDS at the */ on the
SECOND line. The compiler will compile numCars = 5, then generate an error when
reaching a */ that isn't ending a comment. Programmers use // when possible in part so
that /* ... */ can be used to "comment out" code.

JavaDoc comments

Java supports a third type of comment, known as a JavaDoc comment (discussed elsewhere), which is
a specially formatted multi-line comment that can be converted to program documentation in HTML.
Whitespace
Whitespace refers to blank spaces (space and tab characters) between items within a statement and
blank lines between statements (called newlines). A compiler ignores most whitespace.

Good practice is to deliberately and consistently use whitespace to make a program more readable.
Programmers usually follow conventions defined by their company, team, instructor, etc., such as:

● Use blank lines to separate conceptually distinct statements.


● Indent lines the same amount.
● Align items to reduce visual clutter.
● Use a single space before and after any operators like =, +, *, or / to make statements more
readable.

Figure 2.10.2: Good use of whitespace.

import java.util.Scanner;

public class WhitespaceEx {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int myFirstVar; // Aligned comments yield less

int yetAnotherVar; // visual clutter

int thirdVar;

// Above blank line separates variable declarations from the rest

System.out.print("Enter a number: ");


myFirstVar = scnr.nextInt();

// Above blank line separates user input statements from the rest

yetAnotherVar = myFirstVar; // Aligned = operators

thirdVar = yetAnotherVar + 1;

// Also notice the single-space on left and right of + and =

// (except when aligning the second = with the first =)

System.out.println("Final value is " + thirdVar); // Single-space on


each side of +

Figure 2.10.3: Bad use of whitespace.

import java.util.Scanner;

public class PastaCalculator {

public static void main (String [] args) {

Scanner scnr = new Scanner(System.in);int numPeople;int totalOuncesPasta;

System.out.println("Enter number of people:");


numPeople = scnr.nextInt(); totalOuncesPasta = numPeople * 3;

System.out.println("Cook "+totalOuncesPasta+" ounces of pasta.");}}

PARTICIPATION ACTIVITY

2.10.2: Whitespace.

Are the specified lines of code good or bad uses of whitespace?

import java.util.Scanner;

public class WhitespaceGoodAndBad {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int userAge;

int currentDecade;

int nextDecade;

int nextMilestone;

System.out.println("Enter your age: ");

userAge = scnr.nextInt();
currentDecade=userAge/10;

nextDecade = currentDecade + 1;

nextMilestone = nextDecade * 10;

System.out.println("Next big birthday is at " + nextMilestone);

1) int nextDecade;

Bad.The whitespace between int and nextDecade is unnecessary and yields less
readable code.

2) currentDecade=userAge/10;

Bad.Spaces before and after the = and / operators would make the statement more
readable.

3) nextDecade = currentDecade + 1;

Good.The statement is indented the same amount as the preceding lines, and a space is
used before and after the = and + operators.

4) nextMilestone = nextDecade * 10;


Bad.The statement is not indented the same number of spaces as the other related lines
of code.

Compiling code with comments and whitespace


The animation below provides a (simplified) demonstration of how a compiler processes code from
left-to-right and line by line, finding each statement (and generating machine code using 0s and 1s)
and ignoring whitespace and comments.

PARTICIPATION ACTIVITY

2.10.4: Compiling code with whitespace and comments.

1) Spaces are always ignored by the compiler.

False.Not all spaces are ignored by the compiler. Ex: The spaces in a string literal like
"Enter age: " will be printed if the string is output.

2) How many spaces will the compiler ignore in the code below?

numToBuy = numNeeded - numInStock + 2;

6.The spaces before and after the =, -, and + are ignored by the compiler.

3) How many lines will the compiler ignore in the code below?

int userAge;

int currentDecade;

int nextDecade;

int nextMilestone;
// FIXME: Get user age

userAge = 29; // Testing with 29

currentDecade = userAge / 10;

nextDecade = currentDecade + 1;

nextMilestone = nextDecade * 10;

3.The compiler ignores the 2 blank lines and the line that only contains a comment.

2.11 Calling methods (EO)


A program uses the operations supported by objects to perform useful tasks, such as printing
text or getting a user's input. A method call is a statement that invokes an object's method,
allowing the program to perform a particular operation on that object.

Construct 2.11.1: Writing a method call to perform an operation


on an object.

objectName.methodName();

Calling a method on an object requires appending the "." operator and the method's name to the
object's name. The "." operator is also known as the member access operator.

PARTICIPATION ACTIVITY

2.11.1: Object method calls.

Select the statement that correctly performs the requested task on a PeopleCounter object. The
PeopleCounter class contains methods resetCount(), incrementCount(), and printCount().
1) Call the resetCount method on a PeopleCounter object named guestCounter.

guestCounter.resetCount(); . The object name comes before the


".", and the method being called on that object comes after
the ".".

2) Call the printCount method on a PeopleCounter object named guestCounter.

guestCounter.printCount();.The method name is followed by


parentheses.

A class' public methods are the operations that a program can directly invoke on objects of that
class type. The class' public methods are often called the class interface. A programmer only
needs to understand the class interface to use objects of that class type.

Consider a histogram, which is a diagram that groups data into ranges of values, or bins, and
displays the number of items within each bin as a rectangular bar. The histogram below has five
bins (one for each letter grade), and the value of each bin represents the number of students with
each letter grade.

Figure 2.11.1: Histogram representing the distribution of exam


scores.
Feedback?

A programmer could use a Histogram class to create histogram objects within a program.
Although looking at the implementation of a class is not required, the following provides a brief
look inside the Histogram class to illustrate the difference between the class' internal data and
public methods. The methods for a class' interface are listed after the public keyword in the class
definition. The internal data (and internal methods) are listed after the private keyword.

PARTICIPATION ACTIVITY

2.11.2: A look inside the Histogram class.

public class Histogram {

// Internal data (private fields)

private int[] histogramData;


// Operations (public methods)

// Sets the number of bins (previous data is deleted)

public void setNumberOfBins(int numberBins) {...}

// Sets the value for the bin at the specified index

public void setBinValue(int binIndex, int binValue) {...}

// Returns the value of the bin at the specified index

public int getBinValue(int binIndex) {...}

// Prints the histogram

public void printHistogram() {...}

private keyword indicates data is internal to class.

public methods define the class' interface.

The Histogram class' interface provides methods that allow a program to set the number of bins,
set the value of a bin, get the value of a bin, and print the histogram.

PARTICIPATION ACTIVITY

2.11.3: Using a class' public interface.


1) A program can access all methods defined by an object's class, including methods that
are private.

False.Internal (or private) data and methods are not meant to be used outside of the
class.

2) A programmer needs to know the underlying class implementation in order to use an


object of that class type.

True.Only knowledge of a class' public methods is necessary to use an object of that


class type.

Some methods require additional input information from the calling program in order to perform
the intended operation. For example, setting the number of bins on a Histogram object requires
the program to provide an input value representing the number of bins. Likewise, setting the
value for a particular bin requires two input values: A bin index to identify the bin, and the value
for the bin. Programmers influence the behavior of methods by providing additional input values,
called method arguments, in a method call.

Figure 2.11.2: Passing arguments in method calls.

public class MovieExample {

public static void main(String[] args) {

Histogram movieReviewScores = new Histogram();

movieReviewScores.setNumberOfBins(6);

movieReviewScores.setBinValue(0, 1);

movieReviewScores.setBinValue(1, 2);
movieReviewScores.setBinValue(2, 2);

movieReviewScores.setBinValue(3, 7);

movieReviewScores.setBinValue(4, 10);

movieReviewScores.setBinValue(5, 3);

movieReviewScores.printHistogram();

OUTPUT

0 -

1 --

2 --

3 -------

4 ----------

5 ---

The setNumberOfBins() method in the Histogram class is defined as public void


setNumberOfBins(int numberBins), indicating that the method has a parameter of type
int named numberBins. The input specified in a method definition is call a parameter. The
method call movieReviewScores.setNumberOfBins(6) passes the value 6 to that
parameter. The value passed to a parameter is known as an argument.
A method may require multiple arguments, which are separated by commas within the
parentheses of the method call. Argument values are assigned to parameters by position: First
argument to the first parameter, second to the second, etc. The setBinValue() method requires
two arguments: The first argument is the bin index, and the second argument is the bin value.
The method call movieReviewScores.setBinValue(3, 7) sets bin 3's value to 7.

PARTICIPATION ACTIVITY

2.11.4: Calling methods that require arguments.

Select the statement that correctly performs the requested task. Refer to the
Histogram class, which includes the methods setNumberOfBins(), setBinValue(), and
printHistogram().

1)Write a method call that sets the number bins for a Histogram object named
coinFlipHistogram to 2.

coinFlipHistogram.setNumberOfBins(2);

The method calls passes the value 2 as the argument of the method.

2) Write a method call that sets the value of the bin 1 to the value 10 for a Histogram object
named coinFlipHistogram.

coinFlipHistogram.setBinValue(1, 10);

The arguments are comma separated and provided in the appropriate order.

zyDE 2.11.1: Creating and using objects: Histogram.

Try running the histogram program below. Modify the program to display a Histogram object with
4 bins, using bin values of 2, 11, 9, and 5. Methods for Histogram include setNumberOfBins(),
setBinValue(), and printHistogram().
public class MovieExample {

public static void main(String[] args) {

Histogram movieReviewScores = new Histogram();

movieReviewScores.setNumberOfBins(4);

movieReviewScores.setBinValue(0, 2);

movieReviewScores.setBinValue(1, 11);

movieReviewScores.setBinValue(2, 9);

movieReviewScores.setBinValue(3, 5);

// movieReviewScores.setBinValue(4, 5);

// movieReviewScores.setBinValue(5, 3);

movieReviewScores.printHistogram();

Methods can also perform operations that return a value, known as a return value, to the
program. The Histogram class' getBinValue() method returns an integer value representing the
current value of a bin.

PARTICIPATION ACTIVITY

2.11.5: Method returning a value.


public class CoinFlipEx {

public static void main(String[] args) {

Histogram coinFlipHist = new Histogram();

// Set two bins: heads or tails

coinFlipHist.setNumberOfBins(2);

// Record number of heads

coinFlipHist.setBinValue(0, 7);

// Record number of tails

coinFlipHist.setBinValue(1, 9);

System.out.print("Heads: ");

System.out.println(coinFlipHist.getBinValue(0));

}
}

coinFlipHist object

Internal data:

bin 1:

bin 0:

Operations:

setNumberOfBins

setBinValue

getBinValue

printHistogram

setNumberOfBins(2)

setBinValue(0, 7)

setBinValue(1, 9)

Heads:

getBinValue(0)
7

getBinValue() method returns value of specified bin

1. Creating a Histogram object and setting the number of bins.


2. Setting the bin values for the Histogram object.
3. getBinValue() method returns value of specified bin.

The type of value returned by an object's method is defined in object's class definition. A method
may return a single value or none. The Histogram class' getBinValue() method returns an integer
value, which is specified by the int keyword before the method name in the method's declaration:
public int getBinValue(int binIndex) {. The printHistogram() method does not
return a value, specified the void in the method declaration.

PARTICIPATION ACTIVITY

2.11.6: Method return value.

1) A method can return more than one value.

False

2) methods can only return int values.

False
3) The Histogram's class getBinValue() method returns an integer representing a bin's
value.

True

2.12 Constructing objects (EO)


Creating an object and assigning a variable with that object involves three parts:

1. Reference variable: The first part of the statement, Histogram gradesHistogram


declares a reference variable that can refer to an object. But, the variable declaration does not
create an object. A reference is a variable type that refers to an object. A reference may be
thought of as storing the memory address of an object.
2. new operator: The next part of the statement, new Histogram(), creates a new object.
The new operator creates an object by allocating memory for the object and initializing the
object by calling a constructor.
3. Constructor: A constructor is a special method for an object that is called whenever a new
object is created, and is used to initialize the object's internal data. A class may define more
than one constructor. The Histogram() part of the statement indicates which constructor
should be called.

PARTICIPATION ACTIVITY

2.12.1: Constructing an object.

PARTICIPATION ACTIVITY

2.12.2: Constructing objects.

How many objects are created in each of the following segments?

1) PeopleCounter inCounter = new PeopleCounter();


PeopleCounter outCounter = new PeopleCounter();

2.Each statement declares a reference variable and creates a new object.

2)

PeopleCounter passengerCount;

PeopleCounter staffCount;

0.No objects are created. The new operator must be called to create an object.

3)

PeopleCounter studentCount;

PeopleCounter examCount;

studentCount = new PeopleCounter();

The variable declaration and object creation can be split into two statements.

Programmers often want to initialize newly created objects with different options. A class may define
several constructors with different parameter types. For example, the Histogram class defines a
constructor that takes a single argument specifying the number of bins in the histogram. The
statement Histogram passFailHistogram = new Histogram(2) passes the value 2
as an argument to the object's constructor. The following program illustrates.

Figure 2.12.1: Passing arguments to a constructor.


public class PartsInspection {

public static void main(String[] args) {

// Histogram object for tracking number of parts

// that pass (bin 0) or fail (bin 1) inspection.

Histogram passFailHistogram = new Histogram(2);

passFailHistogram.setBinValue(0, 56);

passFailHistogram.setBinValue(1, 3);

System.out.println("Parts passing(0) or failing(1) inspection:");

passFailHistogram.printHistogram();

Parts passing(0) or failing(1) inspection:

0 --------------------------------------------------------

1 ---

PARTICIPATION ACTIVITY
2.12.3: Creating objects using different constructors.

Consider a Timer that has multiple constructors defined as follows. Which constructor is
called in each of the following object creation statements?

public class Timer {

Timer() {...}

Timer(int minutes) {...}

Timer(int hours, int minutes) {...}

1) Timer ovenTimer = new Timer();

Timer(). No arguments are passed to the constructor. A constructor that does


not require arguments is called the default constructor.

2) Timer roastChickenTimer = new Timer(1, 30);

Timer(int hours, int minutes)

Passing arguments to a constructor works just like passing arguments to


other methods. The value 1 is passed to the hours parameter, and the value
30 is passed to the minutes parameter.

3) Timer hardBoiledEggTimer = new Timer(10.5);


None of the above.No constructor takes a floating-pointing value as an argument.

Using the Java Rectangle class


The Java Rectangle class contains four instance members for the X and Y location of the rectangle's
upper left corner, the rectangle's width, and the rectangle's height. Ex: new Rectangle(40, 80,
100, 120) creates a Rectangle with the upper left corner at location (40, 80) and with a size that is
100 units wide by 120 units high.

The Rectangle class has mutator methods to manipulate a rectangle's size and location. The
setSize(width, height) method changes the width and height. The setLocation(xLoc, yLoc) method
changes the location of the upper left corner. The translate(xDist, yDist) method repositions the
Rectangle by the specified distances in the X and Y direction. Ex: translate(30, 40) moves the
rectangle to the right 30 units and downward 40 units. Note, the Java coordinate system places the
origin (0, 0) in the upper left corner. The X-axis increases to the right and the Y-axis increases
downward.

The program below creates and manipulates two Rectangle objects. The animation draws Rectangle
outlines to show how instance members are manipulated. However, the program would not actually
draw the Rectangles without additional effort (discussed elsewhere).

PARTICIPATION ACTIVITY

2.12.4: Using the Java Rectangle class.

import java.awt.Rectangle;

public class UsingRectangle {

public static void main(String[] args) {

Rectangle redRect = new Rectangle(20, 20, 60, 20);

redRect.setSize(120, 20);

redRect.translate(40, 40);
redRect.setLocation(10, 160);

Rectangle blueRect = new Rectangle(150, 30, 40, 100);

blueRect.translate(-75, 0);

CAPTION

A redRect object is created at location (20, 20) with a width of 60 and a


height of 20.

The setSize(120, 20) method increases redRect's width to 120. The


translate(40, 40) method move's the redRect's position 40 units right and
40 units down.

setLocation(10, 160) sets redRect's upper left corner to coordinates (10,


160).

Another Rectangle object, blueRect, is created at location (150, 30) with


width 40 and height 100. The translate(-75, 0) method then moves blueRect
75 units left.

PARTICIPATION ACTIVITY

2.12.5: Java Rectangle class.


Refer to the animation above.

1) What will be the area of the blue rectangle after executing

blueRect.setSize(20, 40);

800

2) Which direction will the blue rectangle move by executing

blueRect.translate(0, -40);

Up.The y-axis in Java increases from top to bottom, so a negative value does not move
down.The rectangle moves -40 units along the y-axis, which is 40 units upwards.

2.13 Accessors and mutators (EO)


An object's methods are commonly classified as either mutators or accessors. A mutator
method may modify ("mutate") the object, thereby changing the object's internal data. An
accessor method accesses the object's data but does not modify the internal data.

PARTICIPATION ACTIVITY

2.13.1: Accessors and mutators.

void setNumberOfBins(int numberBins)

int getBinValue(int binIndex)

void printHistogram()

void setBinValue(int binIndex, int binValue)

public class Histogram {


// Internal data (private fields)

private int[] histogramData;

// Operations (public methods)

// Sets the number of bins (previous data is deleted)

public void setNumberOfBins(int numberBins) {...}

// Sets the value for the bin at the specified index

public void setBinValue(int binIndex, int binValue) {...}

// Returns the value of the bin at the specified index

public int getBinValue(int binIndex) {...}

// Prints the histogram

public void printHistogram() {...}

CAPTION

Mutators change the object's internal data.

Accessors access object's data but do not modify the data.

PARTICIPATION ACTIVITY
2.13.2: Mutator or accessor.

1) A mutator should not change an object's internal data.

False.A mutator "mutates", meaning changes, an object's internal data.

2) An accessor should not change an object's internal data.

True.An accessor may access the object's data, and then returns some value or performs
some operation.

3) The printHistogram() method for a Histogram object is an accessor.

True.The printHistogram method must read the object's internal data to print the
histogram.

4)The getBinValue() method for a Histogram object is a mutator.

False.The getBinValue method only accesses a Histogram object's data, but does not
modify the object's data.

2.14 Reading API documentation


Oracle's Java API Specification
Java provides an extensive set of classes for creating programs. Oracle's Java API Specification
provides detailed documents describing how to use those classes. The class' documentation is
known as an API, short for application programming interface.

The main page of the Java documentation lists all Java modules. A module is a group of related
packages. A package is a group of related classes. Organizing classes into modules and packages
helps programmers find needed classes. Ex: The java.base module defines Java's foundational
packages and APIs.

Figure 2.14.1: java.base module's documentation lists and


describes available packages.
Feedback?

Class overview
Previous programs in this material used a Scanner object to read input from the user. The Scanner
class is located in the package java.util. The Java documentation for a class consists of four
main elements. The following uses the Scanner class to illustrate these documentation elements. The
documentation for the Scanner is located at: Scanner class documentation.

Class overview: The first part of the documentation provides an overview of the class, describing the
class' functionality and providing examples of how the class is commonly used in a program.

Figure 2.14.2: Scanner class' overview.


Feedback?

The package in which a class is located appears immediately above the class name. The figure above
shows the Scanner class is located in the java.util package. To use a class, a program must include an
import statement that informs the compiler of the class' location.

Construct 2.14.1: Import statement.

import packageName.ClassName;

Feedback?

The statement import java.util.Scanner; imports the scanner class.


Constructor summary
Constructor summary: Provides a list and brief description of the constructors that can be used to
create objects of the class.

Figure 2.14.3: Scanner class' constructor summary.

Feedback?
Previous programs in this material used the statement Scanner scnr = new
Scanner(System.in); to construct a Scanner object. System.in is a InputStream object
automatically created when a Java programs executes. So, the constructor
Scanner(InputStream source) listed in the documentation is the matching constructor.

Method summary
Method summary: Provides a list and brief description of all methods that can be called on objects of
the class. The Java documentation only lists the public methods that a program may use.

Figure 2.14.4: Scanner class' method summary.

Feedback?

Constructor and method details


Constructor and method details: Lastly, the documentation for a class provides a detailed description
of all constructors and methods for the class. For each method, the documentation provides the
method declaration, a description of the method, a list of parameters (if any), a description of the
method's return value, and a list of possible exceptions the method may throw (discussed elsewhere).

The following shows the method details for the nextInt() method.

Figure 2.14.5: Scanner class' nextInt method documentation.

2.15 Debugging

Debugging is the process of determining and fixing the cause of a problem in a computer program.
Troubleshooting is another word for debugging. Far from being an occasional nuisance, debugging is
a core programmer task, like diagnosing is a core medical doctor task. Skill in carrying out a
methodical debugging process can improve a programmer's productivity.

Figure 2.15.1: A methodical debugging process.


Feedback?

A common error among new programmers is to try to debug without a methodical process, instead
staring at the program, or making random changes to see if the output is improved.

Consider a program that, given a circle's circumference, computes the circle's area. Below, the output
area is clearly too large. In particular, if circumference is 10, then radius is 10 / (2 * PI_VAL), so about
1.6. The area is then PI_VAL * 1.6 * 1.6, or about 8, but the program outputs about 775.

Figure 2.15.2: Circle area program: Problem detected.

import java.util.Scanner; Enter circumference: 10

public class CircumferenceToArea {


public static void main(String[] args) {
Circle area is:
Scanner scnr = new Scanner(System.in);
775.1569143502577
final double PI_VAL = 3.14159265;

double circleRadius;
double circleCircumference;
double circleArea;

System.out.print("Enter circumference: ");


circleCircumference = scnr.nextDouble();

circleRadius = circleCircumference / 2 *
PI_VAL;
circleArea = PI_VAL * circleRadius *
circleRadius;

System.out.println("Circle area is: " +


circleArea);
}
}
Feedback?

First, a programmer may predict that the problem is a bad output statement. This prediction can be
tested by adding the statement circleArea = 999;. The output statement is OK, and the
predicted problem is invalidated. Note that a temporary statement commonly has a "FIXME" comment
to remind the programmer to delete this statement.

Figure 2.15.3: Circle area program: Predict problem is bad


output.

import java.util.Scanner; Enter circumference: 0

public class CircumferenceToArea {


public static void main(String[] args) {
Circle area is: 999.0
Scanner scnr = new Scanner(System.in);
final double PI_VAL = 3.14159265;

double circleRadius;
double circleCircumference;
double circleArea;

System.out.print("Enter circumference: ");


circleCircumference = scnr.nextDouble();

circleRadius = circleCircumference / 2 * PI_VAL;


circleArea = PI_VAL * circleRadius * circleRadius;

circleArea = 999; // FIXME delete


System.out.println("Circle area is: " +
circleArea);
}
}
Feedback?

Next, the programmer predicts the problem is a bad area computation. This prediction is tested by
assigning the value 0.5 to radius and checking to see if the output is 0.7855 (which was computed by
hand). The area computation is OK, and the predicted problem is invalidated. Note that a temporary
statement is commonly left-aligned to make clear it is temporary.

Figure 2.15.4: Circle area program: Predict problem is bad area


computation.

import java.util.Scanner; Enter circumference: 0

public class CircumferenceToArea {


public static void main(String[] args) {
Circle area is:
Scanner scnr = new Scanner(System.in);
0.7853981625
final double PI_VAL = 3.14159265;

double circleRadius;
double circleCircumference;
double circleArea;

System.out.print("Enter circumference: ");


circleCircumference = scnr.nextDouble();

circleRadius = circleCircumference / 2 *
PI_VAL;

circleRadius = 0.5; // FIXME delete


circleArea = PI_VAL * circleRadius *
circleRadius;

System.out.println("Circle area is: " +


circleArea);
}
}

Feedback?
The programmer then predicts the problem is a bad radius computation. This prediction is tested by
assigning PI_VAL to the circumference, and checking to see if the radius is 0.5. The radius
computation fails, and the prediction is likely validated. Note that unused code was temporarily
commented out.

Figure 2.15.5: Circle area program: Predict problem is bad radius


computation.

import java.util.Scanner; Enter circumference: 0

public class CircumferenceToArea {


public static void main(String[] args) {
Radius:
Scanner scnr = new Scanner(System.in);
4.934802189267012
final double PI_VAL = 3.14159265;

double circleRadius;
double circleCircumference;
double circleArea;

System.out.print("Enter circumference: ");


circleCircumference = scnr.nextDouble();

circleCircumference = PI_VAL; // FIXME


delete
circleRadius = circleCircumference / 2 * PI_VAL;
System.out.println("Radius: " + circleRadius); // FIXME
delete

/*
area = PI_VAL * radius * radius;

System.out.println("Circle area is: " + area);


*/
}
}

Feedback?

The last test seems to validate that the problem is a bad radius computation. The programmer
visually examines the expression for a circle's radius given the circumference, which looks fine at first
glance. However, the programmer notices that radius = circumference / 2 * PI_VAL;
should have been radius = circumference / (2 * PI_VAL);. The parentheses around
the product in the denominator are necessary and represent the desired order of operations. Changing
to radius = circumference / (2 * PI_VAL); solves the problem.

The above example illustrates several common techniques used while testing to validate a predicted
problem:

● Manually set a variable to a value.


● Insert print statements to observe variable values.
● Comment out unused code.
● Visually inspect the code (not every test requires modifying/running the code).

Statements inserted for debugging must be created and removed with care. A common error is to
forget to remove a debug statement, such as a temporary statement that manually sets a variable to a
value. Left-aligning such a statement and/or including a FIXME comment can help the programmer
remember. Another common error is to use /* */ to comment out code that itself contains /* */
characters. The first */ ends the comment before intended, which usually yields a syntax error when
the second */ is reached or sooner.

The predicted problem is commonly vague, such as "Something is wrong with the input values."
Conducting a general test (like printing all input values) may give the programmer new ideas as to a
more-specific predicted problems. The process is highly iterative—new tests may lead to new
predicted problems. A programmer typically has a few initial predictions, and tests the most likely
ones first.

zyDE 2.15.1: Debugging using a repeated two-step process.

Use the above repeating two-step process (predict problem, test to validate) to find the problem in the
following code for the provided input.

Load default template...


1

10

11

12

13

14
15

16

17

import java.util.Scanner;

public class CubeVolume {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int sideLength;

int cubeVolume;

System.out.println("Enter cube's side length: ");

sideLength = scnr.nextInt();

cubeVolume = sideLength * sideLength * sideLength;


System.out.println("Cube's volume is: " + cubeVolume);

Run

Feedback?

PARTICIPATION ACTIVITY

2.15.1: Debugging.

Answer based on the above discussion.

1)

The first step in debugging is to make random changes to the code and see what happens.

True

False
2)

A common predicted-problem testing approach is to insert print statements.

True

False

3)

Variables in temporary statements can be written in uppercase, as in MYVAR = 999, to remind the
programmer to remove them.

True

False

4)

A programmer lists all possible predicted problems first, then runs tests to validate each.

True
False

5)

Most beginning programmers naturally follow a methodical process.

True

False

6)

A program's expected output is a positive integer. When run, the program's output is usually positive,
but in some cases the output becomes negative. Overflow is a good prediction of the problem.

True

2.16 Basic graphics


Java supports a set of objects for developing graphical applications. A graphical application is a
program that displays drawings and other graphical objects. Graphical applications display their
contents inside a window called a frame using a JFrame object. The following program shows how to
create and configure an JFrame object to display an empty application window.
Figure 2.16.1: Creating a JFrame object for a graphical
application.

import javax.swing.JFrame;

public class EmptyFrame {

public static void main(String[] args)

// Construct the JFrame object

JFrame appFrame = new JFrame();

// Set the frame's width (400) and height (250) in pixels

appFrame.setSize(400, 250);

// Set the frame's title

appFrame.setTitle("An Empty Frame");

// Set the program to exit when the user

// closes the frame

appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make the frame visible to the user

appFrame.setVisible(true);
}

Figure 2.16.2: Screenshot of empty application window.

Feedback?

Constructing a JFrame object does not immediately display a frame. The program uses the methods
supported by the JFrame object to configure and display the frame as follows:

1. Set the frame's size by calling the setSize() method with arguments for the width and height,
as in appFrame.setSize(400, 250). Forgetting to set the frame's size results in a
frame too small to see.
2. Set the frame's title by calling the setTitle() method with a String as the argument.
Alternatively, the frame's title can be provided as an argument to JFrame's constructor as in
JFrame appFrame = new JFrame("An Empty Frame").
3. Set the frame's closing operation by calling the setDefaultCloseOperation() method, as in
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE). This
statement configures the program to exit when the user closes the frame.
4. Make the frame visible to the user by calling the setVisible() method with a boolean argument
of true.

PARTICIPATION ACTIVITY

2.16.1: Configuring a JFrame.

Select the code statement that would resolve the described problem. Assume an empty
JFrame object named appFrame.

1)

The frame window lacks a title. User would like the title to be "My program".

appFrame.setTitle(My program);

appFrame.setTitle("My program");

2)

The program called the setVisible() method correctly (i.e., appFrame.setVisible(true);),


but the frame is not visible on the screen. The frame should be 500 pixels wide and 300 pixels tall.

appFrame.setSize(500, 300);

appFrame.setVisible(false);

appFrame.setSize(300, 500);

3)
The program does not exit when the user closes the frame.

appFrame.setDefaultCloseOperation();

appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Feedback?

A JFrame can be used to draw graphical objects, such as rectangles, circles, and lines. To display
graphical objects, a programmer can add a custom JComponent object to a frame. A JComponent is a
blank graphical component that a programmer extends (or customizes) with custom code in order to
draw basic shapes.

The following program demonstrates how to create a custom class that extends JComponent to draw
2D graphics. Creating a class that extends JComponent involves advanced topics, including defining a
class and inheritance, which are discussed elsewhere. For now, the following class can be used as a
template.

Figure 2.16.3: Basic example showing how to create a class


extending JComponent to draw 2D graphics.

import java.awt.Graphics;

import java.awt.Graphics2D;

import javax.swing.JComponent;

public class MyCustomJComponent extends JComponent {


@Override

public void paintComponent(Graphics g) {

// Cast to Graphics2D

Graphics2D graphicsObj = (Graphics2D)g;

// Write your drawing instructions

Feedback?

The above code defines a class named MyCustomJComponent that extends JComponent. The class
should be saved to a separate file named with the same name, MyCustomJComponent.java. A
programmer completes the template by providing custom drawing instructions in the
paintComponent() method. For example, the following program extends a JComponent to draw a
simple histogram using Rectangle and Color objects.

Figure 2.16.4: Drawing a histogram in a frame.

HistogramComponent.java

import java.awt.Color;

import java.awt.Graphics;
import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

// HistogramComponent extends the functionality of a JComponent

// in order to draw a histogram.

public class HistogramComponent extends JComponent {

// Paints a histogram with three bins

@Override

public void paintComponent(Graphics g) {

// Cast to Graphics2D

Graphics2D graphicsObj = (Graphics2D) g;

// Draw 1st bin as an olive colored rectangle at (10,10)

// with width = 200 and height = 50


Rectangle binRectangle1 = new Rectangle(10, 10, 200, 50);

Color binColor1 = new Color(128, 128, 0);

graphicsObj.setColor(binColor1);

graphicsObj.fill(binRectangle1);

// Draw 2nd bin as a teal blue rectangle at (10,75)

// with width = 150 and height = 50

Rectangle binRectangle2 = new Rectangle(10, 75, 150, 50);

Color binColor2 = new Color(0, 200, 200);

graphicsObj.setColor(binColor2);

graphicsObj.fill(binRectangle2);

// Draw 3rd bin as a gray rectangle at (10,140)

// with width = 350 and height = 50

Rectangle binRectangle3 = new Rectangle(10, 140, 350, 50);

Color binColor3 = new Color(100, 100, 100);


graphicsObj.setColor(binColor3);

graphicsObj.fill(binRectangle3);

HistogramViewer.java

import javax.swing.JFrame;

public class HistogramViewer {

public static void main(String[] args) {

JFrame appFrame = new JFrame();

HistogramComponent histogramComponent = new HistogramComponent();

appFrame.setSize(400, 250);

appFrame.setTitle("Histogram Viewer");

appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the HistogramComponent object to the frame

appFrame.add(histogramComponent);

// Set the frame and its contents visible

appFrame.setVisible(true);

Feedback?

Figure 2.16.5: Screenshot of HistogramViewer application.


Feedback?

The program first creates a HistogramComponent object named histogramComponent and adds the
object to the JFrame object using the add() method. Once added, the JFrame automatically calls the
histogramComponent objects paintComponent() method whenever the JFrame object is updated,
such as when the frame is resized.

The HistogramComponent's paintComponent() uses Rectangle and Color objects to draw a simple
histogram with three bins, using the operations:

1. Cast the Graphics object to Graphics2D: The statement Graphics2D graphicsObj =


(Graphics2D) g; converts the original Graphics object argument to a graphics object
that supports drawing two-dimensional objects.
2. Create a Rectangle object: A Rectangle object stores the location and size of a rectangle
shape. A Rectangle's constructor accepts arguments for location and size (in pixel units) as
specified by the constructor definition: Rectangle(int x, int y, int width,
int height).
3. Create a Color object: A Color object represents a color in the red, green, blue color space. A
Color constructor accepts an integer value between 0 to 255 for each color channel as
specified by the constructor definition: Color(int red, int green, int blue).
For example, the statement Color binColor1 = new Color(128, 128, 0);
creates a Color object with an olive color.
4. Set the color used by the Graphics2D object: Graphic2D's setColor() method sets the color
that the Graphics2D object will use for subsequent drawing operations.
5. Draw the shape: A Graphic2D object provides different methods for drawing shapes. The
draw() method will draw an outline of a shape, such as a Rectangle object, using the
Graphic2D object's current color. The fill() method will draw a shape filling the interior of the
shape with the Graphic2D object's current color.

PARTICIPATION ACTIVITY

2.16.2: Drawing a filled rectangle.

Start

2x speed

Rectangle binRect = new Rectangle(10, 75, 150, 50);

Color binColor = new Color(0, 200, 200);

graphicsObj.setColor(binColor);

graphicsObj.fill(binRect);

binRect object

Internal data:

(10, 75)

150

50

binColor object
Internal data:

(0, 200, 200)

Histogram Viewer

Internal data:

(0, 200, 200)

graphicsObj object

frame

Captions

keyboard_arrow_down

Feedback?

The programmer needs to know the positioning coordinate system in order to draw shapes in the
intended location. As the following figure illustrates, the top-left corner of a JComponent corresponds
to coordinates (0, 0). The x-coordinate increases horizontally to the right and the y-coordinate
increases vertically downward.

Figure 2.16.6: Graphics coordinate system.


Feedback?

PARTICIPATION ACTIVITY

2.16.3: Drawing colored rectangles.

Which code segment (type the letter) performs the described operation? Assume each
code segment is written within the paintComponent() method of an extended JComponent
class, and that the Graphics2D object is called graphicsObj.

Rectangle rectangle = new Rectangle(0, 0, 150, 100);

Color color = new Color(0, 255, 0);

graphicsObj.setColor(color);

graphicsObj.fill(rectangle);

1.

Rectangle rectangle = new Rectangle(0, 100, 200, 200);

Color color = new Color(255, 0, 0);

graphicsObj.setColor(color);

graphicsObj.fill(rectangle);

2.
Rectangle rectangle = new Rectangle(0, 100, 50, 150);

Color color = new Color(255, 0, 255);

graphicsObj.setColor(color);

graphicsObj.draw(rectangle);

3.

1)

Draws a filled in red square.

CheckShow answer

2)

Draws the outline of a purple rectangle 50 pixels wide and 150 pixels in height.

CheckShow answer

3)

Draws a rectangle whose top-left corner is located at the origin of the coordinate system.

CheckShow answer
4)

Draws a green, filled in rectangle.

CheckShow answer

Feedback?

A Graphics2D object can draw a variety of shapes, of which some common shapes are summarized
below:

Table 2.16.1: Summary of common shapes for drawing.

Shape Description Documentation

Rectangle The Rectangle class for drawing a rectangle. Oracle's documentation for
Rectangle class

RoundRectan The RoundRectangle2D class for drawing a Oracle's documentation for


gle2D rectangle with rounded corners. RoundRectangle2D class
Ellipse2D.Dou The Ellipse2D.Double class for drawing an Oracle's documentation for
ble ellipse with a size and location. Ellipse2D.Double class

Line2D.Doubl The Line2D.Double class for drawing a line Oracle's documentation for
e between two coordinate points. Line2D.Double class

Polygon The Polygon class for drawing a generic Oracle's documentation for
polygon with user-specified boundary points. Polygon class

2.17 Style guidelines


Each programming team, whether a company, open source project, or a classroom, may have style
guidelines for writing code. Below are the style guidelines followed by most code in this material. That
style is not necessarily better than any other style. The key is to be consistent in style so that code
within a team is easily understandable and maintainable.

You may not have learned all of the constructs discussed below; you may wish to revisit this section
after covering new constructs.

Table 2.17.1: Sample style guide.

Sample guidelines used in this material Yes No (for our sample


style)
Whitespace

x = 25; x = 25; y = x
y = x + 1; + 1; // No
if (x == 5) { y
Each statement usually appears on its own line.
= 14; } // No

x = 25; x = 25;
y = x + 1; //
No
A blank line can separate conceptually distinct
y = x + 1;
groups of statements, but related statements
usually have no blank lines between them.

C = 25; C=25;
F = ((9 * C) / 5) + // No
32; F = ((9*C)/5) +
Most items are separated by one space (and not
F = F / 2; 32; // No
less or more). No space precedes an ending F = F / 2 ;
semicolon. // No

if (a < b) { if (a < b) {
x = 25; x = 25;
y = x + 1; // No
Sub-statements are indented 3 spaces from
} y = x +
parent statement. Tabs are not used as tabs 1; // No
may behave inconsistently if code is copied to }
if (a < b) {
different editors. x = 25;
// No
}

(Auto-tabbing may need to be disabled in some


source code editors).
Braces

if (a < b) { if (a < b)
// Called K&R {
style // Also
For branches, loops, methods, or classes,
} popular, but we
opening brace appears at end of the item's line. while (x < y) { use K&R
Closing brace appears under item's start. // K&R style }
}

if (a < b) { if (a < b) {
... ...
} } else {
For if-else, the else appears on its own line
else { // Original
// Called K&R style
Stroustrup style }
// (modified K&R)
}

if (a < b) { if (a < b)
x = 25; x = 25; //
} No, can lead to
Braces always used even if only one
error later
sub-statement

Naming

int numItems; int NumItems;


// No
int num_items;
Variable/parameter names are camelCase,
// Common, but
starting with lowercase we don't use
int numBoxes; int boxes; //
char userKey; No
int b; //
Variable/parameter names are descriptive, use
No
at least two words (if possible, to reduce char k; //
conflicts), and avoid abbreviations unless No
char usrKey; //
widely-known like "num". Single-letter variables No
are rare; exceptions for loop indices (i, j), or
math items like point coordinates (x, y).

final int final int


MAXIMUM_WEIGHT = 300; MAXIMUMWEIGHT =
300; // No
Constants use upper case and underscores (and
final int
at least two words) maximumWeight =
300; // No
final int
MAXIMUM = 300;
// No

int i; int i;
char userKey = '-'; char userKey;
Variables usually declared early (not within
userKey = 'c';
code), and initialized where appropriate and int j;
practical. // No

printHello() PrintHello()
// No
print_hello()
Method names are camelCase with lowercase
// No
first.

Miscellaneous
Lines of code are typically less than 100 Code is more easily
characters wide. readable when lines are
kept short. One long line
can usually be broken up
into several smaller ones.

Feedback?

K&R style for braces and indents is named after C language creators Kernighan and Ritchie.
Stroustrup style for braces and indents is named after C++ language creator Bjarne Stroustrup. The
above are merely example guidelines.

2.17 Style guidelines

2.18 Java example: Salary calculation


with variables

Using variables in expressions, rather than numbers like 40, makes a program more general and
makes expressions more meaningful when read too.

zyDE 2.18.1: Calculate salary: Generalize a program with


variables and input.

The following program uses a variable workHoursPerWeek rather than directly using 40 in the salary
calculation expression.
1. Run the program, observe the output. Change 40 to 35 (France's work week), and run again.
2. Generalize the program further by using a variable workWeeksPerYear. Run the program.
Change 50 to 52, and run again.
3. Introduce a variable monthlySalary, used similarly to annualSalary, to further improve program
readability.

You might also like