Java Programming II on YouTube:
https://www.youtube.com/playlist?list=PLLIqcoGpl73hdVsj_auS8gs2cTFG1pYZx
Classes to use when working with character data:
Character
holds single character value
defines methods that can manipulate or inspect single-character data
String
class for fixed-string data
holds immutable data composed of multiple characters
StringBuilder and StringBuffer
classes for storing and manipulating changeable data composed of multiple characters
Contains standard methods for testing values of characters
Methods that begin with is..., such as isUpperCase()
return boolean value
can be used in comparison statements
Methods that begin with to..., such as toUpperCase()
return character converted to the stated format
Literal string, e.g. "hello"
Sequence of characters enclosed within double quotation marks
Unnamed object, or anonymous object of String class
String variable, e.g. String hello = "hello";
Named object of String class
Defined in java.lang.String
Automatically imported into every program
Creating String object:
String aGreeting = new String("Hello"); // Using keyword new String aGreeting = "Hello"; // Explicitly calling class constructor
java.lang.String
Common constructors of the String class:
String() String( arrayName ) String( arrayName, intOffset, intLength )
Compare two Strings using the == operator
Doesn't compare values
Compares computer memory locations of two strings
String equals() method
Evaluates contents of two String objects to determine if they are equivalent
Returns true if objects have identical contents
public boolean equals( String str )
The equalsIgnoreCase() method
ignores case when determining if two strings equivalent
useful when users type responses to prompts in programs
if ( aWord.compareTo( anotherWord ) < 0 ) { //... }
The compareTo() method compares two Strings and returns:
Zero if two Strings refer to the same value
Negative number if calling object is less than the argument object
Positive number if calling object is greater than the argument object
There are two ways to create an empty string:
String name = ""; String name = new String();
String bookTitle = "Beginning Java"; String title = bookTitle;
(Think why would you do this, this can be confusing.)
Two ways to create a string from an array of characters:
char cityArray[] = { 'D', 'a', 'l', 'l', 'a', 's' }; String cityString1 = new String( cityArray ); String cityString2 = new String( cityArray, 0, 3 );
Two ways to create a string from an array of bytes:
byte cityArray[] = { 68, 97, 108, 108, 97, 115 };
String cityString1 = new String( cityArray );
String cityString2 = new String( cityArray, 0, 3 );
Methods for manipulating strings:
length() indexOf(String) // first occurence of the String indexOf(String, startIndex) // occurence of the String lastIndexOf(String) // last occurence of the String lastIndexOf(String, startIndex) trim() // remove white space substring(startIndex) substring(startIndex, endIndex) replace(oldChar, newChar) // replaces all instances of oldChar split(delimiter) // returns array of substrings charAt(index) equals(String) // compares data equalsIgnoreCase(String) startsWith(String) // true if String matches startsWith(String, startIndex) // true if match after startIndex endsWith(String) // true if String matches at the end isEmpty() compareTo(String) compareToIgnoreCase(String)
Convert any String to its uppercase or lowercase equivalent
Returns the length of String
Determines whether specific character occurs within the String
Returns position of character
First position of String begins with zero
Returns –1 if character is not found in the String
Requires integer argument
Indicates position of the character that method returns
Takes String argument
Returns
true, if String object begins with the specified argument
false otherwise
Takes String argument
Returns
true, if String object ends with the specified argument
false otherwise
Replaces all occurrences of a char within String
Not part of String class
Other classes want to convert themselves to a String
Primitive data types need to be converted to Strings. For example,
String theString; int someInt = 4; theString = Integer.toString( someInt );
Code that parses a first name from a person's name
String fullName = " Pamela Caldwell "; fullName = fullName.trim(); int indexOfSpace = fullName.indexOf( " " ); String firstName = fullName.substring( 0, indexOfSpace );
Joins simple variable to String
Uses the plus sign (+)
String aString = "My age is " + myAge;
Extract part of String
Takes two integer arguments
int Start position
int End position
Length of extracted substring:
Difference between Ending and Starting positions
Code that parses a String containing a tab-delimited address:
String address = "805 Main Street\tDallas\tTX\t12345"; address = address.trim(); String[] addressParts = address.split("\t"); String street = addressParts[0]; String city = addressParts[1]; String state = addressParts[2]; String zip = addressParts[3];
Code that adds dashes to a phone number:
String phoneNumber1 = "9775551212"; String phoneNumber2 = phoneNumber1.substring(0, 3); phoneNumber2 += "-"; phoneNumber2 += phoneNumber1.substring(3, 6); phoneNumber2 += "-"; phoneNumber2 += phoneNumber1.substring(6);
Code that removes dashes from a phone number:
String phoneNumber3 = "977-555-1212"; String phoneNumber4 = ""; for(int i = 0; i < phoneNumber3.length(); i++) { if (phoneNumber3.charAt(i) != '-') { phoneNumber4 += phoneNumber3.charAt(i); } }
Code that compares strings
String lastName1 = "Smith"; String lastName2 = "Lee"; int sortResult = lastName1.compareToIgnoreCase(lastName2); if ( sortResult < 0 ) { System.out.println( lastName1 + " comes first." ); } else if ( sortResult == 0 ) { System.out.println( "The names are the same." ); } else { System.out.println( lastName2 + " comes first." ); }
Code that uses the isEmpty method:
String customerNumber = ""; //if ( customerNumber.equals("") ) // old way //if ( customerNumber.length() == 0 ) // old way if ( customerNumber.isEmpty() ) { // Java 1.6+ System.out.println( "customerNumber contains an empty string."); }
The value of the String is fixed:
After String is created, it is immutable
Alternative to String class
Used when String will be modified
Can use anywhere you would use String
Part of java.lang package
Automatically imported into every program
StringBuffer:
Thread safe
Use in multithreaded programs
Note:
StringBuilder is more efficient.
The rest of examples uses StringBuilder, but the same code will compile for the StringBuffer.
java.lang.StringBuilder
Constructors of the StringBuilder class
StringBuilder() StringBuilder( int capacity ) StringBuilder( String data )
StringBuilder greeting = new StringBuilder ("Hello there");
Using StringBuilder for mutable text
improves performance compared to String, because StringBuilder permits changes
allows inserts and appends of new data
StringBuilder has a buffer describing the allocated memory block.
Contained text data might not occupy the entire buffer
The length of text can be different from length of the buffer
The actual length of buffer determines StringBuilder's capacity
Common methods of the StringBuilder class are:
capacity() // get capacity length() // get logical length setLength(intNumOfChars) // set logical length append(value) // adds characters at the end insert(index, value) // inserts characters at specific location replace(startIndex, endIndex, String) delete(startIndex, endIndex) deleteCharAt(index) // removes one character setCharAt(index, character) //changes characters at specified position charAt(index) //returns character at specified position substring(index) // from index to the end substring(startIndex, endIndex) toString() // convert StringBuilder to String
Code that creates a phone number:
StringBuilder phoneNumber = new StringBuilder(); phoneNumber.append( "977" ); phoneNumber.append( "555" ); phoneNumber.append( "1212" );
Code that adds dashes to a phone number:
phoneNumber.insert( 3, "-" ); phoneNumber.insert( 7, "-" );
Code that removes dashes from a phone number:
for( int i = 0; i < phoneNumber.length(); ++i ) { if ( phoneNumber.charAt( i ) == '-' ) { phoneNumber.deleteCharAt( i-- ); } }
Code that parses a phone number
StringBuilder phoneNumber = new StringBuilder( "977-555-1212" ); String areaCode = phoneNumber.substring( 0, 3 ); String prefix = phoneNumber.substring( 4, 7 ); String suffix = phoneNumber.substring( 8 );
Code that shows how capacity automatically increases:
StringBuilder name = new StringBuilder( 8 ); int capacity1 = name.capacity(); // capacity1 is 8 name.append( "Raymond R. Thomas" ); int length = name.length(); // length is 17 int capacity2 = name.capacity(); // capacity2 is 18 // (2 * capacity1 + 2)
length() returns number of characters of the text data in the StringBuilder
setLength() method changes length of the text data encapsulated by the StringBuilder object
capacity() returns capacity of the StringBuilder object
StringBuilder equals() method compares references, not data!
To compare the contents of two StringBuilder objects, use
objOne.toString().equals( objTwo.toString() )