Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does.

Similar presentations

Presentation on theme: "Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does."— Presentation transcript:

1 Strings Chapter 7

2  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.

3  string: An object storing a sequence of text characters.  Two ways to create a string  As a new object through the String class String name = new String(" text ");  Convenient shorthand method String name = " text ";

4  immutable.  String name = " text ";  Once created in memory, a string cannot be changed: none of its methods changes the string  If a string variable is reassigned, the memory address is deleted and a new memory address is created  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.

5 Uses less memory. String word1 = "Java"; String word2 = word1; String word1 = “Java"; String word2 = new String(word1); word1 OK Less efficient: wastes memory "Java" word2 word1 word2

6 Less efficient — you need to create a new string and throw away the old one even for small changes. String word = "java"; word = "HTML"; word "java" "HTML"

7  Character class  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 that has been converted to stated format

8  Characters of a string are numbered with 0-based indexes: String name = "Java fun";  First character's index : 0  Last character's index : 1 less than the string's length  The individual characters are values of type char index character Java fun

9  These methods are called using the dot notation: String name = "Hello World"; System.out.println(name.length()); Method nameDescription indexOf(str)index where the start of the given string appears in this string (-1 if not found) length()number of characters in this string substring(index1, index2) or substring(index1) the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string toLowerCase()a new string with all lowercase letters toUpperCase()a new string with all uppercase letters charAt(index)Returns the character at the specified index

10  It is sometimes useful to determine the length of a string  Use the length( ) methods String s = "Java is Fun"; int sLength = s.length(); System.out.println(sLength); // 11  The method counts the number of characters in the string variable. It produces an integer result.

11  Java is case sensitive String s1 = "Java"; String s2 = "java";  s1 and s2 represent two different strings  To get around this possible obstacle, Java has methods that display a string in all upper case letters or all lower case letters  toUpperCase( )  toLowerCase( )

12  These methods build and return a new string, rather than modifying the current string.  To modify a variable's value, you must reassign it: String s = "Hello World"; s1 = s.toUpperCase(); s2 = s.toLowerCase(); System.out.println(s1 + " " + s2); // HELLO WORLD hello world

13  Another common task when handling strings is to see whether one string can be found inside another. This is useful when you are looking for a specific text inside a large string (such as a document)  To look inside a string, use  indexOf( string )  If string is found, an integer that represents the starting position of the first occurrence is returned  If string is not found, -1 is returned  lastIndexOf( string )  Returns the position of the last occurrence String s = "Java is fun"; int sfind = s.indexOf("fun"); System.out.println(sfind);// 8

14 // index String name = "President George Washington"; name.indexOf ('P'); 0 name.indexOf ('e'); 2 name.indexOf ("George"); 10 name.indexOf ('e', 3); 6 name.indexOf ("Bob"); -1 name.lastIndexOf ('e'); 15 Returns: (not found) (starts searching at position 3)

15  We may also want to find and replace parts of a large string  There are a few replace methods available  replace(oldString, newString)  replaceFirst(oldString, newString)  replaceAll(oldString, newString) String s = "Java is fan"; s1 = s.replace("fan","fun"); System.out.println(s1); // Java is fun

16 // index String s1 = "Hello World"; System.out.println(s1.length()); System.out.println(s1.indexOf("r")); System.out.println(s1.charAt(1)); System.out.println(s1.substring(3, 7)); String s2 = s1.substring(0, 5); System.out.println(s2.toLowerCase()); 11 8 e lo W hello

17  One thing we will be testing often in our programs is whether one string is the same as the other  Two basic commands:  equals( )  compareTo( )  Do not compare two Strings using the == operator  Not comparing values  Comparing computer memory locations

18  equals() method  Evaluates contents of two String objects to determine if they are equivalent  Returns true if objects have identical contents  equalsIgnoreCase() method  Ignores case when determining if two Strings equivalent  Useful when users type responses to prompts in programs s1 = "Java"; s2 = "java"; boolean eq = s1.equals(s2); System.out.println(eq); // false

19  compareTo() method  Compares two Strings and returns:  Zero  Only if two Strings refer to same value  Negative number  If calling object “less than” argument  Positive number  If calling object “more than” argument

20 These methods return a boolean value (true or false) MethodDescription equals(str)whether two strings contain the same characters equalsIgnoreCase(str)whether two strings contain the same characters, ignoring upper vs. lower case startsWith(str)whether one contains other's characters at start endsWith(str)whether one contains other's characters at end contains(str)whether the given string is found within this one

21  Concatenation  Join multiple variables together  Two ways to concatenate  concat method  String s3 = s1.concat(s2);  Convenient shorthand  String s3 = s1 + s2; s1 = "Hello"; s2 = "World"; s3 = s1 + " " + s2;

22 Three ways to convert a number into a string: 1. String s = "" + num; 2. String s = Integer.toString (i); String s = Double.toString (d); 3. String s = String.valueOf (num); Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. They also provide useful static methods. s = String.valueOf(123);//"123" s = "" + 123;//"123" s = Integer.toString(123);//"123" s = Double.toString(3.14); //"3.14"

23  Integer and Double class  Automatically imported into programs (java.lang)  Convert String to integer  valueOf() method  Convert String to Integer class object  intValue() method  Extract simple integer from wrapper class  parseInt() method  Returns its integer value  Convert String to double  parseDouble() method  Returns its double value

24 The StringBuilder / StringBuffer class is an alternative to the String class.  Can be used wherever a string is used.  More flexible than String.  You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created.

25  Using StringBuilder objects  Provides improved computer performance over String objects  Can insert or append new contents into StringBuilder  StringBuilder constructors public StringBuilder () public StringBuilder (int capacity) public StringBuilder (String s) StringBuilder name = new StringBuilder("Hello");

26 MethodDescription append(str)Adds a string to the end of the StringBuilder object delete(start, end)Deletes characters at the specified index insert(index, str)Inserts string into the builder at the position offset replace(start, end, str)Replaces the characters in this builder at the specified index with the specified string setCharAt(index, char)Changes a character at the specified index CharAt(index)Returns character at the specified index

27  Write a program to check whether a string is a palindrome: a string that reads the same forward and backward. civic radar level rotor kayak reviver racecar redder

28 import java.util.Scanner; public class CheckPalindrome { public static void main(String[] args) { Scanner input = new Scanner(; System.out.print("Enter a string: "); String s = input.nextLine(); if (isPalindrome(s)) System.out.println(s + " is a palindrome"); else System.out.println(s + " is not a palindrome"); } // continued on next page

29 public static boolean isPalindrome(String s) { // Set index of the first and last characters in the string int low = 0; int high = s.length() - 1; while (low < high) { if (s.charAt(low) != s.charAt(high)) return false; // Not a palindrome low++; high--; } return true; // The string is a palindrome }

Download ppt "Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does."

Similar presentations

Ads by Google