String Handling

Author: Ravi Poswal

Although it is a collection of characters, Java's String class has several methods. String class implements a Serializable and Comparable interface. There are four types

  1. String

  2. String Buffer

  3. String Builder

  4. String Tokenizer

1. STRING: The object of the string class isan immutable sequence of characters, which means that once a string object is created, it cannot be modified. It is an example of overriding.

Benefits of the String class

  • Security

  • Synchronization

  • Performance

  • Reusability (Caching)

A string Object class can be created using the following constructor.

  • public String();

  • public String(String);

  • pubic String(char[]);

  • public String (char[], int, int);

  • public String(int[], int, int)

  • public String(byte [])

  • public String (byte[], int, int)

Code Example

class Example
{
public static void main(String args[])
{
char[] a = {'A', 'B', 'C', 'D', 'E', 'F'};
byte b[] = {65, 66, 67, 68, 69, 70};
String s1 = new String(a);
String s2 = new String(a, 2, 3);
String s3 = new String(b);
String s4 = new String(b, 0, 3);
String s5 = new String(s2);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s1==s3); // ”==”operator 
System.out.println(s2==s5);
System.out.println(s2==s4);
System.out.println(s1.equals(s3)); //”equal()” method
System.out.println(s2.equals(s5));
System.out.println(s2.equals(s4));
}
}
// Note:- “==” equal operator for reference comparison (address comparison) but “equal” method for content comparison.