Utility Classes java.util.Date Date Test java.util.Calendar java.util

advertisement

COMP209

Object Oriented Programming

Utility Classes

Mark Hall

n n n n n n n

Date

Calendar

Math

Random

String

StringBuffer

Parsing strings

Department of Computer Science 1

Utility Classes

• Java gives us a number of small utility classes that can be useful in a variety of situations

• We’ll take a look at a subset of these

– Some live in java.util, others in java.lang

• Recall in lecture 18 we saw that a utility class often groups together a set of related static methods and constants

Department of Computer Science 2

java.util.Date

• Represents an instance in time with millisecond precision

– long value = # milliseconds since Jan 1, 1970 ( epoch )

• Some details of Date : class Date { public Date() // current time and date!

public Date(int y, int m, int d, int h, int m, int s)

Public int getDate() // day of month, 1-31 public int getMonth() // 0-11 public int getSeconds() // 0-59 public int getDay() // day of the week, 1-6 public int getYear() // year – 1900 public long getTime() // milliseconds since epoch public void setMonth(int m), .., setSeconds(int s)

Date Test

import java.util.*; public class DateTest {

public static void main(String [] args) {

Date s = new Date();

System.out.println("s toString = "

+ s.toString()); int j = 0; for (int i=0; i<100000; i++) {j = j + i};

Date e = new Date();

System.out.println("That took " +

(e.getTime() - s.getTime()) + " msecs");

}

}

java.util.Calendar

• Some methods in Date have been deprecated since the introduction of Java1.2

– Reduce the connection between dates and the western style

Gregorian calendar

• Use Calendar and Date for performing certain functions

– Convert between a Date object and a set of integer fields such as YEAR, MONTH, HOUR etc.

• Calendar is an abstract base class

– Concrete subclasses provide locale sensitive implementations that interpret a Date according to the rules of a specific calendar system

Department of Computer Science 5

Department of Computer Science java.util.Calendar

Date now = new Date();

// get a calandar for the default time zone

// and locale

Calendar c = Calendar.getInstance(); c.setTime(now);

System.out.println(“Day of month: “

+ c.get(Calendar.DAY_OF_MONTH));

Department of Computer Science 6

1

java.util.Math

• Supplies static constants and methods public static final double E // = 2.71828

public static final double PI // = 3.1415926

– Trigonometric ops (double ‡ double): sin, cos, tan, asin, acos, atan, atan2

– Rounding ops: ceil, floor, rint, round

– Exponentials: exp, pow, log, sqrt

– Other: abs, max, min, random

Department of Computer Science 7

Example: Draw from weighted distribution

static public int weightedDistribution (int[ ] weights){ int sum = 0; // sum of weights for(int i = 0; i < weights.length; i++) {

sum += weights[i];

}

// compute random value less than sum int val = (int) Math.floor(Math.random() * sum + 1);

// find point in distribution for(int i = 0; i < weights.length; i++) {

val -= weights[i];

if (val < 0) { return i; }

} return 0; // should never happen

}

Ë weights (1,3,2) will yield p(0)=1/6, p(1)=1/2, p(2)=1/3

java.util.Random

• The method java.util.Math.random() can be used to generate random floating point numbers uniformly distributed between 0 and 1.0

• The class java.util.Random provides more general facilities

– Random integers

– Seed value (for repeatable sequences of pseudo-random numbers)

– etc.

Department of Computer Science 9

java.util.Random

class Random {

boolean nextBoolean() // uniformly distributed boolean

void nextBytes(byte [] bytes) // random bytes into array

double nextDouble()

float nextFloat()

double nextGaussian() // normally distrib. m =0, s =1.0

int nextInt()

long nextLong()

setSeed(long seed) // set the random seed

}

Department of Computer Science 10

java.lang.String

• In Java a String is an immutable value

– Once constructed its contents never change

– Has only accessor methods and no side effects

• Constructing Strings

– With a literal: String name = “John Smith”

– With various constructors in the String class

• String name = new String(“John Smith”);

• Char [] data = {‘a’, ‘b’, ‘c’};

String abc = new String(data);

Department of Computer Science 11

java.lang.String

• The + operator is overloaded and can be used to concatenate two strings

– If either the left or right expression is a String , then the other is automatically converted to a String as well

– System.out.println(“Answer = ”+answer)

• + groups from left to right:

– System.out.println(“Catch-”+2+2) ‡ “Catch22”

– System.out.println(2+2+“warned”) ‡ “4warned”

– System.out.println(“”+2+2+“warned”) ‡

“22warned” the old “leading empty string” trick

Department of Computer Science 12

Department of Computer Science 2

java.lang.String

• String methods

– Because strings are immutable, methods that operate on strings return new String objects

• Some methods

– concat, length, replace (characters), (retrieve) substring, toLowerCase, toUpperCase, trim

(whitespace), valueOf, compareTo, equalsIgnoreCase, endsWith, startsWith, indexOf, lastIndexOf

Department of Computer Science 13

java.lang.String

• The indexOf method can be used to search for the occurrence of a substring

String mainString = “Hello there world!”; if (mainString.indexOf(“there world”) != -1) {

System.out.println(“Found a match!”);

}

• The substring method computes substrings of a String

String tail = mainString.substring(12, mainString.length()-1);

// tail = “world!”

java.lang.String

public static String valueOf(Object o) { return (o == null) ? “null” : o.toString();

}

• valueOf safer than toString

– valueOf is a polymorphic method—its argument can be of any type of object, including a null object

Shape aShape = null;

String a = String.valueOf(aShape); // “null”

String b = aShape.toString();

// NullPointerException

Department of Computer Science 15

java.lang.String

• == on Strings

– String constructor makes a copy

– valueOf method returns a reference

String one = “One”;

String two = new String(one); // copy of one

String three = String.valueOf(one); // ref to one

System.out.println((one == two)); // “false”

System.out.println((one == three)); // “true”

Department of Computer Science 16

java.lang.StringBuffer

• StringBuffer implements a mutable sequence of characters

– i.e. it is like a String , but can be modified

– is similar to the C language concept of a string as an array of characters

– At any point in time it contains some sequence of characters, but the length and content of the sequence can be changed through method calls

Department of Computer Science 17

java.lang.StringBuffer

• The principal operations on a StringBuffer are append and insert

– Are overloaded methods that accept data of any type—convert given datum to String and then inserts or appends the characters of the string to the

StringBuffer

• Constructors:

– StringBuffer() — allocates enough space to initially hold 16 characters

– StringBuffer(String str) — makes a StringBuffer that holds the contents of str

+ initial extra space for 16 more characters

– StringBuffer(int capacity) — allocates enough space for capacity number of characters

Department of Computer Science 3

java.lang.StringBuffer

• append, insert, reverse —all modify the buffer

• setCharAt, charAt

• length, setLength (can be used to allocate more space or truncate the string buffer)

• ensureCapacity — takes a min capacity argument and sets the size of the string buffer to the larger of min capacity or twice the old capacity + 2

• substring, toString

Department of Computer Science 19

java.lang.StringBuffer

• Forming new strings by concatenating many smaller strings is inefficient

– Each intermediate String is a new object that is used only once

– StringBuffer’s append, insert and reverse methods return the implicit parameter (i.e. this ) rather than a new object (like String does)

– Therefore, string buffers are used by the compiler to implement

+ for strings x = "a" + 4 + "c”; gets compiled to: x = new StringBuffer().append("a").

append(4).append("c");

Department of Computer Science 20

java.util.StringTokenizer

• Breaks a String into a sequence of tokens

• Tokens are defined by delimiters (e.g. space)

• Tokenization process is much simpler than that used by the StreamTokenizer

– Doesn’t distinguish among words, numbers, quoted strings, comments etc

• Implements the Enumeration protocol

// uses default delims - "!\t\n\r\f" public StringTokenizer(String s) public StringTokenizer(String s, String delims) public boolean hasMoreElements() // Enum. interface

Public boolean hasMoreTokens() public Object nextElement() public String nextToken() public int countTokens() // remaining tokens

StringTokenizer Example

public void readLines(BufferedReader r) throws IOException {

String delims = " \t\n.,!?;:";

String line;

while ((line = r.readLine()) != null) {

line = line.toLowerCase();

StringTokenizer tok = new StringTokenizer(line, delims);

while (tok.hasMoreTokens()) {

System.out.println(tok.nextToken());

}

}

}

Parsing String Values

• Unlike StreamTokenizer ,

StringTokenizer does not parse numbers for us

• If a token represents a primitive value, we can parse it using a wrapper class:

String dstr = “23.7”;

Double dval = Double.parseDouble(dstr);

• Similar for int, float, boolean etc

Department of Computer Science 23

Department of Computer Science

Exercises

• Write a program Palindrome in two ways:

– First, using StringBuffer (and reverse)

• public StringBuffer reverse( )

– Second, using String

• public char charAt(int index)

• Write a program that takes the name of a text file as an argument and

– Counts the number of words in the file

– Computes letter frequencies

Department of Computer Science 24

4

• Budd chapter 17

Readings

Department of Computer Science 25

Department of Computer Science 5

Download