Transcript Document
Miscellaneous Java
… a collection of short topics that we
need to get to at some point …
1
Topics
Look at Student.java example
Formatting output
Method overloading
ArrayList revisited
Testing (time permitting)
2
Formatting Output
The default output from System.out.print
isn’t always formatted the way we want
e.g. System.out.print(3.0/7);
output: 0.42857142857142855
It is also hard to combine values
e.g. produce “3 + 4 = 7” from a=3 and b=4
need to print 5 things seperately:
a, “ + “, b “ = “, a+b
3
printf
The system.out.printf statement can
output values based on a “format string”
similar to printf in C
uses place holders to define an abstract form
new in Java 5.0
e.g.
System.out.printf(“%d + %d %d\n”,a,b,a+b);
4
printf
Inputs
A String object, left mostly as is
% sign used to precede replacements
Common types:
%d: int/long
%f - %e: float/double
decimals – scientific
%s: String
%%: prints a %
5
printf
Can control number of characters printed and
decimal places
e.g. %10.2f replacement will take 10 characters
and have 2 decimal places: “
34.21”
e.g. %8d will take 8 characters: “
34”
Can also control other details
e.g. %08d replacement will take 8 characters,
padded with zeroes: “00000034”
6
String.format
Another way to do String formatting
Return a String object instead of printing directly
to the screen
Use the static function format in the
String class
e.g.
String s = String.format
(“%d + %d = %d\n”,a,b,a+b);
7
Example 1
for(int i=0; i<=10; i++)
System.out.printf(“%2d %6.0f\n”, i,
Math.pow(2, i));
What does this code output?
8
Example 2
In Student.java, we could add a toString
method:
String toString()
{
return String.format(“%09d: %s, %s”,
studentNumber, lastName, firstName);
}
9
Why this approach is good
Simple, flexible string formatting
Similar to C, which is useful for translating
legacy code
Particularly useful for just testing outputs…
when the print isn’t “really” part of the
program
In this case introducing a bunch of new objects
seems unecessary
10
Why this approach is not so good
This is not a good example of object-oriented
programming
Formatting a string is an often-required task
The formatting is independent of the surrounding
code
An object-oriented approach suggests
introducing objects for formatting
11
Formatting Output
The Java standard class library contains
classes that provide formatting capabilities
The NumberFormat class allows you to
format values as currency or percentages
The DecimalFormat class allows you to
format values based on a pattern
Both are part of the java.text package
12
Formatting Output
The NumberFormat class has static
methods that return a formatter object
getCurrencyInstance()
getPercentInstance()
Each formatter object has a method called
format that returns a string with the
specified information in the appropriate
format
13
Formatting Output
{import java.text.NumberFormat;
…
NumberFormat fmt = NumberFormat.getCurrencyInstance();
double cost = 4.19;
double tax = 0.06;
double totalcost = cost + cost * tax;
System.out.println(“Cost: “ + fmt.format(totalcost));
}
Output
Cost: $4.44
(actual double value = 4.4414)
see Purchase.java in text for a larger example
14
Formatting Output
The DecimalFormat class can be used to format a
floating point value in various ways
For example, you can specify that the number
should be truncated to three decimal places
The constructor of the DecimalFormat class takes
a string that represents a pattern for the formatted
number
See CircleStats.java in text
15
Multiple Argument Types
The print method can take many types of
arguments
System.out.println(16);
\\
System.out.println(true);
\\
System.out.println(“Hello”);\\
System.out.println(s);
\\
int
boolean
Object (String)
Object (Student)
How would we define such a function?
public static void print(????)
Need an argument type… which one?
16
Multiple Argument Types
There are actually several print methods:
public
public
public
public
static
static
static
static
void
void
void
void
print(int i){…}
print(boolean b){…}
print(String s){…}
print(Object obj){…}
When print is called, the compiler matches
the arguments you give with the methods
available
17
Multiple Argument Types
Strong-typing makes this unambiguous
float tryMe(int x)
{
return x + .375;
}
Invocation
result = tryMe(25, 4.32)
float tryMe(int x, float y)
{
return x*y;
}
18
Method Overloading
Method overloading is the process of giving a single
method name multiple definitions
If a method is overloaded, the method name is not
sufficient to determine which method is being called
The signature of each overloaded method must be
unique
The signature includes the number, type, and order
of the parameters
19
Why do we overload?
Similar operation to do on different types
Similar operation to do with different
arguments
printing is the simplest example
sum(int i1, int i2){…}
sum(int i1, int i2, int i3){…}
Handling incomplete information
addMember(String name, int birth){…}
addMember(String name){…}
20
Why do we overload?
Component-wise operations on arrays
static int addOne(int i)
{
return i+1;
}
static int[] addOne(int[] arr)
{
for(int i=0; i<arr.length; i++)
addOne(arr[i]);
return arr;
}
21
Overloading Constructors
Constructors can be overloaded (and they
often are)
Student(int number){…}
Student(String name){…}
Construct a new object with the information
available
22
Overloading: Return types
Consider the following functions:
// returns the square root of d
static double squareRoot(double d)
{
return Math.sqrt(d);
}
// returns the square root rounded to an integer
static int squareRoot(double d)
{
int i = (int)Math.sqrt(d);
return i;
}
23
What Happens in Binding?
Complier looks for the right method
?
int squareRoot(double x)
{
…
result = squareRoot(4.32)
}
double squareRoot(double x)
{
…
}
?
24
Overloading: Return types
The return type is not part of the signature
However… overloaded methods can differ in
the return type...
The compiler cannot distinguish two methods that
differ only in the return type
provided there is some other difference as well
Key idea: you need to be giving enough
information for Java to pick out one specific
method declaration
25
ArrayList Revisited
Recall: the ArrayList class is a growable
and shrinkable list
In general, it contains objects from the
generic Object class
Uses a special syntax if we want to restrict to
a specific type
To deal with primitive types… use wrappers
26
Example: DoubleArrayList
DoubleArrayList.java
Notes:
ArrayList<Type> declares an arraylist
containing objects of type <Type>
Autoboxing allows us to add double and Double
variables into ArrayList<Double>
ArrayList<double> does not work
27
Testing
Testing can mean many different things
It certainly includes running a completed program
with various inputs
It also includes any evaluation performed by human
or computer to assess quality
Some evaluations should occur before coding even
begins
The earlier we find an problem, the easier and
cheaper it is to fix
28
Testing
The goal of testing is to find errors
As we find and fix errors, we raise our confidence that a program
will perform as intended
We can never really be sure that all errors have been eliminated
So when do we stop testing?
Conceptual answer: Never
Snide answer: When we run out of time
Better answer: When we are willing to risk that an undiscovered
error still exists
29
Reviews
A review is a meeting in which several people
examine a design document or section of code
It is a common and effective form of human-based
testing
Presenting a design or code to others:
makes us think more carefully about it
provides an outside perspective
Reviews are sometimes called inspections or
walkthroughs
30
Test Cases
A test case is a set of input and user actions,
coupled with the expected results
Often test cases are organized formally into test
suites which are stored and reused as needed
For medium and large systems, testing must be a
carefully managed process
Many organizations have a separate Quality
Assurance (QA) department to lead testing efforts
31
Defect and Regression Testing
Defect testing is the execution of test cases to
uncover errors
The act of fixing an error may introduce new errors
After fixing a set of errors we should perform
regression testing – running previous test suites to
ensure new errors haven't been introduced
It is not possible to create test cases for all possible
input and user actions
Therefore we should design tests to maximize their
ability to find problems
32
Black-Box Testing
In black-box testing, test cases are developed
without considering the internal logic
They are based on the input and expected output
Input can be organized into equivalence categories
Two input values in the same equivalence category
would produce similar results
Therefore a good test suite will cover all equivalence
categories and focus on the boundaries between
categories
33
White-Box Testing
White-box testing focuses on the internal structure
of the code
The goal is to ensure that every path through the
code is tested
Paths through the code are governed by any
conditional or looping statements in a program
A good testing effort will include both black-box and
white-box tests
34