chapter 7 - characters strings

22
Characters, Strings Characters, Strings and the String and the String Buffer Buffer Jim Burns Jim Burns

Upload: norazlina-abdullah

Post on 18-Nov-2015

239 views

Category:

Documents


5 download

TRANSCRIPT

  • Characters, Strings and the String BufferJim Burns

  • Identifying problems that can occur when you manipulate string dataString is not a simple data type like int, float, or doubleString creates an instance of a class, the class StringAs such it contains a reference or an address and not the actual stringSo you cannot do equality comparisons of two different instances of String, because you are simply testing if the addresses are the same

  • Three classes for working with stringsCharactera class whose instances can hold a single character valueprovides methods that can manipulate or inspect single-character dataStringa class for working with fixed-string datathat is unchanging data composed of multiple characters, strings that are immutableStringBuffera class for storing and manipulating changeable data composed of mulltiple characters

  • Manipulating CharactersWe know the char data type can hold any single characterCharacter class provides the following methodsisUpperCase(), toUpperCase(), isLowerCase(), toLowerCase(), isDigit(), isLetter(), isLetterOrDigit(), isWhitespace()Methods that begin with is perform tests delivering true or false valuesMethods that begin with to perform conversions

  • Declaring a String ObjectWe know that characters enclosed within double quotation marks are literal stringsWeve learned to print these strings using println()An literal string is an unnamed object, or anonymous object, of the String classA String variable is simply a named object of the same class.The class String is defined in java.lang.String, which is automatically imported into every program you write

  • Declaring a String variableWhen you declare a String variable, the String itselfthat is, the series of characters contained in the Stringis distinct from the variable you use to refer to it.Can initialize a String variable with or without a String constructor

  • With or without a String ConstructorWith the constructor

    String aGreeting = new String(Hello);

    Without the constructor

    String aGreeting = Hello;

    Unlike other classes, you can create a String object without using the keyword new or explicitly calling the class constructor

  • Comparing String ValuesConsider the following two statements:

    String aGreeting = hello;aGreeting = Bonjour;

    These statements are syntactically correct. What happens is that the address contained in aGreeting is changed to point to Bonjour rather than hello, both of which are contained at different locations in memory. Eventually, the garbage collector discards the hello characters.

  • Comparing String ValuesThe String class provides methods for comparing stringsIn the example above the == sign is comparing memory addresses, not the actual strings.The String class equals() method evaluates the contents of two String objects to determine if they are equivalent.

  • compareTo() methodReturns an integer that is the numeric difference between the first two non-matching characters

  • Using other String MethodstoUpperCase() and toLowerCase() convert any String to its uppercase and lowercase equivalentLength() returns the length of a String

  • ConcatenationYou know you can concatenate strings to strings as in System.out.println(firstName + + lastName);

  • Concatenationnumbers to strings by using +The following is permissible:

    Int myAge = 25;String aString = My age is + myAge;Another example would beString anotherString;

    float someFloat = 12.34f;anotherString = + someFloat;

  • Converting Strings to NumbersUse a wrapper like the Integer class which is a part of java.langA wrapper is a class that is wrapped around a simpler elementInt anInt = Integer.parseInt(649) stores the value 649 in the variable anInt

  • public class TestCharacter{ public static void main(String[] args) { char aChar = 'C'; System.out.println("The character is " + aChar); if(Character.isUpperCase(aChar)) System.out.println(aChar + " is uppercase"); else System.out.println(aChar + " is not uppercase"); if(Character.isLowerCase(aChar)) System.out.println(aChar + " is lowercase"); else System.out.println(aChar + " is not lowercase"); aChar = Character.toLowerCase(aChar); System.out.println("After toLowerCase(), aChar is " + aChar); aChar = Character.toUpperCase(aChar); System.out.println("After toUpperCase(), aChar is " + aChar); if(Character.isLetterOrDigit(aChar)) System.out.println(aChar + " is a letter or digit"); else System.out.println(aChar + " is neither a letter nor a digit"); if(Character.isWhitespace(aChar)) System.out.println(aChar + " is whitespace"); else System.out.println(aChar + " is not whitespace"); }}//see next slide

  • Test Character Apppublic class TestCharacter{ public static void main(String[] args) { char aChar = 'C'; System.out.println("The character is " + aChar); if(Character.isUpperCase(aChar)) System.out.println(aChar + " is uppercase"); else System.out.println(aChar + " is not uppercase"); if(Character.isLowerCase(aChar)) System.out.println(aChar + " is lowercase"); else

  • System.out.println(aChar + " is not lowercase"); aChar = Character.toLowerCase(aChar); System.out.println("After toLowerCase(), aChar is " + aChar); aChar = Character.toUpperCase(aChar); System.out.println("After toUpperCase(), aChar is " + aChar); if(Character.isLetterOrDigit(aChar)) System.out.println(aChar + " is a letter or digit"); else System.out.println(aChar + " is neither a letter nor a digit"); if(Character.isWhitespace(aChar)) System.out.println(aChar + " is whitespace"); else System.out.println(aChar + " is not whitespace"); }}

  • Learning about the StringBuffer ClassSome strings are not constants, not immutable

    String someChars = Goodbye;someChars = Goodbye Everybody;someChars = Goodbye + Everybody;You cannot change the string GoodbyeTo overcome these limitations, you can use the StringBuffer classThe StringBuffer class was invented to accommodate strings that are not immutable (constants)

  • The StringBuffer ClassUses a buffer that is much larger than any one string; actual size of the buffer is the capacityProvides methods that can change individual characters within a stringMust initialize StringBuffer objects as follows:StringBuffer eventString = new StringBuffer(Hello there);Cannot use StringBuffer eventString = Hello there;

  • Methods in the StringBuffer ClasssetLength() will change the length of a String in a StringBuffer objectcapacity() will find the capacity of an objectHas four constructors:public StringBuffer() constructs a StringBuffer with no characters and a default size of 16 characterspublic StringBuffer(int Capacity) creates a StringBuffer with no characters and a capacity defined by the parameterpublic StringBuffer(String s) contains the same characters as those stored in the String object s

  • Still more methods in the StringBuffer ClassAppend() lets you add characters to the end of a StringBuffer objectInsert() lets you add characters at a specific location within a StringBuffer object

    StringBuffer someBuffer = new StringBuffer(Happy Birthday);someBuffer.insert(6,30th );

    Produces Happy 30th Birthday

  • Still more methods in StringBuffersetCharAt() method allows you to change a single character at a specified locationsomeBuffer.setCharAt(6,4);Changes someBuffer to Happy 40th BirthdayCan use charAt() method will return the character at an offset number of positions from the first characterStringBuffer text = new StringBuffer(Java Programming);Then text.charAt(5) returns the character P.