String Handling

String is probably the most commonly used class in java library. String class is encapsulated underjava.lang package. In java, every string that you create is actually an object of type String. One important thing to notice about string object is that string objects are immutable that means once a string object is created it cannot be altered.

What is String in Java? Is String is data type?

String in Java is not a primitive data type like int, long or double. String is a class or in more simple term a user defined type. This is confusing for someone who comes from C background. String is defined in java.lang package and wrappers its content in a character array. String provides equals() method to COMPARE two String and provides various other method to operate on String like toUpperCase() to convert String into upper case, replace() to replace String contents, substring() to get substring, split() to split long String into multiple String.

What is String handling?

Performing different operations on string data is called String Handling.

sh

All these three classes are final class

These three Classes are such as of java.io.serializable interface implements.

String class is a subclass of comparable interface, but string buffer and string builder is not.

 

STRING CLASS

In General string can be defined as it as sequence of characters string is constant, their values cannot be changed in the same memory after they are created.

It is an immutable sequence of characters.

Default values are null.

String class has Totally 15 Constructors but 8 is important Constructors. They are following.

  • String()

Creates empty string object not null string object.

 

  • String(String value)

Creates string object with string object character. It is perform copy String operation.

 

In string copy of different string object are created. In string argument current objects reference is copied into destination, new object is not created.

  • String(StringBuffer sb)

Create new String object with the given StringBuffer object data.

Perform string copy operations form stringBuffer object too string object.

  • String(StringBuilder sb)

Create new String object with the given StringBuilder object data.

Perform string copy operations form StringBuilder object too string object.

  • String(char[] ch)

Creates String object with the given char array values.

Perform string copy operations form char [] object too String object.

 

  • String(char[] value, int offset, int count)

Allocates a new String that contains characters from a subarray of the character array argument.

  • String(byte[] bytes)

Constructs a new String by decoding the specified array of bytes using the platform’s default charset.

  • String(byte[] bytes, int offset, int length, Charsetcharset)

Constructs a new String by decoding the specified subarray of bytes using the specified charset.

Rules:

Char[] & byte[] parameter constructrs the gives offset & count arg value must be within the rang of [0 to String length ], else if leads the RE. java.lang.StringIndexOutOfBoundException.

We cannot pass null as arg directly too constructor, if leads CE. Ambiguous error  because  if  matched with all parameters of String class constructors.

We cannot create String  object with null it leads to RE. java.lang.NullPointerException.

String s1=null;

String s2=new String(s1); RE. NPE.

 

String Class Methods:

       Methods      Description 
char charAt(int index) Returns the character at the specified index.
int compareTo(Object o) Compares this String to another Object.
int compareTo(String anotherString) Compares two strings lexicographically.
int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences.
String concat(String str) Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence
of characters as the specified StringBuffer.
static String copyValueOf(char[] data) Returns a String that represents the character sequence in the array
specified.
static String copyValueOf(char[] data, int offset,
int count)
Returns a String that represents the character sequence in the array
specified.
boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
boolean equals(Object anObject) Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations.
byte getBytes() Encodes this String into a sequence of bytes using the platform’s default
charset, storing the result into a new byte array.
byte[] getBytes(String charsetName) Encodes this String into a sequence of bytes using the named charset,
storing the result into a new byte array.
void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
int hashCode() Returns a hash code for this string.
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified
character.
int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
int indexOf(String str) Returns the index within this string of the first occurrence of the specified
substring.
int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
String intern() Returns a canonical representation for the string object.
int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified
character.
int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.
int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the
specified substring.
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.
int length() Returns the length of this string.
boolean matches(String regex) Tells whether or not this string matches the given regular expression.
boolean regionMatches(boolean ignoreCase,
int toffset, String other, int ooffset, int len)
Tests if two string regions are equal
boolean regionMatches(int toffset, String other,
int ooffset, int len)
Tests if two string regions are equal.
String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar
in this string with newChar.
String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular
expression with the given replacement.
String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular
expression with the given replacement.
String[] split(String regex) Splits this string around matches of the given regular expression.
String[] split(String regex, int limit) Splits this string around matches of the given regular expression.
boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix beginning a
specified index.
CharSequence subSequence(int beginIndex,
int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex) Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.
char[] toCharArray() Converts this string to a new character array.
String toLowerCase() Converts all of the characters in this String to lower case using the rules of
the default locale.
tring toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules
of the given Locale.
String toString() This object (which is already a string!) is itself returned.
String toUpperCase() Converts all of the characters in this String to upper case using the rules of
the default locale.
String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of
the given Locale.
String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(primitive data type x) Returns the string representation of the passed data type argument.

What are different ways to create String Object?

We can create String object using new operator like any normal java class or we can use double quotes to create a String object. There are several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilder.

 

1

2

String str = new String(“abc”);

String str1 = “abc”;

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.

 

How to compare two Strings in java program?

Java String implements Comparable interface and it has two variants of compareTo() methods.

compareTo(String anotherString) method compares the String object with the String argument passed lexicographically. If String object precedes the argument passed, it returns negative integer and if String object follows the argument String passed, it returns positive integer. It returns zero when both the String have same value, in this case equals(String str) method will also return true.

compareToIgnoreCase(String str): This method is similar to the first one, except that it ignores the case. It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison. If the value is zero thenequalsIgnoreCase(String str) will also return true.

Why String is Immutable in Java?

  1. Requirement of String Pool

String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

The following code will create only one string object in the heap.

String string1 = “abcd”;

String string2 = “abcd”;

shh

If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

  1. Allow String to Cache its Hashcode

The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.

  1. Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

 

What is String pool in Java?

String pool is a special storage area in Java heap, mostly located on PerGen space, to store String literals like “abc”. When Java program creates a new String using String literal, JVM checks for that String in pool and if String literal is already present in pool than same object is returned instead of creating a whole new object. String pool check is only performed when you create String as literal, if you create String using new() operator, a new String object will be created even if String with same content is available in pool.

STRINGBUFFER CLASS

StringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and character string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).

Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer manipulations.

CREATION OF STRINGBUFFERS

 

Constructor Summary
StringBuffer()
Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(CharSequence seq)
Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity)
Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
Constructs a string buffer initialized to the contents of the specified string.

StringBuffer

public StringBuffer()

Constructs a string buffer with no characters in it and an initial capacity of 16 characters.

StringBuffer

public StringBuffer(CharSequence seq)

Constructs a string buffer that contains the same characters as the specified CharSequence. The initial capacity of the string buffer is 16 plus the length of the CharSequence argument.

If the length of the specified CharSequence is less than or equal to zero, then an empty buffer of capacity 16 is returned.

Parameters:

seq – the sequence to copy.

StringBuffer

public StringBuffer(int capacity)

Constructs a string buffer with no characters in it and the specified initial capacity.

Parameters:

capacity – the initial capacity.

 

StringBuffer

public StringBuffer(String str)

Constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is 16 plus the length of the string argument.

Parameters:

str – the initial contents of the buffer.

 

 

Method Detail

append

public synchronized StringBuffer append(boolean b)

Overrides:

append in class AbstractStringBuilder

Parameters:

b

 

append

public synchronized StringBuffer append(char c)

Overrides:

append in class AbstractStringBuilder

Parameters:

c

append

public StringBuffer append(CharSequence s)

Appends the specified CharSequence to this sequence.

The characters of the CharSequence argument are appended, in order, increasing the length of this sequence by the length of the argument.

The result of this method is exactly the same as if it were an invocation of this.append(s, 0, s.length());

This method synchronizes on this (the destination) object but does not synchronize on the source (s).

If s is null, then the four characters “null” are appended.

Overrides:

append in class AbstractStringBuilder

Parameters:

s – the CharSequence to append.

Returns:

a reference to this object.

 

append

public synchronized StringBuffer append(CharSequence s,   int start,  int end)

Overrides:

append in class AbstractStringBuilder

Parameters:

s

start

end

append

public synchronized StringBuffer append(char[] str)

Overrides:

append in class AbstractStringBuilder

Parameters:

str

append

public synchronized StringBuffer append(char[] str,  int offset,  int len)

Overrides:

append in class AbstractStringBuilder

Parameters:

str

offset

len

 

append

public synchronized StringBuffer append(double d)

Overrides:

append in class AbstractStringBuilder

Parameters:

d

append

public synchronized StringBuffer append(float f)

Overrides:

append in class AbstractStringBuilder

Parameters:

f

append

public synchronized StringBuffer append(int i)

Overrides:

append in class AbstractStringBuilder

Parameters:

i

 

append

public synchronized StringBuffer append(long lng)

Overrides:

append in class AbstractStringBuilder

Parameters:

lng

append

public synchronized StringBuffer append(Object obj)

Overrides:

append in class AbstractStringBuilder

Parameters:

obj

append

public synchronized StringBuffer append(String str)

Overrides:

append in class AbstractStringBuilder

Parameters:

str

 

append

public synchronized StringBuffer append(StringBuffer sb)

Appends the specified StringBuffer to this sequence.

The characters of the StringBuffer argument are appended, in order, to the contents of this StringBuffer, increasing the length of this StringBuffer by the length of the argument. If sb is null, then the four characters “null” are appended to this StringBuffer.

Let n be the length of the old character sequence, the one contained in the StringBuffer just prior to execution of the append method. Then the character at index k in the new character sequence is equal to the character at index k in the old character sequence, if k is less than n; otherwise, it is equal to the character at index k-n in the argument sb.

This method synchronizes on this (the destination) object but does not synchronize on the source (sb).

Overrides:

append in class AbstractStringBuilder

Parameters:

sb – the StringBuffer to append.

Returns:

a reference to this object.

appendCodePoint

public synchronized StringBuffer appendCodePoint(int codePoint)

Overrides:

appendCodePoint in class AbstractStringBuilder

Parameters:

codePoint

 

capacity

public synchronized int capacity()

Overrides:

capacity in class AbstractStringBuilder

charAt

public synchronized char charAt(int index)

Overrides:

charAt in class AbstractStringBuilder

Parameters:

index

codePointAt

public synchronized int codePointAt(int index)

Overrides:

codePointAt in class AbstractStringBuilder

Parameters:

index

codePointBefore

public synchronized int codePointBefore(int index)

Overrides:

codePointBefore in class AbstractStringBuilder

Parameters:

index

codePointCount

public synchronized int codePointCount(int beginIndex,   int endIndex)

Overrides:

codePointCount in class AbstractStringBuilder

Parameters:

beginIndex

endIndex

delete

public synchronized StringBuffer delete(int start,  int end)

Overrides:

delete in class AbstractStringBuilder

Parameters:

start

end

deleteCharAt

public synchronized StringBuffer deleteCharAt(int index)

Overrides:

deleteCharAt in class AbstractStringBuilder

Parameters:

index

 

ensureCapacity

public synchronized void ensureCapacity(int minimumCapacity)

Overrides:

ensureCapacity in class AbstractStringBuilder

Parameters:

minimumCapacity

getChars

public synchronized void getChars(int srcBegin,  int srcEnd,   char[] dst,  int dstBegin)

Overrides:

getChars in class AbstractStringBuilder

Parameters:

srcBegin

srcEnd

dst

dstBegin

indexOf

public int indexOf(String str)

Overrides:

indexOf in class AbstractStringBuilder

Parameters:

str

indexOf

public synchronized int indexOf(String str,     int fromIndex)

Overrides:

indexOf in class AbstractStringBuilder

Parameters:

str

fromIndex

insert

public StringBuffer insert(int offset, boolean b)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

b

insert

public synchronized StringBuffer insert(int offset, char c)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

c

 

insert

public StringBuffer insert(int dstOffset,  CharSequence s)

Overrides:

insert in class AbstractStringBuilder

Parameters:

dstOffset

s

insert

public synchronized StringBuffer insert(int dstOffset, CharSequence s,   int start,     int end)

Overrides:

insert in class AbstractStringBuilder

Parameters:

dstOffset

s

start

end

insert

public synchronized StringBuffer insert(int offset, char[] str)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

str

insert

public synchronized StringBuffer insert(int index,   char[] str,   int offset,    int len)

Overrides:

insert in class AbstractStringBuilder

Parameters:

index

str

offset

len

insert

public StringBuffer insert(int offset,    double d)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

d

 

insert

public StringBuffer insert(int offset, float f)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

f

insert

public StringBuffer insert(int offset,   int i)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

i

insert

public StringBuffer insert(int offset,  long l)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

l

 

insert

public synchronized StringBuffer insert(int offset,Object obj)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

obj

insert

public synchronized StringBuffer insert(int offset,     String str)

Overrides:

insert in class AbstractStringBuilder

Parameters:

offset

str

lastIndexOf

public int lastIndexOf(String str)

Overrides:

lastIndexOf in class AbstractStringBuilder

Parameters:

str

lastIndexOf

public synchronized int lastIndexOf(String str,    int fromIndex)

Overrides:

lastIndexOf in class AbstractStringBuilder

Parameters:

str

fromIndex

length

public synchronized int length()

Overrides:

length in class AbstractStringBuilder

offsetByCodePoints

public synchronized int offsetByCodePoints(int index,  int codePointOffset)

Overrides:

offsetByCodePoints in class AbstractStringBuilder

Parameters:

index

codePointOffset

replace

public synchronized StringBuffer replace(int start,         int end,    String str)

Overrides:

replace in class AbstractStringBuilder

Parameters:

start

end

str

reverse

public synchronized StringBuffer reverse()

Overrides:

reverse in class AbstractStringBuilder

setCharAt

public synchronized void setCharAt(int index,  char ch)

Overrides:

setCharAt in class AbstractStringBuilder

Parameters:

index

ch

setLength

public synchronized void setLength(int newLength)

Overrides:

setLength in class AbstractStringBuilder

Parameters:

newLength

subSequence

public synchronized CharSequence subSequence(int start, nt end)

Overrides:

subSequence in class AbstractStringBuilder

Parameters:

start

end

substring

public synchronized String substring(int start)

Overrides:

substring in class AbstractStringBuilder

Parameters:

start

substring

public synchronized String substring(int start,    int end)

Overrides:

substring in class AbstractStringBuilder

Parameters:

start

end

 

toString

public synchronized String toString()

Overrides:

toString in class AbstractStringBuilder

trimToSize

public synchronized void trimToSize()

Overrides:

trimToSize in class AbstractStringBuilder

STRINGBUilder CLASS

public final class StringBuilder extends AbstractStringBuilder

implements Serializable, CharSequence

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

For example, if z refers to a string builder object whose current contents are “start”, then the method call z.append(“le”) would cause the string builder to contain “startle”, whereas z.insert(4, “le”) would alter the string builder to contain “starlet”.

In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that {@link java.lang.StringBuffer} be used.

 

INTERVIEW QUESTIONS

How to compare two Strings in java program?

Java String implements Comparable interface and it has two variants of compareTo() methods.

compareTo(String anotherString) method compares the String object with the String argument passed lexicographically. If String object precedes the argument passed, it returns negative integer and if String object follows the argument String passed, it returns positive integer. It returns zero when both the String have same value, in this case equals(String str) method will also return true.

compareToIgnoreCase(String str): This method is similar to the first one, except that it ignores the case. It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison. If the value is zero thenequalsIgnoreCase(String str) will also return true.

What does intern() method do in Java?

As discussed in previous String interview question, String object crated by new() operator is by default not added in String pool as opposed to String literal. intern() method allows to put an String object into pool. 

 

Does String is thread-safe in Java?

If you are familiar with the concept of immutability and thread-safety you can easily answer this String interview question in Java. Since String is immutable, it is thread-safe and it can be shared between multiple thread without external synchronization.

Can we compare String using == operator? What is risk?

You can compare String using equality operator but that is not suggested or advised because equality operator is used to compare primitives and equals() method should be used to compare objects. As we have seen in pitfall of autoboxing in Java that how equality operator can cause subtle issue while comparing primitive to Object, any way String is free from that issue because it doesn’t have corresponding primitive type and not participate in autoboxing. Almost all the time comparing String means comparing contents of String i.e. characters and equals() method is used to perform character based comparison. equals() return true if two String points to same object or two String has same contents while == operator returns true if two String object points to same object but return false if two different String object contains same contents. That explains why sometime it works and sometime it doesn’t. In short always use equals method in Java to check equality of two String object.

Builder vs StringBuffer

String vs StringBuilder: StringBuilder is mutable, which means you can modify it after its creation.
StringBuilder vs StringBuffer: StringBuffer is synchronized, which means it is thread-safe but slower than StringBuilder.

 

 

String vs StringBuffer

 

No. String StringBuffer
1) String class is immutable. StringBuffer class is mutable.
2) String is slow and consumes more memory when you concat too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when you cancat strings.
3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn’t override the equals() method of Object class.