SlideShare uma empresa Scribd logo
1 de 27
JAVA

                            STRINGS



Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                               rights reserved. 0-13-222158-6
                                                                                               1
The String Class
Constructing a String:
– String message = "Welcome to Java“;
– String message = new String("Welcome to Java“);
– String s = new String();
Obtaining String length and Retrieving Individual Characters in
a string
String Concatenation (concat)
Substrings (substring(index), substring(start, end))
Comparisons (equals, compareTo)
String Conversions
Finding a Character or a Substring in a String
Conversions between Strings and Arrays
Converting Characters and Numeric Values to Strings
           Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                          rights reserved. 0-13-222158-6
                                                                                                          2
java.lang.String

+String()                                             Constructs an empty string
+String(value: String)                                Constructs a string with the specified string literal value
+String(value: char[])                                Constructs a string with the specified character array
+charAt(index: int): char                             Returns the character at the specified index from this string
+compareTo(anotherString: String): int                Compares this string with another string
+compareToIgnoreCase(anotherString: String): int      Compares this string with another string ignoring case
+concat(anotherString: String): String                Concat this string with another string
+endsWith(suffix: String): boolean                    Returns true if this string ends with the specified suffix
+equals(anotherString: String): boolean             Returns true if this string is equal to anther string
+equalsIgnoreCase(anotherString: String): boolean Checks if this string equals anther string ignoring case
+getChars(int srcBegin, int srcEnd, char[] dst, int Copies characters from this string into the destination character
 dstBegin): void                                     array
+indexOf(ch: int): int                              Returns the index of the first occurrence of ch
+indexOf(ch: int, fromIndex: int): int                Returns the index of the first occurrence of ch after fromIndex
+indexOf(str: String): int                            Returns the index of the first occurrence of str
+indexOf(str: String, fromIndex: int): int            Returns the index of the first occurrence of str after fromIndex
+lastIndexOf(ch: int): int                            Returns the index of the last occurrence of ch
+lastIndexOf(ch: int, fromIndex: int): int            Returns the index of the last occurrence of ch before fromIndex
+lastIndexOf(str: String): int                        Returns the index of the last occurrence of str
+lastIndexOf(str: String, fromIndex: int): int        Returns the index of the last occurrence of str before fromIndex
+regionMatches(toffset: int, other: String, offset:   Returns true if the specified subregion of this string exactly
 int, len: int): boolean                               matches the specified subregion of the string argument
+length(): int                                        Returns the number of characters in this string
+replace(oldChar: char, newChar: char): String        Returns a new string with oldChar replaced by newChar
+startsWith(prefix: String): boolean                  Returns true if this string starts with the specified prefix
+subString(beginIndex: int): String                   Returns the substring from beginIndex
+subString(beginIndex: int, endIndex: int): String    Returns the substring from beginIndex to endIndex-1.
+toCharArray(): char[]                                Returns a char array consisting characters from this string
+toLowerCase(): String                                Returns a new string with all characters converted to lowercase
+toString(): String                                   Returns a new string with itself
+toUpperCase(): String                                Returns a new string with all characters converted to uppercase
+trim(): String                                       Returns a string with blank characters trimmed on both sides
+copyValueOf(data: char[]): String                    Returns a new string consisting of the char array data
+valueOf(c: char): String                             Returns a string consisting of the character c
+valueOf(data: char[]): String                        Same as copyValueOf(data: char[]): String
+valueOf(d: double): String                           Returns a string representing the double value
+valueOf(f: float): String                            Returns a string representing the float value
+valueOf(i:Liang, Introduction
            int): String         to Java Programming, Sixth string representing Pearson Education, Inc. All
                                                     Returns a Edition, (c) 2007 the int value
+valueOf(l: long): String                   rights reserved.a0-13-222158-6
                                                     Returns string representing the long value                          3
Constructing Strings
String newString = new String(stringLiteral);

String message = new String("Welcome to Java");

Since strings are used frequently, Java provides a
shorthand initializer for creating a string:

String message = "Welcome to Java";

         Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                        rights reserved. 0-13-222158-6
                                                                                                        4
Strings Are Immutable
A String object is immutable; its contents cannot be changed.
Does the following code change the contents of the string?
    String s = "Java";
    s = "HTML";




            Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                           rights reserved. 0-13-222158-6
                                                                                                           5
animation

                                            Trace Code
           String s = "Java";
           s = "HTML";


After executing String s = "Java";                                  After executing s = "HTML";

  s                     : String                              s                              : String             This string object is
                                                                                                                  now unreferenced
                 String object for "Java"                                           String object for "Java"



      Contents cannot be changed                                                              : String

                                                                                    String object for "HTML"




                   Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                                  rights reserved. 0-13-222158-6
                                                                                                                               6
animation

                                            Trace Code

              String s = "Java";
              s = "HTML";


After executing String s = "Java";                                  After executing s = "HTML";

  s                     : String                              s                              : String             This string object is
                                                                                                                  now unreferenced
                 String object for "Java"                                           String object for "Java"



      Contents cannot be changed                                                              : String

                                                                                    String object for "HTML"




                   Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                                  rights reserved. 0-13-222158-6
                                                                                                                               7
Interned Strings
Since strings are immutable and are frequently
used, to improve efficiency and save memory, the
JVM uses a unique instance for string literals with
the same character sequence. Such an instance is
called interned. You can also use a String object’s
intern method to return an interned string. For
example, the following statements:




         Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                        rights reserved. 0-13-222158-6
                                                                                                        8
Examples
                                                                                  s
String s = "Welcome to Java";                                                                               : String
                                                                                  s2
String s1 = new String("Welcome to Java");                                        s3                Interned string object for
                                                                                                    "Welcome to Java"
String s2 = s1.intern();

String s3 = "Welcome to Java";                                                    s1                        : String
System.out.println("s1 == s is " + (s1 == s));                                                       A string object for
System.out.println("s2 == s is " + (s2 == s));                                                       "Welcome to Java"
System.out.println("s == s3 is " + (s == s3));



display                            A new object is created if you use the
  s1 == s is false                 new operator.
                                   If you use the string initializer, no new
  s2 == s is true                  object is created if the interned object is
                                   already created.
  s == s3 is true
             Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                            rights reserved. 0-13-222158-6
                                                                                                                           9
Trace Code
                                                                                   s
String s = "Welcome to Java";                                                                                 : String
String s1 = new String("Welcome to Java");                                                            Interned string object for
                                                                                                      "Welcome to Java"
String s2 = s1.intern();

String s3 = "Welcome to Java";




             Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                            rights reserved. 0-13-222158-6
                                                                                                                         10
Trace Code
                                                                                   s
String s = "Welcome to Java";                                                                                 : String
String s1 = new String("Welcome to Java");                                                            Interned string object for
                                                                                                      "Welcome to Java"
String s2 = s1.intern();

String s3 = "Welcome to Java";                                                      s1                        : String
                                                                                                       A string object for
                                                                                                       "Welcome to Java"




             Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                            rights reserved. 0-13-222158-6
                                                                                                                         11
Trace Code
                                                                                   s
String s = "Welcome to Java";                                                                                 : String
                                                                                   s2
String s1 = new String("Welcome to Java");                                                            Interned string object for
                                                                                                      "Welcome to Java"
String s2 = s1.intern();

String s3 = "Welcome to Java";                                                      s1                        : String
                                                                                                       A string object for
                                                                                                       "Welcome to Java"




             Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                            rights reserved. 0-13-222158-6
                                                                                                                         12
Trace Code
                                                                                   s
String s = "Welcome to Java";                                                                                 : String
                                                                                   s2
String s1 = new String("Welcome to Java");                                         s3                 Interned string object for
                                                                                                      "Welcome to Java"
String s2 = s1.intern();

String s3 = "Welcome to Java";                                                      s1                        : String
                                                                                                       A string object for
                                                                                                       "Welcome to Java"




             Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                            rights reserved. 0-13-222158-6
                                                                                                                         13
Finding String Length
Finding string length using the length()
method:

message = "Welcome";
message.length() (returns 7)




     Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                    rights reserved. 0-13-222158-6
                                                                                                    14
Retrieving Individual Characters
                in a String
          Do not use message[0]
          Use message.charAt(index)
          Index starts from 0

Indices     0       1       2        3       4        5       6       7       8        9       10 11 12 13 14

message     W       e       l        c       o        m       e                t        o              J       a   v   a

message.charAt(0)                           message.length() is 15                                      message.charAt(14)

                Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                               rights reserved. 0-13-222158-6
                                                                                                                       15
String Concatenation
String s3 = s1.concat(s2);


String s3 = s1 + s2;

s1 + s2 + s3 + s4 + s5 same as
(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);



           Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                          rights reserved. 0-13-222158-6
                                                                                                          16
Extracting Substrings
You can extract a single character from a string using the
charAt method. You can also extract a substring from a
string using the substring method in the String class.

String s1 = "Welcome to Java";
String s2 = s1.substring(0, 11) + "HTML";


Indices   0      1       2       3       4        5       6       7       8       9       10 11 12 13 14

message   W      e       l       c       o        m       e                t       o              J          a   v   a


                               message.substring(0, 11)                                          message.substring(11)
              Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                             rights reserved. 0-13-222158-6
                                                                                                                         17
String Comparisons
equals

String s1 = new String("Welcome“);
String s2 = "welcome";

if (s1.equals(s2)){
    // s1 and s2 have the same contents
}

if (s1 == s2) {
 // s1 and s2 have the same reference
}
        Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                       rights reserved. 0-13-222158-6
                                                                                                       18
String Comparisons, cont.
compareTo(Object object)

String s1 = new String("Welcome“);
String s2 = "welcome";

if (s1.compareTo(s2) > 0) {
  // s1 is greater than s2
}
else if (s1.compareTo(s2) == 0) {
  // s1 and s2 have the same contents
}
else
   // s1 is less than s2
     Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                    rights reserved. 0-13-222158-6
                                                                                                    19
String Conversions
The contents of a string cannot be changed once
the string is created. But you can convert a string
to a new string using the following methods:

   toLowerCase
   toUpperCase
   trim
   replace(oldChar, newChar)
         Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                        rights reserved. 0-13-222158-6
                                                                                                        20
Finding a Character or a
             Substring in a String
"Welcome   to        Java".indexOf('W') returns 0.
"Welcome   to        Java".indexOf('x') returns -1.
"Welcome   to        Java".indexOf('o', 5) returns 9.
"Welcome   to        Java".indexOf("come") returns 3.
"Welcome   to        Java".indexOf("Java", 5) returns 11.
"Welcome   to        Java".indexOf("java", 5) returns -1.
"Welcome   to        Java".lastIndexOf('a') returns 14.



           Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                          rights reserved. 0-13-222158-6
                                                                                                          21
The StringBuffer Class
The StringBuffer class is an alternative to the
String class. In general, a string buffer can be
used wherever a string is used.

StringBuffer is more flexible than String.
You can add, insert, or append new contents
into a string buffer. However, the value of
a String object is fixed once the string is created.




       Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                      rights reserved. 0-13-222158-6
                                                                                                      22
java.lang.StringBuffer

+StringBuffer()                                                 Constructs an empty string buffer with capacity 16
+StringBuffer(capacity: int)                                    Constructs a string buffer with the specified capacity
+StringBuffer(str: String)                                      Constructs a string buffer with the specified string
+append(data: char[]): StringBuffer                             Appends a char array into this string buffer
+append(data: char[], offset: int, len: int): StringBuffer      Appends a subarray in data into this string buffer
+append(v: aPrimitiveType): StringBuffer                        Appends a primitive type value as string to this buffer
+append(str: String): StringBuffer                              Appends a string to this string buffer
+capacity(): int                                                Returns the capacity of this string buffer
+charAt(index: int): char                                       Returns the character at the specified index
+delete(startIndex: int, endIndex: int): StringBuffer           Deletes characters from startIndex to endIndex
+deleteCharAt(int index): StringBuffer                          Deletes a character at the specified index
+insert(index: int, data: char[], offset: int, len: int):       Inserts a subarray of the data in the array to the buffer at
 StringBuffer                                                     the specified index
+insert(offset: int, data: char[]): StringBuffer                Inserts data to this buffer at the position offset
+insert(offset: int, b: aPrimitiveType): StringBuffer           Inserts a value converted to string into this buffer
+insert(offset: int, str: String): StringBuffer                 Inserts a string into this buffer at the position offset
+length(): int                                                  Returns the number of characters in this buffer
+replace(int startIndex, int endIndex, String str):             Replaces the characters in this buffer from startIndex to
 StringBuffer                                                    endIndex with the specified string
+reverse(): StringBuffer                                        Reveres the characters in the buffer
+setCharAt(index: int, ch: char): void                          Sets a new character at the specified index in this buffer
+setLength(newLength: int): void                                Sets a new length in this buffer
+substring(startIndex: int): String                             Returns a substring starting at startIndex
+substring(startIndex: int, endIndex: int): String Sixth Edition, (c) a substring from startIndex to endIndex
                Liang, Introduction to Java Programming,  Returns 2007 Pearson Education, Inc. All
                                              rights reserved. 0-13-222158-6
                                                                                                                           23
StringBuffer Constructors
public StringBuffer()
No characters, initial capacity 16 characters.

public StringBuffer(int length)
No characters, initial capacity specified by the
length argument.

public StringBuffer(String str)
Represents the same sequence of characters
as the string argument. Initial capacity 16
plus the length of the string argument.


      Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                     rights reserved. 0-13-222158-6
                                                                                                     24
Appending New Contents
      into a String Buffer
StringBuffer strBuf = new StringBuffer();
strBuf.append("Welcome");
strBuf.append(' ');
strBuf.append("to");
strBuf.append(' ');
strBuf.append("Java");




     Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                    rights reserved. 0-13-222158-6
                                                                                                    25
The StringTokenizer Class

       java.util.StringTokenizer

+StringTokenizer(s: String)                                Constructs a string tokenizer for the string.
+StringTokenizer(s: String, delimiters: Constructs a string tokenizer for the string
  String)                                with the specified delimiters.
+StringTokenizer(s: String, delimiters: Constructs a string tokenizer for the string
  String, returnDelimiters: boolean)     with the delimiters and returnDelims.
+countTokens(): int                     Returns the number of remaining tokens.
+hasMoreTokens(): boolean                                  Returns true if there are more tokens left.
+nextToken(): String                                       Returns the next token.
+nextToken(delimiters: String): String Returns the next token using new delimiters.



              Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                             rights reserved. 0-13-222158-6
                                                                                                             26
Examples 1
String s = "Java is cool.";
StringTokenizer tokenizer = new StringTokenizer(s);

System.out.println("The total number of tokens is " +
 tokenizer.countTokens());

while (tokenizer.hasMoreTokens())
 System.out.println(tokenizer.nextToken());
   The code displays
                                                             The total number of tokens is 3
                                                             Java
                                                             is
                                                             cool.
         Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
                                        rights reserved. 0-13-222158-6
                                                                                                        27

Mais conteúdo relacionado

Mais procurados

String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)Anwar Hasan Shuvo
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanKavita Ganesan
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)teach4uin
 
Java - Strings Concepts
Java - Strings ConceptsJava - Strings Concepts
Java - Strings ConceptsVicter Paul
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?RAKESH P
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper classSimoniShah6
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Edureka!
 
String java
String javaString java
String java774474
 

Mais procurados (20)

String in java
String in javaString in java
String in java
 
Java String
Java String Java String
Java String
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java String
Java StringJava String
Java String
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Java strings
Java   stringsJava   strings
Java strings
 
Java - Strings Concepts
Java - Strings ConceptsJava - Strings Concepts
Java - Strings Concepts
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
 
String java
String javaString java
String java
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 

Destaque

Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Strings and common operations
Strings and common operationsStrings and common operations
Strings and common operationsTurnToTech
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Indian Property Lawyers .com - How It Works
Indian Property Lawyers .com - How It WorksIndian Property Lawyers .com - How It Works
Indian Property Lawyers .com - How It Worksbuzzfactory
 
Java: strings e arrays
Java: strings e arraysJava: strings e arrays
Java: strings e arraysArthur Emanuel
 
Java cơ bản java co ban
Java cơ bản java co ban Java cơ bản java co ban
Java cơ bản java co ban ifis
 
kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931
 
bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1ifis
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02Terry Yoast
 

Destaque (20)

Java Starting
Java StartingJava Starting
Java Starting
 
Exception handling
Exception handlingException handling
Exception handling
 
Java packages
Java packagesJava packages
Java packages
 
Strings and common operations
Strings and common operationsStrings and common operations
Strings and common operations
 
Java 06 Strings Arrays
Java 06 Strings ArraysJava 06 Strings Arrays
Java 06 Strings Arrays
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Indian Property Lawyers .com - How It Works
Indian Property Lawyers .com - How It WorksIndian Property Lawyers .com - How It Works
Indian Property Lawyers .com - How It Works
 
Java: strings e arrays
Java: strings e arraysJava: strings e arrays
Java: strings e arrays
 
JavaYDL18
JavaYDL18JavaYDL18
JavaYDL18
 
Java cơ bản java co ban
Java cơ bản java co ban Java cơ bản java co ban
Java cơ bản java co ban
 
kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia
 
JavaYDL5
JavaYDL5JavaYDL5
JavaYDL5
 
01slide
01slide01slide
01slide
 
bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1
 
April 2014
April 2014April 2014
April 2014
 
Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02
 
05slide
05slide05slide
05slide
 

Semelhante a String handling session 5

LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .pptzainiiqbal761
 
Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Gouda Mando
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...Indu32
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi_Kant_Sahu
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10mlrbrown
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdflearnEnglish51
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.Brian Hsu
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vectornurkhaledah
 
stringstringbuilderstringbuffer-190830060142.pptx
stringstringbuilderstringbuffer-190830060142.pptxstringstringbuilderstringbuffer-190830060142.pptx
stringstringbuilderstringbuffer-190830060142.pptxssuser99ca78
 

Semelhante a String handling session 5 (20)

JavaYDL9
JavaYDL9JavaYDL9
JavaYDL9
 
09slide
09slide09slide
09slide
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .ppt
 
Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"
 
07slide
07slide07slide
07slide
 
JavaYDL17
JavaYDL17JavaYDL17
JavaYDL17
 
8. String
8. String8. String
8. String
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10
 
Json demo
Json demoJson demo
Json demo
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
stringstringbuilderstringbuffer-190830060142.pptx
stringstringbuilderstringbuffer-190830060142.pptxstringstringbuilderstringbuffer-190830060142.pptx
stringstringbuilderstringbuffer-190830060142.pptx
 

Último

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

String handling session 5

  • 1. JAVA STRINGS Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 1
  • 2. The String Class Constructing a String: – String message = "Welcome to Java“; – String message = new String("Welcome to Java“); – String s = new String(); Obtaining String length and Retrieving Individual Characters in a string String Concatenation (concat) Substrings (substring(index), substring(start, end)) Comparisons (equals, compareTo) String Conversions Finding a Character or a Substring in a String Conversions between Strings and Arrays Converting Characters and Numeric Values to Strings Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 2
  • 3. java.lang.String +String() Constructs an empty string +String(value: String) Constructs a string with the specified string literal value +String(value: char[]) Constructs a string with the specified character array +charAt(index: int): char Returns the character at the specified index from this string +compareTo(anotherString: String): int Compares this string with another string +compareToIgnoreCase(anotherString: String): int Compares this string with another string ignoring case +concat(anotherString: String): String Concat this string with another string +endsWith(suffix: String): boolean Returns true if this string ends with the specified suffix +equals(anotherString: String): boolean Returns true if this string is equal to anther string +equalsIgnoreCase(anotherString: String): boolean Checks if this string equals anther string ignoring case +getChars(int srcBegin, int srcEnd, char[] dst, int Copies characters from this string into the destination character dstBegin): void array +indexOf(ch: int): int Returns the index of the first occurrence of ch +indexOf(ch: int, fromIndex: int): int Returns the index of the first occurrence of ch after fromIndex +indexOf(str: String): int Returns the index of the first occurrence of str +indexOf(str: String, fromIndex: int): int Returns the index of the first occurrence of str after fromIndex +lastIndexOf(ch: int): int Returns the index of the last occurrence of ch +lastIndexOf(ch: int, fromIndex: int): int Returns the index of the last occurrence of ch before fromIndex +lastIndexOf(str: String): int Returns the index of the last occurrence of str +lastIndexOf(str: String, fromIndex: int): int Returns the index of the last occurrence of str before fromIndex +regionMatches(toffset: int, other: String, offset: Returns true if the specified subregion of this string exactly int, len: int): boolean matches the specified subregion of the string argument +length(): int Returns the number of characters in this string +replace(oldChar: char, newChar: char): String Returns a new string with oldChar replaced by newChar +startsWith(prefix: String): boolean Returns true if this string starts with the specified prefix +subString(beginIndex: int): String Returns the substring from beginIndex +subString(beginIndex: int, endIndex: int): String Returns the substring from beginIndex to endIndex-1. +toCharArray(): char[] Returns a char array consisting characters from this string +toLowerCase(): String Returns a new string with all characters converted to lowercase +toString(): String Returns a new string with itself +toUpperCase(): String Returns a new string with all characters converted to uppercase +trim(): String Returns a string with blank characters trimmed on both sides +copyValueOf(data: char[]): String Returns a new string consisting of the char array data +valueOf(c: char): String Returns a string consisting of the character c +valueOf(data: char[]): String Same as copyValueOf(data: char[]): String +valueOf(d: double): String Returns a string representing the double value +valueOf(f: float): String Returns a string representing the float value +valueOf(i:Liang, Introduction int): String to Java Programming, Sixth string representing Pearson Education, Inc. All Returns a Edition, (c) 2007 the int value +valueOf(l: long): String rights reserved.a0-13-222158-6 Returns string representing the long value 3
  • 4. Constructing Strings String newString = new String(stringLiteral); String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java"; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 4
  • 5. Strings Are Immutable A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 5
  • 6. animation Trace Code String s = "Java"; s = "HTML"; After executing String s = "Java"; After executing s = "HTML"; s : String s : String This string object is now unreferenced String object for "Java" String object for "Java" Contents cannot be changed : String String object for "HTML" Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 6
  • 7. animation Trace Code String s = "Java"; s = "HTML"; After executing String s = "Java"; After executing s = "HTML"; s : String s : String This string object is now unreferenced String object for "Java" String object for "Java" Contents cannot be changed : String String object for "HTML" Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 7
  • 8. Interned Strings Since strings are immutable and are frequently used, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. You can also use a String object’s intern method to return an interned string. For example, the following statements: Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 8
  • 9. Examples s String s = "Welcome to Java"; : String s2 String s1 = new String("Welcome to Java"); s3 Interned string object for "Welcome to Java" String s2 = s1.intern(); String s3 = "Welcome to Java"; s1 : String System.out.println("s1 == s is " + (s1 == s)); A string object for System.out.println("s2 == s is " + (s2 == s)); "Welcome to Java" System.out.println("s == s3 is " + (s == s3)); display A new object is created if you use the s1 == s is false new operator. If you use the string initializer, no new s2 == s is true object is created if the interned object is already created. s == s3 is true Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 9
  • 10. Trace Code s String s = "Welcome to Java"; : String String s1 = new String("Welcome to Java"); Interned string object for "Welcome to Java" String s2 = s1.intern(); String s3 = "Welcome to Java"; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 10
  • 11. Trace Code s String s = "Welcome to Java"; : String String s1 = new String("Welcome to Java"); Interned string object for "Welcome to Java" String s2 = s1.intern(); String s3 = "Welcome to Java"; s1 : String A string object for "Welcome to Java" Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 11
  • 12. Trace Code s String s = "Welcome to Java"; : String s2 String s1 = new String("Welcome to Java"); Interned string object for "Welcome to Java" String s2 = s1.intern(); String s3 = "Welcome to Java"; s1 : String A string object for "Welcome to Java" Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 12
  • 13. Trace Code s String s = "Welcome to Java"; : String s2 String s1 = new String("Welcome to Java"); s3 Interned string object for "Welcome to Java" String s2 = s1.intern(); String s3 = "Welcome to Java"; s1 : String A string object for "Welcome to Java" Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 13
  • 14. Finding String Length Finding string length using the length() method: message = "Welcome"; message.length() (returns 7) Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 14
  • 15. Retrieving Individual Characters in a String Do not use message[0] Use message.charAt(index) Index starts from 0 Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 message W e l c o m e t o J a v a message.charAt(0) message.length() is 15 message.charAt(14) Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 15
  • 16. String Concatenation String s3 = s1.concat(s2); String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 same as (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5); Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 16
  • 17. Extracting Substrings You can extract a single character from a string using the charAt method. You can also extract a substring from a string using the substring method in the String class. String s1 = "Welcome to Java"; String s2 = s1.substring(0, 11) + "HTML"; Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 message W e l c o m e t o J a v a message.substring(0, 11) message.substring(11) Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 17
  • 18. String Comparisons equals String s1 = new String("Welcome“); String s2 = "welcome"; if (s1.equals(s2)){ // s1 and s2 have the same contents } if (s1 == s2) { // s1 and s2 have the same reference } Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 18
  • 19. String Comparisons, cont. compareTo(Object object) String s1 = new String("Welcome“); String s2 = "welcome"; if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents } else // s1 is less than s2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 19
  • 20. String Conversions The contents of a string cannot be changed once the string is created. But you can convert a string to a new string using the following methods: toLowerCase toUpperCase trim replace(oldChar, newChar) Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 20
  • 21. Finding a Character or a Substring in a String "Welcome to Java".indexOf('W') returns 0. "Welcome to Java".indexOf('x') returns -1. "Welcome to Java".indexOf('o', 5) returns 9. "Welcome to Java".indexOf("come") returns 3. "Welcome to Java".indexOf("Java", 5) returns 11. "Welcome to Java".indexOf("java", 5) returns -1. "Welcome to Java".lastIndexOf('a') returns 14. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 21
  • 22. The StringBuffer Class The StringBuffer class is an alternative to the String class. In general, a string buffer can be used wherever a string is used. StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer. However, the value of a String object is fixed once the string is created. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 22
  • 23. java.lang.StringBuffer +StringBuffer() Constructs an empty string buffer with capacity 16 +StringBuffer(capacity: int) Constructs a string buffer with the specified capacity +StringBuffer(str: String) Constructs a string buffer with the specified string +append(data: char[]): StringBuffer Appends a char array into this string buffer +append(data: char[], offset: int, len: int): StringBuffer Appends a subarray in data into this string buffer +append(v: aPrimitiveType): StringBuffer Appends a primitive type value as string to this buffer +append(str: String): StringBuffer Appends a string to this string buffer +capacity(): int Returns the capacity of this string buffer +charAt(index: int): char Returns the character at the specified index +delete(startIndex: int, endIndex: int): StringBuffer Deletes characters from startIndex to endIndex +deleteCharAt(int index): StringBuffer Deletes a character at the specified index +insert(index: int, data: char[], offset: int, len: int): Inserts a subarray of the data in the array to the buffer at StringBuffer the specified index +insert(offset: int, data: char[]): StringBuffer Inserts data to this buffer at the position offset +insert(offset: int, b: aPrimitiveType): StringBuffer Inserts a value converted to string into this buffer +insert(offset: int, str: String): StringBuffer Inserts a string into this buffer at the position offset +length(): int Returns the number of characters in this buffer +replace(int startIndex, int endIndex, String str): Replaces the characters in this buffer from startIndex to StringBuffer endIndex with the specified string +reverse(): StringBuffer Reveres the characters in the buffer +setCharAt(index: int, ch: char): void Sets a new character at the specified index in this buffer +setLength(newLength: int): void Sets a new length in this buffer +substring(startIndex: int): String Returns a substring starting at startIndex +substring(startIndex: int, endIndex: int): String Sixth Edition, (c) a substring from startIndex to endIndex Liang, Introduction to Java Programming, Returns 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 23
  • 24. StringBuffer Constructors public StringBuffer() No characters, initial capacity 16 characters. public StringBuffer(int length) No characters, initial capacity specified by the length argument. public StringBuffer(String str) Represents the same sequence of characters as the string argument. Initial capacity 16 plus the length of the string argument. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 24
  • 25. Appending New Contents into a String Buffer StringBuffer strBuf = new StringBuffer(); strBuf.append("Welcome"); strBuf.append(' '); strBuf.append("to"); strBuf.append(' '); strBuf.append("Java"); Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 25
  • 26. The StringTokenizer Class java.util.StringTokenizer +StringTokenizer(s: String) Constructs a string tokenizer for the string. +StringTokenizer(s: String, delimiters: Constructs a string tokenizer for the string String) with the specified delimiters. +StringTokenizer(s: String, delimiters: Constructs a string tokenizer for the string String, returnDelimiters: boolean) with the delimiters and returnDelims. +countTokens(): int Returns the number of remaining tokens. +hasMoreTokens(): boolean Returns true if there are more tokens left. +nextToken(): String Returns the next token. +nextToken(delimiters: String): String Returns the next token using new delimiters. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 26
  • 27. Examples 1 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s); System.out.println("The total number of tokens is " + tokenizer.countTokens()); while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); The code displays The total number of tokens is 3 Java is cool. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 27