Title: Chapter 3: Assignments and More
1Chapter 3 Assignments and More
- Here, we build on the idea arithmetic
expressions, variables and assigning variables
values - The instruction used to assign a variable a value
is the assignment statement - Form
- variable expression
- expression can be
- A literal value or a variable
- v 10
- An arithmetic expression
- x y z 1
- A string expression
- s "hi" " bye"
- A boolean or relational expression
- a b c or a (x lt y)
- A method call that returns a value
- q Math.abs(p)
2Types of Expressions
- While the assignment statement seems
straightforward, you have to remember - the expression will generate a type of value and
your variable on the left-hand side of the
assignment statement must be the same (or a
compatible) type - if your expression generates a float and your
variable is an int, it will not work - Example
- double y 5.3, z 10.1
- int x y z
- similarly, if your expression generates a double
and your variable is a float, it will not work - we will find two ways of dealing with this
problem later in this chapter
3Equality vs. Assignment
- The assignment statement is not the same as
mathematical equality - x y in algebra means that x and y are the same
- This is very different from x y as an
assignment statement in Java - in Java, the variable on the left-hand side is
being overwritten with the value computed on the
right-hand side - the left-hand side variables original value is
lost
4Example Expressions
length 25 // assign variable a literal int
value width 17.5 // assign variable a literal
double value area length width // assign
variable result of expression large (area gt
100) // assign variable a boolean based on
comparison cost area 3.71 // this expression
combines a previous result and a literal first
"Frank" // assign variable a String
literal last "Zappa" whole first " "
last // String assignment using String
concatenation size whole.length( ) //
assignment using method call x 5 y 3 //
if z is an int, the result is 1, if z is a
double, the result z x / y // is
1.666666666667 // assume x is an int and y is a
double x y 5 // this assignment is illegal
because x is not compatible // with the double
resulting from y 5
5Example Program
public class AreaComputation public
static void main(String args) double
length, width, area String output length
27.3 width 13.4 area length
width System.out.println("The area is "
length " " width " " area)
- To the left is an example program that combines
the ideas learned so far - Declaring variables
- Assignment statements
- Output statements
- The output of this program is
- The area is 27.3 13.4 365.82
6Variation
- A variation of this program is given on page 91
- Here, the author has replaced the
System.out.println statement with a
JOptionPane.showMessageDialog statement - The main difference is that JOptionPane.showMessag
eDialog is an interactive output message - it stays on the screen until the user has clicked
on the ok button in the pop-up window - Other differences
- JOptionPane must be import from the javax.swing
library - The author has decided to store the output in the
String variable output prior passing this
parameter (output) to JOptionPane - Notice that the showMessageDialog message expects
4 parameters which are null, output, title, and
the type of message box (INFORMATION_MESSAGE)
7Multiple Assignments
- Java provides a number of programming shortcuts
to make the programmers task easier - One such shortcut is the ability to assign
multiple variables to the same value - The form is
- a b c 5
- Here, the variables a, b and c will all get the
same value, 5 - This operation is a right-to-left operation
- Consider the following variation
- a (b (c 5) 3) 1
- Here, c 5, b 15 and a 16
8Reassignment Statements
- Recall that an assignment statement is not the
same as equality - a b sets a to the value stored in b
- What happens if the left-hand side variable
appears in the right-hand side expression? - a a 5
- This is known as a reassignment, the variable is
getting a new value based on its old value - This might be used to count how many times
something has happened for instance by using - count count 1
- Or to accumulate a running total
- sum sum newValue
9Example Accumulating a Sum
- The output for this program is
- The sum is 10
- The sum is now 18
- The sum is now 34
- Notice that sum changes after each new assignment
- We will use running totals in many different
applications - we will find a better way to do this by using
loops (chapter 5)
public class ComputingSum public static
void main(String args) int
value, sum 0 value 10
sum sum value System.out.println("T
he sum is " sum) value 8
sum sum value System.out.println("
The sum is now " sum) value 16
sum sum value
System.out.println("The sum is now " sum)
10Shortcut Reassignment Operators
- Because reassignment statements are so common,
Java gives us several shortcuts - Instead of a a 10 we can use as in a
10 - Notice that by using , we do not have to repeat
the variable being reassigned, it is implied that
we are adding to it - Other reassignment operators are -, , / and
- Other examples
- x 3 y // same as x x (3 y)
- i 2 // same as i i 2
- name last // assume name and last are Strings
- Notice in this last case, we see that the
reassignment operators are not limited to
operations on numbers, but can also be used for
String concatenation
11Increment/Decrement Shortcuts
- Imagine that we are counting the number of times
that the code has done something and using a
statement like count count 1 - We have seen that we can use a shortcut operator
and do this with count 1 - However, we can also use an increment shortcut
- count // postfix increment operator
- count // prefix increment operator
- We also have the same types of operators for
decrement - count--
- --count
- By themselves, these four instructions are the
same as count count 1 and count count 1
or count 1 and count - 1 - But we can use these operations in other
expressions
12Increment/Decrement in Expressions
- In order to reduce the number of instructions, a
programmer can use these increment/decrement
operators in other expressions - For instance, consider
- number count
- count
- This can be reduced to
- number count
- Now consider this
- x y --z
- What does this do?
13Prefix vs. Postfix Operators
- In order to answer the question on the last
slide, we have to understand the difference
between a prefix and postfix operator - Prefix operator perform the incr/decr, store
the result, and then use the new value of the
variable in the expression - Postfix operator compute the expression, then
perform the incr/decr and store the result - Assume y 5 and z 3
- Then x y --z is equivalent to
- --z // z is now 2
- x y z // x is now 5 2 10
- y // y is now 6
- What would be the result of x y z-- ?
- If prefix/postfix operators confuse you, its best
to not use them and do things the long way, at
least until you do get used to them!
14Example Computing an Average
public class ComputeAverage public
static void main(String args)
int sum 0, count 0, value double
average value 81 sum
value count value 93
sum value count
value 70 sum value
count average sum / count
System.out.println("The average on " count
" exams is " average)
- Here we have a program that computes the average
of 3 numbers - Notice the use of the reassignment shortcut
and the postfix increment - Without these instructions, the program would be
slightly longer in terms of the number of
characters - Note this program has two problems
- Average will not be precise (we will see why
later) and the output of average is not being
formatted
15Math Methods
- Java includes a class, Math, that has a number of
useful mathematical methods available - Note we do not have to import this class as it
is imported automatically - Note we do not create a variable of type Math
like we do with a String or DecimalFormat - This class is like JOptionPane
- This is a property known as a static class we
will discuss this briefly later in the semester
Math includes such operations as abs (absolute
value) pow (raise to the power of) sqrt (square
root) log (natural logarithm) ceil (for ceiling,
round up to nearest int) floor (truncate down to
nearest int) min, max (determine min or max of 2
values) round (round to nearest int) sin, cos,
tan, asin, cos, atan (trig ops) random (generate
random value gt 0.0 and lt 1.0)
16Example Program
- The program to the left computes, through a
series of individual assignment statements, the
integer value nearest to the square root of x2
y3 - Notice that we did not have to import the Math
class or instantiate an object of type Math
making it easier - In all cases, we passed the numeric value(s) as a
parameter in our message
public class MathExample public static
void main(String args)
double x 6.28189 double y 2.1
double a Math.pow(x, 2)
double b Math.pow(y, 3) double c
Math.abs(a b) double d
Math.sqrt(c) int answer
Math.round(d) System.out.println("The
result is " d)
17Math Class Types
- One thing to be aware of when using the Math
methods - Types of parameters may be important
- Or the type of value returned may depend on the
types of parameters - abs for instance can take any of int, float,
double but returns the same type as the
parameters - Since in Math.abs(c d), c and d are double,
this message returns a double - However, round expects a float or double and
always returns an int - See table 3.1 on page 102 which describes the
types returned
18Message Passing
- Lets more formally analyze these instructions
- Math.abs(c d) consists of 3 parts
- Math the object that is being passed a message
- abs the message itself this tells the object
what operation to perform - (c d) the parameter being used to perform the
operation - Note that c d is actually a single value
whereas in pow, two separate parameters are being
supplied - It is important to know the parameter(s) type(s)
expected in a message or else you will get a
syntax error when compiling your program - For instance, Math.abs(a, b) will yield an error
as will Math.abs(name) if name is not an int,
double or float
19Other Examples
- We have seen other examples of passing messages
already - JOptionPane.showMessageDialog(null, message,
title, JOptionPane.INFORMATION_MESSAGE) - This passes to the JOptionPane object the message
showMessageDialog passing 4 parameters - JOptionPane.showInputDialog(message)
- This passes to the JOptionPane object a message
to perform showInputDialog - df.format(x)
- This passes to the DecimalFormat object df the
message form with the parameter x (presumably a
float or double variable)
20Recall average sum / count
- Remember from a previous example, this statement
will give the wrong answer, why? - sum and count are int values
- / performs an integer division
- Since average is a double, the resulting quotient
is converted into a double - If sum 265 and count 3, sum / count yields 88
instead of 88.33333333 so average gets the value
88.0 instead of 88.33333333 - Java automatically performs this conversion from
int (88) to double (88.0) for us - This is known as a coercion
- A coercion occurs when Java must convert from one
type to another - Java will only perform a coercion though if going
from a narrower type to a wider type
21Widening vs. Narrowing
- The term widening means that the value is being
converted from a narrower type to a wider type - A wider type has greater precision
- double is wider than float which is wider than
int - Widening will be performed automatically for us
when Java detects that it is necessary - as in the case double x y / z where y and z
are int or float values - Narrowing means that a value is being converted
from a wider type to a narrower type - This requires an explicit cast statement
- Narrowing can be dangerous, you are throwing away
precision
22Casting
- A cast is an explicit changing of a values type
- The cast is stated in the program by the
programmer rather than the automatic coercion
that is performed by Java for you - The cast itself precedes some variable or
expression by placing the type to be converted in
parens - (int) x this returns the int value of x
- Note the (int) cast truncates the value, it does
not round - To fix our previous problem, we could do either
- average (double) sum / count // change sum to
double before division - average sum / (double) count // change count
to double before division - But doing the following would not solve our
problem, why not? - average (double) (sum / count) // change
result of division to double
23More on Casting
- Notice in the previous example, our cast was a
widening cast (which is always safe) - This was necessary to make sure that the division
was performed as a double and not an int - We will also use casts to narrow as in the
following - weeklyHours (int) hours
- Here, we want to know how many hours someone
worked for the week, but we are only interested
in the int value (assume hours was a double) - This is dangerous, we threw out precision, what
if you had worked 32.8 hours? Now, we only know
that you have worked 32 hours, doesnt seem fair
does it? - Note that neither coercions nor casts can be used
to convert between String and primitive types - We must find another approach for this
24Conversion Methods
- There are other classes and methods available so
that we can perform additional types of
conversions - Consider the String age 31
- because age is a String, it cannot be treated as
an int value, but what if you wanted to convert
it into an int? - could you just do (int) age ? No.
- Instead, the Integer class allows you to convert
a String to an int by using the parseInt method - int ageAsNumber Integer.parseInt(age)
- Note dont confuse the Integer class with the
int primitive type, they are two different things
entirely - There are similar methods to convert from String
to int, String to float, String to double, String
to char and from int, float, double or char to
String
25Examples
- Assume str1 "31.91", str2 "6.99", str3
"10", str4 "hi there" and i 4 - double x Double.parseDouble(str1) // x
31.91 - float y Float.parseFloat(str2) // y
6.99 - int z Integer.parseInt(str3) // z 10
- char c str4.charAt(i)
// c h - Note that c is h not t, why?
- String str5 "" x // str5 "31.91"
- String str6 "" z // str6 "10"
- String str7 "" c // str7 "t"
- What is the result of String str8 "" x y ?
- Do we get 38.9? No, we get 31.916.99 why?
- Note that if str3 "10.1", then the third
statement above results in an error you cannot
parse a value with a decimal point into an int
26Input
- We have saved input until now because input in
Java is difficult - Input in most languages tends to be easy
- But in Java, you must use an object to perform
input - There is an easy class available
- JOptionPane, which youve already seen in your in
your first assignment and in previous examples - However, JOptionPane is not necessarily the
preferred way to go it hides too many details
that you should know - So here, we will first examine using JOptionPane
for input and then focus on the harder approach
using the BufferedReader class
27JOptionPane for Input
- import the JOptionPane class
- part of javax.swing library
- whenever you need input, pass JOptionPane the
showInputDialog message - JOptionPane.showInputDialog(someString)
- someString will appear in the pop-up window
- You will want this String to be a message
indicating what you expect for input - Examples Enter your name or How old are you
(enter an int value), etc - This message will return a String value that you
will have to store in a String variable - Example
- String name JOptionPane.showInputDialog("Enter
your name")
28Inputting Numbers
- Unfortunately, showInputDialog only inputs
Strings and if you expect a number (such as the
users age), you must convert it - Example
- String strAge JOptionPane.showInputDialog("Enter
your age (an int value) ") - int age Integer.parseInt(strAge)
- These two instructions can be combined into
- int age Integer.parseInt(JOptionPane.showInputDi
alog ("Enter your age (an int value) ")) - Notice the number of close parens ) above!
29Example Program
import javax.swing. public class Example
public static void main(String args)
int age String name
JOptionPane.showInputDialog( "Enter your first
name") String strAge
JOptionPane.showInputDialog( "Enter your age (as
an int value) ") age
Integer.parseInt(strAge) int year1
2003 age int year2 year1 - 1
JOptionPane.showMessageDialog(name ", you
must have been born in either " year1 " or
" year2, JOptionPane.INFORMATION_MESSAGE)
- Here we have a complete program that receives
input and performs output - Both input and output use JOptionPane
30JOptionPane 3 Problems
- In future programs and exams, you will be
required to use the BufferedReader class for
input - JOptionPane has 3 problems
- First, it causes a pop-up window to appear which
takes resources (the Operating System) and more
time than is usually necessary - Second, it might be annoying to the user
- do you ever get sick of pop-up windows?
- Third, and most importantly, it hides details
that you should know about - These details deal with exceptions and exception
handling, a topic that we will cover later in the
semester - So for now, we wont worry about these details
other than following the instructions properly - You will see that using BufferedReader is a
little more complicated than using JOptionPane,
but not by much
31Using BufferedReader
- You will use two classes to perform input
- BufferedReader and InputStreamReader
- Both of these classes are part of java.io library
- import java.io.
- add throws IOException to the header of your
method that will perform input - this will be your main method
- declare and instantiate an InputStreamReader
object followed by a BufferedReader object - or, just declare a BufferedReader object,
examples are shown next - for each input, pass the BufferedReader object
the message readLine( ) - Note the readLine( ) message causes the
BufferedReader to return a String, so like
JOptionPane, if you are expecting a number, you
will have to convert it
32Instantiating BufferedReader
- Use the following notation
- InputStreamReader isrName new
InputStreamReader(System.in) - BufferedReader brName new BufferedReader(isrName
) - You will only reference your BufferedReader
object, not the InputStreamReaderObject - So, you can accomplish the above by combining the
two individual operations into a single one as - BufferedReader brName new BufferedReader(new
InputStreamReader(System.in)) - Here, there is no variable name for the
InputStreamReader object - Note In my examples, I will use this latter
approach calling the BufferedReader object key
(short for keyboard)
33Prompting the User
- Recall in showInputDialog for JOptionPane that
you included a prompting message - This was a String that explained to the user what
they were to input - You will need to precede your readLine( ) inputs
with a prompting message since readLine( ) does
not allow for this - The prompting message will be a System.out.print
or println instruction that outputs the command
to the user - Example
- System.out.print("Enter your name ")
- String name keyboard.readLine( )
- Where keyboard is the BufferedReader object
- Notice the use of the print instruction instead
of println what is the difference??
34Example Program Computing Average
- The program to the left is similar to a previous
one but computes the average of 3 test scores by
inputting them from the user - Again, the output is not formatted
- we should use DecimalFormat to fix this but
this was omitted to save space
import java.io. public class ComputeAverage2
public static void main(String args)
throws IOException BufferedReader
key new BufferedReader(new InputStreamReader(Sy
stem.in)) int sum 0, count 0,
value System.out.print("Enter your
first test score ") value
Integer.parseInt(key.readLine( )) sum
value count System.out.print("En
ter your second test score ") value
Integer.parseInt(key.readLine( )) sum
value count System.out.print("En
ter your third test score ") value
Integer.parseInt(key.readLine( )) sum
value count double average
(double) sum / count System.out.println(
"Your class average is " average)
35System.exit(0)
- System is the Operating System
- System.exit(0) tells the Operating System to
exit (terminate) this program - This is necessary in programs that use
JOptionPane because your program creates pop-up
windows which may stay on the screen after your
last instructions have executed - We wont need this statement if we use System.out
for output and BufferedReader for input but
including this statement is a good habit to get
into
- You might notice the examples from the textbook
end some of their programs with - System.exit(0)
- What is this statement?
- You might recall that we have used System to pass
the messages out.print and out.println
36Constants the Final Qualifier
- You might recall from chapter 1 that we name
classes, variables, methods and constants - What is a constant?
- A constant is like a variable, but once assigned
its initial value, it cannot be changed - So the value is constant
- unchanging through the lifetime of the program
- We dont need constants because we have
variables, but often constants can be useful as
we will see from time to time during this course - To declare a constant, you use the same approach
as any variable but you include the reserved word
final - final int A_VALUE 10 // X is 10
throughout the rest of this code - final double PI 3.1416
- Remember our naming convention to fully
capitalize constant names
37Placement of Statements
- Another convention is where we will want to place
types of statements in our program - Here is a skeleton of our main method
- This convention does not have to be followed, but
is common - If we have a variable used only at the end of the
program, we could declare, assign and use it only
at that location, but that violates the above
convention - You will find your own style for programming
- the best thing is to be consistent but also to
make sure that your code is easy to read and
understand
public static void main(String args)
constant declarations variable
declarations (and possibly initializations)
executable statements
38Common Errors
- As with the last chapter
- Forgetting to declare or initialize variables or
constants - Misspelling variable or constant names
- Misusing the increment/decrement or shortcut
reassignment operators - Incorrect message passing
- Wrong message to an object
- Not instantiating the object first
- Wrong number or type of parameters, or parameters
in the wrong order - Forgetting throws IOException for BufferedReader
- Forgetting to cast a variable or expression
resulting either in an error or an incorrect
calculation