Java Methods

Download Report

Transcript Java Methods

Εισαγωγή στον Αντικειμενόστρεφη
Προγραμματισμό
(Object-Oriented Programming)
Strings
Δρ. Μαρία Ι. Ανδρέου
Στόχοι:





Μαθαίνουμε για literal strings
Μαθαίνουμε για String constructors και
commonly used methods
Κατανοούμε immutability of strings
Μαθαίνουμε να μετατρέπουμε convert
strings σε αριθμούς και αριθμούς σε strings
μαθαίνουμε several useful methods της
Character class
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-2
The String class




Ένα object της String class αναπαριστά string
από characters.
Το String class ανήκει στο java.lang package,
το οποίο κάνει built into Java.
Όπως και σε άλλες classes, String έχουν
constructors και methods.
Σε διαφορά με other classes, String έχουν
δυο operators, τους + και += (used for
concatenation).
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-3
Literal Strings


Literal strings είναι anonymous constant objects
του String class που ορίζονται σαν text in
double quotes.
το string text μπορεί να περιλαμβάνει “escape”
characters. Για παράδειγμα:
\\ stands for \
\n stands for the newline character
"Biology”, "C:\\jdk1.4\\docs”, "Hello\n"
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-4
Literal Strings


(συνέχ.)
ΔΕΝ πρέπει να κατασκευαστούν: απλά
υπάρχουν εκεί (they are “just there.”)
Μπορούν να ανατεθούν σε String variables.

can be passed to methods and constructors
as arguments.

have methods you can call:
String fileName = "fish.dat";
button = new JButton("Next slide");
if (”Start".equals(cmd)) ...
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-5
Immutability




Έτσι και δημιουργηθεί ένα string ΔΕΝ μπορεί να
αλλάξει. ΚΑΜΙΑ από τις methods του δεν αλλάζει
το string.
Τέτοιου τύπου objects ονομάζονται immutable.
Immutable objects μας
εξυπηρετούν/διευκολίνουν (are convenient)
επειδή two references can point to the same
object με ασφάλεια.
Δεν υπάρχει κίνδυνος να αλλάξει το object
through one reference χωρίς να το γνωρίζουν οι
άλλες.
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-6
Immutability

(συνέχ.)
Πλεονεκτήματα: ΠΙΟ αποδοτικά, δεν υπάρχει
ανάγκη αντιγραφής.
String s1 = "Sun";
String s2 = s1;
s1
String s1 = "Sun";
String s2 = new String(s1);
s1
"Sun"
s2
"Sun"
"Sun"
s2
OK
Εισαγωγή στο ΟΟΡ και Java
Less efficient
and wasteful
Δρ. Μαρία Ι. Ανδρέου
1-7
Immutability

(συνέχ.)
Μειονέκτημα: ΛΙΓΟΤΕΡΟ αποδοτικό — πρέπει
να δημιουργήσουμε ένα ΝΕΟ string και να
πετάξουμε το παλιό σε κάθε μικρή αλλαγή.
String s = "sun";
char ch = Character.toUpper(s.charAt (0));
s = ch + s.substring (1);
s
"sun"
'S'
Εισαγωγή στο ΟΟΡ και Java
+ "un"
Δρ. Μαρία Ι. Ανδρέου
1-8
Empty Strings

ένα empty string ΔΕΝ έχει characters;
Είναι of length 0.
String s1 = "";
String s2 = new String();

Empty strings
ΜΗΝ το συγχύζεται με ένα ΜΗ
αρχικοποιημένο string:
private String errorMsg;
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
errorMsg
is null
1-9
Constructors


String’s no-args and copy constructors are
not used much.
String s1 = new String ();
String s1 = "";
String s2 = new String (s1);
String s2 = s1;
Other constructors convert arrays into strings
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-10
Methods — length, charAt
int length ();

char charAt (k);

Επιστρέφει τον αριθμό
των characters μέσα στο
string
Επιστρέφει τον k-th char
Οι θέσεις των Character σε ένα
strings αριθμούνται αρχίζοντας
από το 0
Returns:
”Flower".length();
6
”Wind".charAt (2);
’n'
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-11
Methods — substring
String s2 = s.substring (i, k);
– returns the substring of chars in
positions from i to k-1
strawberry
i k
String s2 = s.substring (i);
– returns the substring from the i-th char to the
end
Returns:
”raw"
”strawberry".substring (2,5);
"happy"
"unhappy".substring (2);
"" (empty string)
"emptiness".substring (9);
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-12
Methods — Concatenation
String result = s1 + s2;
– concatenates s1 and s2
String result = s1.concat (s2);
– the same as s1 + s2
result += s3;
– concatenates s3 to result
result += num;
– converts num to String and concatenates
it to result
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-13
Methods — Find (indexOf)
0
8
11
15
String date ="July 5, 2012 1:28:19 PM";
date.indexOf ('J');
date.indexOf ('2');
date.indexOf ("2012");
date.indexOf ('2', 9);
date.indexOf ("2020");
date.lastIndexOf
('2');
Εισαγωγή στο ΟΟΡ και Java
Returns:
0
8
8
(starts searching
11
at position 9)
-1
15
Δρ. Μαρία Ι. Ανδρέου
(not found)
1-14
Methods — Comparisons
boolean b = s1.equals(s2);
– returns true if the string s1 is equal to s2
boolean b = s1.equalsIgnoreCase(s2);
– returns true if the string s1 matches s2, caseblind
int diff = s1.compareTo(s2);
– returns the “difference” s1 - s2
int diff = s1.compareToIgnoreCase(s2);
– returns the “difference” s1 - s2, case-blind
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-15
Methods — Replacements
String s2 = s1.trim ();
– returns a new string formed from s1 by
removing white space at both ends
String s2 = s1.replace(oldCh, newCh);
– returns a new string formed from s1 by
replacing all occurrences of oldCh with newCh
String s2 = s1.toUpperCase();
String s2 = s1.toLowerCase();
– returns a new string formed from s1 by
converting its characters to upper (lower) case
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-16
Replacements (cont’d)

Example: how to convert s1 to upper case
s1 = s1.toUpperCase();

A common bug:
s1 remains
unchanged
s1.toUpperCase();
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-17
Methods — toString

It is customary to provide a toString
method for your class.

toString converts an object into a String
(for printing it out, for debugging, etc.).
System.out.print (obj);
is the same as
System.out.print (obj.toString());
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-18
Numbers to Strings and
Strings to Numbers


Integer and Double are “wrapper” classes
from java.lang that represent numbers as
objects.
Integer and Double provide useful static
methods for conversions:
String s1 = Integer.toString (i);
String s2 = Double.toString (d);
int i;
double d;
int n = Integer.parseInt (s1);
double x = Double.parseDouble (s2);
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-19
Numbers to Strings

Three ways to convert a number into a string:
1.
String s = "" + num;
2.
String s = Integer.toString (i);
String s = Double.toString (d);
int i;
double d;
3.
String s = String.valueOf (num);
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-20
Numbers to Strings (cont’d)

The DecimalFormat class can be used
for more controlled conversions of
numbers into strings:
import java.text.DecimalFormat;
...
DecimalFormat money =
new DecimalFormat("0.00");
...
double amt = …;
...
String s = money.format (amt);
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
56.7899
"56.79"
1-21
Strings to Numbers
int n = Integer.parseInt(s);
double x = Double.parseDouble(s);

These methods throw a
NumberFormatException if s does not
represent a valid number.

Older versions of SDK (before 1.2) did not
have Double.parseDouble; you had to use
double x = Double.valueOf(s).doubleValue();
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-22
Character Methods

java.lang.Character is a class that
represents characters as objects.

Character has several useful static
methods that determine the type of a
character.

Character also has methods that convert
a letter to the upper or lower case.
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-23
Character Methods (cont’d)
if (Character.isDigit (ch)) ...
.isLetter...
.isLetterOrDigit...
.isUpperCase...
.isLowerCase...
.isWhitespace...
Whitespace is
space, tab,
newline, etc.
– return true if ch belongs to the
corresponding category
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-24
Character methods (cont’d)
char ch2 = Character.toUpperCase (ch1);
.toLowerCase (ch1);
– if ch1 is a letter, returns its upper (lower)
case; otherwise returns ch1
int d = Character.digit (ch, radix);
– returns the int value of the digit ch in the
given int radix
char ch = Character.forDigit (d, radix);
– returns a char that represents int d in a
given int radix
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-25
StringTokenizer

java.util.StringTokenizer is used to extract
“tokens” from a string.

Tokens are separated by delimiters (e.g.,
whitespace).

A tokenizer object is constructed with a given
string as an argument.

The second optional argument is a string that
lists all delimiters (default is whitespace).
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-26
StringTokenizer (cont’d)
import java.util.StringTokenizer;
Delimiters are
...
whitespace
String str = input.readLine();
StringTokenizer q =
new StringTokenizer (str);
All delimiters
// or:
// new StringTokenizer (str, ";+ \t, ");
The number of
int n = q.countTokens ();
found tokens
while ( q.hasMoreTokens() )
{
String word = q.nextToken();
...
Δρ. Μαρία Ι. Ανδρέου
Εισαγωγή στο ΟΟΡ και Java
1-27
EquationSolver Applet
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-28
EquationSolver (cont’d)

Uses many techniques discussed earlier:
– trim, substring, and other String methods clean the
input, surround operation signs with spaces
– StringTokenizer extracts tokens
– Character.isDigit, and other Character methods
identify tokens
– Integer.parseInt converts tokens to numbers
– String's + operator combines strings and numbers
to generate output
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-29
Review:





What makes the String class unusual?
How can you include a double quote
character into a literal string?
Is "length".length() allowed syntax? If so,
what is the returned value?
Define immutable objects.
Does immutability of Strings make Java
more efficient or less efficient?
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-30
Review (cont’d):





How do you declare an empty string?
Why are String constructors not used very
often?
If the value of String city is "Boston", what
is returned by city.charAt (2)?
By city.substring (2, 4)?
How come String doesn’t have a
setCharAt method?
Is s1 += s2 the same as s1 = s1 + s2 for
strings?
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-31
Review (cont’d):





What do the indexOf methods do? Name
a few overloaded versions.
What is more efficient for strings: == and
other relational operators or equals and
compareTo methods?
What does the trim method do?
What does s.toUpperCase() do to s?
What does the toString method return for
a String object?
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-32
Review (cont’d):




Name a simple way to convert a number
into a string.
Which class has a method for converting
a String into an int?
Name a few Character methods that help
identify the category to which a given
character belongs.
What is the StringTokenizer class used
for?
Εισαγωγή στο ΟΟΡ και Java
Δρ. Μαρία Ι. Ανδρέου
1-33