SlideShare a Scribd company logo
1 of 31
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

What's hot

What's hot (20)

Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
StringTokenizer in java
StringTokenizer in javaStringTokenizer in java
StringTokenizer in java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 

Viewers also liked (20)

Strings
StringsStrings
Strings
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
Java String
Java String Java String
Java String
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
String java
String javaString java
String java
 
Open and Close Door ppt
 Open and Close Door ppt Open and Close Door ppt
Open and Close Door ppt
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
java Applet Introduction
java Applet Introductionjava Applet Introduction
java Applet Introduction
 
Java Applet
Java AppletJava Applet
Java Applet
 
applet using java
applet using javaapplet using java
applet using java
 
ITFT- Applet in java
ITFT- Applet in javaITFT- Applet in java
ITFT- Applet in java
 
Java applet
Java appletJava applet
Java applet
 
L18 applets
L18 appletsL18 applets
L18 applets
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Java Applet
Java AppletJava Applet
Java Applet
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 

Similar to String and string buffer

Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdflearnEnglish51
 
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
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptxadityaraj7711
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string classfedcoordinator
 
Text processing
Text processingText processing
Text processingIcancode
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
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
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 

Similar to String and string buffer (20)

Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
07slide
07slide07slide
07slide
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
 
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
 
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Java string handling
Java string handlingJava string handling
Java string handling
 
M C6java7
M C6java7M C6java7
M C6java7
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
String handling
String handlingString handling
String handling
 
Strings part2
Strings part2Strings part2
Strings part2
 
Text processing
Text processingText processing
Text processing
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
package
packagepackage
package
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Strings
StringsStrings
Strings
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 

More from kamal kotecha

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 

More from kamal kotecha (20)

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Java rmi
Java rmiJava rmi
Java rmi
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Interface
InterfaceInterface
Interface
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Class method
Class methodClass method
Class method
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Control statements
Control statementsControl statements
Control statements
 
Jsp myeclipse
Jsp myeclipseJsp myeclipse
Jsp myeclipse
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 

Recently uploaded

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

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

  1. White Space Characters
  2. White Space Characters
  3. White Space Characters
  4. White Space Characters
  5. White Space Characters