Uploaded by Mario saleh salama jabra

Lec 5 ( wrapper class && String)

advertisement
1
Wrapper classes
Dr. Hadeer A. Hosny
Second term
2023-2024
Problem
Data structures such as ArrayList can only store objects,
NOT primitive data types.
 Quick review: What are some primitive data types?
 byte, short, int, long, double, float, char
 Corresponding wrapper classes:
 Byte, Short, Integer, Long, Double, Float, Character
 Wrapper classes have methods
 Examples: – Integer IntNumber;
– Double DblNumber;
– Character Char;
Solution: Wrapper Classes
Wrapper classes allow programmers to store primitive data
types in lists. To do this, they convert a primitive data type
to an object.
 The wrapper class for int is Integer
 The wrapper class for double is Double
 The wrapper class for boolean is Boolean
(Notice the capitalization)
 A wrapper class is a class that is “wrapped around” a primitive data
type.
 The wrapper classes are part of java.lang so to use them, there is no
import statement required.
 Wrapper classes provide static methods that are very useful
4
Wrapper class and Array list
 ArrayList<int> list = new ArrayList<int>();
No
 ArrayList<Integer> list = new ArrayList<Integer>();
Yes
Wrapper Methods - Creating
 Creating an int with a value of 3:
➢
int i = 3;
 Creating an Integer with a value of 3:
➢ Integer ii = new Integer(3);
 You can also assign a primitive value to a wrapper class object:
 Integer ii = 3;
Wrapper Methods - Equality
⚫
Testing two ints (i and j) for equality:
if (i = = j)
Testing two Integers (i and j) for equality:
if ( i.equals(j) )
OR
if ( i.compareTo(j) = = 0 )
Program #1 What is happening?
Integer i1 = new Integer(33);
Integer i2 = new Integer(33);
System.out.println(i1 == i2);
System.out.println(i1.equals(i2));
Fraction f1 = new Fraction(33,1);
System.out.println(i1.equals(f1));
System.out.println(i1.equals(33));
System.out.println(i1.equals(f1.getNumerator()));
Program #1 This happened:
Integer i1 = new Integer(33);
Integer i2 = new Integer(33);
System.out.println(i1 == i2);
System.out.println(i1.equals(i2));
Answers:
//false
//true
Fraction f1 = new Fraction(33,1);
//false
System.out.println(i1.equals(f1));
//true
System.out.println(i1.equals(33));
System.out.println(i1.equals(f1.getNumerator())); //true
Program #2 What is happening?
ArrayList<Object> aL = new ArrayList<Object>();
ANSWERS:
aL.add(new Integer(1));
aL.add(new Double(2));
aL.add(new Fraction(3,1));
aL.add(new String("4"));
//Display the fraction
System.out.println(aL.get(2));
//What is really happening in the next line?
//
System.out.println(aL);
//
3/1
[1, 2.0, 3/1, 4]
Introduction to Casting
Introduction to Casting
ArrayList<Object> aL = new ArrayList<Object>();
aL.add(new Integer(1));
aL.add(new Double(2));
aL.add(new Fraction(3,1));
aL.add(new String("4"));
System.out.println(aL); //[1, 2.0, 3/1, 4]
//Display the fraction
System.out.println(aL.get(2)); // 3/1
// Display only the fractions numerator:
System.out.println(aL.get(2).getNumerator());
PROBLEM!!!!!!
Solution: Casting
System.out.println(aL.get(2).getNumerator());
In the line above, the compiler can not locate
the getNumerator() method. As declared,
the ArrayList stores Objects, and there is no
.getNumerator method in the Object class.
How do we tell the compiler where to find the
getNumerator() method?
By Casting!!!!
Solution: Casting
Instead of:
System.out.println(aL.get(2).getNumerator());
We say:
System.out.println(((Fraction)aL.get(2)).getNumerator());
This tells the compiler where to find the getNumerator method.
Notice that this is similar to
int quarters = (int) (change/.25);
Casting Summary
If the compiler is asked to call a method that does not
belong to an object’s class, the programmer must
comfort the compiler by directing it to the
appropriate class.
The compiler is trusting, and will believe that the
object is, indeed, a member of that class.
System.out.println(((Fraction)aL.get(2)).getNumerator());
Parsing
15
 Each of the numeric wrapper classes has a static method that
converts a string to a number.
 The Integer class has a method that converts a String to an int,
 The Double class has a method that converts a String to a
double,
 These methods are known as parse methods because their
names begin with the word “parse.”
 // Store 2599 in iVar.
 int iVar = Integer.parseInt("2599");
The toString Methods
16
 Each of the numeric wrapper classes has a static toString method
that converts a number to a string.
 The method accepts the number as its argument and returns a
string representation of that number.
int i = 12;
double d = 14.95;
String str1 = Integer.toString(i);
String str2 = Double.toString(d)
17
The toBinaryString, toHexString,
and toOctalString Methods
 The Integer and Long classes have three additional
methods: –
toBinaryString, toHexString, and toOctalString
int number = 14;
System.out.println(Integer.toBinaryString(number)); 1110
System.out.println(Integer.toHexString(number));
e
System.out.println(Integer.toOctalString(number));
16
18
MIN_VALUE and MAX_VALUE
 The numeric wrapper classes each have a set of static final
variables
 MIN_VALUE and – MAX_VALUE.
 These variables hold the minimum and maximum values for a
particular data type.
 System.out.println("The minimum value for an " + "int is "
+ Integer.MIN_VALUE);
 System.out.println("The maximum value for an " + "int is
" + Integer.MAX_VALUE);
19
Numeric Wrapper Class
Character Wrapper Class
20
21
Character Wrapper Class
22
String Wrapper Class
 Wraps around an array of char
– char[] Str=new char[10];
– String Str
23
String Wrapper Class:
Substrings
 The String class provides several methods that
search for a string inside of a string.
 A substring is a string that is part of another string.
 The startsWith method determines whether a string
begins with a specified substring.
 Some of the substring searching methods provided
by the String class
 boolean startsWith(String str)
 boolean endsWith(String str)
24
String Wrapper Class: Substrings(boolean
startsWith(String str) )
str.startsWith("Four") returns true because str does begin with “Four”.
startsWith is a case sensitive comparison
25
String Wrapper Class: Substrings(boolean
endsWith(String str) )
The endsWith method determines whether a string ends with a
specified substring.
The endsWith method also performs a case sensitive comparison.
26
String Wrapper Class: Substrings
• The String class provides methods to extract substrings in a
String object.
• The substring method returns a substring beginning at a start
location and an optional ending location.
• String Str.substring (beginIndex);
• String Str.substring (beginIndex, endIndex);
27
String Wrapper Class: Substrings
28
Returning Modified Strings
 The String class provides methods to return modified
String objects
 – concat
• Returns a String object that is the concatenation of two
String objects.
 – trim
• Returns a String object with all leading and trailing
whitespace characters removed.
29
Returning Modified Strings
30
Returning Modified Strings
 The String class provides methods to return modified
String objects
 – replace
• Returns a String object with all occurrences of one
character being replaced by another character.
31
The valueOf Methods
 The String class provides several overloaded valueOf
methods.
 They return a String object representation of
– a primitive value or
– a character array.
32
The valueOf Methods
33
Other Useful String Methods
 char Str.charAt(int); returns the character at given index.
 int Str.length(); returns the length of array
 – int Str.indexOf(char); returns index no. of char
 – int Str.indexOf(str); returns index no. of str
 – int Str.indexOf(char, from); returns index no. of char from
index from
 – int Str.indexOf(str, from); returns index no. of str from index
from
 – String Str.replace(oldchar, newchar); replace oldchar with
newchar
34
Other Useful String Methods
35
The StringTokenizer Class
36
The StringTokenizer Class
 With String Tokenizer in Java, we can break a String into words,
and such words are known as tokens.
 A StringTokenizer class is a class present in the java.util package
and it is used to break a String into tokens.
 There are constructors and methods in this StringTokenizer that
help us to split a sentence into tokens.
37
The StringTokenizer Class
 StringTokenizer, tokenize the string on the basis of the delimiters
provided to the String tokenizer class object.
 The Common delimiters are the whitespaces, tab, and newline.
 These delimiters are taken as default and if a user wants to
provide its own delimiter then he can provide by defining the
delimiter in the parameter as an argument.
38
The StringTokenizer Class
39
The StringTokenizer Class
Java StringTokenizer Constructors
 StringTokenizer generally describes three types of constructors:
1. StringTokenizer(String str)
 This constructor is implemented to perform tokenization of a
particular string that is being provided in the parameter.
 This constructor takes all the default delimiters which have been
defined in the definition of the StringTokenizer class.
40
The StringTokenizer Class
Java StringTokenizer Constructors
 StringTokenizer generally describes three types of constructors:
2. StringTokenizer(String str, String delimiter)
 This constructor is implemented to perform string tokenization
based on the delimiter provided by the user in the argument. This
can be explained by an example:
41
The StringTokenizer Class
Java StringTokenizer Constructors
 StringTokenizer generally describes three types of constructors:
3. StringTokenizer(String str, String delimiter, boolean flag)
 This Constructor is implemented to perform string tokenization
based on the delimiter and has additional functionality to display
delimiter also.
 Example of boolean = false :
42
The StringTokenizer Class
Java StringTokenizer Constructors
 StringTokenizer generally describes three types of constructors:
3. StringTokenizer(String str, String delimiter, boolean flag)
 This Constructor is implemented to perform string tokenization
based on the delimiter and has additional functionality to display
delimiter also.
 Example of boolean = TRUE :
43
The StringTokenizer Class
44
The StringTokenizer Class
 Useful Methods of StringTokenizer class in Java
 The StringTokenizer class contains a number of useful
instance methods that we can use to isolate tokens.
 1) int countTokens()
 The countToken() method returns the number of tokens
that are separated by any white space in the given
string.
 Using this method we can know the number of tokens
in the String, and we can, therefore, use this number of
tokens as a loop parameter to process the whole string
very easily.
45
The StringTokenizer Class
46
The StringTokenizer Class
 Useful Methods of StringTokenizer class in Java
 The StringTokenizer class contains a number of useful
instance methods that we can use to isolate tokens.
 2) String nextToken()
 The nextToken() method of the StringTokenizer class returns
the next token in the form of String. When we use it for the first
time, it returns the next token as the first token of the string.
47
The StringTokenizer Class
 Useful Methods of StringTokenizer class in Java
 The StringTokenizer class contains a number of useful
instance methods that we can use to isolate tokens.
 3) String nextToken(String delimiter)
 The nextToken(String delimiter) method is the same as the
nextToken() method that we discussed above, the only
difference is that it returns the next token on the basis of the
delimiter that we provide as an argument to this method.
48
The StringTokenizer Class
 Useful Methods of StringTokenizer class in Java
 The StringTokenizer class contains a number of useful
instance methods that we can use to isolate tokens.
 4) boolean hasMoreTokens()
 This method just checks whether there is any more token
present in the String. It returns true if a token is available and
false if no token is available.
49
The StringTokenizer Class
 Useful Methods of StringTokenizer class in Java
 The StringTokenizer class contains a number of useful
instance methods that we can use to isolate tokens.
 5) Object nextElement()
 The nextElement() method is similar to the nextToken()
method of the StringTokenizer class;
 the difference is that it returns the value in the form of Object
unlike the nextToken() method that returns a String.
50
The StringTokenizer Class
51
Multiple Delimiters
 To extract the tokens from this string we must specify both
characters as delimiters to the constructor.
Download