9 PrimitiveWrappers,StringBuilder, Pattern Matching
-
Upload
suresh1130 -
Category
Documents
-
view
119 -
download
3
Transcript of 9 PrimitiveWrappers,StringBuilder, Pattern Matching
1Java
Wrappers classes, StringBuilder, Pattern
matching
2Java
Contents
1 Wrapper classes
2 Primitive Wrappers
3 Why should one wrap the primitive types?
4 Constructors
5 Character and Float
6 Methods in Wrapper Class
7 Conversion of String to numeric primitive type
8 NumberFormatException
9 valueOf() methods
10 toString()
3Java
Contents
11 toXxxString()
12 equals() and ==
13 Autoboxing
14 Situations
15 No automatic conversions in case of long
16 Comparisons between primitive and wrapper
17 Comparisons between wrappers with boxing
18 Strange but true!
19 Method argument conversions
20 Method resolution with boxing
4Java
Contents
21 Resolution Pre 1.5 procedure
22 Resolution using boxing
23 Resolution with var-args
24 Immutability
25 Problem with String
26 StringBuilder
27 Methods
28 StringBuffer
29 equals()
30 Pattern Matching
5Java
Contents
31 Regular expression
32 Pattern class
33 Methods
34 Matcher class
35 Regular expression strings
36 \d, \s, \w, .
37 []
38 {}
39 ^ , &&
40 matches() and lookingAt() methods
6Java
Contents
41 matches() and lookingAt() signatures
42 More problems
43 Quantifier
44 Greedy Quantifiers
45 Negating ‘greediness' from quantifiers
46 split() method of String class
7Java
Know
• What wrapper classes are and why they are necessary
• The primitive wrapper classes and their methods• Immutability • Autoboxing• Overloading and autoboxing
8Java
Know
• StringBuilder and StringBuffer classes• What Pattern Matching is • Regular Expression
9Java
Be Able To
• Use wrapper classes• Implement Overloading and autoboxing• Implement java.util.regex package classes for
pattern matching.
10Java
Wrapper classes
• Wrapper classes in java are classes which wrap other classes.
• By ‘wrapping’ we mean they extend the functionality of the classes they wrap.
• Therefore wrapper class’ constructor will always take the object of the class they wrap as parameter.
Bottle
Cover is a wrapper enhancing the bottles functionality
11Java
Primitive Wrappers• There are some special kinds of wrappers classes in java.lang
package which wrap primitive types.
Number
Byte
Short
Integer
Long
Float
Double
Character
Before looking ahead at the API ….
Boolean
Abstract class
12Java
Why should one wrap the primitive types?
• Three reasons:
A. For various kinds of conversions
B. Many methods in predefined java class (specially utility classes like ArrayList etc.) use objects instead of primitive types.
C. Serialization
13Java
Constructors
• General form of constructor for all wrapper classes:
a) Constructor with its corresponding primitive type
b) Constructor with its corresponding String type.
Example:Integer(String) and Integer(int)Double(String) and Double(double)• There are two exceptions to this.
14Java
Character and Float
• Character constructor has only type (a) constructor and does not have type (b) constructor with String argument.
Character(char)• Float has an extra constructor that takes double.
Float(double)
15Java
Examples for numeric wrappers• Integer j= new Integer(“32”);• Double d =new Double(3.14);• Float f= new Float(“3.14”);• Integer i= new Integer("\u0031");• Exceptions at runtime:
Integer f= new Integer("0x123");
Integer i= new Integer("\u0041");
Integer i= new Integer(null);• Integer i= new Integer("010");
is not considered as octal number
16Java
Examples for boolean wrappers• String literal “true” in any case represents true.
Boolean b= new Boolean(“true”);
Boolean b= new Boolean(“tRue”);• Anything else is false
Boolean b= new Boolean(“false”);
Boolean b= new Boolean(“fff”);
Boolean b= new Boolean(null);• Creation with boolean literals
Boolean b= new Boolean(true);
Boolean b= new Boolean(false);
17Java
Examples for character wrappers
• Character i= new Character('c');• Character i= new Character(‘\u0041');
• Compilation errors for the following:
Character i= new Character(65);
18Java
Methods in Wrapper Class
Number
byte byteValue()
double doubleValue()
float floatValue()
int intValue()
long longValue()
short shortValue()
Byte
Short
Integer
Long
Float
Double
Boolean
boolean booleanValue()
Character
char charValue()
19Java
Conversion of String to numeric primitive type
• General form of method:
static xxx parseXxx(String s)
where xxx is all numeric primitives
static byte parseByte(String s) in Byte class
• static float parseFloat(String s) in Float class
• For integral types we have another form:
static xxx parseXxx(String s, int radix)
static byte parseByte(String s, int radix)
in Byte class
20Java
Examples
• int x=Integer.parseInt(“-3”);• float x=Float.parseFloat("3.14");• byte x=Byte.parseByte("1010",2); //10
• Exception at run time• byte x=Byte.parseByte("34",2);
21Java
NumberFormatException
• NumberFormatException subclasses from IllegalArgumentException
• When a string is converted to the numeric types, but that does not have the appropriate format, this exception is thrown.
• Example:String s="abc";Integer.parseInt(s);
// NumberFormatException thrown at runtime
22Java
valueOf() methods• Converts string or corresponding primitive
type to Wrapper type• static Xxx valueOf(xxx b) • static Yyy valueOf(String s) • static Zzz valueOf(String s,
int radix)
a) xxx : all the wrapper types, xxx: respective primitive type.
b) yyy: all the wrapper types except Characterc) zzz is only integral class types
23Java
Examples
• Byte x=Byte.valueOf("1010",2); • Double y=Double.valueOf(3.14);• Boolean x=Boolean.valueOf("xx");
// false
24Java
toString()
•String toString()
Available in all wrappers•static String toString(xxx b)
Available in all wrappers.xxx is the respective primitive.•static String toString(xxx i, int radix)
Only in Integer and Long
25Java
Examples
• Byte b= new Byte(“123”);• String s= b.toString();• String s=Double.toString(13.3);• String s=Integer.toString(10,2);
// 1010
26Java
toXxxString()• Returns string with respect to the base specified.
• static String toHexString(xxx d )In Integer, Long, Float and Double • static String toOctalString(xxx i) • String toBinaryString(xxx i) In Integer and Long• Example:String x=Integer.toHexString(27); // 1b
27Java
equals() and ==• equals() will be true provided the wrapper objects are
of same type and the values are same. For example:A) Float f= new Float(3.14);Float f1= new Float(3.14);System.out.println(f1.equals(f));// trueBut,System.out.println(f1==f);// falseB) Float f= new Float(3.14);Double f1= new Double(3.14);System.out.println(f1.equals(f));// false
28Java
Autoboxing
Autoboxing refers to the conversion of wrapper class type to its primitive type (and vice versa) automatically in certain programming situations. Boxing is conversion of primitive to its wrapper type
Unboxing is the reverse.
29Java
Situations•Before :Integer ii=new Integer(10);
Now: Integer ii=10;
•Before : Integer ii=new Integer(10);
int i=ii.intValue();i++;
ii=new Integer(i);
Now: Integer ii=10; ii++;
•Before : Boolean b=new Boolean(true);
if(b.booleanValue() ){}
NOW: Boolean b=true; if(b){}
boxing
30Java
No automatic conversions in case of long
• Long l=34;
gives compiler error since 34 is an integer.
To correct it, make it
Long l=34L;• But, Byte b=34;
gives no compile-time error
31Java
Comparisons between primitive and wrapper
• equals() and == returns true if the values are same between primitive and its wrapper.
A)Float d=3.14f; float f=3.14f;
System.out.println(d.equals(f));//true
B)Float d=3.14f; double f=3.14f;
System.out.println(d.equals(f));//false
C)Short d=934;
System.out.println(d==934); // true
32Java
Comparisons between wrappers with boxing
When using == with wrappers objects which involves boxing, when values –128 to 127 is assigned to a wrapper ,== is treated as ‘.equals’.
A) Short d=34;
Short d1=34;
System.out.println(d==d1);// true
B) Short d=234;
Short d1=234;
System.out.println(d==d1); // false
33Java
• When boolean values are assigned to Boolean ,== is treated as ‘.equals’.Boolean b1=true;Boolean b2=true;System.out.println(b1==b2);// true
• equals()Short d=634;Short d1=634;System.out.println(d.equals(d1));//true• Integer d=34;Long d1=34l;System.out.println(d==d1);//compilation error
34Java
Strange but true!
• Integer d1=45; Integer d2=45; System.out.print(d1==d2); System.out.println(d1!=d2); Prints : truefalse
• Integer d1=245; Integer d2=245; System.out.print(d1==d2); System.out.println(d1!=d2);Prints : falsetrue
Folder 1
35Java
Method argument conversions
• Just as assignments of primitive type to wrapper, method argument conversion also takes place automatically.
static void change(Integer i){}
Call: change(34); static void change(int i){}
Call: Integer d=34; change(d); static void change(long i){}
Call: Integer d=34; change(d);
36Java
Method resolution with boxing
1. Resolve using pre 1.5 procedure
2. Resolve using boxing
3. Resolve using var-args.
37Java
•static void change(int i){ System.out.println("int");}
static void change(Integer i){ System.out.println("Integer");}
Call: change(123);
•static void change(int i){ System.out.println("int");}
static void change(Byte i){ System.out.println(“Byte");}
byte b1=45; change(b1);
Resolution Pre 1.5 procedure
Folder 2
Folder 3
38Java
•static void change(Number i){ System.out.println(“number");}static void change(int i){ System.out.println(“int");}Call:Byte b1=45; change(b1);
•static void change(Byte i){ System.out.println("Byte");}static void change(int i){ System.out.println("int");}Call:Byte b1=45; change(b1);
Folder 4
Folder 5
39Java
Resolution using boxing
• static void change(char i){ System.out.println("int");}static void change(Byte i){ System.out.println("Byte");}Call: byte b1=45; change(b1);
• static void change(Integer i){ System.out.println("integer");}static void change(Number i){ System.out.println("number");}Call:change(45);
Folder 6
Folder 7
40Java
• static void change(Integer i){ System.out.println("integer");}static void change(Number i){ System.out.println("number");}Call: byte b1=25;change(b1);
• No boxing in case of arraystatic void change(Integer[] i){System.out.println("integer");}Call: int arr[]={1,2};change(arr);
Note this method is not match at all
Folder 8
Folder 9
41Java
class Test {int doX(Long x, Long y) { return 1; } int doX(long... x) { return 2; }int doX(Integer x, Integer y) { return 3; }int doX(Number n, Number m) { return 4; } public static void main(String[] args) { new Test().go();}void go() { short s = 7; System.out.print(doX(s,s) + " "); System.out.println(doX(7,7));} } What does the above code print?
Folder 10
42Java
Resolution with var-args
• static void change(Integer i){ System.out.println("integer");}static void change(int... i){ System.out.println("int");}
Call: change(10);
• static void change(Integer... i){ System.out.println("integer");}Call: change(10);
Folder 11
43Java
We will look at more of boxing again when we do collection classes
44Java
Immutability
• Like String, Wrapper objects are also immutable. • That is why there are no setters in wrapper
classes.
45Java
class ImmutablilityTest{
public static void main(String... args){Integer x=10;
change(x); System.out.println(x); }
static void change(Integer i){
i=20;
}}
What does the code print?
Folder 12
46Java
StringBuilder &
StringBuffer
47Java
Problem with String• String class objects are immutable.• In cases where we have lots of string
manipulation we may end up with creating lot of strings in the string pool which are unnecessary.
Java Java Beans
s1.concat(“ Beans”)
s1 s2
Enterprise+
Enterprise Java Beans
Java
BeansJava Beans
Enterprise
Enterprise Java Beans
pool
48Java
StringBuilder
StringBuilder is a new class in Java 1.5. This class can be used in the situations where
we require lot of string manipulations. StringBuilder objects are mutable . Constructors StringBuilder() StringBuilder(String str)
49Java
Methods Methods which are common in both String and StringBuilder classes:
char charAt(int index) int length() String substring(int start) String substring(int start, int end) int indexOf(String str) int indexOf(String str,int fromIndex) int lastIndexOf(String str) int lastIndexOf(String str, int fromIndex)
50Java
ConcatenationStringBuilder append(String str)StringBuilder append(StringBuffer sb)StringBuilder append(Object obj) StringBuilder append(xx b) where xx is boolean, char, int, long float and doubleTrimming:void trimToSize()Replacing charactersStringBuilder replace(int start, int end, String str)
We will see this in a while
51Java
•Insertion and deletion of characters •StringBuilder insert(int offset, String str)•StringBuilder insert(int offset, char[] s) •StringBuilder insert(int offset, xx b)
where xx is boolean, char, int, long float and double•public StringBuilder delete(int start, int end) •StringBuilder deleteCharAt(int index) •Reverse: StringBuilder reverse()
52Java
Are you telling me they did not do anything about this problem until
1.5 ?
53Java
StringBuffer
Pre 1.5, StringBuffer class was used to overcome this string problem.
If we replace StringBuilder with StringBuffer in the methods of StringBuilder class, we have methods of StringBuffer class !
In other words all that we could do with StringBuilder we can do with StringBuffer.
54Java
Then why do we have StringBuilder class?
StringBuilder is much more efficient than StringBuffer if you don’t want thread-safe manipulation of strings. We have seen in Threads chapter,
what thread-safe means.
55Java
equals()• equals() method is not overridden in the StringBuilder/StringBuffer class.
Can you guess the implication of this. For instance what would s1.equals(s2) print if they areStringBuilder s1= new StringBuilder(“a”); StringBuilder s2= new StringBuilder(“a”);
56Java
Pattern Matching
57Java
Pattern Matching
Searching for a set of characters (pattern) in a String is called pattern matching.
Pattern Matching has become an important part of core java.
58Java
Regular expression Regular expression is a syntax which allows us to
specify a string pattern. One of the simplest example which all of us would
have used is when we search for a particular file in our system. To search for all text files, specify “*.txt”. This “*.txt” is a regular expression.
For regular expression we have java.util.regex API which contains three classes: Pattern, Matcher and PatternSyntaxException.
59Java
Pattern class
Pattern object is a compiled representation of a regular expression meaning that a string representing a regular expression is compiled by the Pattern class is used to check if the regular expression contains valid characters. Result of the compilation is an instance of Pattern object.
Pattern is a final class with no public constructors.
60Java
Methods
static Pattern compile(String regex) Matcher matcher(CharSequence input) static boolean matches(String regex, CharSequence input)
public String pattern() public String[] split(CharSequence input)
In the next slide
61Java
Matcher class
It is used to match patterns in a given string. Like Pattern, Matcher is also a final class and does not have any constructor.
It is created by invoking the Pattern class’s matcher() method.
Methods: boolean find() public boolean find(int start) String group() int start() int end()
62Java
Simple Example
import java.util.regex.*;
public class Example1 {
public static void main(String[] a) {
Pattern regex=Pattern.compile("ab");
Matcher m=regex.matcher("ababab");
while(m.find())
System.out.print(m.start());
}}
// prints :024Pattern String source
Folder 13
63Java
Pattern regex=Pattern.compile(“bb");
Matcher m=regex.matcher("abbbb");
while(m.find())
System.out.print(m.start());
}}
// prints :13
Just in case you have not understooda b b b b a b b b b
Folder 14
64Java
Regular expression strings
A regular expression can consist of characters and meta characters. ‘*’ for example is a meta character and ‘.txt’ set of characters.
Each meta character has a predefined meaning. The metacharacters supported by this API are:
([{\^$|)?*+ \d \s \w
65Java
\d, \s, \w, .
• \d is to match any digit• \s is to match any whitespace character• \w is to match any word character (letters, digits, or
"_" (underscore))• . Means any characterExample: Pattern regex=Pattern.compile("\\d"); Matcher m=regex.matcher(“ab1ab1“); while(m.find()) System.out.print(m.start());//prints 25
Folder 15
66Java
[]
• If we need a match to be any one of the characters among a list of characters then [] is used.
• Example 1: Pattern regex=Pattern.compile("[a1]");
Matcher m=regex.matcher(“ad1ad1”); while(m.find()) System.out.print(m.start());// prints 0235
“a-d” prints 0134
Folder 16
67Java
{}• character{n} where n is an integer • matches the character up to n number of
occurances.• Pattern regex=Pattern.compile("a{3}");Matcher m=regex.matcher("aabaaab");while(m.find())System.out.print(m.start());
• Prints 3
Folder 17
68Java
^ , &&
• ^ used to negate the pattern.• && is used specify the intersection of the two sets.
Example 1:
Pattern r=Pattern.compile("[^ad]");
Matcher m=r.matcher(“ad1ad1”);
while(m.find())
System.out.print(m.start());// 25
“a1&&c1” prints 25
Folder 18
69Java
How can we make sure that a pattern is an octal
pattern ?
Pattern regex=Pattern.compile("0[0-7]"); Matcher m=regex.matcher(“077”);if(m.find())System.out.println(m.group());// 07find() method does not ensure that the pattern should begin with 0. It continues to scan the source until it finds the proper pattern.
Folder 19
70Java
matches() and lookingAt() methods
Pattern regex=Pattern.compile("0[0-7]");
Matcher m=regex.matcher(“077");if(m.lookingAt()) System.out.println(m.group());//prints 07
matches() will do an exact match. For 077 and 1077 it returns false while for 07 it returns true.
“1077” does not print anything
Folder 20
71Java
matches() and lookingAt() signatures
boolean lookingAt()
Attempts to match the input sequence, starting at the beginning of the region, against the pattern.
boolean matches()
Attempts to match the entire region against the pattern
72Java
More problems
Pattern r=Pattern.compile("0[0-7]"); Matcher m=r.matcher(“07x");if(m.lookingAt())System.out.println(m.group());//also prints 07 but is not an octal number. Pattern r=Pattern.compile("0[0-7]"); Matcher m=r.matcher(“07");System.out.println (m.matches());// returns true for 07 but this returns false for 077.
Folder 21
Folder 22
73Java
This time the problem is not with the methods but the pattern we formed for the
octal number. An octal number should begin with 0
followed by one or more digits between 0 and 7.
0[0-7]
Matches a pattern beginning with 0 followed by a number between 0 to 7
74Java
Quantifier * : Zero or more occurrences ? : Zero or one occurrence +: One or more occurrences
Octal pattern:Pattern regex=Pattern.compile("0[0-7]+");
Matcher m=regex.matcher(“0775”);if(m.matches()) System.out.println(m.group());// prints 0775 Folder 23
75Java
Greedy Quantifiers *, +, ? if used not mixed with each other are
greedy.Example 1:Pattern regex=Pattern.compile(".*ab");
Matcher m=regex.matcher("aabbbaaaab");
while(m.find()) System.out.println(m.start()+” “+ m.group());
} // prints 0 aabbbaaaab
Let me grab as much as possible.
Folder 24
76Java
Example 2:
Pattern regex=Pattern.compile(".*");
Matcher m=regex.matcher("aabbbaaaab");
while(m.find())
System.out.println(m.start()+” “+ m.group());
Prints:
0 aabbbaaaabFolder 25
77Java
Example 3:
Pattern regex=Pattern.compile("\\d*");
Matcher m=regex.matcher("12ab");
while(m.find())
System.out.println(m.start()+ " "+ m.group());
Prints:
0 12
2
3
4
Folder 26
78Java
Negating ‘greediness' from quantifiers
• Adding a ? With the greedy quantifier makes it generous.
• ?? • *? • +?
79Java
Pattern regex=Pattern.compile(".*?ab");Matcher m=regex.matcher("aabbbaaaab");while(m.find())System.out.println(m.start()+" " + m.group());
Prints :0 aab3 bbaaaab
I can’t be greedy anymore. I must behave normally. They have put a spy next to me !
Folder 27
80Java
split() method of String class
String[] split(String regex) The above method uses the regular expression
specified in the argument as a delimiter to split the string.
Example:String s="boo:and:foo";for(String s1:s.split(":")){ System.out.print(s1);}Prints booandfoo
“o+” prints b:and:f
Folder 28