Text Chapter 2 Basic Objects
Text Chapter 2 Basic Objects
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()
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.
attendeeCounter.incrementCount();
attendeeCounter.incrementCount();
attendeeCounter.incrementCount();
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
.
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
studentCounter.printCount();
The object name comes before the period, and the method being called on that object
comes after the period.
Try to create and use PeopleCounter objects in the following program. Methods for
PeopleCounter include resetCount(), incrementCount(), printCount(), and getCount().
attendeeCounter.incrementCount();
attendeeCounter.incrementCount();
attendeeCounter.incrementCount();
OUTPUT:
Attendee count: 3
PARTICIPATION ACTIVITY
1) x = 1
Valid.x is assigned with 1.
2) x = y
3) x = y + 2
4) x + 1 = 3
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
1) x = 9
y=x+1
What is y?
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.
CAPTIONS
PARTICIPATION ACTIVITY
1) x = 5
x=x+7
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
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.
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
import java.util.Scanner;
int userAge;
userAge = scnr.nextInt();
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
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
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.
System.out.print("and up to ");
annualMice = litterSize * yearlyLitters;
System.out.println(annualMice + " mice, in a year.");
}
}
OUTPUT
PARTICIPATION ACTIVITY
numCars = 99;
The statement assigns the variable numCars with the value 99.
houseSize = 2300;
The program assigns the variable houseSize with the value 2300.
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.
numRodents = houseRats;
numItems = ballCount - 3;
The program reads the value of ballCount, subtract 3 from that value, and assigns numItems
with the result.
animalsTotal = dogCount + 3;
The statement reads the value of dogCount (5), adds 3, and assigns animalsTotal with the
result of 8.
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
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;
numNickels = 5;
numDimes = 6;
numCoins=numNickels+ numDimes;
/* Your solution goes here */
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.
int userAge;
userAge = scnr.nextInt();
}
OUTPUT
Enter your age: 24
24 is a great age
Average lifespan is 70
PARTICIPATION ACTIVITY
2.3.4: Declaring and initializing integer variables.
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.
CHALLENGE ACTIVITY
Write one statement that declares an integer variable numHouses initialized to 25.
import java.util.Scanner;
int numHouses=25;
System.out.println(numHouses);
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
import java.util.Scanner;
public class PeopleKnown {
int yourFriends;
int totalFriends;
yourFriends = scnr.nextInt();
totalFriends = yourFriends;
OUTPUT
CAPTION
PARTICIPATION ACTIVITY
numApples = numApples + 3;
8.The statement reads the current value of numApples (5), adds 3, and assign
numApples with the result of 8.
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.
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;
int numPeople;
numPeople = scnr.nextInt();
numPeople=numPeople+5;
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.
PARTICIPATION ACTIVITY
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;
No error.A variable can be initialized when declared, and an int variable can hold
negative values.
3) int numDays;
int numYears;
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
1) numCars
2) num_Cars1
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
6) thirdPlace_
7) thirdPlace!
8) short
9) very tall
Invalid.Spaces are not allowed. Instead, an underscore can be used (very_tall) or the
words can be abutted (veryTall).
● 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.
PARTICIPATION ACTIVITY
Choose the "best" identifier for a variable with the stated purpose, given
the above discussion.
jellyBeansInJar.Looks OK. Could start with num, but should be fine as is.
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.
case if super
do native try
double new void
extends protected
The words "true", "false", and "null" are also reserved, and used for literals.
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.
Arithmetic Description
operator
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
4) 2
Valid.An expression can just be a literal.
5) 2x
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
1) 6 plus numItems:
6 + numItems
Yes.Straightforward addition.
2) 6 times numItems:
6 x numItems
totDays / 12
Yes.Straightforward division.
4) 5 times i:
5i
-userVal
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.
Feedback?
PARTICIPATION ACTIVITY
PARTICIPATION ACTIVITY
1) y + 2 * z
3) x * y * z
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
numItems = 5;
totCount = 1 + (2 * numItems) * 4;
PARTICIPATION ACTIVITY
1) Would removing the parentheses as below have yielded the same result?
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
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.
PARTICIPATION ACTIVITY
Retype each statement to follow the good practice of a single space around operators.
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;
numBalls = numBalls + 1;
4) numEntries = (userVal+1)*2;
numEntries = (userVal + 1) * 2;
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
12
14
carCount = carCount / 2;
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
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;
int num1;
int num2;
int finalResult;
num1 = scnr.nextInt();
num2 = scnr.nextInt();
finalResult=(num1 +num2)/3;
System.out.println(finalResult);
}
CHALLENGE ACTIVITY
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;
int numDrinks;
int numTacos;
int totalCost;
numDrinks = scnr.nextInt();
numTacos = scnr.nextInt();
totalCost= (numDrinks*2)+(numTacos*3);
System.out.print("Total cost: ");
System.out.println(totalCost);
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.
import java.util.Scanner;
int userAgeYears;
int userAgeDays;
userAgeYears = scnr.nextInt();
OUTPUT
PARTICIPATION ACTIVITY
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.
3650
The program also computes and outputs the user's age in minutes.
import java.util.Scanner;
int userAgeYears;
int userAgeDays;
int userAgeMinutes;
userAgeYears = scnr.nextInt();
OUTPUT
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.
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?
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.
import java.util.Scanner;
public class HealthData {
int userAgeYears;
int userAgeDays;
int userAgeMinutes;
int totalHeartbeats;
userAgeYears = scnr.nextInt();
OUTPUT
PARTICIPATION ACTIVITY
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.
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.
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.
PARTICIPATION ACTIVITY
All variables are of type double and already declared unless otherwise noted.
double 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.
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.
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) 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.
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.
● 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.
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
double.A measurement.
double.A measurement.
int.The number of hairs may be large, but is still countable: 1 hair, 2 hairs, etc.
double.Nobody has exactly 2.2 kids, but the average almost certainly should involve a
fraction.
import java.util.Scanner;
double gasVolume;
double oilVolume;
double mixRatio;
gasVolume = scnr.nextDouble();
oilVolume = scnr.nextDouble();
mixRatio = gasVolume / oilVolume;
Feedback?
PARTICIPATION ACTIVITY
1) 13.0 / 3.0
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.
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
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
1) Which of the following arguments completes printf() to output two digits after the decimal
point?
0.1 System.out.printf("%.1f", 0.125); outputs the value with one digit after
the decimal point.
CHALLENGE ACTIVITY
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.
double sphereVolume;
double sphereRadius;
sphereRadius = scnr.nextDouble();
System.out.printf("%.2f\n", sphereVolume);
import java.util.Scanner;
double gramsGold;
double atomsGold;
gramsGold = scnr.nextDouble();
Feedback?
PARTICIPATION ACTIVITY
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
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;
double G = 6.673e-11;
double M = 5.98e24;
double accelGravity;
double distCenter;
distCenter = scnr.nextDouble();
● 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.
import java.util.Scanner
/*
*/
numPeople = scnr.nextInt();
}
}
PARTICIPATION ACTIVITY
2.10.1: Comments.
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.
calculate volume,
*/
5) // Print "Hello"
//
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
*/
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 /* ... */.
8)/*
numCars = 5;
*/
Valid.The programmer has likely temporarily "commented out" those two statements.
The // within the /* .. */ will be ignored, like the other text.
9)/*
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:
import java.util.Scanner;
int thirdVar;
// Above blank line separates user input statements from the rest
thirdVar = yetAnotherVar + 1;
import java.util.Scanner;
PARTICIPATION ACTIVITY
2.10.2: Whitespace.
import java.util.Scanner;
int userAge;
int currentDecade;
int nextDecade;
int nextMilestone;
userAge = scnr.nextInt();
currentDecade=userAge/10;
nextDecade = currentDecade + 1;
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.
PARTICIPATION ACTIVITY
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?
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
nextDecade = currentDecade + 1;
3.The compiler ignores the 2 blank lines and the line that only contains a comment.
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
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.
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.
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
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
False.Internal (or private) data and methods are not meant to be used outside of the
class.
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.
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 ---
PARTICIPATION ACTIVITY
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.
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 {
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
coinFlipHist.setNumberOfBins(2);
coinFlipHist.setBinValue(0, 7);
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
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
False
False
3) The Histogram's class getBinValue() method returns an integer representing a bin's
value.
True
PARTICIPATION ACTIVITY
PARTICIPATION ACTIVITY
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;
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.
passFailHistogram.setBinValue(0, 56);
passFailHistogram.setBinValue(1, 3);
passFailHistogram.printHistogram();
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?
Timer() {...}
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
import java.awt.Rectangle;
redRect.setSize(120, 20);
redRect.translate(40, 40);
redRect.setLocation(10, 160);
blueRect.translate(-75, 0);
CAPTION
PARTICIPATION ACTIVITY
blueRect.setSize(20, 40);
800
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.
PARTICIPATION ACTIVITY
void printHistogram()
CAPTION
PARTICIPATION ACTIVITY
2.13.2: Mutator or accessor.
True.An accessor may access the object's data, and then returns some value or performs
some operation.
True.The printHistogram method must read the object's internal data to print the
histogram.
False.The getBinValue method only accesses a Histogram object's data, but does not
modify the object's data.
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.
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.
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.
import packageName.ClassName;
Feedback?
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.
Feedback?
The following shows the method details for the nextInt() method.
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.
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.
double circleRadius;
double circleCircumference;
double circleArea;
circleRadius = circleCircumference / 2 *
PI_VAL;
circleArea = PI_VAL * circleRadius *
circleRadius;
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.
double circleRadius;
double circleCircumference;
double circleArea;
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.
double circleRadius;
double circleCircumference;
double circleArea;
circleRadius = circleCircumference / 2 *
PI_VAL;
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.
double circleRadius;
double circleCircumference;
double circleArea;
/*
area = PI_VAL * radius * radius;
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:
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.
Use the above repeating two-step process (predict problem, test to validate) to find the problem in the
following code for the provided input.
10
11
12
13
14
15
16
17
import java.util.Scanner;
int sideLength;
int cubeVolume;
sideLength = scnr.nextInt();
Run
Feedback?
PARTICIPATION ACTIVITY
2.15.1: Debugging.
1)
The first step in debugging is to make random changes to the code and see what happens.
True
False
2)
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)
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
import javax.swing.JFrame;
appFrame.setSize(400, 250);
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
appFrame.setVisible(true);
}
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
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)
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.
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
// Cast to Graphics2D
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.
HistogramComponent.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
@Override
// Cast to Graphics2D
graphicsObj.setColor(binColor1);
graphicsObj.fill(binRectangle1);
graphicsObj.setColor(binColor2);
graphicsObj.fill(binRectangle2);
graphicsObj.fill(binRectangle3);
HistogramViewer.java
import javax.swing.JFrame;
appFrame.setSize(400, 250);
appFrame.setTitle("Histogram Viewer");
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the HistogramComponent object to the frame
appFrame.add(histogramComponent);
appFrame.setVisible(true);
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:
PARTICIPATION ACTIVITY
Start
2x speed
graphicsObj.setColor(binColor);
graphicsObj.fill(binRect);
binRect object
Internal data:
(10, 75)
150
50
binColor object
Internal data:
Histogram Viewer
Internal data:
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.
PARTICIPATION ACTIVITY
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.
graphicsObj.setColor(color);
graphicsObj.fill(rectangle);
1.
graphicsObj.setColor(color);
graphicsObj.fill(rectangle);
2.
Rectangle rectangle = new Rectangle(0, 100, 50, 150);
graphicsObj.setColor(color);
graphicsObj.draw(rectangle);
3.
1)
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)
CheckShow answer
Feedback?
A Graphics2D object can draw a variety of shapes, of which some common shapes are summarized
below:
Rectangle The Rectangle class for drawing a rectangle. Oracle's documentation for
Rectangle 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
You may not have learned all of the constructs discussed below; you may wish to revisit this section
after covering new constructs.
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
}
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 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.
Using variables in expressions, rather than numbers like 40, makes a program more general and
makes expressions more meaningful when read too.
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.