Strings and ArrayLists

Strings and ArrayLists April 23, 2012 ASFA AP CS String class facts An object of the String class represents a string of characters. The String class belongs to the java.lang package, which does not require an import statement. Like other classes, String has constructors and methods. Unlike other classes, String has two operators, + and += (used for concatenation).

Strings are immutable Strings Strings are objects, and thus references String s; // no string String s = new String("Hi"); // string String s = "Hi";

// string String s = ""; // string Literal Strings are anonymous objects of the String class are defined by enclosing text in double quotes. This is a literal String dont have to be constructed. can be assigned to String variables. can be passed to methods and constructors as parameters. have methods you can call.

Literal String examples //assign a literal to a String variable String name = Robert; //assign literals with escape sequences String twoLine = first \nsecond line; String quote = " He said, \" Yes\"."; String bksl = This is backslash: \\; //calling a method on a literal String char firstInitial = Robert.charAt(0); //calling a method on a String variable char firstInitial = name.charAt(0);

Immutability Once created, a string cannot be changed: none of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change. Empty Strings An empty String has no characters. Its length is 0.

String word1 = ""; String word2 = new String(); Empty strings Not the same as an uninitialized String. private String errorMsg; errorMsg is null Changing String Values Strings have no methods to let you change an

existing character in a string. To change a string you have to reassign the variable to a new string. example: String greeting = Hello; greeting = greeting.substr(0,4) + !; Result: greeting is now Hell! Comparing String Values Because String variables hold memory addresses, you cannot make a simple comparison of the contents The String class provides a number of

methods equals() method equalsIgnoreCase() method compareTo() method Comparing String Values equals() method- Evaluates the contents of two String objects to determine if they are equivalent This method returns true if the two String objects have identical contents Can take either a variable String object or a literal string as its argument

s1.equals(s2); s1.equals(Hello); Comparing String Values compareTo() method- Used to compare two Strings Returns zero only if the two Strings hold the same value If there is any difference between the Strings, a negative number is returned if the calling object is less than the argument A positive number is returned if the calling object is

more than the argument Strings are considered less than or more than each other based on their Unicode values String Equality String s1 = new String("Hi"); String s2 = new String("Hi"); System.out.println( s1 == s2 ); // false System.out.println( s1.equals(s2) ); // true s1 String reference

"Hi" s2 String reference "Hi" Methods substring Returns a new String by copying characters from an existing String. String subs = word.substring (i, k);

returns the substring of chars in positions from i to k-1 String subs = word.substring (i); returns the substring from the i-th char to the end television".substring (2,5); immutable".substring (2); bob".substring (3); television i k

television i Returns: lev" mutable" "" (empty string) Methods Concatenation String word1 = re, word2 = think; word3 = ing; int num = 2; String result = word1 + word2;

//concatenates word1 and word2 rethink String result = word1.concat (word2); //the same as word1 + word2 rethink result += word3; //concatenates word3 to result rethinking result += num; //converts num to String //and concatenates it to result rethinking2 Methods Find (indexOf) 0 2

6 10 15 String name =President George Washington"; date.indexOf (P'); 0 date.indexOf (e'); 2 date.indexOf (George"); 10 date.indexOf (e', 3); 6

date.indexOf (Bob"); date.lastIndexOf (e'); -1 15 Returns: (starts searching at position 3) (not found) Some Other String Methods

Object.toString() Every class implements toString( ) because it is defined by Object. The default implementation of toString( ) is seldom sufficient. Most classes override toString( ) and provide string representations. Fortunately, this is easy to do.

Recently Viewed Presentations

  • Manchester eScholar Services: the first 9 months Research

    Manchester eScholar Services: the first 9 months Research

    Manchester eScholar Services: the first 9 months Research Administrators Conference, 15th June 2010 Dr Phil Butler [email protected] What is Manchester eScholar?
  • Diapositiva 1 - Altervista

    Diapositiva 1 - Altervista

    Le Petit Prince Antoine de Saint-Exupery Nasce a Lione nel 1900. Diventa pilota militare a 21 anni. Contemporaneamente si dedica alla scrittura e il suo capolavoro "IL PICCOLO PRINCIPE" viene tradotto in 160 lingue.
  • Canadian Path Information Sharing session  Part 3 Working

    Canadian Path Information Sharing session Part 3 Working

    Personal Progression . 10 minutes. Our group hasn't had much success with personal progression badges and top section awards. We've tried to promote it to the youth and the parents but it seems like they mostly prefer to keep scouting...
  • Sleep Hygiene - NDSU

    Sleep Hygiene - NDSU

    Sleep deprivation can cause the following shortened life spans increased risk of heart disease and stomach problems irritability, depression increased risk of automobile crashes decreased work performance and memory lapses marital, social and employment problems difficulty learning Basics of Good...
  • Saving energy, making your home more comfortable with

    Saving energy, making your home more comfortable with

    A Victorian Residential Efficiency Scorecard assessment can help if you have high energy bills . A Scorecard assessment can tell you what kind of renovations will increase your home's energy efficiency and comfort. ... PowerPoint Presentation Last modified by:

    It isn't just the stack... Control flow attacks require that the attacker overwrite a piece of memory that contains a pointer for future code execution. The return address on the stack is just the easiest target. ... An attempt at...
  • Forming a Union - PC\|MAC

    Forming a Union - PC\|MAC

    Forming a National Government. Although the states have formed 13 separate governments, the Continental Congress drafted a (11) national constitution for the nation as a whole. In order for America to be successful all of the states must be united...
  • Adult steelhead evaluations in Imnaha River tributaries William

    Adult steelhead evaluations in Imnaha River tributaries William

    William Young, Jocelyn Hatch. Nez Perce Tribe . Department of Fisheries Resources Management. Determine adult steelhead abundance in 3 Lower Imnaha River tributaries - Cow Creek, Lightning Creek and Horse Creek. Fish weirs for a minimum of 5 years per...