Chapter 6 - Object-Oriented Programming
- Object-oriented programming overview
- objects
- classes
- encapsulation
- UML Class Diagram
- First OOP Class
- private and public Access
- Driver Class
- Reference Variables and Instantiation
- Calling a Method
- Calling Object
1
1
*
- The this Reference
- Default Values
- Variable Persistence
- OOP Tracing Procedure (hidden)
- UML Class Diagram for Next Version of the Mouse Program
- Local Variables
- return statement
- void Return Type
- Empty return Statement
- Argument Passing
- Specialized methods:
- accessor methods
- mutator methods
- boolean methods
Chapter 6 - Object-Oriented Programming
2
2
*
Object-Oriented Programming Overview
- In the old days, the standard programming technique was called "procedural programming."
- That's because the emphasis was on the procedures or tasks that made up a program.
- You'd design your program around what you thought were the key procedures.
- Today, the most popular programming technique is object-oriented programming (OOP).
- With OOP, instead of thinking first about procedures, you think first about the things in your problem. The things are called objects.
3
3
*
Object-Oriented Programming Overview
- An object is:
A set of related data which identifies the current state of the object
+ a set of behaviors.
- Example objects:
- Car object in a traffic-flow simulation:
- data = ?
- behaviors = ?
4
human entities | physical objects | mathematical entities |
employees | cars in a traffic-flow simulation | points in a coordinate system |
customers | aircraft in an air-traffic control system | complex numbers |
students | electrical components in a circuit-design program | time |
4
*
Object-Oriented Programming Overview
- Benefits of OOP:
- Programs are more understandable -
- Since people tend to think about problems in terms of objects, it's easier for people to understand a program that's split into objects.
- Fewer errors -
- Since objects provide encapsulation (isolation) for the data, it's harder for the data to get messed up.
5
5
*
��
methods�
data�
rest of program�
object�
Object-Oriented Programming Overview
- A class is a description for a set of objects.
- On the next slide, note the three computers on a conveyer belt in a manufacturing plant:
- The three computers represent objects, and the specifications document represents a class. The specifications document is a blueprint that describes the computers: it lists the computers' components and describes the computers' features.
- Think of an object as a physical example for a class's description. More formally, we say that an object is an instance of a class.
6
6
*
Object-Oriented Programming Overview
7
7
*
( com puter objects Specifications for a com puter )
�
Object-Oriented Programming Overview
- A class is a description for a set of objects. The description consists of:
a list of variables
+ a list of methods
- Classes can define two types of variables – instance variables and class variables. And classes can define two types of methods – instance methods and class methods. Instance variables and instance methods are more common than class variables and class methods, and we'll focus on instance variables and instance methods in this chapter.
8
8
*
Object-Oriented Programming Overview
- A class's instance variables specify the type of data that an object can store.
- For example, if you have a class for computer objects, and the Computer class contains a hardDiskSize instance variable, then each computer object stores a value for the size of the computer's hard disk.
- A class's instance methods specify the behavior that an object can exhibit.
- For example, if you have a class for computer objects, and the Computer class contains a printSpecifications instance method, then each computer object can print a specifications report (the specifications report shows the computer's hard disk size, CPU speed, cost, etc.).
9
9
*
Object-Oriented Programming Overview
- Note the use of the term “instance” in “instance variable” and “instance method.” That reinforces the fact that instance variables and instance methods are associated with a particular object instance. For example, each computer object has its own value for the hardDiskSize instance variable.
- That contrasts with class variables and class methods, which you saw in Chapter 5. Class variables and class methods are associated with an entire class. For example, the Math class contains the PI class variable and the round class method. PI and round are associated with the entire Math class, not with a particular instance of the Math class. We'll cover class variables and class methods in more detail at the end of Chapter 7.
10
10
*
UML Class Diagram
- UML:
- Stands for Unified Modeling Language.
- It's a diagrammatic methodology for describing classes, objects, and the relationships between them.
- It is widely accepted in the software industry as a standard for modeling OOP designs.
- Example:
- UML class diagram for a Mouse class:
11
Mouse | | class name |
age : int weight : double percentGrowthRate : double | | attributes / variables |
setPercentGrowthRate(percentGrowthRate : double) grow() display() | | operations / methods |
11
*
First OOP Class
/************************************************************
* Mouse.java
* Dean & Dean
*
* This class models a mouse for a growth simulation program.
************************************************************/
public class Mouse
{
private int age = 0; // age of mouse in days
private double weight = 1.0; // weight of mouse in grams
private double percentGrowthRate; // % weight increase per day
//*********************************************************
// This method assigns the mouse's percent growth rate.
public void setPercentGrowthRate(double percentGrowthRate)
{
this.percentGrowthRate = percentGrowthRate;
} // end setPercentGrowthRate
instance variable declarations
To access instance variables, use this dot.
parameter
method body
12
12
*
First OOP Class
//*********************************************************
// This method simulates one day of growth for the mouse.
public void grow()
{
this.weight += (.01 * this.percentGrowthRate * this.weight);
this.age++;
} // end grow
//*********************************************************
// This method prints the mouses's age and weight.
public void display()
{
System.out.printf(
"Age = %d, weight = %.3f\n", this.age, this.weight);
} // end display
} // end class Mouse
14
14
*
private and public Access
- private and public are access modifiers. When you apply an access modifier to a member of a class, you determine how easy it is for the member to be accessed. Accessing a member refers to either reading the member's value or modifying it.
- If you declare a member to be private, then the member can be accessed only from within the member's class. Instance variables are almost always declared with the private modifier because you almost always want an object's data to be hidden. Making the data hard to access is what encapsulation is all about and it's one of the cornerstones of OOP.
- If you declare a member to be public, then the member can be accessed from anywhere (from within the member's class, and also from outside the member's class). Methods are usually declared with the public modifier because you normally want to be able to call them from anywhere.
15
15
*
Driver Class
/****************************************
* MouseDriver.java
* Dean & Dean
*
* This is a driver for the Mouse class.
****************************************/
import java.util.Scanner;
public class MouseDriver
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
double growthRate;
Mouse gus = new Mouse();
Mouse jaq = new Mouse();
16
16
*
Driver Class
System.out.print("Enter growth rate as a percentage: ");
growthRate = stdIn.nextDouble();
gus.setPercentGrowthRate(growthRate);
jaq.setPercentGrowthRate(growthRate);
gus.grow();
jaq.grow();
gus.grow();
gus.display();
jaq.display();
} // end main
} // end class MouseDriver
17
17
*
Reference Variables and Instantiation
- To declare a reference variable (which holds the address in memory where an object is stored):
<class-name> <reference-variable>;
- To instantiate/create an object and assign its address into a reference variable:
<reference-variable> = new <class-name>()
- Example code:
Mouse gus;
gus = new Mouse();
- This single line is equivalent to the two lines above :
Mouse gus = new Mouse();
declaration
instantiation
initialization
18
18
*
Calling a Method
- After instantiating an object and assigning its address into a reference variable, call/invoke an instance method using this syntax:
<reference-variable>.<method-name>(<comma-separated-arguments>);
- Here are three example instance method calls from the MouseDriver class:
gus.setPercentGrowthRate(growthRate);
gus.grow();
gus.display();
19
19
*
- A calling object is the object that appears at the left of the dot in a call to an instance method.
- Can you find the calling objects below?
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
double growthRate;
Mouse gus = new Mouse();
System.out.print("Enter growth rate as a percentage: ");
growthRate = stdIn.nextDouble();
gus.setPercentGrowthRate(growthRate);
gus.grow();
gus.display();
} // end main
Calling Object
20
20
*
- The this reference:
- When used in conjunction with a dot and an instance variable, "this" is referred to as the this reference. Note this example from the Mouse class's grow method:
this.weight += (.01 * this.percentGrowthRate * this.weight);
- The this reference is used inside of a method to refer to the object that called the method; in other words, the this reference refers to the calling object.
So what’s so great about having a special name for the calling object inside of a method? Why not just use the original name, gus or jaq, inside the method?
- Because if the original name were to be used, then the method would only work for the one specified calling object. By using a generic name (this) for the calling object, then the method is more general purpose. For example, by using this, the grow method is able to specify weight gain for any Mouse object that calls it. If gus calls grow, then gus’s weight is updated, whereas if jaq calls grow, then jaq’s weight is updated.
The this Reference
21
21
*
- A variable's default value is the value that the variable gets if there's no explicit initialization.
- Mouse class's instance variable declarations:
private int age = 0;
private double weight = 1.0;
private double percentGrowthRate;
- Here are the default values for instance variables:
- integer types get 0
- floating point types get 0.0
- boolean types get false
- reference types get null
- Note that a String is a reference type so it gets null by default.
Default Values
explicit initializations
percentGrowthRate gets default value of 0.0
22
22
*
- A variable's persistence is how long a variable's value survives before it's wiped out.
- Instance variables persist for the duration of a particular object. Thus, if an object makes two method calls, the second called method does not reset the calling object's instance variables to their initialized values. Instead, the object's instance variables retain their values from one method call to the next.
Variable Persistence
23
23
*
UML Class Diagram for Next Version of the Mouse Program
Member accessibility:
Use "-" for private access and "+" for public access.
Method notes:
We use them here to specify local variables.
Initialization values:
Use "= <value>".
32
32
*
Local Variables
- A local variable is a variable that's declared inside a method. That's different from an instance variable, which is declared at the top of a class, outside all the methods.
- A local variable is called "local" because it can be used only inside of the method in which it is declared – it is completely local to the method.
- In the Mouse2Driver class on the next slide, note how the main method has three local variables - stdIn , mickey, and days. And in the Mouse2 class, note how the grow method has one local variable - i.
33
33
*
Mouse2Driver Class
import java.util.Scanner;
public class Mouse2Driver
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
Mouse2 mickey = new Mouse2();
int days;
mickey.setPercentGrowthRate(10);
System.out.print("Enter number of days to grow: ");
days = stdIn.nextInt();
mickey.grow(days);
System.out.printf("Age = %d, weight = %.3f\n",
mickey.getAge(), mickey.getWeight());
} // end main
} // end class Mouse2Driver
local variables
34
34
*
Mouse2 Class
import java.util.Scanner;
public class Mouse2
{
private int age = 0; // age in days
private double weight = 1.0; // weight in grams
private double percentGrowthRate; // % daily weight gain
//********************************************************
public void setPercentGrowthRate(double percentGrowthRate)
{
this.percentGrowthRate = percentGrowthRate;
} // end setPercentGrowthRate
//********************************************************
public int getAge()
{
return this.age;
} // end getAge
35
35
*
Mouse2 Class
//********************************************************
public double getWeight()
{
return this.weight;
} // end getWeight
//********************************************************
public void grow(int days)
{
for (int i=0; i<days; i++)
{
this.weight +=
(.01 * this.percentGrowthRate * this.weight);
}
this.age += days;
} // end grow
} // end class Mouse2
local variable
36
36
*
return Statement
- The return statement allows you to pass a value from a method back to the place where the method was called. Note the following example.
- From the Mouse2 class:
public int getAge()
{
return this.age;
} // end getAge
- From the Mouse2Driver class:
System.out.printf("Age = %d, weight = %.3f\n",
mickey.getAge(), mickey.getWeight());
- Note the return type in the above example. It has to match the type of the value that's being returned in the return statement.
return type
return statement
method call
37
37
*
void Return Type
- As shown in the below grow method from the Mouse2 class, if a method does not return a value, then the method must specify void for its return type.
public void grow(int days)
{
for (int i=0; i<days; i++)
{
this.weight +=
(0.01 * this.percentGrowthRate * this.weight);
}
this.age += days;
} // end grow
38
38
*
Empty return Statement
- For methods with a void return type, it's legal to have an empty return statement. The empty return statement looks like this:
return;
- The empty return statement does what you'd expect:
- It terminates the current method and causes control to be passed to the calling module at the point that immediately follows the method call that called the current method.
39
39
*
Empty return Statement
- Suppose you'd like to model mouse growth only up through mouse adolescence. This grow method does that by stopping a mouse's growth after 100 days:
public void grow(int days)
{
int endAge;
endAge = this.age + days;
while (this.age < endAge)
{
if (this.age >= 100)
{
return;
}
this.weight +=
.01 * this.percentGrowthRate * this.weight;
this.age++;
} // end while
} // end grow
empty return statement
40
40
*
Empty return Statement
- Code that uses an empty return statement(s) can always be replaced by code that does not use the empty return statement(s). For example, here's a return-less version of the previous grow method:
public void grow(int days)
{
int endAge;
endAge = this.age + days;
if (endAge > 100)
{
endAge = 100;
}
while (this.age < endAge)
{
this.weight +=
(.01 * this.percentGrowthRate * this.weight);
this.age++;
} // end while
} // end grow
41
41
*
return Statement Within a Loop
- Software engineering observation:
- Real-world programmers are often asked to maintain (fix and improve) other people's code. In doing that, they oftentimes find themselves having to examine the loops and, even more specifically, the loop termination conditions in the program they're working on. Therefore, it's important that the loop termination conditions are clear. Normally, loop termination conditions appear in standard places: while loop heading, do loop closing, for loop heading's condition part. However, in using a return statement inside a loop, the return statement introduces a loop termination that's not in one of the standard places. For example, in the grow method two slides ago, the return statement is "hidden" inside an if statement that's embedded in a while loop.
- In the interest of maintainability, you should use restraint when considering the use of a return statement inside of a loop. Based on the context, if inserting a return statement(s) inside a loop improves clarity, then feel free to insert. However, if it simply makes the coding chores easier and it does not add clarity, then don't insert.
42
42
*
- The default value for a local variable is garbage.
- Garbage means that the variable's value is unknown - it's whatever just happens to be in memory at the time that the variable is created.
- When doing a trace, use a "?" to indicate garbage.
- If a program attempts to access a variable that contains garbage, the compiler generates an error. For example, what happens when the following method is compiled?
public void grow(int days)
{
for (int i; i<days; i++)
{
this.weight +=
(.01 * this.percentGrowthRate * this.weight);
}
this.age += days;
} // end grow
- Since i is no longer assigned zero, i contains garbage when the i<days condition is tested. That causes the compiler to generate this error message:
variable i might not have been initialized
Local Variable Default Values
43
43
*
- Local variables persist only for the duration of the method (or for loop) in which the local variable is defined. The next time the method (or for loop) is executed, the local variable's value resets to its initial value.
Local Variable Persistence
44
44
*
Argument Passing
- What is the output for the following Mouse3Driver and Mouse3 classes?
public class Mouse3Driver
{
public static void main(String[] args)
{
Mouse3 minnie = new Mouse3();
int days = 365;
minnie.grow(days);
System.out.println("# of days aged = " + days);
} // end main
} // end class Mouse3Driver
45
45
*
Argument Passing
public class Mouse3
{
private int age = 0; // age in days
private double weight = 1.0; // weight in grams
private double percentGrowthRate = 10; // % daily weight gain
//********************************************************
public void grow(int days)
{
this.age += days;
while (days > 0)
{
this.weight +=
(.01 * this.percentGrowthRate * this.weight);
days--;
}
} // end grow
} // end class Mouse3
46
46
*
Argument Passing
- Java uses the pass-by-value mechanism to pass arguments to methods.
- Pass-by-value means that the JVM passes a copy of the argument's value (not the argument itself) to the parameter.
- Thus, if the parameter's value changes within the method, the argument in the calling module is unaffected.
- For example, in the previous two program slides, even though the days value within the grow method changes, the main method's days value is unaffected.
47
47
*
Argument Passing
- An argument and its associated parameter often use the same name. For example, we use days for the argument in Mouse3Driver's grow method call, and we also use days for the parameter in Mouse3's grow method heading.
- But be aware that an argument and its associated parameter don't have to use the same name. The only requirement is that an argument and its associated parameter are the same type.
- For example, if num is an int variable, then this method call successfully passes num's value into the days parameter:
minnnie.grow(num);
- As another example, since 365 is an int value, the following method call successfully passes 365 into the days parameter:
minnie.grow(365);
48
48
*
Specialized Methods
- Accessor methods -
- They simply get/access the value of an instance variable.
- Example:
public int getAge()
{
return this.age;
}
- Mutator methods -
- They simply set/mutate the value of an instance variable.
- Example:
public void setPercentGrowthRate(double percentGrowthRate)
{
this.percentGrowthRate = percentGrowthRate;
} // end setPercentGrowthRate
49
49
*
Specialized Methods
- boolean methods -
- They check the truth or falsity of some condition.
- They always return a boolean value.
- They should normally start with "is".
- For example, here's an isAdolescent method that determines whether a Mouse object's age is ≤ 100:
public boolean isAdolescent()
{
if (this.age <= 100)
{
return true;
}
else
{
return false;
}
} // end isAdolescent
- Here's how the isAdolescent method might be used in main:
Mouse pinky = new Mouse();
...
if (pinky.isAdolescent() == false)
{
System.out.println(
"The Mouse's growth is no longer" +
" being simulated - too old.");
}
50
50
*
methods
data
rest of program
object
computer objects
Specifications for a computer
CS151- Lab Four Wiemann
Requirements: 1) Create a C++ Program to convert binary to decimal, decimal to binary,
decimal to hexadecimal, and hexadecimal to decimal. 2) When the program is first executed a menu, similar in design, should be
displayed to the user: Michael Wiemann’s Conversion Program
------------------------------------
1) Convert Binary to Decimal 2) Convert Decimal to Binary 3) Convert Decimal to Hexadecimal 4) Convert Hexadecimal to Decimal 5) Exit Program
Input Choice:
3) The user should be prompted for the input of a choice. If the choice ‘1’ through ‘4’ is selected, then the appropriate input and output should occur for that option. If the user selects ‘5’, the program should be terminated, otherwise an error message should be displayed to the user. The program should continue to display the menu until the user types the value of ‘5’ as his/her choice.
4) You are required to use a function/method to create the menu interface. 5) You are required to use a function/method or a collection of
functions/methods to calculate each menu option. 6) Validation of input must occur on the input of the typed data (i.e. ‘12B’ is not
a valid decimal value). An error message should be displayed to the end user if the required menu option is not valid.
7) All shop standards are to be followed as instructed in class. 8) The output listed above must be mathematically correct, however, formatting
of the numbers with the decimal places and right justification is not required. 9) Save the source code as “mrwJavaProg04.java”. 10) You will submit the Java file to the Dropbox for this lab assignment on or
before the due date.
Chapter 5 - Using Pre-Built Methods
- The API Library
- API Headings
- Math Class
- Wrapper Classes for Primitive Types
- Lottery Example
- String Methods:
- substring
- indexOf
- lastIndexOf
- Formatted Output with the printf Method
1
1
*
The API Library
- When working on a programming problem, you should normally check to see if there are pre-built classes that meet your program's needs.
- If there are such pre-built classes, then use those classes (don't "reinvent the wheel"). For example:
- User input is a rather complicated task. The Scanner class handles user input. Whenever you need user input in a program, use the Scanner class's input methods (rather than writing and using your own input methods).
- Math calculations are sometimes rather complicated. The Math class handles math calculations. Whenever you need to perform non-trivial math calculations in a program, use the Math class's methods (rather than writing and using your own math methods).
2
2
*
The API Library
- Java's pre-built classes are stored in its class library, which is more commonly known as the Application Programming Interface (API) library. See http://docs.oracle.com/javase/7/docs/api/.
- Java's API classes are not part of the core Java language. For a program to use an API class, the class first needs to be loaded/imported into the program. For example, to use the Scanner class, include this at the top of your program:
import java.util.Scanner;
- The java.util thing that precedes Scanner is called a package.
- A package is a group of classes.
- The java.util package contains quite a few general-purpose utility classes. The only one you'll need for now is the Scanner class.
3
3
*
The API Library
- Some classes are considered to be so important that the Java compiler automatically imports them for you. The automatically imported classes are in the java.lang package.
- The Math class is one of those classes, so there's no need for you to import the Math class if you want to perform math operations.
- The Java compiler automatically inserts this statement at the top of every Java program:
import java.lang.*;
- The asterisk is a wild card and it means that all classes in the java.lang package are imported, not just the Math class.
4
4
*
API Headings
- To use an API class, you don't need to know the internals of the class; you just need to know how to "interface" with it.
- To interface with a class, you need to know how to use the methods within the class. For example, to perform input, you need to know how to use the Scanner class's methods - next, nextLine, nextInt, nextDouble, etc.
- To use a method, you need to know what type of argument(s) to pass to it and what type of value it returns.
- The standard way to show that information is to show the method's source code heading.
5
5
*
API Headings
- For example, here's the source code heading for the Scanner class's nextInt method:
public int nextInt()
- And here's an example of calling the nextInt method:
int days = stdIn.nextInt();
All the methods in the API library are public, which means that they are accessible from everywhere; i.e., the "public" can access them.
The return type (int in this example) indicates the type of the value that's being returned from the method.
The arguments that you pass to the method would go inside the parentheses (but no arguments are passed to the nextInt method).
6
6
*
Math Class
- Source code headings for API methods are commonly referred to as API headings.
- Here are the API headings for some of the more popular methods in the Math class:
- public static int abs(int num)
- Returns the absolute value of num.
- public static double abs(double num)
- Returns the absolute value of num.
- public static int max(int x, int y)
- Returns the larger value of x and y.
- public static double max(double x, double y)
- Returns the larger value of x and y.
7
7
*
Math Class
- Math class API headings (continued):
- public static int min(int x, int y)
- Returns the smaller value of x and y.
- public static double min(double x, double y)
- Returns the smaller value of x and y.
- public static double pow(double num, double power)
- Returns num raised to the specified power.
- public static double random()
- Returns a uniformly distributed value between 0.0 and 1.0, but not including 1.0.
- public static long round(double num)
- Returns the whole number that is closest to num.
- public static double sqrt(double num)
- Returns the square root of num.
8
8
*
Math Class
- Note the static modifier at the left of all the Math methods. All the methods in the Math class are static methods (also called class methods), which means they are called by prefacing the method's name with the name of the class in which they are defined. For example:
int position1 = 15, position2 = 18;
int distanceApart = Math.abs(position1 - position2);
- Write a Java statement that updates x's value so x gets the absolute value of its original value.
Call Math methods by prefacing them with Math dot.
9
9
*
Math Class
- It is legal to pass an integer value to a method that accepts a floating-point argument. Note the following example. Horton’s Law says that the length of a river is related to the area drained by the river in accordance with this formula:
length ≈ 1.4 (area)0.6
- Here's how to implement Horton's Law in Java code:
int area = 10000; // square miles drained
double riverLength = 1.4 * Math.pow(area, 0.6);
- A common use of computers is to model real-world activities that rely on random events.
- That's because computers are good at generating random numbers and being able to repeat the random events many, many times.
OK to pass an int (area), into pow, which accepts double arguments.
10
10
*
Math Class
- The Math class contains a named constant, PI.
- Pi, written as in math books, is the ratio of a circle's perimeter to its diameter.
- It contains this double value: 3.14159265358979323846
- It's a constant, which means its value is fixed. If you attempt to assign a value to it, you'll get a compilation error.
- Just like Math's methods are class methods and they are accessed using the Math class name, Math's PI is a class variable and it is accessed using the Math class name. In other words, if you need pi, specify Math.PI.
- Complete this code fragment:
double radius = 3.0;
double volumeOfSphere =
11
11
*
Wrapper Classes For Primitive Types
- A wrapper class is a class that surrounds a relatively simple item in order to add functionality to the simple item.
- Here are wrapper classes for some of the Java primitive types:
Wrapper Class Primitive Type
Integer int
Long long
Float float
Double double
Character char
- Note that the wrapper class names are the same as the primitive names except for the uppercase first letter. What are the exceptions to that rule?
- The wrapper classes are defined in the java.lang package. The Java compiler automatically imports all the classes in the java.lang package, so there's no need to import the wrapper classes explicitly.
12
12
*
Wrapper Classes For Primitive Types
- Most real-world Java programs use GUI I/O instead of text-based I/O. (GUI = graphical user interface. I/O = input/output.)
- What is text-based I/O?
- What is GUI I/O?
- With GUI programs, all numeric output is string based. So to display a number, you need to convert the number to a string prior to calling the GUI display method. All numeric input is string based, too. So to read a number in a GUI program, you first read the input as a string and then convert the string to a number.
- Here are string conversion methods provided by the numeric wrapper classes:
Wrapper Class string number number string
Integer Integer.parseInt(<string>) Integer.toString(<#>)
Long Long.parseLong(<string>) Long.toString(<#>)
Float Float.parseFloat(<string>) Float.toString(<#>)
Double Double.parseDouble(<string>) Double.toString(<#>)
13
13
*
Wrapper Classes For Primitive Types
- Conversion examples - strings to numbers:
String yearStr = "2011";
String scoreStr = "78.5";
int year = Integer.parseInt(yearStr);
double score = Double.parseDouble(scoreStr);
- Remember - to convert a string to a numeric type, use X.parseX where X is the numeric type you're interested in.
- Conversion examples - numbers to strings :
int year = 2011;
double score = 78.5;
String yearStr = Integer.toString(year);
String scoreStr = Double.toString(score);
14
14
*
Wrapper Classes For Primitive Types
- To find the largest and smallest possible values for a particular type, use the type's wrapper class and access the wrapper class's MAX_VALUE and MIN_VALUE named constants. For example:
Integer.MAX_VALUE
Double.MAX_VALUE
Long.MIN_VALUE
- Write a lottery program that prompts the user to guess a randomly generated number between 0 and the maximum int value. The user pays $1.00 for each guess and wins $1,000,000 if the guess is correct. The user enters a "q" to quit.
15
15
*
Lottery Example
import java.util.Scanner;
public class Lottery
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String input;
int winningNumber =
System.out.println("Want to win a million dollars?");
System.out.println("If so, guess the winning number (a" +
" number between 1 and " + Integer.MAX_VALUE + ").");
do
{
System.out.print(
"Insert $1.00 and enter your number or 'q' to quit: ");
input = stdIn.nextLine();
Initialize winningNumber to a randomly chosen integer between 1 and the largest possible int.
16
16
*
Lottery Example
if (input.equals("give me a hint")) // a back door
{
System.out.println("try: " + winningNumber);
}
else if (!input.equals("q"))
{
if (
{
System.out.println("YOU WIN!");
input = "q"; // force winners to quit
}
else
{
System.out.println(
"Sorry, good guess, but not quite right.");
}
} // end else if
} while (!input.equals("q"));
System.out.println("Thanks for playing. Come again!");
} // end main
} // end Lottery class
Compare input with the winning number.
17
17
*
The String Class
- In Chapter 3, you saw several String methods - charAt, length, equals, and equalsIgnoreCase.
- Those methods are defined in the String class, along with quite a few other methods that help with string manipulation tasks.
- The String class is defined in the java.lang package. The Java compiler automatically imports all the classes in the java.lang package, so there's no need to import the String class explicitly.
- We'll now present several additional popular methods in the String class.
18
18
*
The String Class's substring Method
- Here are API headers and brief descriptions for two alternative forms of the substring method:
- public String substring(int beginIndex)
- Returns a string that is a subset of the calling-object string, starting at the beginIndex position and extending to the end of the calling-object string.
- public String substring(int beginIndex, int afterEndIndex)
- Returns a string that is a subset of the calling-object string, starting at the beginIndex position and extending to the afterEndIndex-1 position.
19
19
*
The String Class's substring Method
public class StringMethodDemo
{
public static void main(String[] args)
{
String yoda =
"May the force be with you.";
System.out.println(yoda.substring(8));
System.out.println(yoda.substring(4, 13));
} // end main
} // end StringMethodDemo
calling object
20
20
*
The String Class's indexOf Methods
- Here are API headers and brief descriptions for four alternative forms of the indexOf method:
- public int indexOf(int ch)
- Returns the position of the first occurrence of the given ch character within the calling-object string. Returns -1 if ch is not found.
- public int indexOf(int ch, int fromIndex)
- Returns the position of the first occurrence of the given ch character within the calling-object string, starting the search at the fromIndex position. Returns -1 if ch is not found.
- public int indexOf(String str)
- Returns the position of the first occurrence of the given str string within the calling-object string. Returns -1 if str is not found.
- public int indexOf(String str, int fromIndex)
- Returns the position of the first occurrence of the given str string within the calling-object string, starting the search at the fromIndex position. Returns -1 if str is not found.
21
21
*
The String Class's indexOf Methods
public class StringMethodDemo
{
public static void main(String[] args)
{
String egyptian =
"I will not leave the square. Over my dead body.";
int index = egyptian.indexOf('.');
String egyptian2 = egyptian.substring(index + 2);
System.out.println(egyptian2);
} // end main
} // end StringMethodDemo
22
22
*
The String Class's lastIndexOf Methods
- The lastIndexOf methods are identical to the indexOf methods except that they search the calling-object string from right to left.
- For the one-parameter lastIndexOf methods, the search starts from the rightmost character.
- For the two-parameter lastIndexOf methods, the search starts from the position specified by the second parameter.
- What does this code fragment print?
String quote =
"Peace cannot be kept by force; it can" +
" only be achieved by understanding."
System.out.print(
quote.indexOf("can") + " " +
quote.indexOf("can", 7) + " " +
quote.lastIndexOf("can"));
23
23
*
Formatted Output with the printf Method
- You should strive to make program output be understandable and attractive. To further that goal, format your output. Here's an example of formatted output:
Account Actual Budget Remaining
------- ------ ------ ---------
Office Supplies 1,150.00 1,400.00 250.00
Photocopying 2,100.11 2,000.00 (100.11)
Total remaining: $149.89
- The System.out.printf method is in charge of generating formatted output.
24
24
*
Formatted Output with the printf Method
- Here's how to generate the "Total remaining" line in the previous slide's budget report:
System.out.printf(
"\nTotal remaining: $%.2f\n", remaining1 + remaining2);
- You can have as many format specifiers as you like in a given format string. For each format specifier, you should have a corresponding data item/argument.
format specifier
25
25
*
Format Specifier Details
- Here's the syntax for a format specifier:
%[flags][width][.precision]conversion-character
- The square brackets indicate that something is optional. So the flags, width, and precision parts are optional. Only the % and the conversion character are required.
26
26
*
Conversion Character
- The conversion character tells the Java Virtual Machine (JVM) the type of thing that is to be printed.
- Here is a partial list of conversion characters:
s This displays a string.
d This displays a decimal integer (an int or a long).
f This displays a floating-point number (a float or a double) with a decimal point and at least one digit to the left of the decimal point.
e This displays a floating-point number (float or double) in scientific notation.
27
27
*
Conversion Character
- This code fragment illustrates how to use the conversion characters:
System.out.printf("Planet: %s\n", "Neptune");
System.out.printf("Number of moons: %d\n", 13);
System.out.printf("Orbital period (in earth years): %f\n", 164.79);
System.out.printf(
"Average distance from the sun (in km): %e\n", 4_498_252_900.0);
- Here is the output:
Planet: Neptune
Number of moons: 13
Orbital period (in earth years): 164.790000
Average distance from the sun (in km): 4.498253e+09
28
28
*
Precision and Width
- Precision:
- Applies only to floating-point numbers (i.e., it works only in conjunction with the f and e conversion characters).
- Its syntax consists of a dot and then the number of digits that are to be printed to the right of the decimal point.
- If the data item has more fractional digits than the precision specifier's value, then rounding occurs. If the data item has fewer fractional digits than the precision specifier's value, then zeros are added at the right so the printed value has the specified number of fractional digits.
- Width:
- Specifies the minimum number of characters that are to be printed. If the data item contains more than the specified number of characters, then all of the characters are printed. If the data item contains fewer than the specified number of characters, then spaces are added.
- By default, output values are right aligned, so when spaces are added, they go on the left side.
29
29
*
Precision and Width
- This code fragment illustrates how to specify precision and width in a format specifier:
System.out.printf("Cows are %6s\n", "cool");
System.out.printf("But dogs %2s\n", "rule");
System.out.printf("PI = %7.4f\n", Math.PI);
- Here is the output:
Cows are cool
But dogs rule
PI = 3.1416
6 characters
7 characters
30
30
*
Flags
- Flags allow you to add supplemental formatting features, one flag character for each formatting feature. Here's a partial list of flag characters:
- Display the printed value using left justification.
0 If a numeric data item contains fewer characters than the width specifier's value, then pad the printed value with leading zeros (i.e., display zeros at the left of the number).
, Display a numeric data item with locale-specific grouping separators. In the United States, that means commas are inserted between every third digit at the left of the decimal point.
( Display a negative numeric data item using parentheses, rather than a minus sign. Using parentheses for negative numbers is a common practice in the field of accounting.
31
31
*
BudgetReport Example
public class BudgetReport
{
public static void main(String[] args)
{
final String HEADING_FMT_STR = "%-25s%13s%13s%15s\n";
final String DATA_FMT_STR = "%-25s%,13.2f%,13.2f%(,15.2f\n";
double actual1 = 1149.999; // amount spent on 1st account
double budget1 = 1400; // budgeted for 1st account
double actual2 = 2100.111; // amount spent on 2nd account
double budget2 = 2000; // budgeted for 2nd account
double remaining1, remaining2; // unspent amounts
System.out.printf(HEADING_FMT_STR,
"Account", "Actual", "Budget", "Remaining");
System.out.printf(HEADING_FMT_STR,
"-------", "------", "------", "---------");
left justification
parentheses for negatives, comma for group separators
32
32
*
BudgetReport Example
remaining1 = budget1 - actual1 ;
System.out.printf(DATA_FMT_STR,
"Office Supplies", actual1, budget1, remaining1);
remaining2 = budget2 - actual2;
System.out.printf(DATA_FMT_STR,
"Photocopying", actual2, budget2, remaining2);
System.out.printf(
"\nTotal remaining: $%(,.2f\n", remaining1 + remaining2);
} // end main
} // end class BudgetReport
33
33
*
Chapter 4 - Control Statements
- Conditions
- if Statement
- && Logical Operator
- || Logical Operator
- ! Logical Operator
- switch Statement
- while Loop
- do Loop
- for Loop
- Loop Comparison
- Nested Loops
- Boolean Variables
- Input Validation
- Boolean Logic
- Expression Evaluation Practice
1
1
*
Conditions
- Throughout this chapter, you’ll see if statements and loop statements where conditions appear within a pair of parentheses, like this:
if (<condition>)
{
...
}
while (<condition>)
{
...
}
- Typically, each condition involves some type of comparison, and the comparisons use comparison operators….
2
2
*
Conditions
- Here are Java's comparison operators:
==, !=, <, >, <=, >=
- Each comparison operator evaluates to either true or false.
- ==
- Tests two operands for equality.
- 3 == 3 evaluates to true
- 3 == 4 evaluates to false
- Note that == uses two equal signs, not one!
- !=
- Tests two operands for inequality.
- The != operator is pronounced “not equal.”
- The <, >, <=, and >= operators work as expected.
3
3
*
if Statement
- Use an if statement if you need to ask a question in order to determine what to do next.
- There are three forms for an if statement:
- if by itself
- Use for problems where you want to do something or nothing.
- if, else
- Use for problems where you want to do one thing or another thing.
- if, else if
- Use for problems where you want to do one thing out of three or more choices.
4
4
*
if Statement
pseudocode syntax
- if by itself:
if <condition>
<statement(s)>
- if, else:
if <condition>
<statement(s)>
else
<statement(s)>
Java syntax
- if by itself:
if (<condition>)
{
<statement(s)>
}
- if, else:
if (<condition>)
{
<statement(s)>
}
else
{
<statement(s)>
}
5
5
*
if Statement
pseudocode syntax
if, else if , else:
if <condition>
<statement(s)>
else if <condition>
<statement(s)>
.
.
.
else
<statement(s)>
Java syntax
if, else if, else:
if (<condition>)
{
<statement(s)>
}
else if (<condition>)
{
<statement(s)>
}
.
.
.
else
{
<statement(s)>
}
optional
more else if's here (optional)
optional
more else if's here (optional)
6
6
*
if Statement
- Write a complete program that prompts the user to enter a sentence and then prints an error message if the last character is not a period.
sample session:
Enter a sentence:
Permanent good can never be the outcome of violence
Invalid entry – your sentence needs a period!
Italics indicates input. Never hardcode (include) input as part of your source code!!!
7
7
*
&& Logical Operator
- Suppose you want to print "OK" if the temperature is between 50 and 90 degrees and print "not OK" otherwise.
- Here's the pseudocode solution:
if temp 50 and 90
print "OK"
else
print "not OK"
10
10
*
&& Logical Operator
- And here's the solution using Java:
if (temp >= 50 && temp <= 90)
{
System.out.println("OK");
}
else
{
System.out.println("not OK");
}
- In Java, if two criteria are required for a condition to be satisfied (e.g., temp >= 50 and temp <= 90), then separate the two criteria with the && (and) operator. If both criteria use the same variable (e.g., temp), you must include the variable on both sides of the &&.
11
11
*
&& Logical Operator
- The program on the next slide determines whether fans at a basketball game win free french fries. If the home team wins and scores at least 100 points, then the program prints this message:
Fans: Redeem your ticket stub for a free order of french fries at Yummy Burgers.
- On the next slide, replace <insert code here> with appropriate code.
12
12
*
&& Logical Operator
/***************************************
* FreeFries.java
* Dean & Dean
*
* This program reads points scored by the home team
* and the opposing team and determines whether the
* fans win free french fries.
***************************************/
import java.util.Scanner;
public class FreeFries
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
int homePts; // points scored by home team
int opponentPts; // points scored by opponents
System.out.print("Home team points scored: ");
homePts = stdIn.nextInt();
System.out.print("Opposing team points scored: ");
opponentPts = stdIn.nextInt();
<insert code here>
} // end main
} // end class FreeFries
13
13
*
|| Logical Operator
- Provide code that prints "bye" if a response variable contains a lowercase or uppercase q (for quit). Here’s a pseudocode implementation:
if response equals “q” or “Q”
print “Bye”
- To implement “or” logic in Java, use || (the or operator). Here’s the Java implementation:
if (response.equals(″q″) || response.equals(″Q″))
{
System.out.println("bye");
}
When using the || operator, if both criteria in the or condition use the same variable (e.g., response), you must include the variable on both sides of the ||.
14
14
*
|| Logical Operator
- It’s a common bug to forget to repeat a variable that’s part of an || (or &&) condition. This code generates a compilation error:
if (response.equals(″q″ || ″Q″))
{
System.out.println("bye");
}
- Another common bug is to use the == operator to compare strings for equality. This code compiles successfully, but it doesn’t work properly:
if (response == ″q″ || response == ″Q″)
{
System.out.println("bye");
}
15
15
*
|| Logical Operator
- As an alternative to using the || operator with two equals method calls, you could use an equalsIgnoreCase method call like this:
if (response.equalsIgnoreCase("q"))
{
System.out.println("Bye");
}
16
16
*
! Logical Operator
- The ! (not) operator reverses the truth or falsity of a condition.
- For example, suppose that a char variable named reply holds a q (lowercase or uppercase) if the user wants to quit, or some other character if the user wants to continue. To check for "some other character" (i.e., not a q or Q), use the ! operator like this:
if (!(reply == 'q' || reply == 'Q'))
{
System.out.println("Let's get started....");
...
17
17
*
switch Statement
- When to use a switch statement:
- If you need to do one thing from a list of multiple possibilities.
- Note that the switch statement can always be replaced by an if, else if, else statement, but the switch statement is considered to be more elegant. (Elegant code is easy to understand, easy to update, robust, reasonably compact, and efficient.)
- Syntax:
switch (<controlling-expression>)
{
case <constant1>:
<statements>;
break;
case <constant2>:
<statements>;
break;
...
default:
<statements>;
} // end switch
18
18
*
switch Statement
- How the switch statement works:
- Jump to the case constant that matches the controlling expression's value (or jump to the default label if there are no matches) and execute all subsequent statements until reaching a break.
- The break statement causes a jump out of the switch statement (below the "}").
- Usually, break statements are placed at the end of every case block. However, that's not a requirement and they're sometimes omitted for good reasons.
- Put a : after each case constant.
- Even though statements following the case constants are indented, { }'s are not necessary.
- The controlling expression should evaluate to either an int, a char, or a String.
- Proper style dictates including // end switch after the switch statement's closing brace.
19
19
*
switch Statement
- Given this code fragment:
i = stdIn.nextInt();
switch (i)
{
case 1:
System.out.print("A");
break;
case 2:
System.out.print("B");
case 3: case 4:
System.out.print("C-D");
break;
default:
System.out.print("E-Z");
} // end switch
- If input = 1, what's the output?
- If input = 2, what's the output?
- If input = 3, what's the output?
- If input = 4, what's the output?
- If input = 5, what's the output?
20
20
*
switch Statement
- Write a program that reads in a ZIP Code and uses the first digit to print the associated geographic area:
if zip code print this
begins with message
0-3 <zip> is on the East Coast.
4-6 <zip> is in the Central Plains area.
7 <zip> is in the South.
8-9 <zip> is in the West.
other <zip> is an invalid ZIP Code.
- Note: <zip> represents the entered ZIP Code value.
21
21
*
while Loop
pseudocode syntax
while <condition>
{
<statement(s)>
}
Java syntax
while (<condition>)
{
<statement(s)>
}
- Use a loop statement if you need to do the same thing repeatedly.
23
23
*
*
while Loop
- Write a main method that finds the sum of user-entered integers where -99999 is a sentinel value.
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
int sum = 0; // sum of user-entered values
int x; // a user-entered value
System.out.print("Enter an integer (-99999 to quit): ");
x = stdIn.nextInt();
while (x != -99999)
{
sum = sum + x;
System.out.print("Enter an integer (-99999 to quit): ");
x = stdIn.nextInt();
}
System.out.println("The sum is " + sum);
} // end main
24
24
*
do Loop
- When to use a do loop:
- If you know that the repeated thing will always have to be done at least one time.
- Syntax:
do
{
<statement(s)>
} while (<condition>);
- Note:
- The condition is at the bottom of the loop (in contrast to the while loop, where the condition is at the top of the loop).
- The compiler requires putting a ";" at the very end, after the do loop's condition.
- Proper style dictates putting the "while" part on the same line as the "}"
25
25
*
do Loop
- Problem description:
- As part of an architectural design program, write a main method that prompts the user to enter length and width dimensions for each room in a proposed house so that total floor space can be calculated for the entire house.
- After each length/width entry, ask the user if there are any more rooms.
- Print the total floor space.
26
26
*
for Loop
- When to use a for loop:
- If you know the exact number of loop iterations before the loop begins.
- For example, use a for loop to:
- Print this countdown from 10:
10 9 8 7 6 5 4 3 2 1 Liftoff!
- Find the factorial of a user-entered number.
Sample session:
Enter a whole number: 4
4! = 24
28
28
*
for Loop
for loop syntax
for (<initialization>; <condition>; <update>)
{
<statement(s)>
}
for loop example
for (int i=10; i>0; i--)
{
System.out.print(i + " ");
}
System.out.println("Liftoff!");
- for loop semantics:
- Before the start of the first loop iteration, execute the initialization component.
- At the start of each loop iteration, evaluate the condition component:
- If the condition is true, execute the body of the loop.
- If the condition is false, terminate the loop (jump to the statement below the loop's closing brace).
- At the end of each loop iteration, execute the update component and then jump to the top of the loop.
29
29
*
for Loop
- Trace this code fragment with an input value of 3.
Scanner stdIn = new Scanner(System.in);
int number; // user entered number
double factorial = 1.0; // factorial of user entry
System.out.print("Enter a whole number: ");
number = stdIn.nextInt();
for (int i=2; i<=number; i++)
{
factorial *= i;
}
System.out.println(number + "! = " + factorial);
for loop index variables are often, but not always, named i for “index.”
Declare for loop index variables within the for loop heading.
30
30
*
for Loop
- Write a main method that prints the squares for each odd number between 1 and 99.
- Output:
1
9
25
49
81
...
31
31
*
Loop Comparison
for loop:
do loop:
while loop:
When to use
If you know, prior to the start of loop, how many times you want to repeat the loop.
If you always need to do the repeated thing at least one time.
If you can't use a for loop or a do loop.
Template
for (int i=0; i<max; i++)
{
<statement(s)>
}
do
{
<statement(s)>
<prompt - do it again (y/n)?>
} while (<response == 'y'>);
<prompt - do it (y/n)?>
while (<response == 'y'>)
{
<statement(s)>
<prompt - do it again (y/n)?>
}
32
32
*
Nested Loops
- A nested loop is a loop within a loop.
- Example – Write a program that prints a rectangle of characters where the user specifies the rectangle's height, the rectangle's width, and the character's value.
Sample session:
Enter height: 4
Enter width: 3
Enter character: <
<<<
<<<
<<<
<<<
34
34
*
Boolean Variables
- Programs often need to keep track of the state of some condition.
- For example, if you're writing a program that simulates the operations of a garage door opener, you'll need to keep track of the state of the garage door's direction - is the direction up or down? You need to keep track of the direction "state" because the direction determines what happens when the garage door opener's button is pressed. If the direction state is up, then pressing the garage door button causes the direction to switch to down. If the direction state is down, then pressing the garage door button causes the direction to switch to up.
- To implement the state of some condition, use a boolean variable.
38
38
*
Boolean Variables
- A boolean variable is a variable that:
- Is declared to be of type boolean.
- Holds the value true or the value false.
- Boolean variables are good at keeping track of the state of some condition when the state has one of two values. For example:
39
Values for the state of a garage door opener's direction | Associated values for a boolean variable named upDirection |
up | true |
down | false |
39
*
Boolean Variables
- This code fragment initializes an upDirection variable to true and shows how to toggle its value within a loop.
boolean upDirection = true;
do
{
...
upDirection = !upDirection;
...
} while (<user presses the garage door opener button>);
If upDirection holds the value true, this statement changes it to false, and vice versa.
40
40
*
Boolean Variables
import java.util.Scanner;
public class GarageDoor
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String entry; // user's entry - enter key or q
boolean upDirection = true; // Is the current direction up?
boolean inMotion = false; // Is garage door currently moving?
System.out.println("GARAGE DOOR OPENER SIMULATOR\n");
do
{
System.out.print("Press Enter, or enter 'q' to quit: ");
entry = stdIn.nextLine();
if (entry.equals("")) // pressing Enter generates ""
{
inMotion = !inMotion; // button toggles motion state
41
41
*
Boolean Variables
if (inMotion)
{
if (upDirection)
{
System.out.println("moving up");
}
else
{
System.out.println("moving down");
}
}
else
{
System.out.println("stopped");
upDirection = !upDirection; // direction reverses at stop
}
} // end if entry = ""
} while (entry.equals(""));
} // end main
} // end GarageDoor class
42
42
*
Input Validation
- boolean variables are often used for input validation.
- Input validation is when a program checks a user's input to make sure it's valid (i.e., correct and reasonable). If it's valid, the program continues. If it's invalid, the program enters a loop that warns the user about the erroneous input and then prompts the user to re-enter.
- In the GarageDoor program, note how the program checks for an empty string (which indicates the user wants to continue), but it doesn't check for a q.
43
43
*
Input Validation
- To add input validation to the GarageDoor program, replace the GarageDoor program's prompt with the following code. It forces the user to press Enter or enter a q or Q.
validEntry = false;
do
{
System.out.print("Press Enter, or enter 'q' to quit: ");
entry = stdIn.nextLine();
if (entry.equals("") || entry.equalsIgnoreCase("q"))
{
validEntry = true;
}
else
{
System.out.println("Invalid entry.");
}
} while (validEntry == false);
What is a more elegant implementation for this?
44
44
*
Boolean Logic
- Boolean logic (= Boolean algebra) is the formal logic that determines how conditions are evaluated.
- The building blocks for Boolean logic are things that you've already seen - the logical operators &&, ||, and !.
- Logical operator review:
- For the && operator, both sides need to be true for the whole thing to be true.
- For the || operator, only one side needs to be true for the whole thing to be true.
- The ! operator reverses the truth or falsity of something.
45
45
*
Expression Evaluation Practice
- Assume:
boolean ok = false;
double x = 6.5, y = 10.0;
- Evaluate these expressions:
(x != 6.5) || !ok
true && 12.0 < x + y
46
46
*
not OKOKnot OK
50
o
90
o

Get help from top-rated tutors in any subject.
Efficiently complete your homework and academic assignments by getting help from the experts at homeworkarchive.com