Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming Strings Chapter 7.

Similar presentations


Presentation on theme: "Java Programming Strings Chapter 7."— Presentation transcript:

1 Java Programming Strings Chapter 7

2 String Class 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 Strings 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 Immutability 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 Advantages Of Immutability
Uses less memory. String word1 = "Java"; String word2 = word1; String word1 = “Java"; String word2 = new String(word1); word1 "Java" word1 "Java" word2 "Java" word2 Less efficient: wastes memory OK

6 Disadvantages of Immutability
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 Manipulating Characters
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 Indexes 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 1 2 3 4 5 6 7 character J a v f u n

9 String Methods These methods are called using the dot notation:
Method name Description 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 These methods are called using the dot notation: String name = "Hello World"; System.out.println(name.length());

10 Length of a String 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 Modifying String 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 Modifying String 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 Looking for a String 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 Looking for a String // index 012345678901234567890123456
String name = "President George Washington"; name.indexOf ('P'); name.indexOf ('e'); name.indexOf ("George"); name.indexOf ('e', 3); name.indexOf ("Bob"); name.lastIndexOf ('e'); Returns: (starts searching at position 3) String has four overloaded versions of indexOf and four versions of lastIndexOf. lastIndexOf(ch, fromPos) starts looking at fromPos and goes backward towards the beginning of the string. (not found)

15 Replacing Part of a String
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 String methods // index 01234567890 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 Comparing Strings 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 Comparing Strings equals() method equalsIgnoreCase() 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 Comparing Strings 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 Comparing Strings These methods return a boolean value (true or false)
Description 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 These methods return a boolean value (true or false)

21 String Concatenation 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 Numbers to Strings 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 = "" + 123; //"123" You can also convert a char to a string by using String s = "" + ch; or String s = ch + ""; By convention, a static method valueOf in a class converts something (its arguments) into an object of this class. For example: public class Fraction { public static Fraction valueOf(double x) {...} should take a double and return a corresponding Fraction. Here String.valueOf(x) returns a string. s = Integer.toString(123); //"123" s = Double.toString(3.14); //"3.14" s = String.valueOf(123); //"123"

23 Strings to Numbers 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 StringBuilder 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 StringBuilder Using StringBuilder objects StringBuilder constructors
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 StringBuilder Method Description 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 Finding Palindromes 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 Finding Palindromes import java.util.Scanner;
public class CheckPalindrome { public static void main(String[] args) { Scanner input = new Scanner(System.in); 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 Finding Palindromes 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 "Java Programming Strings Chapter 7."

Similar presentations


Ads by Google