SlideShare a Scribd company logo
CSC 128 - JAVA II
Part 1
Wrapper Classes
&
Strings
9-2
Chapter Topics
We will cover the following topics in this order:
• 7.3.2 Wrapper Classes
• 2.5.6 Type Conversion (Parse Methods)
• 2.3.3 Operations on Strings
• 5.3.1 Some Built-in Classes (StringBuilder)
9-3
Wrapper Classes
• Java provides 8 primitive data types: byte, short, int, long, float,
double, boolean, char
• One of the limitations of the primitive data types is that we
cannot create ArrayLists of primitive data types.
• However, this limitation turns out not to be very limiting after
all, because of the so-called wrapper classes:
– Byte, Short, Integer, Long, Float, Double, Boolean, Character
• These wrapper classes are part of java.lang (just like String and
Math) and there is no need to import them.
9-4
Wrapper Classes Examples
• Creating a new object:
Integer studentCount = new Integer(12);
• Changing the value stored in the object:
studentCount = new Integer(20);
• Getting a primitive data type from the object:
int count = studentCount.intValue();
9-5
Auto Boxing / UnBoxing
• You can also assign a primitive value to a wrapper class
object directly without creating an object. This is called
Autoboxing
Integer studentCount = 12;
• You can get the primitive value out of the wrapper class
object directly without calling a method (as we did when
we called .intValue()). This is called Unboxing
System.out.println(studentCount);
9-6
Wrapper Classes and ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner k = new Scanner(System.in);
System.out.println("Enter some non-zero integers. Enter 0 to end.");
int number = k.nextInt();
while (number != 0)
{
list.add(number); // autoboxing happening here
number = k.nextInt();
}
System.out.println("Your numbers in reverse are:");
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i)); // unboxing happening here
}
9-7
The Parse Methods
• One of the useful methods on the Wrapper classes is the parse
methods. These are static methods that allow you to convert a
String to a number.
• Each class has a different name for its parse method:
– The Integer class has a parseInt method that converts a String to an int
– The Short class has a parseShort method that converts a String to a Short
– The Float class has a parseFloat method that converts a String to a Float
– Etc.
9-8
The Parse Methods Examples
byte b = Byte.parseByte("8");
short sVar = Short.parseShort("17");
int num = Integer.parseInt("28");
long longVal = Long.parseLong("149");
float f = Float.parseFloat("3.14");
double price = Double.parseDouble("18.99");
• If the String cannot be converted to a number, an exception is
thrown. We will discuss exceptions later.
9-9
Helpful Methods on Wrapper Classes
• The toString is static method that can convert a number back to a
String:
int months = 12;
double PI = 3.14;
String monthsStr = Integer.toString(months);
String PIStr = Double.toString(PI);
• The Integer and Long classes have three additional methods to
do base conversions: toBinaryString, toHexString, and
toOctalString
int number = 16;
System.out.print(Integer.toBinaryString(number) + “ “ +
Integer.toHexString(number) + “ “ + Integer.toOctalString(number));
– output: 10000 10 20
9-10
Helpful Static Variables on Wrapper
Classes
• The numeric wrapper classes each have a set of static final
variables to know the range of allowable values for the data
type:
– MIN_VALUE
– MAX_VALUE
System.out.println("The minimum val for an int is “ +
Integer.MIN_VALUE);
System.out.println("The maximum val for an int is “ +
Integer.MAX_VALUE);
9-11
Character Testing and Conversion With The
Character Class
• The Character class allows a char data type to
be wrapped in an object.
Character x = new Character(‘K’);
• The Character class provides methods that
allow easy testing, processing, and conversion of
character data.
9-12
The Character Class – Static Methods
Method Description
boolean isDigit(
char ch)
Returns true if the argument passed into ch is a
digit from 0 through 9. Otherwise returns false.
boolean isLetter(
char ch)
Returns true if the argument passed into ch is an
alphabetic letter. Otherwise returns false.
boolean isLetterOrDigit(
char ch)
Returns true if the character passed into ch
contains a digit (0 through 9) or an alphabetic
letter. Otherwise returns false.
boolean isLowerCase(
char ch)
Returns true if the argument passed into ch is a
lowercase letter. Otherwise returns false.
boolean isUpperCase(
char ch)
Returns true if the argument passed into ch is an
uppercase letter. Otherwise returns false.
boolean isSpaceChar(
char ch)
Returns true if the argument passed into ch is a
space character. Otherwise returns false.
9-13
Character Testing and Conversion
With The Character Class
• The Character class provides two methods that will
change the case of a character.
Method Description
char toLowerCase(
char ch)
Returns the lowercase equivalent of the
argument passed to ch.
char toUpperCase(
char ch)
Returns the uppercase equivalent of the
argument passed to ch.
public static void main(String[] args)
{
Scanner k = new Scanner(System.in);
System.out.println("Enter a character please: ");
char ch = k.nextLine().charAt(0);
if (Character.isLetter(ch))
{
System.out.println("Found a letter!");
if (Character.isLowerCase(ch))
System.out.println("Found a lowercase letter!");
if (Character.isUpperCase(ch))
System.out.println("Found an uppercase letter!");
}
if (Character.isDigit(ch))
System.out.println("Found a digit!");
if (Character.isSpaceChar(ch))
System.out.println("Found a single space!");
if (Character.isWhitespace(ch))
System.out.println("Found a whitespace! (could be tab or enter too");
}
Example
9-15
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.
• Some of the substring searching methods provided by the String
class:
boolean startsWith(String str)
boolean endsWith(String str)
boolean regionMatches(int start, String str, int start2,
int n)
boolean regionMatches(boolean ignoreCase, int start,
String str, int start2, int n)
9-16
Searching Strings - startsWith
• The startsWith method determines whether a
string begins with a specified substring.
String str = "Four score and seven years ago";
if (str.startsWith("Four"))
System.out.println("The string starts with Four.");
else
System.out.println("The string does not start with Four.");
• str.startsWith("Four") returns true because
str does begin with “Four”.
• startsWith is a case sensitive comparison.
9-17
Searching Strings - endsWith
• The endsWith method determines whether a string
ends with a specified substring.
String str = "Four score and seven years ago";
if (str.endsWith("ago"))
System.out.println("The string ends with ago.");
else
System.out.println("The string does not end with ago.");
• The endsWith method also performs a case sensitive
comparison.
9-18
Searching Strings - regionMatches
• The String class provides methods that determine if
specified regions of two strings match.
– regionMatches(int start, String str, int start2,
int n)
• returns true if the specified regions match or false if they
don’t
• Case sensitive comparison
– regionMatches(boolean ignoreCase, int start,
String str, int start2, int n)
• If ignoreCase is true, it performs case insensitive
comparison
9-19
Searching Strings - regionMatches
String str = "Four score and seven years ago";
String str2 = “Those seven years passed quickly!”;
if (str.regionMatches(15, str2, 6, 11))
System.out.println("The regions match.");
else
System.out.println("The regions do not match.");
String str = "Four score and seven years ago";
String str2 = “THOSE SEVEN YEARS PASSED QUICKLY!”;
if (str.regionMatches(true, 15, str2, 6, 11))
System.out.println("The regions match.");
else
System.out.println("The regions do not match.");
Location 15
Location 6
11 characters
to be compared
true:
means
ignore the
case when
comparing
9-20
Searching Strings – indexOf, lastIndexOf
• The String class also provides methods that will
locate the position of a substring.
– indexOf
• returns the first location of a substring or character in the
calling String Object.
– lastIndexOf
• returns the last location of a substring or character in the
calling String Object.
9-21
Searching Strings – indexOf, lastIndexOf
String str = "Four score and seven years ago";
int first, last;
first = str.indexOf('r');
last = str.lastIndexOf('r');
System.out.println("The letter r first appears at position " + first);
System.out.println("The letter r last appears at position " + last);
// This code will find ALL occurences
String str = "and a one and a two and a three";
int position;
System.out.println("The word and appears at the following
locations.");
position = str.indexOf("and");
while (position != -1)
{
System.out.println(position);
position = str.indexOf("and", position + 1);
}
9-22
String Methods For Getting Character Or
Substring Location
See Table 9-4
9-23
String Methods For Getting Character Or
Substring Location
See Table 9-4
9-24
Extracting 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 fullName = "Cynthia Susan Smith";
String lastName = fullName.substring(14);
String firstName = fullName.substring(0, 7);
System.out.println("The full name is “ + fullName);
System.out.println("The last name is “ + lastName);
9-25
Extracting Characters to Arrays
• The String class provides methods to extract substrings in a String object
and store them in char arrays.
– getChars(int srcBegin, int srcEnd, char[] dst,
int dstBegin)
• Stores a substring in a char array
• srcBegin: first index to start copying from in the src string getChars is called on (e.g.
src.getChars(…)
• srcEnd: index after the last character in the string to copy
• dst: the destination array to copy to. Must be created already
• dstBegin: the start offset in the destination array to start copying
– toCharArray()
• Returns the String object’s contents in an array of char values.
String fullName = "Cynthia Susan Smith";
char[] nameArray = fullName.toCharArray();
char[] middleName;
fullName.getChars(8, 13, middleName, 0);
char[] chars = fullName.toCharArray();
8 13
9-26
Returning Modified Strings
• The String class provides methods that return
modified String objects.
– concat(String str)
• Returns a String object that is the concatenation of two String
objects; the original and the str given as input.
String s1 = “Hello”;
s1 = s1.concat(“ there”);
– replace(char oldChar, char newChar)
• Returns a String object with all occurrences of one character being
replaced by another character.
s1 = s1.replace(‘l’, ‘L’);
– trim()
• Returns a String object with all leading and trailing whitespace
characters removed.
s1 = s1.trim();
9-27
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.
String.valueOf(true) will return "true".
String.valueOf(5.0) will return "5.0".
String.valueOf(‘C’) will return "C".
9-28
The valueOf Methods
boolean b = true;
char [] letters = { 'a', 'b', 'c', 'd', 'e' };
double d = 2.4981567;
int i = 7;
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(letters));
System.out.println(String.valueOf(letters, 1, 3));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(i));
• Produces the following output:
true
abcde
bcd
2.4981567
7
9-29
CW Part-1-1: Wrapper Classes, Strings and Characters
Write a program that:
Part A: asks the user for a series of floats until the user enters -1. The program
should store the numbers in an ArrayList of Floats then calls the Collections.sort
method to sort the ArrayList and print the contents back on separate lines.
Part B: asks the user for a String. The program reads in the String and displays the
following statistics:
– Number of upper case letters
– Number of digits
– Number of white spaces
– The location/index of all occurrences of the letter ‘e’. If there are no e’s, it should
print “String has no e’s”. Use an ArrayList to collect the location of all the e’s.
Compile and test your code in NetBeans and then on Hackerrank at
https://www.hackerrank.com/csc128-part-1-classwork
then choose CSC128-Classwork-1-1
Submit your .java file and a screenshot of passing all test cases on Hackerrank.
9-30
The StringBuilder Class
• The String class is immutable – changes cannot made to an
existing String.
• The StringBuilder class is a class similar to the String class, but
it is mutable – changes can be made.
• There are three ways to construct a StringBuilder:
– StringBuilder(): create an empty StringBuilder of length 16
– StringBuilder(int length): create an empty StringBuilder with
the specified length
– StringBuilder(String str): create a StringBuilder with the
string’s contents.
9-31
Common Methods between String and
StringBuilder
• The String and StringBuilder have some methods in common:
char charAt(int position)
void getChars(int start, int end,
char[] array, int arrayStart)
int indexOf(String str)
int indexOf(String str, int start)
int lastIndexOf(String str)
int lastIndexOf(String str, int start)
int length()
String substring(int start)
String substring(int start, int end)
9-32
Appending to a StringBuilder Object
• The StringBuilder class has several overloaded versions
of a method named append.
• They append a string representation of their argument to the
calling object’s current contents.
• The general form of the append method is:
object.append(item);
– where object is an instance of the StringBuilder
class and item is:
• a primitive literal or variable.
• a char array, or
• a String literal or object.
9-33
• After the append method is called, a string representation of
item will be appended to object’s contents.
StringBuilder str = new StringBuilder();
str.append("We sold ");
str.append(12);
str.append(" doughnuts for $");
str.append(15.95);
System.out.println(str);
• This code will produce the following output:
We sold 12 doughnuts for $15.95
Appending to a StringBuilder Object
9-34
• The StringBuilder class also has several overloaded
versions of a method named insert
object.insert(start, item);
• These methods accept two arguments:
– start: an int that specifies the position to begin insertion, and
– item: the value to be inserted.
• The value to be inserted may be
– a primitive literal or variable.
– a char array, or
– a String literal or object.
Appending to a StringBuilder Object
9-35
• The StringBuilder class has a replace method that
replaces a specified substring with a string.
object.replace(start, end, str);
• start: an int that specifies the starting position of a substring in
the calling object
• end: an int that specifies the ending position of the substring.
(The starting position is included in the substring, but the ending
position is not.)
• str: String object to replace in the original string
– After the method executes, the substring will be replaced
with str.
Replacing a Substring in a StringBuilder Object
9-36
• The replace method in this code replaces the word
“Chicago” with “New York”.
StringBuilder str = new StringBuilder(
"We moved from Chicago to Atlanta.");
str.replace(14, 21, "New York");
System.out.println(str);
• The code will produce the following output:
We moved from New York to Atlanta.
Replacing a Substring in a StringBuilder Object
9-37
Other StringBuilder Methods
• The StringBuilder class also provides methods to set and
delete characters in an object.
StringBuilder str = new StringBuilder(
"I ate 100 blueberries!");
// Display the StringBuilder object.
System.out.println(str);
// Delete the '0'.
str.deleteCharAt(8);
// Delete "blue".
str.delete(9, 13); // starting at 9 and ending at 13
// Display the StringBuilder object.
System.out.println(str);
// Change the '1' to '5'
str.setCharAt(6, '5');
// Display the StringBuilder object.
System.out.println(str);
Other StringBuilder Methods
• The toString method
– You can call a StringBuilder's toString
method to convert that StringBuilder object to
a regular String
StringBuilder strb = new StringBuilder("This is a test.");
String str = strb.toString();
9-39
Tokenizing Strings
• Use the String class’s split method
• Tokenizes a String object and returns an array of String
objects
• Each array element is one token.
// Create a String to tokenize.
String str = "one two three four";
// Get the tokens from the string.
String[] tokens = str.split(" ");
// Display each token.
for (String s : tokens)
System.out.println(s);
• This code will produce the following output:
one
two
three
four
9-40
CW Part-1-2: String Tokenizer
• Ask the user for the prices of items bought for lunch. The prices should
be entered separated by commas using a single String. (e.g. $6.99, $1.09,
$1.99)
• Read in the String, remove the $ signs and use the split method to get a
String[] of the prices entered.
• Trim the white spaces around the strings and convert the Strings to
floats using the parse methods and add them all up.
• Display the total price to be paid.
Compile and test your code in NetBeans and then on Hackerrank at
https://www.hackerrank.com/csc128-part-1-classwork
then choose CSC128-Classwork-1-2
Submit your .java file and a screenshot of passing all test cases on Hackerrank.
9-41
Programming Assignment (50 Points)
Write a class with the following static methods:
• WordCounter: This method takes a String and returns the number of words in the String.
• convertToString: This method takes an ArrayList of Characters and returns a String
representation of the characters.
• mostFound: This method takes a String and returns the character that appears the most in the
String. Ignore the case when counting.
• replacePart: This method takes 3 Strings original, toReplace, replaceWith. It finds all
occurrences of toReplace in the original String and returns the original String with toReplace
replaced with replaceWith. For example, if the original String was “I have two dogs and two
cats”, toReplace is “two” and replaceWith is “three”, the method returns the String “I have
three dogs and three cats”.
Write a main method that:
• Asks the user for a String, a toReplace String and a replaceWith String. It prints:
– Number of words in the String
– The character that appears the most in the String
– The new String after calling replacePart
• Asks the user for a series of characters and creates an ArrayList of these characters. The user
should press . when done entering characters. It then prints out the Characters as a String
(using convertToString) and prints the String in all upper case.
Compile and test your code in NetBeans and then on Hackerrank at
https://www.hackerrank.com/contests/csc128-programmingassignments then choose CSC128-Part-1-PA
Submit your .java file and a screenshot of passing all test cases on Hackerrank.
Acknowledgment
"Java II – Part 1 – Wrapper Classes and
Strings" by Ibtsam Mahfouz, Manchester
Community College is licensed under CC BY-
NC-SA 4.0 / A derivative from the original
work
Ad

More Related Content

Similar to CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt (20)

String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
Strings power point in detail with examples
Strings power point in detail with examplesStrings power point in detail with examples
Strings power point in detail with examples
rabiyanaseer1
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
Simon Ritter
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
phanleson
 
11.ppt
11.ppt11.ppt
11.ppt
kavitamittal18
 
strings.ppt
strings.pptstrings.ppt
strings.ppt
BhumaNagaPavan
 
String in java, string constructors and operations
String in java, string constructors and operationsString in java, string constructors and operations
String in java, string constructors and operations
manjeshbngowda
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
adityaraj7711
 
Strings
StringsStrings
Strings
naslin prestilda
 
String Method.pptx
String Method.pptxString Method.pptx
String Method.pptx
Dreime Estandarte
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
Variables In Php 1
Variables In Php 1Variables In Php 1
Variables In Php 1
Digital Insights - Digital Marketing Agency
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
learnEnglish51
 
Lect9
Lect9Lect9
Lect9
Jamsher bhanbhro
 
07slide
07slide07slide
07slide
Aboudi Sabbah
 
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
mohithn2004
 
11-ch04-3-strings.pdf
11-ch04-3-strings.pdf11-ch04-3-strings.pdf
11-ch04-3-strings.pdf
AndreaBatholomeo
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 

More from rani marri (20)

express.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvcexpress.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
rani marri
 
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjjNagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
rani marri
 
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchcLecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
rani marri
 
git.ppt.pptx power point presentation got Google internet
git.ppt.pptx power point presentation got Google internetgit.ppt.pptx power point presentation got Google internet
git.ppt.pptx power point presentation got Google internet
rani marri
 
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjjEJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
rani marri
 
Containers Orchestration using kubernates.pptx
Containers Orchestration using kubernates.pptxContainers Orchestration using kubernates.pptx
Containers Orchestration using kubernates.pptx
rani marri
 
JSP.pptx programming guide for beginners and experts
JSP.pptx programming guide for beginners and expertsJSP.pptx programming guide for beginners and experts
JSP.pptx programming guide for beginners and experts
rani marri
 
nodejs tutorial foor free download from academia
nodejs tutorial foor free download from academianodejs tutorial foor free download from academia
nodejs tutorial foor free download from academia
rani marri
 
NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
rani marri
 
must.pptx
must.pptxmust.pptx
must.pptx
rani marri
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
rani marri
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
rani marri
 
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.pptADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
rani marri
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
data structures module I & II.pptx
data structures module I & II.pptxdata structures module I & II.pptx
data structures module I & II.pptx
rani marri
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvcexpress.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
rani marri
 
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjjNagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
rani marri
 
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchcLecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
rani marri
 
git.ppt.pptx power point presentation got Google internet
git.ppt.pptx power point presentation got Google internetgit.ppt.pptx power point presentation got Google internet
git.ppt.pptx power point presentation got Google internet
rani marri
 
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjjEJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
rani marri
 
Containers Orchestration using kubernates.pptx
Containers Orchestration using kubernates.pptxContainers Orchestration using kubernates.pptx
Containers Orchestration using kubernates.pptx
rani marri
 
JSP.pptx programming guide for beginners and experts
JSP.pptx programming guide for beginners and expertsJSP.pptx programming guide for beginners and experts
JSP.pptx programming guide for beginners and experts
rani marri
 
nodejs tutorial foor free download from academia
nodejs tutorial foor free download from academianodejs tutorial foor free download from academia
nodejs tutorial foor free download from academia
rani marri
 
NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
rani marri
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
rani marri
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
rani marri
 
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.pptADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
rani marri
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
data structures module I & II.pptx
data structures module I & II.pptxdata structures module I & II.pptx
data structures module I & II.pptx
rani marri
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
Ad

Recently uploaded (20)

Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Ad

CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt

  • 1. CSC 128 - JAVA II Part 1 Wrapper Classes & Strings
  • 2. 9-2 Chapter Topics We will cover the following topics in this order: • 7.3.2 Wrapper Classes • 2.5.6 Type Conversion (Parse Methods) • 2.3.3 Operations on Strings • 5.3.1 Some Built-in Classes (StringBuilder)
  • 3. 9-3 Wrapper Classes • Java provides 8 primitive data types: byte, short, int, long, float, double, boolean, char • One of the limitations of the primitive data types is that we cannot create ArrayLists of primitive data types. • However, this limitation turns out not to be very limiting after all, because of the so-called wrapper classes: – Byte, Short, Integer, Long, Float, Double, Boolean, Character • These wrapper classes are part of java.lang (just like String and Math) and there is no need to import them.
  • 4. 9-4 Wrapper Classes Examples • Creating a new object: Integer studentCount = new Integer(12); • Changing the value stored in the object: studentCount = new Integer(20); • Getting a primitive data type from the object: int count = studentCount.intValue();
  • 5. 9-5 Auto Boxing / UnBoxing • You can also assign a primitive value to a wrapper class object directly without creating an object. This is called Autoboxing Integer studentCount = 12; • You can get the primitive value out of the wrapper class object directly without calling a method (as we did when we called .intValue()). This is called Unboxing System.out.println(studentCount);
  • 6. 9-6 Wrapper Classes and ArrayList Example public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); Scanner k = new Scanner(System.in); System.out.println("Enter some non-zero integers. Enter 0 to end."); int number = k.nextInt(); while (number != 0) { list.add(number); // autoboxing happening here number = k.nextInt(); } System.out.println("Your numbers in reverse are:"); for (int i = list.size() - 1; i >= 0; i--) { System.out.println(list.get(i)); // unboxing happening here }
  • 7. 9-7 The Parse Methods • One of the useful methods on the Wrapper classes is the parse methods. These are static methods that allow you to convert a String to a number. • Each class has a different name for its parse method: – The Integer class has a parseInt method that converts a String to an int – The Short class has a parseShort method that converts a String to a Short – The Float class has a parseFloat method that converts a String to a Float – Etc.
  • 8. 9-8 The Parse Methods Examples byte b = Byte.parseByte("8"); short sVar = Short.parseShort("17"); int num = Integer.parseInt("28"); long longVal = Long.parseLong("149"); float f = Float.parseFloat("3.14"); double price = Double.parseDouble("18.99"); • If the String cannot be converted to a number, an exception is thrown. We will discuss exceptions later.
  • 9. 9-9 Helpful Methods on Wrapper Classes • The toString is static method that can convert a number back to a String: int months = 12; double PI = 3.14; String monthsStr = Integer.toString(months); String PIStr = Double.toString(PI); • The Integer and Long classes have three additional methods to do base conversions: toBinaryString, toHexString, and toOctalString int number = 16; System.out.print(Integer.toBinaryString(number) + “ “ + Integer.toHexString(number) + “ “ + Integer.toOctalString(number)); – output: 10000 10 20
  • 10. 9-10 Helpful Static Variables on Wrapper Classes • The numeric wrapper classes each have a set of static final variables to know the range of allowable values for the data type: – MIN_VALUE – MAX_VALUE System.out.println("The minimum val for an int is “ + Integer.MIN_VALUE); System.out.println("The maximum val for an int is “ + Integer.MAX_VALUE);
  • 11. 9-11 Character Testing and Conversion With The Character Class • The Character class allows a char data type to be wrapped in an object. Character x = new Character(‘K’); • The Character class provides methods that allow easy testing, processing, and conversion of character data.
  • 12. 9-12 The Character Class – Static Methods Method Description boolean isDigit( char ch) Returns true if the argument passed into ch is a digit from 0 through 9. Otherwise returns false. boolean isLetter( char ch) Returns true if the argument passed into ch is an alphabetic letter. Otherwise returns false. boolean isLetterOrDigit( char ch) Returns true if the character passed into ch contains a digit (0 through 9) or an alphabetic letter. Otherwise returns false. boolean isLowerCase( char ch) Returns true if the argument passed into ch is a lowercase letter. Otherwise returns false. boolean isUpperCase( char ch) Returns true if the argument passed into ch is an uppercase letter. Otherwise returns false. boolean isSpaceChar( char ch) Returns true if the argument passed into ch is a space character. Otherwise returns false.
  • 13. 9-13 Character Testing and Conversion With The Character Class • The Character class provides two methods that will change the case of a character. Method Description char toLowerCase( char ch) Returns the lowercase equivalent of the argument passed to ch. char toUpperCase( char ch) Returns the uppercase equivalent of the argument passed to ch.
  • 14. public static void main(String[] args) { Scanner k = new Scanner(System.in); System.out.println("Enter a character please: "); char ch = k.nextLine().charAt(0); if (Character.isLetter(ch)) { System.out.println("Found a letter!"); if (Character.isLowerCase(ch)) System.out.println("Found a lowercase letter!"); if (Character.isUpperCase(ch)) System.out.println("Found an uppercase letter!"); } if (Character.isDigit(ch)) System.out.println("Found a digit!"); if (Character.isSpaceChar(ch)) System.out.println("Found a single space!"); if (Character.isWhitespace(ch)) System.out.println("Found a whitespace! (could be tab or enter too"); } Example
  • 15. 9-15 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. • Some of the substring searching methods provided by the String class: boolean startsWith(String str) boolean endsWith(String str) boolean regionMatches(int start, String str, int start2, int n) boolean regionMatches(boolean ignoreCase, int start, String str, int start2, int n)
  • 16. 9-16 Searching Strings - startsWith • The startsWith method determines whether a string begins with a specified substring. String str = "Four score and seven years ago"; if (str.startsWith("Four")) System.out.println("The string starts with Four."); else System.out.println("The string does not start with Four."); • str.startsWith("Four") returns true because str does begin with “Four”. • startsWith is a case sensitive comparison.
  • 17. 9-17 Searching Strings - endsWith • The endsWith method determines whether a string ends with a specified substring. String str = "Four score and seven years ago"; if (str.endsWith("ago")) System.out.println("The string ends with ago."); else System.out.println("The string does not end with ago."); • The endsWith method also performs a case sensitive comparison.
  • 18. 9-18 Searching Strings - regionMatches • The String class provides methods that determine if specified regions of two strings match. – regionMatches(int start, String str, int start2, int n) • returns true if the specified regions match or false if they don’t • Case sensitive comparison – regionMatches(boolean ignoreCase, int start, String str, int start2, int n) • If ignoreCase is true, it performs case insensitive comparison
  • 19. 9-19 Searching Strings - regionMatches String str = "Four score and seven years ago"; String str2 = “Those seven years passed quickly!”; if (str.regionMatches(15, str2, 6, 11)) System.out.println("The regions match."); else System.out.println("The regions do not match."); String str = "Four score and seven years ago"; String str2 = “THOSE SEVEN YEARS PASSED QUICKLY!”; if (str.regionMatches(true, 15, str2, 6, 11)) System.out.println("The regions match."); else System.out.println("The regions do not match."); Location 15 Location 6 11 characters to be compared true: means ignore the case when comparing
  • 20. 9-20 Searching Strings – indexOf, lastIndexOf • The String class also provides methods that will locate the position of a substring. – indexOf • returns the first location of a substring or character in the calling String Object. – lastIndexOf • returns the last location of a substring or character in the calling String Object.
  • 21. 9-21 Searching Strings – indexOf, lastIndexOf String str = "Four score and seven years ago"; int first, last; first = str.indexOf('r'); last = str.lastIndexOf('r'); System.out.println("The letter r first appears at position " + first); System.out.println("The letter r last appears at position " + last); // This code will find ALL occurences String str = "and a one and a two and a three"; int position; System.out.println("The word and appears at the following locations."); position = str.indexOf("and"); while (position != -1) { System.out.println(position); position = str.indexOf("and", position + 1); }
  • 22. 9-22 String Methods For Getting Character Or Substring Location See Table 9-4
  • 23. 9-23 String Methods For Getting Character Or Substring Location See Table 9-4
  • 24. 9-24 Extracting 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 fullName = "Cynthia Susan Smith"; String lastName = fullName.substring(14); String firstName = fullName.substring(0, 7); System.out.println("The full name is “ + fullName); System.out.println("The last name is “ + lastName);
  • 25. 9-25 Extracting Characters to Arrays • The String class provides methods to extract substrings in a String object and store them in char arrays. – getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) • Stores a substring in a char array • srcBegin: first index to start copying from in the src string getChars is called on (e.g. src.getChars(…) • srcEnd: index after the last character in the string to copy • dst: the destination array to copy to. Must be created already • dstBegin: the start offset in the destination array to start copying – toCharArray() • Returns the String object’s contents in an array of char values. String fullName = "Cynthia Susan Smith"; char[] nameArray = fullName.toCharArray(); char[] middleName; fullName.getChars(8, 13, middleName, 0); char[] chars = fullName.toCharArray(); 8 13
  • 26. 9-26 Returning Modified Strings • The String class provides methods that return modified String objects. – concat(String str) • Returns a String object that is the concatenation of two String objects; the original and the str given as input. String s1 = “Hello”; s1 = s1.concat(“ there”); – replace(char oldChar, char newChar) • Returns a String object with all occurrences of one character being replaced by another character. s1 = s1.replace(‘l’, ‘L’); – trim() • Returns a String object with all leading and trailing whitespace characters removed. s1 = s1.trim();
  • 27. 9-27 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. String.valueOf(true) will return "true". String.valueOf(5.0) will return "5.0". String.valueOf(‘C’) will return "C".
  • 28. 9-28 The valueOf Methods boolean b = true; char [] letters = { 'a', 'b', 'c', 'd', 'e' }; double d = 2.4981567; int i = 7; System.out.println(String.valueOf(b)); System.out.println(String.valueOf(letters)); System.out.println(String.valueOf(letters, 1, 3)); System.out.println(String.valueOf(d)); System.out.println(String.valueOf(i)); • Produces the following output: true abcde bcd 2.4981567 7
  • 29. 9-29 CW Part-1-1: Wrapper Classes, Strings and Characters Write a program that: Part A: asks the user for a series of floats until the user enters -1. The program should store the numbers in an ArrayList of Floats then calls the Collections.sort method to sort the ArrayList and print the contents back on separate lines. Part B: asks the user for a String. The program reads in the String and displays the following statistics: – Number of upper case letters – Number of digits – Number of white spaces – The location/index of all occurrences of the letter ‘e’. If there are no e’s, it should print “String has no e’s”. Use an ArrayList to collect the location of all the e’s. Compile and test your code in NetBeans and then on Hackerrank at https://www.hackerrank.com/csc128-part-1-classwork then choose CSC128-Classwork-1-1 Submit your .java file and a screenshot of passing all test cases on Hackerrank.
  • 30. 9-30 The StringBuilder Class • The String class is immutable – changes cannot made to an existing String. • The StringBuilder class is a class similar to the String class, but it is mutable – changes can be made. • There are three ways to construct a StringBuilder: – StringBuilder(): create an empty StringBuilder of length 16 – StringBuilder(int length): create an empty StringBuilder with the specified length – StringBuilder(String str): create a StringBuilder with the string’s contents.
  • 31. 9-31 Common Methods between String and StringBuilder • The String and StringBuilder have some methods in common: char charAt(int position) void getChars(int start, int end, char[] array, int arrayStart) int indexOf(String str) int indexOf(String str, int start) int lastIndexOf(String str) int lastIndexOf(String str, int start) int length() String substring(int start) String substring(int start, int end)
  • 32. 9-32 Appending to a StringBuilder Object • The StringBuilder class has several overloaded versions of a method named append. • They append a string representation of their argument to the calling object’s current contents. • The general form of the append method is: object.append(item); – where object is an instance of the StringBuilder class and item is: • a primitive literal or variable. • a char array, or • a String literal or object.
  • 33. 9-33 • After the append method is called, a string representation of item will be appended to object’s contents. StringBuilder str = new StringBuilder(); str.append("We sold "); str.append(12); str.append(" doughnuts for $"); str.append(15.95); System.out.println(str); • This code will produce the following output: We sold 12 doughnuts for $15.95 Appending to a StringBuilder Object
  • 34. 9-34 • The StringBuilder class also has several overloaded versions of a method named insert object.insert(start, item); • These methods accept two arguments: – start: an int that specifies the position to begin insertion, and – item: the value to be inserted. • The value to be inserted may be – a primitive literal or variable. – a char array, or – a String literal or object. Appending to a StringBuilder Object
  • 35. 9-35 • The StringBuilder class has a replace method that replaces a specified substring with a string. object.replace(start, end, str); • start: an int that specifies the starting position of a substring in the calling object • end: an int that specifies the ending position of the substring. (The starting position is included in the substring, but the ending position is not.) • str: String object to replace in the original string – After the method executes, the substring will be replaced with str. Replacing a Substring in a StringBuilder Object
  • 36. 9-36 • The replace method in this code replaces the word “Chicago” with “New York”. StringBuilder str = new StringBuilder( "We moved from Chicago to Atlanta."); str.replace(14, 21, "New York"); System.out.println(str); • The code will produce the following output: We moved from New York to Atlanta. Replacing a Substring in a StringBuilder Object
  • 37. 9-37 Other StringBuilder Methods • The StringBuilder class also provides methods to set and delete characters in an object. StringBuilder str = new StringBuilder( "I ate 100 blueberries!"); // Display the StringBuilder object. System.out.println(str); // Delete the '0'. str.deleteCharAt(8); // Delete "blue". str.delete(9, 13); // starting at 9 and ending at 13 // Display the StringBuilder object. System.out.println(str); // Change the '1' to '5' str.setCharAt(6, '5'); // Display the StringBuilder object. System.out.println(str);
  • 38. Other StringBuilder Methods • The toString method – You can call a StringBuilder's toString method to convert that StringBuilder object to a regular String StringBuilder strb = new StringBuilder("This is a test."); String str = strb.toString();
  • 39. 9-39 Tokenizing Strings • Use the String class’s split method • Tokenizes a String object and returns an array of String objects • Each array element is one token. // Create a String to tokenize. String str = "one two three four"; // Get the tokens from the string. String[] tokens = str.split(" "); // Display each token. for (String s : tokens) System.out.println(s); • This code will produce the following output: one two three four
  • 40. 9-40 CW Part-1-2: String Tokenizer • Ask the user for the prices of items bought for lunch. The prices should be entered separated by commas using a single String. (e.g. $6.99, $1.09, $1.99) • Read in the String, remove the $ signs and use the split method to get a String[] of the prices entered. • Trim the white spaces around the strings and convert the Strings to floats using the parse methods and add them all up. • Display the total price to be paid. Compile and test your code in NetBeans and then on Hackerrank at https://www.hackerrank.com/csc128-part-1-classwork then choose CSC128-Classwork-1-2 Submit your .java file and a screenshot of passing all test cases on Hackerrank.
  • 41. 9-41 Programming Assignment (50 Points) Write a class with the following static methods: • WordCounter: This method takes a String and returns the number of words in the String. • convertToString: This method takes an ArrayList of Characters and returns a String representation of the characters. • mostFound: This method takes a String and returns the character that appears the most in the String. Ignore the case when counting. • replacePart: This method takes 3 Strings original, toReplace, replaceWith. It finds all occurrences of toReplace in the original String and returns the original String with toReplace replaced with replaceWith. For example, if the original String was “I have two dogs and two cats”, toReplace is “two” and replaceWith is “three”, the method returns the String “I have three dogs and three cats”. Write a main method that: • Asks the user for a String, a toReplace String and a replaceWith String. It prints: – Number of words in the String – The character that appears the most in the String – The new String after calling replacePart • Asks the user for a series of characters and creates an ArrayList of these characters. The user should press . when done entering characters. It then prints out the Characters as a String (using convertToString) and prints the String in all upper case. Compile and test your code in NetBeans and then on Hackerrank at https://www.hackerrank.com/contests/csc128-programmingassignments then choose CSC128-Part-1-PA Submit your .java file and a screenshot of passing all test cases on Hackerrank.
  • 42. Acknowledgment "Java II – Part 1 – Wrapper Classes and Strings" by Ibtsam Mahfouz, Manchester Community College is licensed under CC BY- NC-SA 4.0 / A derivative from the original work