SlideShare a Scribd company logo
Chapter 11



String & StringBuffer


                    http://www.java2all.com
String Handling



                  http://www.java2all.com
String Handling :
    In Java, a string is defined as a sequence of
 characters.
    But, unlike many other languages that
 implement strings as character arrays, java
 implements strings as objects of type String.

    Java handles String by two classes StringBuffer
 and String. The String and StringBuffer classes are
 defined in java.lang.
    Thus, they are available to all programs
 automatically.
                                            http://www.java2all.com
1. String Concatenation (+)
  EX :            Output :
import java.util.*;
class str3                                 S1 = Java
{
  public static void main(String args[])
                                           S2 = 2all
  {                                        Concatenation Operator = Java2all
     String s1 = new String ("Java");
     String s2 = "2all";
                                           S3 = Java2all
     String s3 = s1+s2;                    S4 = ABCD
     System.out.println("S1 = " + s1);
     System.out.println("S2 = " + s2);
     System.out.println("Concatenation Operator = " + s1+s2);
     System.out.println("S3 = " + s3);

      byte num [] = {65,66,67,68};
      String s4 = new String(num);
      System.out.println("S4 = " + s4);
  }

                                                                   http://www.java2all.com
2. Character Extraction :
     The String class provides ways in which
characters can be extracted from a String object.
Method                               Description
                                     charAt() function is used to extract a single character
char charAt(int indexnum)            from a String. indexnum is the index number of the
                                     character that we want to extract.

                                     Used to extract more than one character at a time,
void getChars(int sourceStart, int   sourceStart specifies beginning of the string, and
sourceEnd, char target[], int        sourceEnd specifies end of the string. The array that will
targetStart)                         receive the characters is specified by target. The index
                                     within target at which the substring will be copied.

                                     This is an alternative to getChars( ) that stores the
                                     characters in an array of bytes. It uses the default
Byte[ ] getBytes( )
                                     character-to-byte conversions provided by the
                                     platform.

Char[ ] toCharArray( )               Same as getChars
                                                                              http://www.java2all.com
3. String Comparison :

    The String class provides several methods that
compare strings or substrings within strings.

        equals( ) – used to compare two strings General
form:
        Boolean equals(Object str)

        Here, str is a String object.

     It returns true if the strings contain the same
character otherwise it returns false
.                                               http://www.java2all.com
The comparison is case-sensitive.

     equalsIgnoreCase( ) – Same as equals but this
ignores case. General form:

   Boolean equalsIgnoreCase(String str)

Here, str is the String object.

It returns true if the strings contain the same
character otherwise it returns false.

                                              http://www.java2all.com
This is case in – sensitive.

    regionMatches( )

      This method compares a specific region inside a
string with another specific region in another string.
There is an overloaded form that allows you to ignore
case in such comparisons.

General form:

    Boolean regionMatches(int startIndex, String
str2, int str2StartIndes, int numChars)
                                             http://www.java2all.com
Boolean regionMatches(Boolean ignoreCase, int
startIndex, String str2, int str2StartIndex, int
numChars)

startsWith( ) and endsWith()

      The startsWith( ) method determines whether a
given String begins with a specified string. endsWith(
) determines whether the String ends with a specified
string.
General Form
    Boolean startsWith(String str)
    Boolean endsWith(String str)
equals( ) Versus = =                          http://www.java2all.com
Equals( ) method and the = = operator
perform two different operations. The equals ( )
method compares the characters inside a String
object. The = = operator compares two object
references to see whether they refer to the same
instance.

     compareTo( )

      It is not enough to know that two strings just
for equal or not. For sorting applications, we need
to know which is less than, equal to, or greater
than the other string.
                                              http://www.java2all.com
The String method compareTo( ) serves this
purpose.

     General Form:

        int compareTo(String str)



                                          http://www.java2all.com
4 Modifying a string :
      If we want to modify a String, we must either
copy it into a StringBufer or we can use following
String methods:




                                            http://www.java2all.com
Method                           Description

String substring(int n)          Gives substring starting from nth character.


                                 Gives substring starting from nth char up to
String substring(int n, int m)
                                 mth


S1.concat(s2)                    Concatenates s1 and s2

                                 The replace() method replaces all occurrences
String replace(char original,
                                 of one character in the invoking string with
char replacement)
                                 another character.
                                 Remove white space at the beginning and end
String trim( )
                                 of the string.


                                                                 http://www.java2all.com
5 valueOf() :
      The valueOf() method converts data from
internal format into a human-readable form. It has
several forms:

     String valueOf(double num)
     String valueOf(long num)
     String valueOf(Object ob)
     String valueOf(char chars[ ] )
     String valueOf(char chars[], int startIndex, int
     numChars)

                                             http://www.java2all.com
Method & Example
Method Call              Description

S2=s1.toLowerCase;       Converts the string s1 to lowercase

S2=s1.toUpperCase;       Converts the string s1 to uppercase

S2=s1.replace(‘x’,’y’)   Replace all appearances of x with y.

                         Remove white spaces at the beginning and of the
S2=s1.trim()
                         string s1

S1.equals(s2)            Returns true if s1 and s2 are equal

S1.equalsIgnoreCase(s
                         Returns true if s1=s2, ignoring the case of characters
2)

S1.length()              Gives the length of s1
                                                                 http://www.java2all.com
S1.CharAt(n)            Gives the nth character of s1
S1.compareTo(s2)        Returns –ve if s1<s2 +ve.if s1>s2, and 0 if s1=s2
S1.concat(s2)           Concatenates s1 and s2
S1.substring(n)         Gives substring starting from nth character.
S1.substring(n, m)      Gives substring starting from nth char up to mth
                        Returns the string representation of the specified
String.valueOf(p)
                        type argument.
                        This object (which is already a string!) is itself
toString()
                        returned.
                        Gives the position of the first occurrence of ‘x’ in the
S1.indexOf(‘x’)
                        string s1
                        Gives the position of ‘x’ that occurs after nth position
S1.indexOf(‘x’, n)
                        in the string s1
String.ValueOf(variable
                        Converts the parameter value of string representation
)
                                                                   http://www.java2all.com
import java.util.*;
class str1
{
   public static void main(String args[])
   {
      String s1 = "Bhagirath";
      System.out.println("S1 = " + s1);
      int length = s1.length();
      System.out.println("S1 lenth = " + length);
      System.out.println("S1 lowercase = " + s1.toLowerCase());
      System.out.println("S1 uppercase = " + s1.toUpperCase());
      System.out.println("S1 replace a with z = " + s1.replace('a','z'));
      System.out.println("S1 indexOf('e')= " + s1.indexOf('e'));
      System.out.println("S1 lastindexof('e') = " + s1.lastIndexOf('e'));
      String s2 = "ViewSonic";
      System.out.println("S2 = " + s2);
      System.out.println("S1 and S2 trim = " + s1.trim() + s2.trim());
      System.out.println("S1 and S2 equals = " + s1.equals(s2));
      System.out.println("S1 and S2 equals ignoring case = " + s1.equalsIgnoreCase(s2));
      System.out.println("S1 and S2 compareTo = " + s1.compareTo(s2));
      System.out.println("S1 and S2 concate = " + s1.concat(s2));
      System.out.println("S1 substring(n) = " + s1.substring(5));
      System.out.println("S1 substring(n,m) = " + s1.substring(5,8));
      System.out.println("S1 toString() = " + s1.toString());
      int i = 100;
      System.out.println("S1.valueOf(variable) = " + (s1.valueOf(i)).length()); // converts the parameter
to string
                                                                                      http://www.java2all.com
System.out.println("Start with " + s1.startsWith("P"));
        System.out.println("Start with " + s1.endsWith("y"));

    }
}




                                                                  http://www.java2all.com
Output :
S1 = Bhagirath
S1 lenth = 9
S1 lowercase = bhagirath
S1 uppercase = BHAGIRATH
S1 replace a with z = Bhzgirzth
S1 indexOf('e')= -1
S1 lastindexof('e') = -1
S2 = ViewSonic
S1 and S2 trim = BhagirathViewSonic
S1 and S2 equals = false
S1 and S2 equals ignoring case = false
S1 and S2 compareTo = -20
S1 and S2 concate = BhagirathViewSonic
S1 substring(n) = rath
S1 substring(n,m) = rat
S1 toString() = Bhagirath
S1.valueOf(variable) = 3
Start with false
Start with false                         http://www.java2all.com
import java.util.*;
class str4
{
   public static void main(String args[])
   {
     String s = "This is a dAmo of the getChars method.";
     int start = 10;
     int end = 14;
     char buf[] = new char[10];
     //System.out.println("Character at 10 = " + s.charAt(10));
     s.getChars(start, end, buf,0);                           Output :
     System.out.println(buf);
     s.getChars(start, end, buf,5);
                                                               jav
     System.out.println(buf);                                  jav jav
        byte bt [] = new byte[10];                            32
        s.getBytes(start, end, bt,0);
        System.out.println(bt[0]);                            74
        System.out.println(bt[1]);
        System.out.println(bt[2]);
                                                              97
        System.out.println(bt[3]);                            118
        char buf1[] = s.toCharArray();                        Welcome to Java2all
        System.out.println(buf1);

    }
}
                                                                          http://www.java2all.com
import java.util.*;
class str5
{
   public static void main(String args[])
   {
     String s1 = "Rome was not built in a not day";
     System.out.println("S1 = " + s1);
     /*System.out.println("S1 = " + s1.indexOf('o'));
     System.out.println("S1 = " + s1.indexOf("not"));
     System.out.println("S1 = " + s1.indexOf('o',5));
     System.out.println("S1 = " + s1.indexOf("not", 15));

        System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o'));
        System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not"));
        System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o',15));
        System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not", 15)); */
        String s2 = "Rome was not built in a Not day";
        System.out.println("S2 = " + s2);
        //System.out.println("S1 = " + s1.indexOf("not"));
        //System.out.println("S1 = " + s1.lastIndexOf("not"));
        System.out.println("Region Matches = ");
        boolean b1 = s1.regionMatches(false,9,s2,24,3);
        System.out.println("b1 = " + b1);


    }
}
                                                                                 http://www.java2all.com
Output :

S1 = Rome was not built in a not day
S2 = Rome was not built in a Not day
Region Matches =
b1 = false




                                       http://www.java2all.com
import java.util.*;
class str6
{
   public static void main(String args[])
   {
     String s1 = "Hello";
     String s2 = new String(s1);
     System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
     System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));


    }
}


        Output :

        Hello equals Hello -> true
        Hello == Hello -> false



                                                                          http://www.java2all.com
StringBuffer Class



                 http://www.java2all.com
StringBuffer class :

      StringBuffer is a peer class of String. String
creates strings of fixed length, while StringBuffer
creates strings of flexible length that can be modified
in terms of both length and content.

      So Strings that need modification are handled by
StringBuffer class.

     We can insert characters and substrings in the
middle of a string, or append another string to the end.
                                              http://www.java2all.com
StringBufer defines these Constructor:


       StringBuffer()
       StringBuffer(int size)
       StringBuffer(String str)




                                         http://www.java2all.com
Method Call                   Task Performed
                              Gives the current length of a
Sb.length()
                              StringBuffer.
                              Gives the total allocated capacity
Sb.capacity()
                              (default 16)
                              Set the length of the buffer within
setLength(int len)
                              a String Buffer object.

charAt(int where)             Gives the value of character

                              Set the value of a character within
setCharAt(int where, char ch)
                              a StringBuffer.

                                                      http://www.java2all.com
Appends the string s2 to s1 at
S1.append(s2)
                                the end

                                Inserts the string s2 at the
S1.insert(n,s2)
                                position n of the string s1

S1.reverse()                    Reverse the string of s1

                                Delete the nth character of
S1.deleteCharAt(nth)
                                string s1

                                Delete characters from start to
S1.delete(StartIndex, endIndex)
                                end.


                                                     http://www.java2all.com
import java.util.*;

class strbuf1                                                   Output :
{
     public static void main(String args[])
     {
        StringBuffer s1 = new StringBuffer();
                                                                s1 =
        StringBuffer s2 = new StringBuffer("Bhagirath");        s2 = Bhagirath
        StringBuffer s3 = new StringBuffer(s2);
        StringBuffer s4 = new StringBuffer(100);                s3 = Bhagirath
        System.out.println("s1 = " + s1);
        System.out.println("s2 = " + s2);                       s1.length = 0
        System.out.println("s3 = " + s3);                       s2.length = 9
        System.out.println("s1.length = " + s1.length());       s3.length = 9
        System.out.println("s2.length = " + s2.length());
        System.out.println("s3.length = " + s3.length());       s4.length = 0
        System.out.println("s4.length = " + s4.length());
                                                                s1.capacity = 16
        System.out.println("s1.capacity = " + s1.capacity());
        System.out.println("s2.capacity = " + s2.capacity());
                                                                s2.capacity = 25
        System.out.println("s3.capacity = " + s3.capacity());   s3.capacity = 25
        System.out.println("s4.capacity = " + s4.capacity());
                                                                s4.capacity = 100
    }
}
                                                                            http://www.java2all.com
import java.util.*;
class strbuf2
{
     public static void main(String args[])
     {
        StringBuffer s1 = new StringBuffer("Java2all");
        StringBuffer s2 = new StringBuffer("Hello");
        System.out.println("s1 = " + s1);
        //System.out.println("s1.charAt(5) = " + s1.charAt(5));
        //s1.setCharAt(5,'z');
        //System.out.println("s1 = " + s1);
        //System.out.println("Inserting String = " + s1.insert(5,s2));
        //System.out.println("s1 = " + s1);
        //System.out.println("Appending String = " + s1.append(s2));
        //System.out.println("s1 = " + s1);
        //System.out.println("Reversing String = " + s1.reverse());
        //System.out.println("Deleting 5th character = " + s1.deleteCharAt(5));
        System.out.println("Deleting 5 to 8 character = " + s1.delete(5,8));
     }
}
          Output :

          s1 = Java2all
          Deleting 5 to 8 character =
          Java2                                                                   http://www.java2all.com
import java.util.*;

public class strbuf3
{                                                             Output :
  public static void main(String[] args)
  {

        StringBuffer s = new StringBuffer("Hello world!");
                                                              s = Hello world!
                                                              s.length() = 12
        System.out.println("s = " + s);
        System.out.println("s.length() = " + s.length());     s.length() = 28
        System.out.println("s.length() = " + s.capacity());
        // Change the length of buffer to 5 characters:       Hello
        s.setLength(5);                                       s.length() = 5
        System.out.println(s);                                s.length() = 28
        System.out.println("s.length() = " + s.length());
        System.out.println("s.length() = " + s.capacity());

    }
}




                                                                                 http://www.java2all.com

More Related Content

PPTX
oops concept in java | object oriented programming in java
PPTX
Control Statements in Java
PPTX
Java string handling
PPTX
String, string builder, string buffer
PPTX
Starting a code Club proposal
PPTX
Design and Analysis of Algorithms.pptx
PPTX
Basics of epidemiology
PPTX
Tree - Data Structure
oops concept in java | object oriented programming in java
Control Statements in Java
Java string handling
String, string builder, string buffer
Starting a code Club proposal
Design and Analysis of Algorithms.pptx
Basics of epidemiology
Tree - Data Structure

What's hot (20)

PPTX
Inheritance in java
PDF
Arrays in Java
PPTX
Type casting in java
PPT
Java interfaces
PPTX
Command line arguments
PPTX
Regular expressions in Python
PPSX
Data Types & Variables in JAVA
PPTX
Super keyword in java
PPS
Wrapper class
PPTX
Constructor in java
PPTX
Java abstract class & abstract methods
PPTX
Structure of java program diff c- cpp and java
PPTX
Control statements in java
PPT
Java Streams
PPTX
Strings in Java
PPTX
Java Strings
PPTX
Classes objects in java
PPTX
java interface and packages
PPTX
String Builder & String Buffer (Java Programming)
Inheritance in java
Arrays in Java
Type casting in java
Java interfaces
Command line arguments
Regular expressions in Python
Data Types & Variables in JAVA
Super keyword in java
Wrapper class
Constructor in java
Java abstract class & abstract methods
Structure of java program diff c- cpp and java
Control statements in java
Java Streams
Strings in Java
Java Strings
Classes objects in java
java interface and packages
String Builder & String Buffer (Java Programming)
Ad

Viewers also liked (20)

PPT
PPTX
L13 string handling(string class)
PDF
String handling(string buffer class)
PPTX
Java String
PPTX
Java Basics
PPT
Chapter 2 - Getting Started with Java
PPTX
String java
PPTX
Vectors in Java
PPTX
Open and Close Door ppt
PDF
Arrays string handling java packages
PPTX
java Applet Introduction
PPT
Java Applet
PPTX
applet using java
PDF
ITFT- Applet in java
PPT
Java applet
PPTX
L18 applets
PDF
Java Applet and Graphics
PDF
String handling(string class)
PPT
14. Defining Classes
L13 string handling(string class)
String handling(string buffer class)
Java String
Java Basics
Chapter 2 - Getting Started with Java
String java
Vectors in Java
Open and Close Door ppt
Arrays string handling java packages
java Applet Introduction
Java Applet
applet using java
ITFT- Applet in java
Java applet
L18 applets
Java Applet and Graphics
String handling(string class)
14. Defining Classes
Ad

Similar to String and string buffer (20)

PPTX
Java String Handling
PPT
07slide
PDF
Module-1 Strings Handling.ppt.pdf
PPTX
Java string , string buffer and wrapper class
PPT
Strings.ppt
PDF
Airoli_Grade 10_CompApp_PP000000000000000000000000000000000000000000T_Charact...
PPTX
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
PPTX
String in java, string constructors and operations
PPTX
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
PPTX
10619416141061941614.106194161fff4..pptx
PPTX
Programing with java for begniers .pptx
PPT
JavaScript Objects
PPTX
Java string handling
PPT
M C6java7
PPT
Strings Arrays
PPTX
javastringexample problems using string class
PPTX
Computer programming 2 Lesson 12
PPTX
String handling
PDF
Strings part2
PPT
Text processing
Java String Handling
07slide
Module-1 Strings Handling.ppt.pdf
Java string , string buffer and wrapper class
Strings.ppt
Airoli_Grade 10_CompApp_PP000000000000000000000000000000000000000000T_Charact...
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
String in java, string constructors and operations
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
10619416141061941614.106194161fff4..pptx
Programing with java for begniers .pptx
JavaScript Objects
Java string handling
M C6java7
Strings Arrays
javastringexample problems using string class
Computer programming 2 Lesson 12
String handling
Strings part2
Text processing

More from kamal kotecha (20)

PPS
Java Hibernate Programming with Architecture Diagram and Example
PPTX
Network programming in java - PPT
PPT
Java servlet life cycle - methods ppt
PPS
Java rmi example program with code
PPS
Java rmi
PPS
Jdbc example program with access and MySql
PPS
Jdbc api
PPS
Jdbc architecture and driver types ppt
PPS
Java Exception handling
PPS
JSP Error handling
PPS
Jsp element
PPS
Jsp chapter 1
PPS
Packages and inbuilt classes of java
PPS
Interface
PPS
Inheritance chepter 7
PPS
Class method
PPS
Introduction to class in java
PPS
Control statements
PPTX
Jsp myeclipse
PPTX
basic core java up to operator
Java Hibernate Programming with Architecture Diagram and Example
Network programming in java - PPT
Java servlet life cycle - methods ppt
Java rmi example program with code
Java rmi
Jdbc example program with access and MySql
Jdbc api
Jdbc architecture and driver types ppt
Java Exception handling
JSP Error handling
Jsp element
Jsp chapter 1
Packages and inbuilt classes of java
Interface
Inheritance chepter 7
Class method
Introduction to class in java
Control statements
Jsp myeclipse
basic core java up to operator

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Business Ethics Teaching Materials for college
PPTX
Pharma ospi slides which help in ospi learning
PDF
RMMM.pdf make it easy to upload and study
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
01-Introduction-to-Information-Management.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
master seminar digital applications in india
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Basic Mud Logging Guide for educational purpose
VCE English Exam - Section C Student Revision Booklet
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPH.pptx obstetrics and gynecology in nursing
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Business Ethics Teaching Materials for college
Pharma ospi slides which help in ospi learning
RMMM.pdf make it easy to upload and study
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Structure & Organelles in detailed.
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
01-Introduction-to-Information-Management.pdf
human mycosis Human fungal infections are called human mycosis..pptx
O7-L3 Supply Chain Operations - ICLT Program
Pharmacology of Heart Failure /Pharmacotherapy of CHF

String and string buffer

  • 1. Chapter 11 String & StringBuffer http://www.java2all.com
  • 2. String Handling http://www.java2all.com
  • 3. String Handling : In Java, a string is defined as a sequence of characters. But, unlike many other languages that implement strings as character arrays, java implements strings as objects of type String. Java handles String by two classes StringBuffer and String. The String and StringBuffer classes are defined in java.lang. Thus, they are available to all programs automatically. http://www.java2all.com
  • 4. 1. String Concatenation (+) EX : Output : import java.util.*; class str3 S1 = Java { public static void main(String args[]) S2 = 2all { Concatenation Operator = Java2all String s1 = new String ("Java"); String s2 = "2all"; S3 = Java2all String s3 = s1+s2; S4 = ABCD System.out.println("S1 = " + s1); System.out.println("S2 = " + s2); System.out.println("Concatenation Operator = " + s1+s2); System.out.println("S3 = " + s3); byte num [] = {65,66,67,68}; String s4 = new String(num); System.out.println("S4 = " + s4); } http://www.java2all.com
  • 5. 2. Character Extraction : The String class provides ways in which characters can be extracted from a String object. Method Description charAt() function is used to extract a single character char charAt(int indexnum) from a String. indexnum is the index number of the character that we want to extract. Used to extract more than one character at a time, void getChars(int sourceStart, int sourceStart specifies beginning of the string, and sourceEnd, char target[], int sourceEnd specifies end of the string. The array that will targetStart) receive the characters is specified by target. The index within target at which the substring will be copied. This is an alternative to getChars( ) that stores the characters in an array of bytes. It uses the default Byte[ ] getBytes( ) character-to-byte conversions provided by the platform. Char[ ] toCharArray( ) Same as getChars http://www.java2all.com
  • 6. 3. String Comparison : The String class provides several methods that compare strings or substrings within strings. equals( ) – used to compare two strings General form: Boolean equals(Object str) Here, str is a String object. It returns true if the strings contain the same character otherwise it returns false . http://www.java2all.com
  • 7. The comparison is case-sensitive. equalsIgnoreCase( ) – Same as equals but this ignores case. General form: Boolean equalsIgnoreCase(String str) Here, str is the String object. It returns true if the strings contain the same character otherwise it returns false. http://www.java2all.com
  • 8. This is case in – sensitive. regionMatches( ) This method compares a specific region inside a string with another specific region in another string. There is an overloaded form that allows you to ignore case in such comparisons. General form: Boolean regionMatches(int startIndex, String str2, int str2StartIndes, int numChars) http://www.java2all.com
  • 9. Boolean regionMatches(Boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars) startsWith( ) and endsWith() The startsWith( ) method determines whether a given String begins with a specified string. endsWith( ) determines whether the String ends with a specified string. General Form Boolean startsWith(String str) Boolean endsWith(String str) equals( ) Versus = = http://www.java2all.com
  • 10. Equals( ) method and the = = operator perform two different operations. The equals ( ) method compares the characters inside a String object. The = = operator compares two object references to see whether they refer to the same instance. compareTo( ) It is not enough to know that two strings just for equal or not. For sorting applications, we need to know which is less than, equal to, or greater than the other string. http://www.java2all.com
  • 11. The String method compareTo( ) serves this purpose. General Form: int compareTo(String str) http://www.java2all.com
  • 12. 4 Modifying a string : If we want to modify a String, we must either copy it into a StringBufer or we can use following String methods: http://www.java2all.com
  • 13. Method Description String substring(int n) Gives substring starting from nth character. Gives substring starting from nth char up to String substring(int n, int m) mth S1.concat(s2) Concatenates s1 and s2 The replace() method replaces all occurrences String replace(char original, of one character in the invoking string with char replacement) another character. Remove white space at the beginning and end String trim( ) of the string. http://www.java2all.com
  • 14. 5 valueOf() : The valueOf() method converts data from internal format into a human-readable form. It has several forms: String valueOf(double num) String valueOf(long num) String valueOf(Object ob) String valueOf(char chars[ ] ) String valueOf(char chars[], int startIndex, int numChars) http://www.java2all.com
  • 15. Method & Example Method Call Description S2=s1.toLowerCase; Converts the string s1 to lowercase S2=s1.toUpperCase; Converts the string s1 to uppercase S2=s1.replace(‘x’,’y’) Replace all appearances of x with y. Remove white spaces at the beginning and of the S2=s1.trim() string s1 S1.equals(s2) Returns true if s1 and s2 are equal S1.equalsIgnoreCase(s Returns true if s1=s2, ignoring the case of characters 2) S1.length() Gives the length of s1 http://www.java2all.com
  • 16. S1.CharAt(n) Gives the nth character of s1 S1.compareTo(s2) Returns –ve if s1<s2 +ve.if s1>s2, and 0 if s1=s2 S1.concat(s2) Concatenates s1 and s2 S1.substring(n) Gives substring starting from nth character. S1.substring(n, m) Gives substring starting from nth char up to mth Returns the string representation of the specified String.valueOf(p) type argument. This object (which is already a string!) is itself toString() returned. Gives the position of the first occurrence of ‘x’ in the S1.indexOf(‘x’) string s1 Gives the position of ‘x’ that occurs after nth position S1.indexOf(‘x’, n) in the string s1 String.ValueOf(variable Converts the parameter value of string representation ) http://www.java2all.com
  • 17. import java.util.*; class str1 { public static void main(String args[]) { String s1 = "Bhagirath"; System.out.println("S1 = " + s1); int length = s1.length(); System.out.println("S1 lenth = " + length); System.out.println("S1 lowercase = " + s1.toLowerCase()); System.out.println("S1 uppercase = " + s1.toUpperCase()); System.out.println("S1 replace a with z = " + s1.replace('a','z')); System.out.println("S1 indexOf('e')= " + s1.indexOf('e')); System.out.println("S1 lastindexof('e') = " + s1.lastIndexOf('e')); String s2 = "ViewSonic"; System.out.println("S2 = " + s2); System.out.println("S1 and S2 trim = " + s1.trim() + s2.trim()); System.out.println("S1 and S2 equals = " + s1.equals(s2)); System.out.println("S1 and S2 equals ignoring case = " + s1.equalsIgnoreCase(s2)); System.out.println("S1 and S2 compareTo = " + s1.compareTo(s2)); System.out.println("S1 and S2 concate = " + s1.concat(s2)); System.out.println("S1 substring(n) = " + s1.substring(5)); System.out.println("S1 substring(n,m) = " + s1.substring(5,8)); System.out.println("S1 toString() = " + s1.toString()); int i = 100; System.out.println("S1.valueOf(variable) = " + (s1.valueOf(i)).length()); // converts the parameter to string http://www.java2all.com
  • 18. System.out.println("Start with " + s1.startsWith("P")); System.out.println("Start with " + s1.endsWith("y")); } } http://www.java2all.com
  • 19. Output : S1 = Bhagirath S1 lenth = 9 S1 lowercase = bhagirath S1 uppercase = BHAGIRATH S1 replace a with z = Bhzgirzth S1 indexOf('e')= -1 S1 lastindexof('e') = -1 S2 = ViewSonic S1 and S2 trim = BhagirathViewSonic S1 and S2 equals = false S1 and S2 equals ignoring case = false S1 and S2 compareTo = -20 S1 and S2 concate = BhagirathViewSonic S1 substring(n) = rath S1 substring(n,m) = rat S1 toString() = Bhagirath S1.valueOf(variable) = 3 Start with false Start with false http://www.java2all.com
  • 20. import java.util.*; class str4 { public static void main(String args[]) { String s = "This is a dAmo of the getChars method."; int start = 10; int end = 14; char buf[] = new char[10]; //System.out.println("Character at 10 = " + s.charAt(10)); s.getChars(start, end, buf,0); Output : System.out.println(buf); s.getChars(start, end, buf,5); jav System.out.println(buf); jav jav byte bt [] = new byte[10]; 32 s.getBytes(start, end, bt,0); System.out.println(bt[0]); 74 System.out.println(bt[1]); System.out.println(bt[2]); 97 System.out.println(bt[3]); 118 char buf1[] = s.toCharArray(); Welcome to Java2all System.out.println(buf1); } } http://www.java2all.com
  • 21. import java.util.*; class str5 { public static void main(String args[]) { String s1 = "Rome was not built in a not day"; System.out.println("S1 = " + s1); /*System.out.println("S1 = " + s1.indexOf('o')); System.out.println("S1 = " + s1.indexOf("not")); System.out.println("S1 = " + s1.indexOf('o',5)); System.out.println("S1 = " + s1.indexOf("not", 15)); System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o')); System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not")); System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o',15)); System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not", 15)); */ String s2 = "Rome was not built in a Not day"; System.out.println("S2 = " + s2); //System.out.println("S1 = " + s1.indexOf("not")); //System.out.println("S1 = " + s1.lastIndexOf("not")); System.out.println("Region Matches = "); boolean b1 = s1.regionMatches(false,9,s2,24,3); System.out.println("b1 = " + b1); } } http://www.java2all.com
  • 22. Output : S1 = Rome was not built in a not day S2 = Rome was not built in a Not day Region Matches = b1 = false http://www.java2all.com
  • 23. import java.util.*; class str6 { public static void main(String args[]) { String s1 = "Hello"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); } } Output : Hello equals Hello -> true Hello == Hello -> false http://www.java2all.com
  • 24. StringBuffer Class http://www.java2all.com
  • 25. StringBuffer class : StringBuffer is a peer class of String. String creates strings of fixed length, while StringBuffer creates strings of flexible length that can be modified in terms of both length and content. So Strings that need modification are handled by StringBuffer class. We can insert characters and substrings in the middle of a string, or append another string to the end. http://www.java2all.com
  • 26. StringBufer defines these Constructor: StringBuffer() StringBuffer(int size) StringBuffer(String str) http://www.java2all.com
  • 27. Method Call Task Performed Gives the current length of a Sb.length() StringBuffer. Gives the total allocated capacity Sb.capacity() (default 16) Set the length of the buffer within setLength(int len) a String Buffer object. charAt(int where) Gives the value of character Set the value of a character within setCharAt(int where, char ch) a StringBuffer. http://www.java2all.com
  • 28. Appends the string s2 to s1 at S1.append(s2) the end Inserts the string s2 at the S1.insert(n,s2) position n of the string s1 S1.reverse() Reverse the string of s1 Delete the nth character of S1.deleteCharAt(nth) string s1 Delete characters from start to S1.delete(StartIndex, endIndex) end. http://www.java2all.com
  • 29. import java.util.*; class strbuf1 Output : { public static void main(String args[]) { StringBuffer s1 = new StringBuffer(); s1 = StringBuffer s2 = new StringBuffer("Bhagirath"); s2 = Bhagirath StringBuffer s3 = new StringBuffer(s2); StringBuffer s4 = new StringBuffer(100); s3 = Bhagirath System.out.println("s1 = " + s1); System.out.println("s2 = " + s2); s1.length = 0 System.out.println("s3 = " + s3); s2.length = 9 System.out.println("s1.length = " + s1.length()); s3.length = 9 System.out.println("s2.length = " + s2.length()); System.out.println("s3.length = " + s3.length()); s4.length = 0 System.out.println("s4.length = " + s4.length()); s1.capacity = 16 System.out.println("s1.capacity = " + s1.capacity()); System.out.println("s2.capacity = " + s2.capacity()); s2.capacity = 25 System.out.println("s3.capacity = " + s3.capacity()); s3.capacity = 25 System.out.println("s4.capacity = " + s4.capacity()); s4.capacity = 100 } } http://www.java2all.com
  • 30. import java.util.*; class strbuf2 { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Java2all"); StringBuffer s2 = new StringBuffer("Hello"); System.out.println("s1 = " + s1); //System.out.println("s1.charAt(5) = " + s1.charAt(5)); //s1.setCharAt(5,'z'); //System.out.println("s1 = " + s1); //System.out.println("Inserting String = " + s1.insert(5,s2)); //System.out.println("s1 = " + s1); //System.out.println("Appending String = " + s1.append(s2)); //System.out.println("s1 = " + s1); //System.out.println("Reversing String = " + s1.reverse()); //System.out.println("Deleting 5th character = " + s1.deleteCharAt(5)); System.out.println("Deleting 5 to 8 character = " + s1.delete(5,8)); } } Output : s1 = Java2all Deleting 5 to 8 character = Java2 http://www.java2all.com
  • 31. import java.util.*; public class strbuf3 { Output : public static void main(String[] args) { StringBuffer s = new StringBuffer("Hello world!"); s = Hello world! s.length() = 12 System.out.println("s = " + s); System.out.println("s.length() = " + s.length()); s.length() = 28 System.out.println("s.length() = " + s.capacity()); // Change the length of buffer to 5 characters: Hello s.setLength(5); s.length() = 5 System.out.println(s); s.length() = 28 System.out.println("s.length() = " + s.length()); System.out.println("s.length() = " + s.capacity()); } } http://www.java2all.com

Editor's Notes

  • #14: White Space Characters
  • #17: White Space Characters
  • #27: White Space Characters
  • #28: White Space Characters
  • #32: White Space Characters