1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

34
1 Miscellaneous Java … a collection of short topics that we need to get to at some point …
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    217
  • download

    0

Transcript of 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

Page 1: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

1

Miscellaneous Java

… a collection of short topics that we need to get to at some point …

Page 2: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

2

Topics

Look at Student.java example Formatting output Method overloading ArrayList revisited Testing (time permitting)

Page 3: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

3

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

Page 4: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

4

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);

Page 5: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

5

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 %

Page 6: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

6

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”

Page 7: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

7

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);

Page 8: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

8

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?

Page 9: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

9

Example 2

In Student.java, we could add a toString method:

String toString()

{

return String.format(“%09d: %s, %s”,

studentNumber, lastName, firstName);

}

Page 10: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

10

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

Page 11: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

11

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

Page 12: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

12

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

Page 13: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

13

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

Page 14: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

14

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));}

OutputCost: $4.44(actual double value = 4.4414) see Purchase.java in text for a larger example

Page 15: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

15

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

Page 16: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

16

Multiple Argument Types

The print method can take many types of argumentsSystem.out.println(16); \\ int

System.out.println(true); \\ boolean

System.out.println(“Hello”);\\ Object (String)

System.out.println(s); \\ Object (Student)

How would we define such a function?public static void print(????)

Need an argument type… which one?

Page 17: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

17

Multiple Argument Types

There are actually several print methods:public static void print(int i){…}

public static void print(boolean b){…}

public static void print(String s){…}

public static void print(Object obj){…}

When print is called, the compiler matches the arguments you give with the methods available

Page 18: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

18

Multiple Argument Types

Strong-typing makes this unambiguous

float tryMe(int x){ return x + .375;}

float tryMe(int x, float y){ return x*y;}

result = tryMe(25, 4.32)

Invocation

Page 19: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

19

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

Page 20: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

20

Why do we overload?

Similar operation to do on different types printing is the simplest example

Similar operation to do with different arguments sum(int i1, int i2){…} sum(int i1, int i2, int i3){…}

Handling incomplete information addMember(String name, int birth){…} addMember(String name){…}

Page 21: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

21

Why do we overload?

Component-wise operations on arraysstatic 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;

}

Page 22: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

22

Overloading Constructors

Constructors can be overloaded (and they often are) Student(int number){…} Student(String name){…}

Construct a new object with the information available

Page 23: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

23

Overloading: Return types

Consider the following functions:// returns the square root of dstatic double squareRoot(double d){

return Math.sqrt(d);}

// returns the square root rounded to an integerstatic int squareRoot(double d){

int i = (int)Math.sqrt(d);return i;

}

Page 24: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

24

What Happens in Binding?

Complier looks for the right method

int squareRoot(double x){

…}

double squareRoot(double x){

…}

result = squareRoot(4.32)

?

?

Page 25: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

25

Overloading: Return types

The return type is not part of the signature The compiler cannot distinguish two methods that

differ only in the return type However… overloaded methods can differ 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

Page 26: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

26

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

Page 27: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

27

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

Page 28: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

28

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

Page 29: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

29

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

Page 30: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

30

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

Page 31: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

31

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

Page 32: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

32

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

Page 33: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

33

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

Page 34: 1 Miscellaneous Java … a collection of short topics that we need to get to at some point …

34

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